source
stringlengths
3
92
c
stringlengths
26
2.25M
gemm_x_csr_col.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *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 cc = 0; cc < columns; ++cc) { for (ALPHA_INT cr = 0; cr < mat->rows; ++cr) { ALPHA_Number ctmp; alpha_setzero(ctmp); for (ALPHA_INT ai = mat->rows_start[cr]; ai < mat->rows_end[cr]; ++ai) { alpha_madde(ctmp, mat->values[ai], x[index2(cc, mat->col_indx[ai], ldx)]); } alpha_mule(y[index2(cc, cr, ldy)], beta); alpha_madde(y[index2(cc, cr, ldy)], alpha, ctmp); } } return ALPHA_SPARSE_STATUS_SUCCESS; }
par_csr_matop.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_utilities.h" #include "_hypre_parcsr_mv.h" #include "_hypre_lapack.h" #include "_hypre_blas.h" /*-------------------------------------------------------------------------- * hypre_ParMatmul_RowSizes: * * Computes sizes of C rows. Formerly part of hypre_ParMatmul but removed * so it can also be used for multiplication of Boolean matrices. * * Arrays computed: C_diag_i, C_offd_i. * * Arrays needed: (17, all HYPRE_Int*) * rownnz_A, * A_diag_i, A_diag_j, * A_offd_i, A_offd_j, * B_diag_i, B_diag_j, * B_offd_i, B_offd_j, * B_ext_i, B_ext_j, * col_map_offd_B, col_map_offd_B, * B_offd_i, B_offd_j, * B_ext_i, B_ext_j. * * Scalars computed: C_diag_size, C_offd_size. * * Scalars needed: * num_rownnz_A, num_rows_diag_A, num_cols_offd_A, allsquare, * first_col_diag_B, num_cols_diag_B, num_cols_offd_B, num_cols_offd_C *--------------------------------------------------------------------------*/ void hypre_ParMatmul_RowSizes( HYPRE_MemoryLocation memory_location, HYPRE_Int **C_diag_i, HYPRE_Int **C_offd_i, HYPRE_Int *rownnz_A, HYPRE_Int *A_diag_i, HYPRE_Int *A_diag_j, HYPRE_Int *A_offd_i, HYPRE_Int *A_offd_j, HYPRE_Int *B_diag_i, HYPRE_Int *B_diag_j, HYPRE_Int *B_offd_i, HYPRE_Int *B_offd_j, HYPRE_Int *B_ext_diag_i, HYPRE_Int *B_ext_diag_j, HYPRE_Int *B_ext_offd_i, HYPRE_Int *B_ext_offd_j, HYPRE_Int *map_B_to_C, HYPRE_Int *C_diag_size, HYPRE_Int *C_offd_size, HYPRE_Int num_rownnz_A, HYPRE_Int num_rows_diag_A, HYPRE_Int num_cols_offd_A, HYPRE_Int allsquare, HYPRE_Int num_cols_diag_B, HYPRE_Int num_cols_offd_B, HYPRE_Int num_cols_offd_C ) { HYPRE_Int *jj_count_diag_array; HYPRE_Int *jj_count_offd_array; HYPRE_Int start_indexing = 0; /* start indexing for C_data at 0 */ HYPRE_Int num_threads = hypre_NumThreads(); *C_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1, memory_location); *C_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1, memory_location); jj_count_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_count_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Loop over rows of A *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int jj_row_begin_diag, jj_count_diag; HYPRE_Int jj_row_begin_offd, jj_count_offd; HYPRE_Int i1, ii1, i2, i3, jj2, jj3; HYPRE_Int size, rest, num_threads; HYPRE_Int ii, ns, ne; num_threads = hypre_NumActiveThreads(); size = num_rownnz_A/num_threads; rest = num_rownnz_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = start_indexing; jj_count_offd = start_indexing; if (num_cols_diag_B || num_cols_offd_C) { B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B + num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i1 = 0; i1 < num_cols_diag_B + num_cols_offd_C; i1++) { B_marker[i1] = -1; } for (i1 = ns; i1 < ne; i1++) { jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if (rownnz_A) { ii1 = rownnz_A[i1]; } else { ii1 = i1; /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ if (allsquare) { B_marker[i1] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------------- * Loop over entries in row ii1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[ii1]; jj2 < A_offd_i[ii1+1]; jj2++) { i2 = A_offd_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } } } /*----------------------------------------------------------------- * Loop over entries in row ii1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[ii1]; jj2 < A_diag_i[ii1+1]; jj2++) { i2 = A_diag_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of B_offd. *-----------------------------------------------------------*/ if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } } } /*-------------------------------------------------------------------- * Set C_diag_i and C_offd_i for this row. *--------------------------------------------------------------------*/ (*C_diag_i)[ii1] = jj_row_begin_diag; (*C_offd_i)[ii1] = jj_row_begin_offd; } jj_count_diag_array[ii] = jj_count_diag; jj_count_offd_array[ii] = jj_count_offd; hypre_TFree(B_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /* Correct diag_i and offd_i - phase 1 */ if (ii) { jj_count_diag = jj_count_diag_array[0]; jj_count_offd = jj_count_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { jj_count_diag += jj_count_diag_array[i1]; jj_count_offd += jj_count_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { ii1 = rownnz_A ? rownnz_A[i1] : i1; (*C_diag_i)[ii1] += jj_count_diag; (*C_offd_i)[ii1] += jj_count_offd; } } else { (*C_diag_i)[num_rows_diag_A] = 0; (*C_offd_i)[num_rows_diag_A] = 0; for (i1 = 0; i1 < num_threads; i1++) { (*C_diag_i)[num_rows_diag_A] += jj_count_diag_array[i1]; (*C_offd_i)[num_rows_diag_A] += jj_count_offd_array[i1]; } } /* Correct diag_i and offd_i - phase 2 */ if (rownnz_A != NULL) { #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i1 = ns; i1 < (ne-1); i1++) { for (ii1 = rownnz_A[i1] + 1; ii1 < rownnz_A[i1+1]; ii1++) { (*C_diag_i)[ii1] = (*C_diag_i)[rownnz_A[i1+1]]; (*C_offd_i)[ii1] = (*C_offd_i)[rownnz_A[i1+1]]; } } if (ii < (num_threads - 1)) { for (ii1 = rownnz_A[ne-1] + 1; ii1 < rownnz_A[ne]; ii1++) { (*C_diag_i)[ii1] = (*C_diag_i)[rownnz_A[ne]]; (*C_offd_i)[ii1] = (*C_offd_i)[rownnz_A[ne]]; } } else { for (ii1 = rownnz_A[ne-1] + 1; ii1 < num_rows_diag_A; ii1++) { (*C_diag_i)[ii1] = (*C_diag_i)[num_rows_diag_A]; (*C_offd_i)[ii1] = (*C_offd_i)[num_rows_diag_A]; } } } } /* end parallel loop */ *C_diag_size = (*C_diag_i)[num_rows_diag_A]; *C_offd_size = (*C_offd_i)[num_rows_diag_A]; #ifdef HYPRE_DEBUG HYPRE_Int i; for (i = 0; i < num_rows_diag_A; i++) { hypre_assert((*C_diag_i)[i] <= (*C_diag_i)[i+1]); hypre_assert((*C_offd_i)[i] <= (*C_offd_i)[i+1]); } #endif hypre_TFree(jj_count_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(jj_count_offd_array, HYPRE_MEMORY_HOST); /* End of First Pass */ } /*-------------------------------------------------------------------------- * hypre_ParMatmul: * * Multiplies two ParCSRMatrices A and B and returns the product in * ParCSRMatrix C. * * Note: C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix* hypre_ParMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] -= hypre_MPI_Wtime(); #endif /* ParCSRMatrix A */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_BigInt nrows_A = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt ncols_A = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt *row_starts_A = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_rownnz_A; HYPRE_Int *rownnz_A = NULL; /* ParCSRMatrix B */ HYPRE_BigInt nrows_B = hypre_ParCSRMatrixGlobalNumRows(B); HYPRE_BigInt ncols_B = hypre_ParCSRMatrixGlobalNumCols(B); HYPRE_BigInt first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_BigInt *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_BigInt last_col_diag_B; /* A_diag */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_diag_ir = hypre_CSRMatrixRownnz(A_diag); HYPRE_Int num_rownnz_diag_A = hypre_CSRMatrixNumRownnz(A_diag); HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); /* A_offd */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *A_offd_ir = hypre_CSRMatrixRownnz(A_offd); HYPRE_Int num_rownnz_offd_A = hypre_CSRMatrixNumRownnz(A_offd); HYPRE_Int num_rows_offd_A = hypre_CSRMatrixNumRows(A_offd); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); /* B_diag */ hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); /* B_offd */ hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); /* ParCSRMatrix C */ hypre_ParCSRMatrix *C; HYPRE_BigInt *col_map_offd_C; HYPRE_Int *map_B_to_C = NULL; /* C_diag */ hypre_CSRMatrix *C_diag; HYPRE_Complex *C_diag_data; HYPRE_Int *C_diag_i; HYPRE_Int *C_diag_j; HYPRE_Int C_offd_size; HYPRE_Int num_cols_offd_C = 0; /* C_offd */ hypre_CSRMatrix *C_offd; HYPRE_Complex *C_offd_data = NULL; HYPRE_Int *C_offd_i = NULL; HYPRE_Int *C_offd_j = NULL; HYPRE_Int C_diag_size; /* Bs_ext */ hypre_CSRMatrix *Bs_ext; HYPRE_Complex *Bs_ext_data; HYPRE_Int *Bs_ext_i; HYPRE_BigInt *Bs_ext_j; HYPRE_Complex *B_ext_diag_data; HYPRE_Int *B_ext_diag_i; HYPRE_Int *B_ext_diag_j; HYPRE_Int B_ext_diag_size; HYPRE_Complex *B_ext_offd_data; HYPRE_Int *B_ext_offd_i; HYPRE_Int *B_ext_offd_j; HYPRE_BigInt *B_big_offd_j = NULL; HYPRE_Int B_ext_offd_size; HYPRE_Int allsquare = 0; HYPRE_Int num_procs; HYPRE_Int *my_diag_array; HYPRE_Int *my_offd_array; HYPRE_Int max_num_threads; HYPRE_Complex zero = 0.0; HYPRE_MemoryLocation memory_location_A = hypre_ParCSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_ParCSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); max_num_threads = hypre_NumThreads(); my_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); my_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); if (ncols_A != nrows_B || num_cols_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } /* if C=A*B is square globally and locally, then C_diag should be square also */ if ( num_rows_diag_A == num_cols_diag_B && nrows_A == ncols_B ) { allsquare = 1; } /* Set rownnz of A */ if (num_rownnz_diag_A != num_rows_diag_A && num_rownnz_offd_A != num_rows_offd_A ) { hypre_MergeOrderedArrays(num_rownnz_diag_A, A_diag_ir, num_rownnz_offd_A, A_offd_ir, &num_rownnz_A, &rownnz_A); } else { num_rownnz_A = hypre_max(num_rows_diag_A, num_rows_offd_A); } /*----------------------------------------------------------------------- * Extract B_ext, i.e. portion of B that is stored on neighbor procs * and needed locally for matrix matrix product *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); #endif if (num_procs > 1) { /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings within * hypre_ParCSRMatrixExtractBExt *--------------------------------------------------------------------*/ Bs_ext = hypre_ParCSRMatrixExtractBExt(B,A,1); Bs_ext_data = hypre_CSRMatrixData(Bs_ext); Bs_ext_i = hypre_CSRMatrixI(Bs_ext); Bs_ext_j = hypre_CSRMatrixBigJ(Bs_ext); } B_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1, HYPRE_MEMORY_HOST); B_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1, HYPRE_MEMORY_HOST); B_ext_diag_size = 0; B_ext_offd_size = 0; last_col_diag_B = first_col_diag_B + (HYPRE_BigInt) num_cols_diag_B - 1; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedBigIntSet set; #pragma omp parallel { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i = ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { my_offd_size++; } else { my_diag_size++; } } } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #pragma omp barrier if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size, HYPRE_MEMORY_HOST); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size, HYPRE_MEMORY_HOST); B_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size, HYPRE_MEMORY_HOST); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size, HYPRE_MEMORY_HOST); } hypre_UnorderedBigIntSetCreate(&set, B_ext_offd_size + num_cols_offd_B, 16*hypre_NumThreads()); } #pragma omp barrier cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i = ns; i < ne; i++) { for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { hypre_UnorderedBigIntSetPut(&set, Bs_ext_j[j]); B_big_offd_j[cnt_offd] = Bs_ext_j[j]; //Bs_ext_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = (HYPRE_Int)(Bs_ext_j[j] - first_col_diag_B); B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } } HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_B); for (i = i_begin; i < i_end; i++) { hypre_UnorderedBigIntSetPut(&set, col_map_offd_B[i]); } } /* omp parallel */ col_map_offd_C = hypre_UnorderedBigIntSetCopyToArray(&set, &num_cols_offd_C); hypre_UnorderedBigIntSetDestroy(&set); hypre_UnorderedBigIntMap col_map_offd_C_inverse; hypre_big_sort_and_create_inverse_map(col_map_offd_C, num_cols_offd_C, &col_map_offd_C, &col_map_offd_C_inverse); HYPRE_Int i, j; #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_A; i++) { for (j = B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) { //B_ext_offd_j[j] = hypre_UnorderedIntMapGet(&col_map_offd_C_inverse, B_ext_offd_j[j]); B_ext_offd_j[j] = hypre_UnorderedBigIntMapGet(&col_map_offd_C_inverse, B_big_offd_j[j]); } } if (num_cols_offd_C) { hypre_UnorderedBigIntMapDestroy(&col_map_offd_C_inverse); } hypre_TFree(my_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(my_offd_array, HYPRE_MEMORY_HOST); if (num_cols_offd_B) { HYPRE_Int i; map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); #pragma omp parallel private(i) { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_C); HYPRE_Int cnt; if (i_end > i_begin) { cnt = hypre_BigLowerBound(col_map_offd_B, col_map_offd_B + (HYPRE_BigInt)num_cols_offd_B, col_map_offd_C[i_begin]) - col_map_offd_B; } for (i = i_begin; i < i_end && cnt < num_cols_offd_B; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; } } } } if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ HYPRE_BigInt *temp; #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i = ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { my_offd_size++; } else { my_diag_size++; } } } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size, HYPRE_MEMORY_HOST); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size, HYPRE_MEMORY_HOST); B_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size, HYPRE_MEMORY_HOST); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size || num_cols_offd_B) { temp = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size+num_cols_offd_B, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i = ns; i < ne; i++) { for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { temp[cnt_offd] = Bs_ext_j[j]; B_big_offd_j[cnt_offd] = Bs_ext_j[j]; //Bs_ext_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = (HYPRE_Int)(Bs_ext_j[j] - first_col_diag_B); B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { HYPRE_Int cnt; if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } cnt = 0; if (B_ext_offd_size || num_cols_offd_B) { cnt = B_ext_offd_size; for (i = 0; i < num_cols_offd_B; i++) { temp[cnt++] = col_map_offd_B[i]; } if (cnt) { HYPRE_BigInt value; hypre_BigQsort0(temp, 0, cnt-1); num_cols_offd_C = 1; value = temp[0]; for (i = 1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) { col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i = 0; i < num_cols_offd_C; i++) { col_map_offd_C[i] = temp[i]; } hypre_TFree(temp, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = ns; i < ne; i++) { for (j = B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) { B_ext_offd_j[j] = hypre_BigBinarySearch(col_map_offd_C, B_big_offd_j[j], //B_ext_offd_j[j] = hypre_BigBinarySearch(col_map_offd_C, Bs_ext_j[j], num_cols_offd_C); } } } /* end parallel region */ hypre_TFree(B_big_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(my_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(my_offd_array, HYPRE_MEMORY_HOST); if (num_cols_offd_B) { HYPRE_Int i, cnt; map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_cols_offd_C; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } } } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); #endif hypre_ParMatmul_RowSizes(memory_location_C, &C_diag_i, &C_offd_i, rownnz_A, A_diag_i, A_diag_j, A_offd_i, A_offd_j, B_diag_i, B_diag_j, B_offd_i, B_offd_j, B_ext_diag_i, B_ext_diag_j, B_ext_offd_i, B_ext_offd_j, map_B_to_C, &C_diag_size, &C_offd_size, num_rownnz_A, num_rows_diag_A, num_cols_offd_A, allsquare, num_cols_diag_B, num_cols_offd_B, num_cols_offd_C); /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ last_col_diag_B = first_col_diag_B + (HYPRE_BigInt)num_cols_diag_B - 1; C_diag_data = hypre_CTAlloc(HYPRE_Complex, C_diag_size, memory_location_C); C_diag_j = hypre_CTAlloc(HYPRE_Int, C_diag_size, memory_location_C); if (C_offd_size) { C_offd_data = hypre_CTAlloc(HYPRE_Complex, C_offd_size, memory_location_C); C_offd_j = hypre_CTAlloc(HYPRE_Int, C_offd_size, memory_location_C); } /*----------------------------------------------------------------------- * Second Pass: Fill in C_diag_data and C_diag_j. * Second Pass: Fill in C_offd_data and C_offd_j. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne, size, rest, ii; HYPRE_Int i1, ii1, i2, i3, jj2, jj3; HYPRE_Int jj_row_begin_diag, jj_count_diag; HYPRE_Int jj_row_begin_offd, jj_count_offd; HYPRE_Int num_threads; HYPRE_Complex a_entry; /*, a_b_product;*/ num_threads = hypre_NumActiveThreads(); size = num_rownnz_A/num_threads; rest = num_rownnz_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = C_diag_i[rownnz_A ? rownnz_A[ns] : ns]; jj_count_offd = C_offd_i[rownnz_A ? rownnz_A[ns] : ns]; if (num_cols_diag_B || num_cols_offd_C) { B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B + num_cols_offd_C, HYPRE_MEMORY_HOST); for (i1 = 0; i1 < num_cols_diag_B + num_cols_offd_C; i1++) { B_marker[i1] = -1; } } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (i1 = ns; i1 < ne; i1++) { jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if (rownnz_A) { ii1 = rownnz_A[i1]; } else { ii1 = i1; /*-------------------------------------------------------------------- * Create diagonal entry, C_{i1,i1} *--------------------------------------------------------------------*/ if (allsquare) { B_marker[i1] = jj_count_diag; C_diag_data[jj_count_diag] = zero; C_diag_j[jj_count_diag] = i1; jj_count_diag++; } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[ii1]; jj2 < A_offd_i[ii1+1]; jj2++) { i2 = A_offd_j[jj2]; a_entry = A_offd_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_ext_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else { C_offd_data[B_marker[i3]] += a_entry*B_ext_offd_data[jj3]; } } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_ext_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else { C_diag_data[B_marker[i3]] += a_entry*B_ext_diag_data[jj3]; } } } } /*----------------------------------------------------------------- * Loop over entries in row ii1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[ii1]; jj2 < A_diag_i[ii1+1]; jj2++) { i2 = A_diag_j[jj2]; a_entry = A_diag_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else { C_diag_data[B_marker[i3]] += a_entry*B_diag_data[jj3]; } } if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else { C_offd_data[B_marker[i3]] += a_entry*B_offd_data[jj3]; } } } } } hypre_TFree(B_marker, HYPRE_MEMORY_HOST); } /*end parallel region */ C = hypre_ParCSRMatrixCreate(comm, nrows_A, ncols_B, row_starts_A, col_starts_B, num_cols_offd_C, C_diag_size, C_offd_size); /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C, 0); hypre_ParCSRMatrixSetColStartsOwner(C, 0); C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrixData(C_diag) = C_diag_data; hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixJ(C_diag) = C_diag_j; hypre_CSRMatrixSetRownnz(C_diag); C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_ParCSRMatrixOffd(C) = C_offd; if (num_cols_offd_C) { hypre_CSRMatrixData(C_offd) = C_offd_data; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; } hypre_CSRMatrixSetRownnz(C_offd); hypre_CSRMatrixMemoryLocation(C_diag) = memory_location_C; hypre_CSRMatrixMemoryLocation(C_offd) = memory_location_C; /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ hypre_TFree(B_ext_diag_i, HYPRE_MEMORY_HOST); if (B_ext_diag_size) { hypre_TFree(B_ext_diag_j, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_diag_data, HYPRE_MEMORY_HOST); } hypre_TFree(B_ext_offd_i, HYPRE_MEMORY_HOST); if (B_ext_offd_size) { hypre_TFree(B_ext_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_offd_data, HYPRE_MEMORY_HOST); } if (num_cols_offd_B) { hypre_TFree(map_B_to_C, HYPRE_MEMORY_HOST); } hypre_TFree(rownnz_A, HYPRE_MEMORY_HOST); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] += hypre_MPI_Wtime(); #endif return C; } /* The following function was formerly part of hypre_ParCSRMatrixExtractBExt but the code was removed so it can be used for a corresponding function for Boolean matrices JSP: to allow communication overlapping, it returns comm_handle_idx and comm_handle_data. Before accessing B, they should be destroyed (including send_data contained in the comm_handle). */ void hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( HYPRE_Int ** pB_ext_i, HYPRE_BigInt ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_BigInt ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_BigInt first_col_diag, HYPRE_BigInt * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_BigInt * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, /* 1 if only coarse points are needed */ HYPRE_Int skip_same_sign /* 1 if only points that have the same sign are needed */ // extended based long range interpolation: skip_fine = 1, skip_same_sign = 0 for S matrix, skip_fine = 1, skip_same_sign = 1 for A matrix // other interpolation: skip_fine = 0, skip_same_sign = 0 ) { hypre_ParCSRCommHandle *comm_handle, *row_map_comm_handle = NULL; hypre_ParCSRCommPkg *tmp_comm_pkg; HYPRE_Int *B_int_i; HYPRE_BigInt *B_int_j; HYPRE_Int *B_ext_i; HYPRE_BigInt * B_ext_j; HYPRE_Complex * B_ext_data; HYPRE_Complex * B_int_data; HYPRE_BigInt * B_int_row_map; HYPRE_BigInt * B_ext_row_map; HYPRE_Int num_procs, my_id; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i, j, k; HYPRE_Int start_index; /*HYPRE_Int jrow;*/ HYPRE_Int num_rows_B_ext; HYPRE_Int *prefix_sum_workspace; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); HYPRE_BigInt first_row_index = row_starts[0]; num_rows_B_ext = recv_vec_starts[num_recvs]; if ( num_rows_B_ext < 0 ) { /* no B_ext, no communication */ *pB_ext_i = NULL; *pB_ext_j = NULL; if ( data ) *pB_ext_data = NULL; if ( find_row_map ) *pB_ext_row_map = NULL; *num_nonzeros = 0; return; }; B_int_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends]+1, HYPRE_MEMORY_HOST); B_ext_i = hypre_CTAlloc(HYPRE_Int, num_rows_B_ext+1, HYPRE_MEMORY_HOST); *pB_ext_i = B_ext_i; if ( find_row_map ) { B_int_row_map = hypre_CTAlloc( HYPRE_BigInt, send_map_starts[num_sends]+1 , HYPRE_MEMORY_HOST); B_ext_row_map = hypre_CTAlloc( HYPRE_BigInt, num_rows_B_ext+1 , HYPRE_MEMORY_HOST); *pB_ext_row_map = B_ext_row_map; }; /*-------------------------------------------------------------------------- * generate B_int_i through adding number of row-elements of offd and diag * for corresponding rows. B_int_i[j+1] contains the number of elements of * a row j (which is determined through send_map_elmts) *--------------------------------------------------------------------------*/ jdata_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); jdata_send_map_starts[0] = B_int_i[0] = 0; /*HYPRE_Int prefix_sum_workspace[(hypre_NumThreads() + 1)*num_sends];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, (hypre_NumThreads() + 1)*num_sends, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,k) #endif { /*HYPRE_Int counts[num_sends];*/ HYPRE_Int *counts; counts = hypre_TAlloc(HYPRE_Int, num_sends, HYPRE_MEMORY_HOST); for (i=0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = 0; if (skip_fine && skip_same_sign) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (offd_data[k] < 0) len++; } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (offd_data[k] > 0) len++; } } B_int_i[j + 1] = len; count += len; } } else if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) len++; } B_int_i[j + 1] = len; count += len; } } else { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = diag_i[jrow + 1] - diag_i[jrow]; len += offd_i[jrow + 1] - offd_i[jrow]; B_int_i[j + 1] = len; count += len; } } if (find_row_map) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; B_int_row_map[j] = (HYPRE_BigInt)jrow + first_row_index; } } counts[i] = count; } hypre_prefix_sum_multiple(counts, jdata_send_map_starts + 1, num_sends, prefix_sum_workspace); #ifdef HYPRE_USING_OPENMP #pragma omp master #endif { for (i = 1; i < num_sends; i++) { jdata_send_map_starts[i + 1] += jdata_send_map_starts[i]; } /*-------------------------------------------------------------------------- * initialize communication *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg, &B_int_i[1],&(B_ext_i[1]) ); if ( find_row_map ) { /* scatter/gather B_int row numbers to form array of B_ext row numbers */ row_map_comm_handle = hypre_ParCSRCommHandleCreate (21,comm_pkg, B_int_row_map, B_ext_row_map ); } B_int_j = hypre_TAlloc(HYPRE_BigInt, jdata_send_map_starts[num_sends], HYPRE_MEMORY_HOST); if (data) B_int_data = hypre_TAlloc(HYPRE_Complex, jdata_send_map_starts[num_sends], HYPRE_MEMORY_HOST); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = 0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = counts[i] + jdata_send_map_starts[i]; if (data) { if (skip_same_sign && skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; /*HYPRE_Int count_begin = count;*/ if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; if (offd_data[k] < 0) { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; if (offd_data[k] > 0) { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } for (k = offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; B_int_data[count] = offd_data[k]; count++; } } } } // data else { if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k] + first_col_diag; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; count++; } for (k = offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } // !data } /* for each send target */ hypre_TFree(counts, HYPRE_MEMORY_HOST); } /* omp parallel. JSP: this takes most of time in this function */ hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST); tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = jdata_send_map_starts; hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; /*-------------------------------------------------------------------------- * after communication exchange B_ext_i[j+1] contains the number of elements * of a row j ! * evaluate B_ext_i and compute *num_nonzeros for B_ext *--------------------------------------------------------------------------*/ for (i = 0; i < num_recvs; i++) { for (j = recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) { B_ext_i[j+1] += B_ext_i[j]; } } *num_nonzeros = B_ext_i[num_rows_B_ext]; *pB_ext_j = hypre_TAlloc(HYPRE_BigInt, *num_nonzeros, HYPRE_MEMORY_HOST); B_ext_j = *pB_ext_j; if (data) { *pB_ext_data = hypre_TAlloc(HYPRE_Complex, *num_nonzeros, HYPRE_MEMORY_HOST); B_ext_data = *pB_ext_data; } for (i = 0; i < num_recvs; i++) { start_index = B_ext_i[recv_vec_starts[i]]; *num_nonzeros = B_ext_i[recv_vec_starts[i+1]]-start_index; jdata_recv_vec_starts[i+1] = B_ext_i[recv_vec_starts[i+1]]; } hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = jdata_recv_vec_starts; *comm_handle_idx = hypre_ParCSRCommHandleCreate(21,tmp_comm_pkg,B_int_j,B_ext_j); if (data) { *comm_handle_data = hypre_ParCSRCommHandleCreate(1,tmp_comm_pkg,B_int_data, B_ext_data); } if (row_map_comm_handle) { hypre_ParCSRCommHandleDestroy(row_map_comm_handle); row_map_comm_handle = NULL; } hypre_TFree(jdata_send_map_starts, HYPRE_MEMORY_HOST); hypre_TFree(jdata_recv_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_comm_pkg, HYPRE_MEMORY_HOST); hypre_TFree(B_int_i, HYPRE_MEMORY_HOST); if ( find_row_map ) hypre_TFree(B_int_row_map, HYPRE_MEMORY_HOST); /* end generic part */ } void hypre_ParCSRMatrixExtractBExt_Arrays( HYPRE_Int ** pB_ext_i, HYPRE_BigInt ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_BigInt ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_BigInt first_col_diag, HYPRE_BigInt * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_BigInt * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data ) { hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( pB_ext_i, pB_ext_j, pB_ext_data, pB_ext_row_map, num_nonzeros, data, find_row_map, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx, HYPRE_MEMORY_HOST); if (data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data, HYPRE_MEMORY_HOST); } } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixExtractBExt : extracts rows from B which are located on * other processors and needed for multiplication with A locally. The rows * are returned as CSRMatrix. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt_Overlap( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, HYPRE_Int skip_same_sign ) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); HYPRE_BigInt first_col_diag = hypre_ParCSRMatrixFirstColDiag(B); /*HYPRE_Int first_row_index = hypre_ParCSRMatrixFirstRowIndex(B);*/ HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(B); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_recvs; HYPRE_Int *recv_vec_starts; HYPRE_Int num_sends; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(B); HYPRE_Int *diag_i = hypre_CSRMatrixI(diag); HYPRE_Int *diag_j = hypre_CSRMatrixJ(diag); HYPRE_Real *diag_data = hypre_CSRMatrixData(diag); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *offd_i = hypre_CSRMatrixI(offd); HYPRE_Int *offd_j = hypre_CSRMatrixJ(offd); HYPRE_Real *offd_data = hypre_CSRMatrixData(offd); HYPRE_Int num_cols_B, num_nonzeros; HYPRE_Int num_rows_B_ext; hypre_CSRMatrix *B_ext; HYPRE_Int *B_ext_i; HYPRE_BigInt *B_ext_j; HYPRE_Complex *B_ext_data; HYPRE_BigInt *idummy; /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } comm_pkg = hypre_ParCSRMatrixCommPkg(A); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); num_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); num_rows_B_ext = recv_vec_starts[num_recvs]; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap ( &B_ext_i, &B_ext_j, &B_ext_data, &idummy, &num_nonzeros, data, 0, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, B->row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, comm_handle_idx, comm_handle_data, CF_marker, CF_marker_offd, skip_fine, skip_same_sign ); B_ext = hypre_CSRMatrixCreate(num_rows_B_ext,num_cols_B,num_nonzeros); hypre_CSRMatrixMemoryLocation(B_ext) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(B_ext) = B_ext_i; hypre_CSRMatrixBigJ(B_ext) = B_ext_j; if (data) hypre_CSRMatrixData(B_ext) = B_ext_data; return B_ext; } hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int want_data ) { #if 0 hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_CSRMatrix *B_ext = hypre_ParCSRMatrixExtractBExt_Overlap(B, A, want_data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx, HYPRE_MEMORY_HOST); if (want_data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data, HYPRE_MEMORY_HOST); } #else hypre_assert( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B)) == hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(B)) ); hypre_CSRMatrix *B_ext; void *request; if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } hypre_ParcsrGetExternalRowsInit(B, hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)), hypre_ParCSRMatrixColMapOffd(A), hypre_ParCSRMatrixCommPkg(A), want_data, &request); B_ext = hypre_ParcsrGetExternalRowsWait(request); #endif return B_ext; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixTranspose *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixTransposeHost( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { hypre_ParCSRCommHandle *comm_handle; MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int num_cols = hypre_ParCSRMatrixNumCols(A); HYPRE_BigInt first_row_index = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_BigInt *col_starts = hypre_ParCSRMatrixColStarts(A); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, num_recvs, num_cols_offd_AT; HYPRE_Int i, j, k, index, counter, j_row; HYPRE_BigInt value; hypre_ParCSRMatrix *AT; hypre_CSRMatrix *AT_diag; hypre_CSRMatrix *AT_offd; hypre_CSRMatrix *AT_tmp; HYPRE_BigInt first_row_index_AT, first_col_diag_AT; HYPRE_Int local_num_rows_AT, local_num_cols_AT; HYPRE_Int *AT_tmp_i; HYPRE_Int *AT_tmp_j; HYPRE_BigInt *AT_big_j = NULL; HYPRE_Complex *AT_tmp_data; HYPRE_Int *AT_buf_i; HYPRE_BigInt *AT_buf_j; HYPRE_Complex *AT_buf_data; HYPRE_Int *AT_offd_i; HYPRE_Int *AT_offd_j; HYPRE_Complex *AT_offd_data; HYPRE_BigInt *col_map_offd_AT; HYPRE_BigInt *row_starts_AT; HYPRE_BigInt *col_starts_AT; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs; HYPRE_Int *send_procs; HYPRE_Int *recv_vec_starts; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int *tmp_recv_vec_starts; HYPRE_Int *tmp_send_map_starts; hypre_ParCSRCommPkg *tmp_comm_pkg; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_cols_offd_AT = 0; counter = 0; AT_offd_j = NULL; AT_offd_data = NULL; col_map_offd_AT = NULL; HYPRE_MemoryLocation memory_location = hypre_ParCSRMatrixMemoryLocation(A); /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (num_procs > 1) { hypre_CSRMatrixTranspose (A_offd, &AT_tmp, data); AT_tmp_i = hypre_CSRMatrixI(AT_tmp); AT_tmp_j = hypre_CSRMatrixJ(AT_tmp); if (data) { AT_tmp_data = hypre_CSRMatrixData(AT_tmp); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); AT_buf_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends], HYPRE_MEMORY_HOST); if (AT_tmp_i[num_cols_offd]) { AT_big_j = hypre_CTAlloc(HYPRE_BigInt, AT_tmp_i[num_cols_offd], HYPRE_MEMORY_HOST); } for (i = 0; i < AT_tmp_i[num_cols_offd]; i++) { //AT_tmp_j[i] += first_row_index; AT_big_j[i] = (HYPRE_BigInt)AT_tmp_j[i]+first_row_index; } for (i = 0; i < num_cols_offd; i++) { AT_tmp_i[i] = AT_tmp_i[i+1]-AT_tmp_i[i]; } comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg, AT_tmp_i, AT_buf_i); } hypre_CSRMatrixTranspose(A_diag, &AT_diag, data); AT_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols+1, memory_location); if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; tmp_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); tmp_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); tmp_send_map_starts[0] = send_map_starts[0]; for (i = 0; i < num_sends; i++) { tmp_send_map_starts[i+1] = tmp_send_map_starts[i]; for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++) { tmp_send_map_starts[i+1] += AT_buf_i[j]; AT_offd_i[send_map_elmts[j]+1] += AT_buf_i[j]; } } for (i = 0; i < num_cols; i++) { AT_offd_i[i+1] += AT_offd_i[i]; } tmp_recv_vec_starts[0] = recv_vec_starts[0]; for (i = 0; i < num_recvs; i++) { tmp_recv_vec_starts[i+1] = tmp_recv_vec_starts[i]; for (j = recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) { tmp_recv_vec_starts[i+1] += AT_tmp_i[j]; } } tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = recv_procs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = send_procs; hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = tmp_recv_vec_starts; hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = tmp_send_map_starts; AT_buf_j = hypre_CTAlloc(HYPRE_BigInt, tmp_send_map_starts[num_sends], HYPRE_MEMORY_HOST); comm_handle = hypre_ParCSRCommHandleCreate(22, tmp_comm_pkg, AT_big_j, AT_buf_j); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; hypre_TFree(AT_big_j, HYPRE_MEMORY_HOST); if (data) { AT_buf_data = hypre_CTAlloc(HYPRE_Complex, tmp_send_map_starts[num_sends], HYPRE_MEMORY_HOST); comm_handle = hypre_ParCSRCommHandleCreate(2,tmp_comm_pkg,AT_tmp_data, AT_buf_data); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } hypre_TFree(tmp_recv_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_send_map_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_comm_pkg, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(AT_tmp); if (AT_offd_i[num_cols]) { AT_offd_j = hypre_CTAlloc(HYPRE_Int, AT_offd_i[num_cols], memory_location); AT_big_j = hypre_CTAlloc(HYPRE_BigInt, AT_offd_i[num_cols], HYPRE_MEMORY_HOST); if (data) { AT_offd_data = hypre_CTAlloc(HYPRE_Complex, AT_offd_i[num_cols], memory_location); } } else { AT_offd_j = NULL; AT_offd_data = NULL; } counter = 0; for (i = 0; i < num_sends; i++) { for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++) { j_row = send_map_elmts[j]; index = AT_offd_i[j_row]; for (k = 0; k < AT_buf_i[j]; k++) { if (data) { AT_offd_data[index] = AT_buf_data[counter]; } AT_big_j[index++] = AT_buf_j[counter++]; } AT_offd_i[j_row] = index; } } for (i = num_cols; i > 0; i--) { AT_offd_i[i] = AT_offd_i[i-1]; } AT_offd_i[0] = 0; if (counter) { hypre_BigQsort0(AT_buf_j,0,counter-1); num_cols_offd_AT = 1; value = AT_buf_j[0]; for (i = 1; i < counter; i++) { if (value < AT_buf_j[i]) { AT_buf_j[num_cols_offd_AT++] = AT_buf_j[i]; value = AT_buf_j[i]; } } } if (num_cols_offd_AT) { col_map_offd_AT = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST); } else { col_map_offd_AT = NULL; } for (i = 0; i < num_cols_offd_AT; i++) { col_map_offd_AT[i] = AT_buf_j[i]; } hypre_TFree(AT_buf_i, HYPRE_MEMORY_HOST); hypre_TFree(AT_buf_j, HYPRE_MEMORY_HOST); if (data) { hypre_TFree(AT_buf_data, HYPRE_MEMORY_HOST); } for (i = 0; i < counter; i++) { AT_offd_j[i] = hypre_BigBinarySearch(col_map_offd_AT,AT_big_j[i], num_cols_offd_AT); } hypre_TFree(AT_big_j, HYPRE_MEMORY_HOST); } AT_offd = hypre_CSRMatrixCreate(num_cols, num_cols_offd_AT, counter); hypre_CSRMatrixMemoryLocation(AT_offd) = memory_location; hypre_CSRMatrixI(AT_offd) = AT_offd_i; hypre_CSRMatrixJ(AT_offd) = AT_offd_j; hypre_CSRMatrixData(AT_offd) = AT_offd_data; row_starts_AT = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); for (i = 0; i < 2; i++) { row_starts_AT[i] = col_starts[i]; } if (row_starts != col_starts) { col_starts_AT = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); for (i = 0; i < 2; i++) { col_starts_AT[i] = row_starts[i]; } } else { col_starts_AT = row_starts_AT; } first_row_index_AT = row_starts_AT[0]; first_col_diag_AT = col_starts_AT[0]; local_num_rows_AT = (HYPRE_Int)(row_starts_AT[1]-first_row_index_AT ); local_num_cols_AT = (HYPRE_Int)(col_starts_AT[1]-first_col_diag_AT); AT = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixComm(AT) = comm; hypre_ParCSRMatrixDiag(AT) = AT_diag; hypre_ParCSRMatrixOffd(AT) = AT_offd; hypre_ParCSRMatrixGlobalNumRows(AT) = hypre_ParCSRMatrixGlobalNumCols(A); hypre_ParCSRMatrixGlobalNumCols(AT) = hypre_ParCSRMatrixGlobalNumRows(A); hypre_ParCSRMatrixRowStarts(AT) = row_starts_AT; hypre_ParCSRMatrixColStarts(AT) = col_starts_AT; hypre_ParCSRMatrixColMapOffd(AT) = col_map_offd_AT; hypre_ParCSRMatrixFirstRowIndex(AT) = first_row_index_AT; hypre_ParCSRMatrixFirstColDiag(AT) = first_col_diag_AT; hypre_ParCSRMatrixLastRowIndex(AT) = first_row_index_AT + local_num_rows_AT - 1; hypre_ParCSRMatrixLastColDiag(AT) = first_col_diag_AT + local_num_cols_AT - 1; hypre_ParCSRMatrixOwnsData(AT) = 1; hypre_ParCSRMatrixOwnsRowStarts(AT) = 1; hypre_ParCSRMatrixOwnsColStarts(AT) = 1; if (row_starts_AT == col_starts_AT) { hypre_ParCSRMatrixOwnsColStarts(AT) = 0; } hypre_ParCSRMatrixCommPkg(AT) = NULL; hypre_ParCSRMatrixCommPkgT(AT) = NULL; hypre_ParCSRMatrixRowindices(AT) = NULL; hypre_ParCSRMatrixRowvalues(AT) = NULL; hypre_ParCSRMatrixGetrowactive(AT) = 0; hypre_ParCSRMatrixOwnsAssumedPartition(AT) = 1; *AT_ptr = AT; return ierr; } HYPRE_Int hypre_ParCSRMatrixTranspose( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ParCSRMatrixTranspose"); #endif #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { hypre_ParCSRMatrixTransposeDevice(A, AT_ptr, data); } else #endif { hypre_ParCSRMatrixTransposeHost(A, AT_ptr, data); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return hypre_error_flag; } /* ----------------------------------------------------------------------------- * generate a parallel spanning tree (for Maxwell Equation) * G_csr is the node to edge connectivity matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixGenSpanningTree( hypre_ParCSRMatrix *G_csr, HYPRE_Int **indices, HYPRE_Int G_type ) { HYPRE_BigInt nrows_G, ncols_G; HYPRE_Int *G_diag_i, *G_diag_j, *GT_diag_mat, i, j, k, edge; HYPRE_Int *nodes_marked, *edges_marked, *queue, queue_tail, queue_head, node; HYPRE_Int mypid, nprocs, n_children, *children, nsends, *send_procs, *recv_cnts; HYPRE_Int nrecvs, *recv_procs, n_proc_array, *proc_array, *pgraph_i, *pgraph_j; HYPRE_Int parent, proc, proc2, node2, found, *t_indices, tree_size, *T_diag_i; HYPRE_Int *T_diag_j, *counts, offset; MPI_Comm comm; hypre_ParCSRCommPkg *comm_pkg; hypre_CSRMatrix *G_diag; /* fetch G matrix (G_type = 0 ==> node to edge) */ if (G_type == 0) { nrows_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); G_diag_i = hypre_CSRMatrixI(G_diag); G_diag_j = hypre_CSRMatrixJ(G_diag); } else { nrows_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); T_diag_i = hypre_CSRMatrixI(G_diag); T_diag_j = hypre_CSRMatrixJ(G_diag); counts = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_G; i++) counts[i] = 0; for (i = 0; i < T_diag_i[ncols_G]; i++) counts[T_diag_j[i]]++; G_diag_i = hypre_TAlloc(HYPRE_Int, (nrows_G+1) , HYPRE_MEMORY_HOST); G_diag_j = hypre_TAlloc(HYPRE_Int, T_diag_i[ncols_G] , HYPRE_MEMORY_HOST); G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; for (i = 0; i < ncols_G; i++) { for (j = T_diag_i[i]; j < T_diag_i[i+1]; j++) { k = T_diag_j[j]; offset = G_diag_i[k]++; G_diag_j[offset] = i; } } G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) { G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; } hypre_TFree(counts, HYPRE_MEMORY_HOST); } /* form G transpose in special form (2 nodes per edge max) */ GT_diag_mat = hypre_TAlloc(HYPRE_Int, 2 * ncols_G , HYPRE_MEMORY_HOST); for (i = 0; i < 2 * ncols_G; i++) GT_diag_mat[i] = -1; for (i = 0; i < nrows_G; i++) { for (j = G_diag_i[i]; j < G_diag_i[i+1]; j++) { edge = G_diag_j[j]; if (GT_diag_mat[edge*2] == -1) GT_diag_mat[edge*2] = i; else GT_diag_mat[edge*2+1] = i; } } /* BFS on the local matrix graph to find tree */ nodes_marked = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); edges_marked = hypre_TAlloc(HYPRE_Int, ncols_G , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_G; i++) nodes_marked[i] = 0; for (i = 0; i < ncols_G; i++) edges_marked[i] = 0; queue = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); queue_head = 0; queue_tail = 1; queue[0] = 0; nodes_marked[0] = 1; while ((queue_tail-queue_head) > 0) { node = queue[queue_tail-1]; queue_tail--; for (i = G_diag_i[node]; i < G_diag_i[node+1]; i++) { edge = G_diag_j[i]; if (edges_marked[edge] == 0) { if (GT_diag_mat[2*edge+1] != -1) { node2 = GT_diag_mat[2*edge]; if (node2 == node) node2 = GT_diag_mat[2*edge+1]; if (nodes_marked[node2] == 0) { nodes_marked[node2] = 1; edges_marked[edge] = 1; queue[queue_tail] = node2; queue_tail++; } } } } } hypre_TFree(nodes_marked, HYPRE_MEMORY_HOST); hypre_TFree(queue, HYPRE_MEMORY_HOST); hypre_TFree(GT_diag_mat, HYPRE_MEMORY_HOST); /* fetch the communication information from */ comm = hypre_ParCSRMatrixComm(G_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); if (nprocs == 1 && comm_pkg == NULL) { hypre_MatvecCommPkgCreate((hypre_ParCSRMatrix *) G_csr); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); } /* construct processor graph based on node-edge connection */ /* (local edges connected to neighbor processor nodes) */ n_children = 0; nrecvs = nsends = 0; if (nprocs > 1) { nsends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); nrecvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); proc_array = NULL; if ((nsends+nrecvs) > 0) { n_proc_array = 0; proc_array = hypre_TAlloc(HYPRE_Int, (nsends+nrecvs) , HYPRE_MEMORY_HOST); for (i = 0; i < nsends; i++) proc_array[i] = send_procs[i]; for (i = 0; i < nrecvs; i++) proc_array[nsends+i] = recv_procs[i]; hypre_qsort0(proc_array, 0, nsends+nrecvs-1); n_proc_array = 1; for (i = 1; i < nrecvs+nsends; i++) if (proc_array[i] != proc_array[n_proc_array]) proc_array[n_proc_array++] = proc_array[i]; } pgraph_i = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); recv_cnts = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&n_proc_array, 1, HYPRE_MPI_INT, recv_cnts, 1, HYPRE_MPI_INT, comm); pgraph_i[0] = 0; for (i = 1; i <= nprocs; i++) pgraph_i[i] = pgraph_i[i-1] + recv_cnts[i-1]; pgraph_j = hypre_TAlloc(HYPRE_Int, pgraph_i[nprocs] , HYPRE_MEMORY_HOST); hypre_MPI_Allgatherv(proc_array, n_proc_array, HYPRE_MPI_INT, pgraph_j, recv_cnts, pgraph_i, HYPRE_MPI_INT, comm); hypre_TFree(recv_cnts, HYPRE_MEMORY_HOST); /* BFS on the processor graph to determine parent and children */ nodes_marked = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); for (i = 0; i < nprocs; i++) nodes_marked[i] = -1; queue = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); queue_head = 0; queue_tail = 1; node = 0; queue[0] = node; while ((queue_tail-queue_head) > 0) { proc = queue[queue_tail-1]; queue_tail--; for (i = pgraph_i[proc]; i < pgraph_i[proc+1]; i++) { proc2 = pgraph_j[i]; if (nodes_marked[proc2] < 0) { nodes_marked[proc2] = proc; queue[queue_tail] = proc2; queue_tail++; } } } parent = nodes_marked[mypid]; n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) n_children++; if (n_children == 0) {n_children = 0; children = NULL;} else { children = hypre_TAlloc(HYPRE_Int, n_children , HYPRE_MEMORY_HOST); n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) children[n_children++] = i; } hypre_TFree(nodes_marked, HYPRE_MEMORY_HOST); hypre_TFree(queue, HYPRE_MEMORY_HOST); hypre_TFree(pgraph_i, HYPRE_MEMORY_HOST); hypre_TFree(pgraph_j, HYPRE_MEMORY_HOST); } /* first, connection with my parent : if the edge in my parent * * is incident to one of my nodes, then my parent will mark it */ found = 0; for (i = 0; i < nrecvs; i++) { proc = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); if (proc == parent) { found = 1; break; } } /* but if all the edges connected to my parent are on my side, * * then I will just pick one of them as tree edge */ if (found == 0) { for (i = 0; i < nsends; i++) { proc = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == parent) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } /* next, if my processor has an edge incident on one node in my * * child, put this edge on the tree. But if there is no such * * edge, then I will assume my child will pick up an edge */ for (j = 0; j < n_children; j++) { proc = children[j]; for (i = 0; i < nsends; i++) { proc2 = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == proc2) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } if (n_children > 0) { hypre_TFree(children, HYPRE_MEMORY_HOST); } /* count the size of the tree */ tree_size = 0; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) tree_size++; t_indices = hypre_TAlloc(HYPRE_Int, (tree_size+1) , HYPRE_MEMORY_HOST); t_indices[0] = tree_size; tree_size = 1; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) t_indices[tree_size++] = i; (*indices) = t_indices; hypre_TFree(edges_marked, HYPRE_MEMORY_HOST); if (G_type != 0) { hypre_TFree(G_diag_i, HYPRE_MEMORY_HOST); hypre_TFree(G_diag_j, HYPRE_MEMORY_HOST); } } /* ----------------------------------------------------------------------------- * extract submatrices based on given indices * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nrows_A, nindices, *indices, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *exp_indices; HYPRE_BigInt *itmp_array; HYPRE_Int nnz11, nnz12, nnz21, nnz22, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int nrows, nnz; HYPRE_BigInt global_nrows, global_ncols, *row_starts, *col_starts; HYPRE_Int *diag_i, *diag_j, row, *offd_i; HYPRE_Complex *A_diag_a, *diag_a; hypre_ParCSRMatrix *A11_csr, *A12_csr, *A21_csr, *A22_csr; hypre_CSRMatrix *A_diag, *diag, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = (HYPRE_Int) hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); if (nprocs > 1) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: cannot handle nprocs > 1 yet.\n"); exit(1); } /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); proc_offsets2 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) { proc_offsets2[i] = itmp_array[i] - proc_offsets1[i]; } /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = hypre_TAlloc(HYPRE_Int, nrows_A , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz12 = nnz21 = nnz22 = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; else nnz12++; } } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz21++; else nnz22++; } } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz11; /* This case is not yet implemented! */ global_nrows = 0; global_ncols = 0; row_starts = NULL; col_starts = NULL; A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A12 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz12; global_nrows = (HYPRE_BigInt)proc_offsets1[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; } A12_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } if (nnz > nnz_diag) { hypre_assert(0); hypre_error(HYPRE_ERROR_GENERIC); } diag = hypre_ParCSRMatrixDiag(A12_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A12_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A21 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz21; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets1[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A22 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz22; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; } A22_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A22_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A22_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A12_csr; (*submatrices)[2] = A21_csr; (*submatrices)[3] = A22_csr; hypre_TFree(proc_offsets1, HYPRE_MEMORY_HOST); hypre_TFree(proc_offsets2, HYPRE_MEMORY_HOST); hypre_TFree(exp_indices, HYPRE_MEMORY_HOST); } /* ----------------------------------------------------------------------------- * extract submatrices of a rectangular matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractRowSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nrows_A, nindices, *indices, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *exp_indices; HYPRE_Int nnz11, nnz21, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int *A_offd_i, *A_offd_j; HYPRE_Int nrows, nnz; HYPRE_BigInt global_nrows, global_ncols, *row_starts, *col_starts, *itmp_array; HYPRE_Int *diag_i, *diag_j, row, *offd_i, *offd_j, nnz11_offd, nnz21_offd; HYPRE_Complex *A_diag_a, *diag_a, *offd_a; hypre_ParCSRMatrix *A11_csr, *A21_csr; hypre_CSRMatrix *A_diag, *diag, *A_offd, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = (HYPRE_Int)hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); A_offd = hypre_ParCSRMatrixOffd(A_csr); A_offd_i = hypre_CSRMatrixI(A_offd); A_offd_j = hypre_CSRMatrixJ(A_offd); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); proc_offsets2 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) proc_offsets2[i] = (HYPRE_Int)(itmp_array[i] - proc_offsets1[i]); /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = hypre_TAlloc(HYPRE_Int, nrows_A , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractRowSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz21 = nnz11_offd = nnz21_offd = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; } nnz11_offd += A_offd_i[i+1] - A_offd_i[i]; } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) nnz21++; } nnz21_offd += A_offd_i[i+1] - A_offd_i[i]; } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_diag = nnz11; nnz_offd = nnz11_offd; global_nrows = (HYPRE_BigInt)proc_offsets1[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; col_starts[i] = itmp_array[i]; } A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd, HYPRE_MEMORY_HOST); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd, HYPRE_MEMORY_HOST); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * create A21 matrix * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_offd = nnz21_offd; nnz_diag = nnz21; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = itmp_array[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { diag_j[nnz] = A_diag_j[j]; diag_a[nnz++] = A_diag_a[j]; } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd, HYPRE_MEMORY_HOST); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd, HYPRE_MEMORY_HOST); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A21_csr; hypre_TFree(proc_offsets1, HYPRE_MEMORY_HOST); hypre_TFree(proc_offsets2, HYPRE_MEMORY_HOST); hypre_TFree(exp_indices, HYPRE_MEMORY_HOST); } /* ----------------------------------------------------------------------------- * return the sum of all local elements of the matrix * ----------------------------------------------------------------------------- */ HYPRE_Complex hypre_ParCSRMatrixLocalSumElts( hypre_ParCSRMatrix * A ) { hypre_CSRMatrix * A_diag = hypre_ParCSRMatrixDiag( A ); hypre_CSRMatrix * A_offd = hypre_ParCSRMatrixOffd( A ); return hypre_CSRMatrixSumElts(A_diag) + hypre_CSRMatrixSumElts(A_offd); } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatAminvDB * computes C = (A - inv(D)B) where D is a diagonal matrix * Note: Data structure of A is expected to be a subset of data structure of B! *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixAminvDB( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B, HYPRE_Complex *d, hypre_ParCSRMatrix **C_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_ParCSRMatrix *C = NULL; HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_ParCSRCommPkg *comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_Int num_sends_B, num_recvs_B; HYPRE_Int i, j, cnt; HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_offd = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_offd_i = NULL; HYPRE_Int *C_offd_j = NULL; HYPRE_Complex *C_offd_data = NULL; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs_B; HYPRE_Int *send_procs_B; HYPRE_Int *recv_vec_starts_B; HYPRE_Int *send_map_starts_B; HYPRE_Int *send_map_elmts_B; hypre_ParCSRCommPkg *comm_pkg_C; HYPRE_Int *recv_procs_C; HYPRE_Int *send_procs_C; HYPRE_Int *recv_vec_starts_C; HYPRE_Int *send_map_starts_C; HYPRE_Int *send_map_elmts_C; HYPRE_Int *map_to_B; /*HYPRE_Int *C_diag_array; HYPRE_Int *C_offd_array;*/ HYPRE_Complex *D_tmp; HYPRE_Int size, rest, num_threads, ii; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_threads = hypre_NumThreads(); /*C_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads); C_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);*/ /*--------------------------------------------------------------------- * If there exists no CommPkg for B, a CommPkg is generated *--------------------------------------------------------------------*/ if (!comm_pkg_B) { hypre_MatvecCommPkgCreate(B); comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); } C = hypre_ParCSRMatrixClone(B, 0); /*hypre_ParCSRMatrixInitialize(C);*/ C_diag = hypre_ParCSRMatrixDiag(C); C_diag_i = hypre_CSRMatrixI(C_diag); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); C_offd = hypre_ParCSRMatrixOffd(C); C_offd_i = hypre_CSRMatrixI(C_offd); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); size = num_rows/num_threads; rest = num_rows - size*num_threads; D_tmp = hypre_CTAlloc(HYPRE_Complex, num_rows, HYPRE_MEMORY_HOST); if (num_cols_offd_A) { map_to_B = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A, HYPRE_MEMORY_HOST); cnt = 0; for (i=0; i < num_cols_offd_A; i++) { while (col_map_offd_B[cnt] < col_map_offd_A[i]) { cnt++; } map_to_B[i] = cnt; cnt++; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii, i, j) #endif for (ii=0; ii < num_threads; ii++) { HYPRE_Int *A_marker = NULL; HYPRE_Int ns, ne, A_col, num_cols, nmax; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } nmax = hypre_max(num_rows, num_cols_offd_B); A_marker = hypre_CTAlloc(HYPRE_Int, nmax, HYPRE_MEMORY_HOST); for (i=0; i < num_rows; i++) { A_marker[i] = -1; } for (i = ns; i < ne; i++) { D_tmp[i] = 1.0/d[i]; } num_cols = C_diag_i[ns]; for (i = ns; i < ne; i++) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { A_col = A_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = A_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] += A_diag_data[j]; } } for (j = B_diag_i[i]; j < B_diag_i[i+1]; j++) { A_col = B_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = -D_tmp[i]*B_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] -= D_tmp[i]*B_diag_data[j]; } } } for (i = 0; i < num_cols_offd_B; i++) { A_marker[i] = -1; } num_cols = C_offd_i[ns]; for (i = ns; i < ne; i++) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { A_col = map_to_B[A_offd_j[j]]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = A_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] += A_offd_data[j]; } } for (j = B_offd_i[i]; j < B_offd_i[i+1]; j++) { A_col = B_offd_j[j]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = -D_tmp[i]*B_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] -= D_tmp[i]*B_offd_data[j]; } } } hypre_TFree(A_marker, HYPRE_MEMORY_HOST); } /* end parallel region */ /*for (i=0; i < num_cols_offd_B; i++) col_map_offd_C[i] = col_map_offd_B[i]; */ num_sends_B = hypre_ParCSRCommPkgNumSends(comm_pkg_B); num_recvs_B = hypre_ParCSRCommPkgNumRecvs(comm_pkg_B); recv_procs_B = hypre_ParCSRCommPkgRecvProcs(comm_pkg_B); recv_vec_starts_B = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_B); send_procs_B = hypre_ParCSRCommPkgSendProcs(comm_pkg_B); send_map_starts_B = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_B); send_map_elmts_B = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_B); recv_procs_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B, HYPRE_MEMORY_HOST); recv_vec_starts_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B+1, HYPRE_MEMORY_HOST); send_procs_C = hypre_CTAlloc(HYPRE_Int, num_sends_B, HYPRE_MEMORY_HOST); send_map_starts_C = hypre_CTAlloc(HYPRE_Int, num_sends_B+1, HYPRE_MEMORY_HOST); send_map_elmts_C = hypre_CTAlloc(HYPRE_Int, send_map_starts_B[num_sends_B], HYPRE_MEMORY_HOST); for (i=0; i < num_recvs_B; i++) recv_procs_C[i] = recv_procs_B[i]; for (i=0; i < num_recvs_B+1; i++) recv_vec_starts_C[i] = recv_vec_starts_B[i]; for (i=0; i < num_sends_B; i++) send_procs_C[i] = send_procs_B[i]; for (i=0; i < num_sends_B+1; i++) send_map_starts_C[i] = send_map_starts_B[i]; for (i=0; i < send_map_starts_B[num_sends_B]; i++) send_map_elmts_C[i] = send_map_elmts_B[i]; comm_pkg_C = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_C) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg_C) = num_recvs_B; hypre_ParCSRCommPkgRecvProcs(comm_pkg_C) = recv_procs_C; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_C) = recv_vec_starts_C; hypre_ParCSRCommPkgNumSends(comm_pkg_C) = num_sends_B; hypre_ParCSRCommPkgSendProcs(comm_pkg_C) = send_procs_C; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_C) = send_map_starts_C; hypre_ParCSRCommPkgSendMapElmts(comm_pkg_C) = send_map_elmts_C; hypre_ParCSRMatrixCommPkg(C) = comm_pkg_C; hypre_TFree(D_tmp, HYPRE_MEMORY_HOST); if (num_cols_offd_A) hypre_TFree(map_to_B, HYPRE_MEMORY_HOST); *C_ptr = C; return (hypre_error_flag); } /*-------------------------------------------------------------------------- * hypre_ParTMatmul: * * Multiplies two ParCSRMatrices transpose(A) and B and returns * the product in ParCSRMatrix C * * Note that C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix* hypre_ParTMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *AT_diag = NULL; hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *AT_offd = NULL; HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_BigInt first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_BigInt *col_starts_A = hypre_ParCSRMatrixColStarts(A); HYPRE_BigInt *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); hypre_ParCSRMatrix *C; HYPRE_BigInt *col_map_offd_C = NULL; HYPRE_Int *map_B_to_C; hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_tmp_diag = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_BigInt first_col_diag_C; HYPRE_BigInt last_col_diag_C; hypre_CSRMatrix *C_offd = NULL; hypre_CSRMatrix *C_tmp_offd = NULL; hypre_CSRMatrix *C_int = NULL; hypre_CSRMatrix *C_ext = NULL; HYPRE_Int *C_ext_i; HYPRE_BigInt *C_ext_j; HYPRE_Complex *C_ext_data; HYPRE_Int *C_ext_diag_i; HYPRE_Int *C_ext_diag_j; HYPRE_Complex *C_ext_diag_data; HYPRE_Int *C_ext_offd_i; HYPRE_Int *C_ext_offd_j; HYPRE_Complex *C_ext_offd_data; HYPRE_Int C_ext_size = 0; HYPRE_Int C_ext_diag_size = 0; HYPRE_Int C_ext_offd_size = 0; HYPRE_Int *C_tmp_diag_i; HYPRE_Int *C_tmp_diag_j; HYPRE_Complex *C_tmp_diag_data; HYPRE_Int *C_tmp_offd_i; HYPRE_Int *C_tmp_offd_j; HYPRE_Complex *C_tmp_offd_data; HYPRE_Complex *C_offd_data=NULL; HYPRE_Int *C_offd_i=NULL; HYPRE_Int *C_offd_j=NULL; HYPRE_BigInt *temp; HYPRE_Int *send_map_starts_A; HYPRE_Int *send_map_elmts_A; HYPRE_Int num_sends_A; HYPRE_Int num_cols_offd_C = 0; HYPRE_Int *P_marker; HYPRE_Int i, j; HYPRE_Int i1, j_indx; HYPRE_BigInt nrows_A, ncols_A; HYPRE_BigInt nrows_B, ncols_B; /*HYPRE_Int allsquare = 0;*/ HYPRE_Int cnt, cnt_offd, cnt_diag; HYPRE_BigInt value; HYPRE_Int num_procs, my_id; HYPRE_Int max_num_threads; HYPRE_Int *C_diag_array = NULL; HYPRE_Int *C_offd_array = NULL; HYPRE_BigInt first_row_index, first_col_diag; HYPRE_Int local_num_rows, local_num_cols; nrows_A = hypre_ParCSRMatrixGlobalNumRows(A); ncols_A = hypre_ParCSRMatrixGlobalNumCols(A); nrows_B = hypre_ParCSRMatrixGlobalNumRows(B); ncols_B = hypre_ParCSRMatrixGlobalNumCols(B); hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm, &my_id); max_num_threads = hypre_NumThreads(); if (nrows_A != nrows_B || num_rows_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } HYPRE_MemoryLocation memory_location_A = hypre_ParCSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_ParCSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); /*if (num_cols_diag_A == num_cols_diag_B) allsquare = 1;*/ hypre_CSRMatrixTranspose(A_diag, &AT_diag, 1); hypre_CSRMatrixTranspose(A_offd, &AT_offd, 1); C_tmp_diag = hypre_CSRMatrixMultiply(AT_diag, B_diag); C_ext_size = 0; if (num_procs > 1) { hypre_CSRMatrix *C_int_diag; hypre_CSRMatrix *C_int_offd; void *request; C_tmp_offd = hypre_CSRMatrixMultiply(AT_diag, B_offd); C_int_diag = hypre_CSRMatrixMultiply(AT_offd, B_diag); C_int_offd = hypre_CSRMatrixMultiply(AT_offd, B_offd); hypre_ParCSRMatrixDiag(B) = C_int_diag; hypre_ParCSRMatrixOffd(B) = C_int_offd; C_int = hypre_MergeDiagAndOffd(B); hypre_ParCSRMatrixDiag(B) = B_diag; hypre_ParCSRMatrixOffd(B) = B_offd; hypre_ExchangeExternalRowsInit(C_int, comm_pkg_A, &request); C_ext = hypre_ExchangeExternalRowsWait(request); C_ext_i = hypre_CSRMatrixI(C_ext); C_ext_j = hypre_CSRMatrixBigJ(C_ext); C_ext_data = hypre_CSRMatrixData(C_ext); C_ext_size = C_ext_i[hypre_CSRMatrixNumRows(C_ext)]; hypre_CSRMatrixDestroy(C_int); hypre_CSRMatrixDestroy(C_int_diag); hypre_CSRMatrixDestroy(C_int_offd); } else { C_tmp_offd = hypre_CSRMatrixCreate(num_cols_diag_A, 0, 0); hypre_CSRMatrixInitialize(C_tmp_offd); hypre_CSRMatrixNumRownnz(C_tmp_offd) = 0; } hypre_CSRMatrixDestroy(AT_diag); hypre_CSRMatrixDestroy(AT_offd); /*----------------------------------------------------------------------- * Add contents of C_ext to C_tmp_diag and C_tmp_offd * to obtain C_diag and C_offd *-----------------------------------------------------------------------*/ /* check for new nonzero columns in C_offd generated through C_ext */ first_col_diag_C = first_col_diag_B; last_col_diag_C = first_col_diag_B + (HYPRE_BigInt)num_cols_diag_B - 1; C_tmp_diag_i = hypre_CSRMatrixI(C_tmp_diag); if (C_ext_size || num_cols_offd_B) { HYPRE_Int C_ext_num_rows; num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); send_map_starts_A = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); send_map_elmts_A = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_A); C_ext_num_rows = send_map_starts_A[num_sends_A]; C_ext_diag_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1, HYPRE_MEMORY_HOST); C_ext_offd_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1, HYPRE_MEMORY_HOST); temp = hypre_CTAlloc(HYPRE_BigInt, C_ext_size+num_cols_offd_B, HYPRE_MEMORY_HOST); C_ext_diag_size = 0; C_ext_offd_size = 0; for (i = 0; i < C_ext_num_rows; i++) { for (j = C_ext_i[i]; j < C_ext_i[i+1]; j++) { if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) { temp[C_ext_offd_size++] = C_ext_j[j]; } else { C_ext_diag_size++; } } C_ext_diag_i[i+1] = C_ext_diag_size; C_ext_offd_i[i+1] = C_ext_offd_size; } cnt = C_ext_offd_size; for (i = 0; i < num_cols_offd_B; i++) { temp[cnt++] = col_map_offd_B[i]; } if (cnt) { hypre_BigQsort0(temp,0,cnt-1); value = temp[0]; num_cols_offd_C = 1; for (i = 1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) { col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i = 0; i < num_cols_offd_C; i++) { col_map_offd_C[i] = temp[i]; } hypre_TFree(temp, HYPRE_MEMORY_HOST); if (C_ext_diag_size) { C_ext_diag_j = hypre_CTAlloc(HYPRE_Int, C_ext_diag_size, HYPRE_MEMORY_HOST); C_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, C_ext_diag_size, HYPRE_MEMORY_HOST); } if (C_ext_offd_size) { C_ext_offd_j = hypre_CTAlloc(HYPRE_Int, C_ext_offd_size, HYPRE_MEMORY_HOST); C_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, C_ext_offd_size, HYPRE_MEMORY_HOST); } C_tmp_diag_j = hypre_CSRMatrixJ(C_tmp_diag); C_tmp_diag_data = hypre_CSRMatrixData(C_tmp_diag); C_tmp_offd_i = hypre_CSRMatrixI(C_tmp_offd); C_tmp_offd_j = hypre_CSRMatrixJ(C_tmp_offd); C_tmp_offd_data = hypre_CSRMatrixData(C_tmp_offd); cnt_offd = 0; cnt_diag = 0; for (i = 0; i < C_ext_num_rows; i++) { for (j = C_ext_i[i]; j < C_ext_i[i+1]; j++) { if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) { C_ext_offd_j[cnt_offd] = hypre_BigBinarySearch(col_map_offd_C, C_ext_j[j], num_cols_offd_C); C_ext_offd_data[cnt_offd++] = C_ext_data[j]; } else { C_ext_diag_j[cnt_diag] = (HYPRE_Int)(C_ext_j[j] - first_col_diag_C); C_ext_diag_data[cnt_diag++] = C_ext_data[j]; } } } } if (C_ext) { hypre_CSRMatrixDestroy(C_ext); C_ext = NULL; } if (num_cols_offd_B) { map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_cols_offd_C; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } } for (i = 0; i < hypre_CSRMatrixI(C_tmp_offd)[hypre_CSRMatrixNumRows(C_tmp_offd)]; i++) { j_indx = C_tmp_offd_j[i]; C_tmp_offd_j[i] = map_B_to_C[j_indx]; } } /*----------------------------------------------------------------------- * Need to compute: * C_diag = C_tmp_diag + C_ext_diag * C_offd = C_tmp_offd + C_ext_offd * * First generate structure *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { C_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1, memory_location_C); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1, memory_location_C); C_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); C_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int *B_marker_offd = NULL; HYPRE_Int ik, jk, j1, j2, jcol; HYPRE_Int ns, ne, ii, nnz_d, nnz_o; HYPRE_Int rest, size; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_diag_A/num_threads; rest = num_cols_diag_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B, HYPRE_MEMORY_HOST); B_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); for (ik = 0; ik < num_cols_diag_B; ik++) { B_marker[ik] = -1; } for (ik = 0; ik < num_cols_offd_C; ik++) { B_marker_offd[ik] = -1; } nnz_d = 0; nnz_o = 0; for (ik = ns; ik < ne; ik++) { for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; B_marker[jcol] = ik; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; B_marker_offd[jcol] = ik; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) { for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) { if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < ik) { B_marker[jcol] = ik; nnz_d++; } } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < ik) { B_marker_offd[jcol] = ik; nnz_o++; } } break; } } } C_diag_array[ii] = nnz_d; C_offd_array[ii] = nnz_o; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { nnz_d = 0; nnz_o = 0; for (ik = 0; ik < num_threads-1; ik++) { C_diag_array[ik+1] += C_diag_array[ik]; C_offd_array[ik+1] += C_offd_array[ik]; } nnz_d = C_diag_array[num_threads-1]; nnz_o = C_offd_array[num_threads-1]; C_diag_i[num_cols_diag_A] = nnz_d; C_offd_i[num_cols_diag_A] = nnz_o; C_diag = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_diag_A, nnz_d); C_offd = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_offd_C, nnz_o); hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixInitialize_v2(C_diag, 0, memory_location_C); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_CSRMatrixInitialize_v2(C_offd, 0, memory_location_C); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /*----------------------------------------------------------------------- * Need to compute C_diag = C_tmp_diag + C_ext_diag * and C_offd = C_tmp_offd + C_ext_offd !!!! * Now fill in values *-----------------------------------------------------------------------*/ for (ik = 0; ik < num_cols_diag_B; ik++) { B_marker[ik] = -1; } for (ik = 0; ik < num_cols_offd_C; ik++) { B_marker_offd[ik] = -1; } /*----------------------------------------------------------------------- * Populate matrices *-----------------------------------------------------------------------*/ nnz_d = 0; nnz_o = 0; if (ii) { nnz_d = C_diag_array[ii-1]; nnz_o = C_offd_array[ii-1]; } for (ik = ns; ik < ne; ik++) { C_diag_i[ik] = nnz_d; C_offd_i[ik] = nnz_o; for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_tmp_diag_data[jk]; B_marker[jcol] = nnz_d; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_tmp_offd_data[jk]; B_marker_offd[jcol] = nnz_o; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) { for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) { if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < C_diag_i[ik]) { C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_ext_diag_data[j2]; B_marker[jcol] = nnz_d; nnz_d++; } else { C_diag_data[B_marker[jcol]] += C_ext_diag_data[j2]; } } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < C_offd_i[ik]) { C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_ext_offd_data[j2]; B_marker_offd[jcol] = nnz_o; nnz_o++; } else { C_offd_data[B_marker_offd[jcol]] += C_ext_offd_data[j2]; } } break; } } } } hypre_TFree(B_marker, HYPRE_MEMORY_HOST); hypre_TFree(B_marker_offd, HYPRE_MEMORY_HOST); } /*end parallel region */ hypre_TFree(C_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(C_offd_array, HYPRE_MEMORY_HOST); } /*C = hypre_ParCSRMatrixCreate(comm, ncols_A, ncols_B, col_starts_A, col_starts_B, num_cols_offd_C, nnz_diag, nnz_offd); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); */ /* row_starts[0] is start of local rows. row_starts[1] is start of next processor's rows */ first_row_index = col_starts_A[0]; local_num_rows = (HYPRE_Int)(col_starts_A[1]-first_row_index ); first_col_diag = col_starts_B[0]; local_num_cols = (HYPRE_Int)(col_starts_B[1]-first_col_diag); C = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixComm(C) = comm; hypre_ParCSRMatrixGlobalNumRows(C) = ncols_A; hypre_ParCSRMatrixGlobalNumCols(C) = ncols_B; hypre_ParCSRMatrixFirstRowIndex(C) = first_row_index; hypre_ParCSRMatrixFirstColDiag(C) = first_col_diag; hypre_ParCSRMatrixLastRowIndex(C) = first_row_index + (HYPRE_BigInt)local_num_rows - 1; hypre_ParCSRMatrixLastColDiag(C) = first_col_diag + (HYPRE_BigInt)local_num_cols - 1; hypre_ParCSRMatrixColMapOffd(C) = NULL; hypre_ParCSRMatrixAssumedPartition(C) = NULL; hypre_ParCSRMatrixRowStarts(C) = col_starts_A; hypre_ParCSRMatrixColStarts(C) = col_starts_B; hypre_ParCSRMatrixCommPkg(C) = NULL; hypre_ParCSRMatrixCommPkgT(C) = NULL; /* set defaults */ hypre_ParCSRMatrixOwnsData(C) = 1; hypre_ParCSRMatrixRowindices(C) = NULL; hypre_ParCSRMatrixRowvalues(C) = NULL; hypre_ParCSRMatrixGetrowactive(C) = 0; /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C,0); hypre_ParCSRMatrixSetColStartsOwner(C,0); if (C_diag) { hypre_CSRMatrixSetRownnz(C_diag); hypre_ParCSRMatrixDiag(C) = C_diag; } else { hypre_ParCSRMatrixDiag(C) = C_tmp_diag; } if (C_offd) { hypre_CSRMatrixSetRownnz(C_offd); hypre_ParCSRMatrixOffd(C) = C_offd; } else { hypre_ParCSRMatrixOffd(C) = C_tmp_offd; } hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(C)) = memory_location_C; hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(C)) = memory_location_C; if (num_cols_offd_C) { HYPRE_Int jj_count_offd, nnz_offd; HYPRE_BigInt *new_col_map_offd_C = NULL; P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); for (i = 0; i < num_cols_offd_C; i++) { P_marker[i] = -1; } jj_count_offd = 0; nnz_offd = C_offd_i[num_cols_diag_A]; for (i = 0; i < nnz_offd; i++) { i1 = C_offd_j[i]; if (P_marker[i1]) { P_marker[i1] = 0; jj_count_offd++; } } if (jj_count_offd < num_cols_offd_C) { new_col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, jj_count_offd, HYPRE_MEMORY_HOST); jj_count_offd = 0; for (i = 0; i < num_cols_offd_C; i++) { if (!P_marker[i]) { P_marker[i] = jj_count_offd; new_col_map_offd_C[jj_count_offd++] = col_map_offd_C[i]; } } for (i = 0; i < nnz_offd; i++) { i1 = C_offd_j[i]; C_offd_j[i] = P_marker[i1]; } num_cols_offd_C = jj_count_offd; hypre_TFree(col_map_offd_C, HYPRE_MEMORY_HOST); col_map_offd_C = new_col_map_offd_C; hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(C)) = num_cols_offd_C; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); } hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { hypre_TFree(C_ext_diag_i, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_offd_i, HYPRE_MEMORY_HOST); } if (C_ext_diag_size) { hypre_TFree(C_ext_diag_j, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_diag_data, HYPRE_MEMORY_HOST); } if (C_ext_offd_size) { hypre_TFree(C_ext_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_offd_data, HYPRE_MEMORY_HOST); } if (num_cols_offd_B) { hypre_TFree(map_B_to_C, HYPRE_MEMORY_HOST); } if (C_diag) { hypre_CSRMatrixDestroy(C_tmp_diag); } if (C_offd) { hypre_CSRMatrixDestroy(C_tmp_offd); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) if ( hypre_GetExecPolicy2(memory_location_A, memory_location_B) == HYPRE_EXEC_DEVICE ) { hypre_CSRMatrixMoveDiagFirstDevice(hypre_ParCSRMatrixDiag(C)); hypre_SyncCudaComputeStream(hypre_handle()); } #endif return C; } HYPRE_Int hypre_ParvecBdiagInvScal( hypre_ParVector *b, HYPRE_Int blockSize, hypre_ParVector **bs, hypre_ParCSRMatrix *A) { MPI_Comm comm = hypre_ParCSRMatrixComm(b); HYPRE_Int num_procs, my_id; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); HYPRE_Int i, j, s, block_start, block_end; HYPRE_BigInt nrow_global = hypre_ParVectorGlobalSize(b); HYPRE_BigInt first_row = hypre_ParVectorFirstIndex(b); HYPRE_BigInt last_row = hypre_ParVectorLastIndex(b); HYPRE_BigInt end_row = last_row + 1; /* one past-the-last */ HYPRE_BigInt first_row_block = first_row / (HYPRE_BigInt)(blockSize) * (HYPRE_BigInt)blockSize; HYPRE_BigInt end_row_block = hypre_min( (last_row / (HYPRE_BigInt)blockSize + 1) * (HYPRE_BigInt)blockSize, nrow_global ); hypre_assert(blockSize == A->bdiag_size); HYPRE_Complex *bdiaginv = A->bdiaginv; hypre_ParCSRCommPkg *comm_pkg = A->bdiaginv_comm_pkg; HYPRE_Complex *dense = bdiaginv; //for (i=first_row_block; i < end_row; i+=blockSize) ; //printf("===[%d %d), [ %d %d ) %d === \n", first_row, end_row, first_row_block, end_row_block, i); /* local vector of b */ hypre_Vector *b_local = hypre_ParVectorLocalVector(b); HYPRE_Complex *b_local_data = hypre_VectorData(b_local); /* number of sends (#procs) */ HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ HYPRE_Int num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ HYPRE_Int num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); hypre_ParCSRCommHandle *comm_handle; HYPRE_BigInt *part = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_TMemcpy(part, hypre_ParVectorPartitioning(b), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_ParVector *bnew = hypre_ParVectorCreate( hypre_ParVectorComm(b), hypre_ParVectorGlobalSize(b), part ); hypre_ParVectorInitialize(bnew); hypre_Vector *bnew_local = hypre_ParVectorLocalVector(bnew); HYPRE_Complex *bnew_local_data = hypre_VectorData(bnew_local); /* send and recv b */ HYPRE_Complex *send_b = hypre_TAlloc(HYPRE_Complex, num_rows_send, HYPRE_MEMORY_HOST); HYPRE_Complex *recv_b = hypre_TAlloc(HYPRE_Complex, num_rows_recv, HYPRE_MEMORY_HOST); for (i = 0; i < num_rows_send; i++) { j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); send_b[i] = b_local_data[j]; } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, send_b, recv_b); /* ... */ hypre_ParCSRCommHandleDestroy(comm_handle); for (block_start = first_row_block; block_start < end_row_block; block_start += blockSize) { HYPRE_BigInt big_i; block_end = hypre_min(block_start + (HYPRE_BigInt)blockSize, nrow_global); s = (HYPRE_Int)(block_end - block_start); for (big_i = block_start; big_i < block_end; big_i++) { if (big_i < first_row || big_i >= end_row) { continue; } HYPRE_Int local_i = (HYPRE_Int)(big_i - first_row); HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); bnew_local_data[local_i] = 0.0; for (j = 0; j < s; j++) { HYPRE_BigInt global_rid = block_start + (HYPRE_BigInt)j; HYPRE_Complex val = dense[block_i + j*blockSize]; if (val == 0.0) { continue; } if (global_rid >= first_row && global_rid < end_row) { HYPRE_Int rid = (HYPRE_Int)(global_rid - first_row); bnew_local_data[local_i] += val * b_local_data[rid]; } else { HYPRE_Int rid; if (global_rid < first_row) { rid = (HYPRE_Int)(global_rid - first_row_block); } else { rid = (HYPRE_Int)(first_row - first_row_block + global_rid - end_row); } bnew_local_data[local_i] += val * recv_b[rid]; } } } dense += blockSize * blockSize; } hypre_TFree(send_b, HYPRE_MEMORY_HOST); hypre_TFree(recv_b, HYPRE_MEMORY_HOST); *bs = bnew; return hypre_error_flag; } /** * @brief Compute As = B^{-1}*A, where B is the block diagonal of A * @param[in] A : * @param[in] blockSize: block size * @param[out] B : * @return * @warning */ HYPRE_Int hypre_ParcsrBdiagInvScal( hypre_ParCSRMatrix *A, HYPRE_Int blockSize, hypre_ParCSRMatrix **As) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs, my_id; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); HYPRE_Int i, j, k, s; HYPRE_BigInt block_start, block_end; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int nrow_local = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt first_row = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_BigInt last_row = hypre_ParCSRMatrixLastRowIndex(A); HYPRE_BigInt end_row = first_row + (HYPRE_BigInt)nrow_local; /* one past-the-last */ HYPRE_Int ncol_local = hypre_CSRMatrixNumCols(A_diag); HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); /* HYPRE_Int last_col = hypre_ParCSRMatrixLastColDiag(A); */ HYPRE_BigInt end_col = first_col + (HYPRE_BigInt)ncol_local; HYPRE_BigInt nrow_global = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt ncol_global = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); void *request; /* if square globally and locally */ HYPRE_Int square2 = (nrow_global == ncol_global) && (nrow_local == ncol_local) && (first_row == first_col); if (nrow_global != ncol_global) { hypre_printf("hypre_ParcsrBdiagInvScal: only support N_ROW == N_COL\n"); return hypre_error_flag; } /* in block diagonals, row range of the blocks this proc span */ HYPRE_BigInt first_row_block = first_row / (HYPRE_BigInt)blockSize * (HYPRE_BigInt)blockSize; HYPRE_BigInt end_row_block = hypre_min( (last_row / (HYPRE_BigInt)blockSize + 1) * (HYPRE_BigInt)blockSize, nrow_global ); HYPRE_Int num_blocks = (HYPRE_Int)(last_row / (HYPRE_BigInt)blockSize + 1 - first_row / (HYPRE_BigInt)blockSize); //for (i=first_row_block; i < end_row; i+=blockSize) ; //printf("===[%d %d), [ %d %d ) %d === \n", first_row, end_row, first_row_block, end_row_block, i); //return 0; /* number of external rows */ HYPRE_Int num_ext_rows = (HYPRE_Int)(end_row_block - first_row_block - (end_row - first_row)); HYPRE_BigInt *ext_indices; HYPRE_Int A_ext_nnz; hypre_CSRMatrix *A_ext = NULL; HYPRE_Complex *A_ext_a = NULL; HYPRE_Int *A_ext_i = NULL; HYPRE_BigInt *A_ext_j = NULL; HYPRE_Real *dense_all = hypre_CTAlloc(HYPRE_Complex, num_blocks*blockSize*blockSize, HYPRE_MEMORY_HOST); HYPRE_Real *dense = dense_all; HYPRE_Int *IPIV = hypre_TAlloc(HYPRE_Int, blockSize, HYPRE_MEMORY_HOST); HYPRE_Complex *dgetri_work = NULL; HYPRE_Int dgetri_lwork = -1, lapack_info; HYPRE_Int num_cols_A_offd_new; HYPRE_BigInt *col_map_offd_A_new; HYPRE_BigInt big_i; HYPRE_Int *offd2new = NULL; HYPRE_Int *marker_diag, *marker_newoffd; HYPRE_Int nnz_diag = A_diag_i[nrow_local]; HYPRE_Int nnz_offd = A_offd_i[nrow_local]; HYPRE_Int nnz_diag_new = 0, nnz_offd_new = 0; HYPRE_Int *A_diag_i_new, *A_diag_j_new, *A_offd_i_new, *A_offd_j_new; HYPRE_Complex *A_diag_a_new, *A_offd_a_new; /* heuristic */ HYPRE_Int nnz_diag_alloc = 2 * nnz_diag; HYPRE_Int nnz_offd_alloc = 2 * nnz_offd; A_diag_i_new = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); A_diag_j_new = hypre_CTAlloc(HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_CTAlloc(HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_offd_i_new = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); A_offd_j_new = hypre_CTAlloc(HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_CTAlloc(HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); hypre_ParCSRMatrix *Anew; hypre_CSRMatrix *Anew_diag; hypre_CSRMatrix *Anew_offd; HYPRE_BigInt *row_starts_new, *col_starts_new; HYPRE_Real eps = 2.2e-16; /* Start with extracting the external rows */ HYPRE_BigInt *ext_offd; ext_indices = hypre_CTAlloc(HYPRE_BigInt, num_ext_rows, HYPRE_MEMORY_HOST); j = 0; for (big_i = first_row_block; big_i < first_row; big_i++) { ext_indices[j++] = big_i; } for (big_i = end_row; big_i < end_row_block; big_i++) { ext_indices[j++] = big_i; } hypre_assert(j == num_ext_rows); /* create CommPkg for external rows */ hypre_ParCSRFindExtendCommPkg(comm, nrow_global, first_row, nrow_local, row_starts, hypre_ParCSRMatrixAssumedPartition(A), num_ext_rows, ext_indices, &A->bdiaginv_comm_pkg); hypre_ParcsrGetExternalRowsInit(A, num_ext_rows, ext_indices, A->bdiaginv_comm_pkg, 1, &request); A_ext = hypre_ParcsrGetExternalRowsWait(request); hypre_TFree(ext_indices, HYPRE_MEMORY_HOST); A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_a = hypre_CSRMatrixData(A_ext); A_ext_nnz = A_ext_i[num_ext_rows]; ext_offd = hypre_CTAlloc(HYPRE_BigInt, A_ext_nnz, HYPRE_MEMORY_HOST); /* fint the offd incides in A_ext */ for (i = 0, j = 0; i < A_ext_nnz; i++) { /* global index */ HYPRE_BigInt cid = A_ext_j[i]; /* keep the offd indices */ if (cid < first_col || cid >= end_col) { ext_offd[j++] = cid; } } /* remove duplicates after sorting (TODO better ways?) */ hypre_BigQsort0(ext_offd, 0, j-1); for (i = 0, k = 0; i < j; i++) { if (i == 0 || ext_offd[i] != ext_offd[i-1]) { ext_offd[k++] = ext_offd[i]; } } /* uniion these `k' new indices into col_map_offd_A */ col_map_offd_A_new = hypre_CTAlloc(HYPRE_BigInt, num_cols_A_offd + k, HYPRE_MEMORY_HOST); if (k) { /* map offd to offd_new */ offd2new = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); } hypre_union2(num_cols_A_offd, col_map_offd_A, k, ext_offd, &num_cols_A_offd_new, col_map_offd_A_new, offd2new, NULL); hypre_TFree(ext_offd, HYPRE_MEMORY_HOST); /* * adjust column indices in A_ext */ for (i = 0; i < A_ext_nnz; i++) { HYPRE_BigInt cid = A_ext_j[i]; if (cid < first_col || cid >= end_col) { j = hypre_BigBinarySearch(col_map_offd_A_new, cid, num_cols_A_offd_new); /* searching must succeed */ hypre_assert(j >= 0 && j < num_cols_A_offd_new); /* trick: save ncol_local + j back */ A_ext_j[i] = ncol_local + j; } else { /* save local index: [0, ncol_local-1] */ A_ext_j[i] = cid - first_col; } } /* marker for diag */ marker_diag = hypre_TAlloc(HYPRE_Int, ncol_local, HYPRE_MEMORY_HOST); for (i = 0; i < ncol_local; i++) { marker_diag[i] = -1; } /* marker for newoffd */ marker_newoffd = hypre_TAlloc(HYPRE_Int, num_cols_A_offd_new, HYPRE_MEMORY_HOST); for (i = 0; i < num_cols_A_offd_new; i++) { marker_newoffd[i] = -1; } /* outer most loop for blocks */ for (block_start = first_row_block; block_start < end_row_block; block_start += (HYPRE_BigInt)blockSize) { HYPRE_BigInt big_i; block_end = hypre_min(block_start + (HYPRE_BigInt)blockSize, nrow_global); s = (HYPRE_Int)(block_end - block_start); /* 1. fill the dense block diag matrix */ for (big_i = block_start; big_i < block_end; big_i++) { /* row index in this block */ HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); /* row index i: it can be local or external */ if (big_i >= first_row && big_i < end_row) { /* is a local row */ j = (HYPRE_Int)(big_i - first_row); for (k = A_diag_i[j]; k < A_diag_i[j+1]; k++) { HYPRE_BigInt cid = (HYPRE_BigInt)A_diag_j[k] + first_col; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_diag_a[k]; } } if (num_cols_A_offd) { for (k = A_offd_i[j]; k < A_offd_i[j+1]; k++) { HYPRE_BigInt cid = col_map_offd_A[A_offd_j[k]]; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_offd_a[k]; } } } } else { /* is an external row */ if (big_i < first_row) { j = (HYPRE_Int)(big_i - first_row_block); } else { j = (HYPRE_Int)(first_row - first_row_block + big_i - end_row); } for (k = A_ext_i[j]; k < A_ext_i[j+1]; k++) { HYPRE_BigInt cid = A_ext_j[k]; /* recover the global index */ cid = cid < (HYPRE_BigInt)ncol_local ? cid + first_col : col_map_offd_A_new[cid-ncol_local]; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_ext_a[k]; } } } } /* 2. invert the dense matrix */ hypre_dgetrf(&s, &s, dense, &blockSize, IPIV, &lapack_info); hypre_assert(lapack_info == 0); if (lapack_info == 0) { HYPRE_Int query = -1; HYPRE_Real lwork_opt; /* query the optimal size of work */ hypre_dgetri(&s, dense, &blockSize, IPIV, &lwork_opt, &query, &lapack_info); hypre_assert(lapack_info == 0); if (lwork_opt > dgetri_lwork) { dgetri_lwork = lwork_opt; dgetri_work = hypre_TReAlloc(dgetri_work, HYPRE_Complex, dgetri_lwork, HYPRE_MEMORY_HOST); } hypre_dgetri(&s, dense, &blockSize, IPIV, dgetri_work, &dgetri_lwork, &lapack_info); hypre_assert(lapack_info == 0); } /* filter out *zeros* */ HYPRE_Real Fnorm = 0.0; for (i = 0; i < s; i++) { for (j = 0; j < s; j++) { HYPRE_Complex t = dense[j+i*blockSize]; Fnorm += t * t; } } Fnorm = sqrt(Fnorm); for (i = 0; i < s; i++) { for (j = 0; j < s; j++) { if ( hypre_abs(dense[j+i*blockSize]) < eps * Fnorm ) { dense[j+i*blockSize] = 0.0; } } } /* 3. premultiplication: one-pass dynamic allocation */ for (big_i = block_start; big_i < block_end; big_i++) { /* starting points of this row in j */ HYPRE_Int diag_i_start = nnz_diag_new; HYPRE_Int offd_i_start = nnz_offd_new; /* compute a new row with global index 'i' and local index 'local_i' */ HYPRE_Int local_i = (HYPRE_Int)(big_i - first_row); /* row index in this block */ HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); if (big_i < first_row || big_i >= end_row) { continue; } /* if square^2: reserve the first space in diag part to the diag entry */ if (square2) { marker_diag[local_i] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = local_i; A_diag_a_new[nnz_diag_new] = 0.0; nnz_diag_new ++; } /* combine s rows */ for (j = 0; j < s; j++) { /* row to combine: global row id */ HYPRE_BigInt global_rid = block_start + (HYPRE_BigInt)j; /* the multipiler */ HYPRE_Complex val = dense[block_i + j*blockSize]; if (val == 0.0) { continue; } if (global_rid >= first_row && global_rid < end_row) { /* this row is local */ HYPRE_Int rid = (HYPRE_Int)(global_rid - first_row); HYPRE_Int ii; for (ii = A_diag_i[rid]; ii < A_diag_i[rid+1]; ii++) { HYPRE_Int col = A_diag_j[ii]; HYPRE_Complex vv = A_diag_a[ii]; if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = col; A_diag_a_new[nnz_diag_new] = val * vv; nnz_diag_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_diag[col]; hypre_assert(A_diag_j_new[p] == col); A_diag_a_new[p] += val * vv; } } for (ii = A_offd_i[rid]; ii < A_offd_i[rid+1]; ii++) { HYPRE_Int col = A_offd_j[ii]; /* use the mapper to map to new offd */ HYPRE_Int col_new = offd2new ? offd2new[col] : col; HYPRE_Complex vv = A_offd_a[ii]; if (marker_newoffd[col_new] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_newoffd[col_new] = nnz_offd_new; if (nnz_offd_new == nnz_offd_alloc) { nnz_offd_alloc = nnz_offd_alloc * 2 + 1; A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); } A_offd_j_new[nnz_offd_new] = col_new; A_offd_a_new[nnz_offd_new] = val * vv; nnz_offd_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_newoffd[col_new]; hypre_assert(A_offd_j_new[p] == col_new); A_offd_a_new[p] += val * vv; } } } else { /* this is an external row: go to A_ext */ HYPRE_Int rid, ii; if (global_rid < first_row) { rid = (HYPRE_Int)(global_rid - first_row_block); } else { rid = (HYPRE_Int)(first_row - first_row_block + global_rid - end_row); } for (ii = A_ext_i[rid]; ii < A_ext_i[rid+1]; ii++) { HYPRE_Int col = (HYPRE_Int)A_ext_j[ii]; HYPRE_Complex vv = A_ext_a[ii]; if (col < ncol_local) { /* in diag part */ if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = col; A_diag_a_new[nnz_diag_new] = val * vv; nnz_diag_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_diag[col]; hypre_assert(A_diag_j_new[p] == col); A_diag_a_new[p] += val * vv; } } else { /* in offd part */ col -= ncol_local; if (marker_newoffd[col] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_newoffd[col] = nnz_offd_new; if (nnz_offd_new == nnz_offd_alloc) { nnz_offd_alloc = nnz_offd_alloc * 2 + 1; A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); } A_offd_j_new[nnz_offd_new] = col; A_offd_a_new[nnz_offd_new] = val * vv; nnz_offd_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_newoffd[col]; hypre_assert(A_offd_j_new[p] == col); A_offd_a_new[p] += val * vv; } } } } } /* done for row local_i */ A_diag_i_new[local_i + 1] = nnz_diag_new; A_offd_i_new[local_i + 1] = nnz_offd_new; } /* for i, each row */ dense += blockSize * blockSize; } /* for each block */ /* done with all rows */ /* resize properly */ A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_new, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_new, HYPRE_MEMORY_HOST); A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_new, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_new, HYPRE_MEMORY_HOST); /* readjust col_map_offd_new */ for (i = 0; i < num_cols_A_offd_new; i++) { marker_newoffd[i] = -1; } for (i = 0; i < nnz_offd_new; i++) { j = A_offd_j_new[i]; if (marker_newoffd[j] == -1) { marker_newoffd[j] = 1; } } for (i = 0, j = 0; i < num_cols_A_offd_new; i++) { if (marker_newoffd[i] == 1) { col_map_offd_A_new[j] = col_map_offd_A_new[i]; marker_newoffd[i] = j++; } } num_cols_A_offd_new = j; for (i = 0; i < nnz_offd_new; i++) { j = marker_newoffd[A_offd_j_new[i]]; hypre_assert(j >= 0 && j < num_cols_A_offd_new); A_offd_j_new[i] = j; } row_starts_new = hypre_CTAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); col_starts_new = hypre_CTAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); hypre_TMemcpy(row_starts_new, hypre_ParCSRMatrixRowStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_TMemcpy(col_starts_new, hypre_ParCSRMatrixColStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); /* Now, we should have everything of Parcsr matrix As */ Anew = hypre_ParCSRMatrixCreate(comm, nrow_global, ncol_global, row_starts_new, col_starts_new, num_cols_A_offd_new, nnz_diag_new, nnz_offd_new); Anew_diag = hypre_ParCSRMatrixDiag(Anew); hypre_CSRMatrixData(Anew_diag) = A_diag_a_new; hypre_CSRMatrixI(Anew_diag) = A_diag_i_new; hypre_CSRMatrixJ(Anew_diag) = A_diag_j_new; Anew_offd = hypre_ParCSRMatrixOffd(Anew); hypre_CSRMatrixData(Anew_offd) = A_offd_a_new; hypre_CSRMatrixI(Anew_offd) = A_offd_i_new; hypre_CSRMatrixJ(Anew_offd) = A_offd_j_new; hypre_ParCSRMatrixColMapOffd(Anew) = col_map_offd_A_new; hypre_ParCSRMatrixSetNumNonzeros(Anew); hypre_ParCSRMatrixDNumNonzeros(Anew) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(Anew); //printf("nnz_diag %d --> %d, nnz_offd %d --> %d\n", nnz_diag, nnz_diag_new, nnz_offd, nnz_offd_new); /* create CommPkg of Anew */ hypre_MatvecCommPkgCreate(Anew); *As = Anew; /* if (bdiaginv) { *bdiaginv = dense_all; } else { hypre_TFree(dense_all, HYPRE_MEMORY_HOST); } */ /* save diagonal blocks in A */ A->bdiag_size = blockSize; A->bdiaginv = dense_all; /* free workspace */ hypre_TFree(IPIV, HYPRE_MEMORY_HOST); hypre_TFree(dgetri_work, HYPRE_MEMORY_HOST); hypre_TFree(marker_diag, HYPRE_MEMORY_HOST); hypre_TFree(marker_newoffd, HYPRE_MEMORY_HOST); hypre_TFree(offd2new, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(A_ext); return hypre_error_flag; } HYPRE_Int hypre_ParcsrGetExternalRowsInit( hypre_ParCSRMatrix *A, HYPRE_Int indices_len, HYPRE_BigInt *indices, hypre_ParCSRCommPkg *comm_pkg, HYPRE_Int want_data, void **request_ptr) { HYPRE_Int i, j, k; HYPRE_Int num_sends, num_rows_send, num_nnz_send, *send_i, num_recvs, num_rows_recv, num_nnz_recv, *recv_i, *send_jstarts, *recv_jstarts, *send_i_offset; HYPRE_BigInt *send_j, *recv_j; HYPRE_Complex *send_a = NULL, *recv_a = NULL; hypre_ParCSRCommPkg *comm_pkg_j; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; /* HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); */ /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); */ /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /* HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); */ /* HYPRE_BigInt first_row = hypre_ParCSRMatrixFirstRowIndex(A); */ HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs; HYPRE_Int my_id; void **vrequest; hypre_CSRMatrix *A_ext; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /* number of sends (#procs) */ num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); /* must be true if indices contains proper offd indices */ hypre_assert(indices_len == num_rows_recv); /* send_i/recv_i: * the arrays to send and recv: we first send and recv the row lengths */ send_i = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST); recv_i = hypre_CTAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_HOST); /* fill the send array with row lengths */ for (i = 0, num_nnz_send = 0; i < num_rows_send; i++) { /* j: row index to send */ j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); send_i[i] = A_diag_i[j+1] - A_diag_i[j] + A_offd_i[j+1] - A_offd_i[j]; num_nnz_send += send_i[i]; } /* send this array out: note the shift in recv_i by one (async) */ comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_i, recv_i+1); /* prepare data to send out. overlap with the above commmunication */ send_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_send, HYPRE_MEMORY_HOST); if (want_data) { send_a = hypre_TAlloc(HYPRE_Complex, num_nnz_send, HYPRE_MEMORY_HOST); } send_i_offset = hypre_TAlloc(HYPRE_Int, num_rows_send + 1, HYPRE_MEMORY_HOST); send_i_offset[0] = 0; hypre_TMemcpy(send_i_offset + 1, send_i, HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); /* prefix sum. TODO: OMP parallelization */ for (i = 1; i <= num_rows_send; i++) { send_i_offset[i] += send_i_offset[i-1]; } hypre_assert(send_i_offset[num_rows_send] == num_nnz_send); /* pointers to each proc in send_j */ send_jstarts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = 0; i <= num_sends; i++) { send_jstarts[i] = send_i_offset[hypre_ParCSRCommPkgSendMapStart(comm_pkg, i)]; } hypre_assert(send_jstarts[num_sends] == num_nnz_send); /* fill the CSR matrix: j and a */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE private(i,j,k) #endif for (i = 0; i < num_rows_send; i++) { HYPRE_Int i1 = send_i_offset[i]; j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); /* open row j and fill ja and a to send */ for (k = A_diag_i[j]; k < A_diag_i[j+1]; k++) { send_j[i1] = first_col + A_diag_j[k]; if (want_data) { send_a[i1] = A_diag_a[k]; } i1++; } if (num_procs > 1) { for (k = A_offd_i[j]; k < A_offd_i[j+1]; k++) { send_j[i1] = col_map_offd_A[A_offd_j[k]]; if (want_data) { send_a[i1] = A_offd_a[k]; } i1++; } } hypre_assert(send_i_offset[i+1] == i1); } /* finish the above communication: send_i/recv_i */ hypre_ParCSRCommHandleDestroy(comm_handle); /* adjust recv_i to ptrs */ for (i = 1; i <= num_rows_recv; i++) { recv_i[i] += recv_i[i-1]; } num_nnz_recv = recv_i[num_rows_recv]; recv_j = hypre_CTAlloc(HYPRE_BigInt, num_nnz_recv, HYPRE_MEMORY_HOST); if (want_data) { recv_a = hypre_CTAlloc(HYPRE_Complex, num_nnz_recv, HYPRE_MEMORY_HOST); } recv_jstarts = hypre_CTAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); for (i = 1; i <= num_recvs; i++) { j = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); recv_jstarts[i] = recv_i[j]; } /* ready to send and recv: create a communication package for data */ comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm (comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends (comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs (comm_pkg_j) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = send_jstarts; hypre_ParCSRCommPkgNumRecvs (comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgRecvProcs (comm_pkg_j) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = recv_jstarts; /* init communication */ /* ja */ comm_handle_j = hypre_ParCSRCommHandleCreate(21, comm_pkg_j, send_j, recv_j); if (want_data) { /* a */ comm_handle_a = hypre_ParCSRCommHandleCreate(1, comm_pkg_j, send_a, recv_a); } else { comm_handle_a = NULL; } /* create A_ext */ A_ext = hypre_CSRMatrixCreate(num_rows_recv, hypre_ParCSRMatrixGlobalNumCols(A), num_nnz_recv); hypre_CSRMatrixMemoryLocation(A_ext) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI (A_ext) = recv_i; hypre_CSRMatrixBigJ(A_ext) = recv_j; hypre_CSRMatrixData(A_ext) = recv_a; /* output */ vrequest = hypre_TAlloc(void *, 4, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) A_ext; vrequest[3] = (void *) comm_pkg_j; *request_ptr = (void *) vrequest; /* free */ hypre_TFree(send_i, HYPRE_MEMORY_HOST); hypre_TFree(send_i_offset, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ParcsrGetExternalRowsWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *A_ext = (hypre_CSRMatrix *) request[2]; hypre_ParCSRCommPkg *comm_pkg_j = (hypre_ParCSRCommPkg *) request[3]; HYPRE_BigInt *send_j = (HYPRE_BigInt *) hypre_ParCSRCommHandleSendData(comm_handle_j); if (comm_handle_a) { HYPRE_Complex *send_a = (HYPRE_Complex *) hypre_ParCSRCommHandleSendData(comm_handle_a); hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_TFree(send_a, HYPRE_MEMORY_HOST); } hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_TFree(send_j, HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); hypre_TFree(request, HYPRE_MEMORY_HOST); return A_ext; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixAdd: performs C = alpha*A + beta*B * * A and B are assumed to have the same row and column partitionings *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixAddHost( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, HYPRE_Complex beta, hypre_ParCSRMatrix *B, hypre_ParCSRMatrix **C_ptr ) { /* ParCSRMatrix data */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_BigInt num_rows_A = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt num_cols_A = hypre_ParCSRMatrixGlobalNumCols(A); /* HYPRE_BigInt num_rows_B = hypre_ParCSRMatrixGlobalNumRows(B); */ /* HYPRE_BigInt num_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); */ /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *rownnz_diag_A = hypre_CSRMatrixRownnz(A_diag); HYPRE_Int num_rownnz_diag_A = hypre_CSRMatrixNumRownnz(A_diag); HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *rownnz_offd_A = hypre_CSRMatrixRownnz(A_offd); HYPRE_Int num_rownnz_offd_A = hypre_CSRMatrixNumRownnz(A_offd); HYPRE_Int num_rows_offd_A = hypre_CSRMatrixNumRows(A_offd); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int *A2C_offd; /* diag part of B */ hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Int *rownnz_diag_B = hypre_CSRMatrixRownnz(B_diag); HYPRE_Int num_rownnz_diag_B = hypre_CSRMatrixNumRownnz(B_diag); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); /* HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); */ /* off-diag part of B */ hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *rownnz_offd_B = hypre_CSRMatrixRownnz(B_offd); HYPRE_Int num_rownnz_offd_B = hypre_CSRMatrixNumRownnz(B_offd); HYPRE_Int num_rows_offd_B = hypre_CSRMatrixNumRows(B_offd); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Int *B2C_offd; /* C data */ hypre_ParCSRMatrix *C; HYPRE_BigInt *row_starts_C; HYPRE_BigInt *col_starts_C; hypre_CSRMatrix *C_diag; hypre_CSRMatrix *C_offd; HYPRE_BigInt *col_map_offd_C; HYPRE_Int *C_diag_i, *C_offd_i; HYPRE_Int *rownnz_diag_C = NULL; HYPRE_Int *rownnz_offd_C = NULL; HYPRE_Int num_rownnz_diag_C; HYPRE_Int num_rownnz_offd_C; HYPRE_Int num_rows_diag_C = num_rows_diag_A; HYPRE_Int num_cols_diag_C = num_cols_diag_A; HYPRE_Int num_rows_offd_C = num_rows_offd_A; HYPRE_Int num_cols_offd_C = num_cols_offd_A + num_cols_offd_B; HYPRE_Int *twspace; HYPRE_MemoryLocation memory_location_A = hypre_ParCSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_ParCSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); HYPRE_ANNOTATE_FUNC_BEGIN; /* Allocate memory */ twspace = hypre_TAlloc(HYPRE_Int, hypre_NumThreads(), HYPRE_MEMORY_HOST); C_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A + 1, memory_location_C); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_offd_A + 1, memory_location_C); col_map_offd_C = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); /* Compute num_cols_offd_C, A2C_offd, and B2C_offd*/ A2C_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_A, HYPRE_MEMORY_HOST); B2C_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); hypre_union2(num_cols_offd_A, col_map_offd_A, num_cols_offd_B, col_map_offd_B, &num_cols_offd_C, col_map_offd_C, A2C_offd, B2C_offd); /* Set nonzero rows data of diag_C */ num_rownnz_diag_C = num_rows_diag_A; if ((num_rownnz_diag_A < num_rows_diag_A) && (num_rownnz_diag_B < num_rows_diag_B)) { hypre_MergeOrderedArrays( num_rownnz_diag_A, rownnz_diag_A, num_rownnz_diag_B, rownnz_diag_B, &num_rownnz_diag_C, &rownnz_diag_C); } /* Set nonzero rows data of offd_C */ num_rownnz_offd_C = num_rows_offd_A; if ((num_rownnz_offd_A < num_rows_offd_A) && (num_rownnz_offd_B < num_rows_offd_B)) { hypre_MergeOrderedArrays( num_rownnz_offd_A, rownnz_offd_A, num_rownnz_offd_B, rownnz_offd_B, &num_rownnz_offd_C, &rownnz_offd_C); } /* Set diag_C */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int ii, num_threads; HYPRE_Int size, rest, ns, ne; HYPRE_Int *marker_diag; HYPRE_Int *marker_offd; ii = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); /*----------------------------------------------------------------------- * Compute C_diag = alpha*A_diag + beta*B_diag *-----------------------------------------------------------------------*/ size = num_rownnz_diag_C/num_threads; rest = num_rownnz_diag_C - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } marker_diag = hypre_TAlloc(HYPRE_Int, num_cols_diag_A, HYPRE_MEMORY_HOST); hypre_CSRMatrixAddFirstPass(ns, ne, twspace, marker_diag, NULL, NULL, A_diag, B_diag, num_rows_diag_C, num_rownnz_diag_C, num_cols_diag_C, rownnz_diag_C, memory_location_C, C_diag_i, &C_diag); hypre_CSRMatrixAddSecondPass(ns, ne, twspace, marker_diag, NULL, NULL, rownnz_diag_C, alpha, beta, A_diag, B_diag, C_diag); hypre_TFree(marker_diag, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Compute C_offd = alpha*A_offd + beta*B_offd *-----------------------------------------------------------------------*/ size = num_rownnz_offd_C/num_threads; rest = num_rownnz_offd_C - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } marker_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); hypre_CSRMatrixAddFirstPass(ns, ne, twspace, marker_offd, A2C_offd, B2C_offd, A_offd, B_offd, num_rows_offd_C, num_rownnz_offd_C, num_cols_offd_C, rownnz_offd_C, memory_location_C, C_offd_i, &C_offd); hypre_CSRMatrixAddSecondPass(ns, ne, twspace, marker_offd, A2C_offd, B2C_offd, rownnz_offd_C, alpha, beta, A_offd, B_offd, C_offd); hypre_TFree(marker_offd, HYPRE_MEMORY_HOST); } /* end of omp parallel region */ /* Free memory */ hypre_TFree(twspace, HYPRE_MEMORY_HOST); hypre_TFree(A2C_offd, HYPRE_MEMORY_HOST); hypre_TFree(B2C_offd, HYPRE_MEMORY_HOST); /* Create ParCSRMatrix C */ row_starts_C = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); col_starts_C = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_TMemcpy(row_starts_C, hypre_ParCSRMatrixRowStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_TMemcpy(col_starts_C, hypre_ParCSRMatrixColStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); C = hypre_ParCSRMatrixCreate(comm, num_rows_A, num_cols_A, row_starts_C, col_starts_C, num_cols_offd_C, hypre_CSRMatrixNumNonzeros(C_diag), hypre_CSRMatrixNumNonzeros(C_offd)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); hypre_ParCSRMatrixDiag(C) = C_diag; hypre_ParCSRMatrixOffd(C) = C_offd; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; hypre_ParCSRMatrixSetNumNonzeros(C); hypre_ParCSRMatrixDNumNonzeros(C) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(C); /* create CommPkg of C */ hypre_MatvecCommPkgCreate(C); *C_ptr = C; HYPRE_ANNOTATE_FUNC_END; return hypre_error_flag; } HYPRE_Int hypre_ParCSRMatrixAdd( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, HYPRE_Complex beta, hypre_ParCSRMatrix *B, hypre_ParCSRMatrix **C_ptr ) { hypre_assert(hypre_ParCSRMatrixGlobalNumRows(A) == hypre_ParCSRMatrixGlobalNumRows(B)); hypre_assert(hypre_ParCSRMatrixGlobalNumCols(A) == hypre_ParCSRMatrixGlobalNumCols(B)); hypre_assert(hypre_ParCSRMatrixNumRows(A) == hypre_ParCSRMatrixNumRows(B)); hypre_assert(hypre_ParCSRMatrixNumCols(A) == hypre_ParCSRMatrixNumCols(B)); #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) if ( hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_ParCSRMatrixMemoryLocation(B) ) == HYPRE_EXEC_DEVICE ) { hypre_ParCSRMatrixAddDevice(alpha, A, beta, B, C_ptr); } else #endif { hypre_ParCSRMatrixAddHost(alpha, A, beta, B, C_ptr); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixFnorm *--------------------------------------------------------------------------*/ HYPRE_Real hypre_ParCSRMatrixFnorm( hypre_ParCSRMatrix *A ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Real f_diag, f_offd, local_result, result; f_diag = hypre_CSRMatrixFnorm(hypre_ParCSRMatrixDiag(A)); f_offd = hypre_CSRMatrixFnorm(hypre_ParCSRMatrixOffd(A)); local_result = f_diag * f_diag + f_offd * f_offd; hypre_MPI_Allreduce(&local_result, &result, 1, HYPRE_MPI_REAL, hypre_MPI_SUM, comm); return sqrt(result); } /*-------------------------------------------------------------------------- * hypre_ExchangeExternalRowsInit *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ExchangeExternalRowsInit( hypre_CSRMatrix *B_ext, hypre_ParCSRCommPkg *comm_pkg_A, void **request_ptr) { MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg_A); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int *recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); HYPRE_Int *send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); HYPRE_Int num_elmts_send = send_map_starts[num_sends]; HYPRE_Int num_elmts_recv = recv_vec_starts[num_recvs]; HYPRE_Int *B_ext_i = B_ext ? hypre_CSRMatrixI(B_ext) : NULL; HYPRE_BigInt *B_ext_j = B_ext ? hypre_CSRMatrixBigJ(B_ext) : NULL; HYPRE_Complex *B_ext_data = B_ext ? hypre_CSRMatrixData(B_ext) : NULL; HYPRE_Int B_ext_ncols = B_ext ? hypre_CSRMatrixNumCols(B_ext) : 0; HYPRE_Int B_ext_nrows = B_ext ? hypre_CSRMatrixNumRows(B_ext) : 0; HYPRE_Int *B_ext_rownnz = hypre_CTAlloc(HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST); hypre_assert(num_elmts_recv == B_ext_nrows); /* output matrix */ hypre_CSRMatrix *B_int; HYPRE_Int B_int_nrows = num_elmts_send; HYPRE_Int B_int_ncols = B_ext_ncols; HYPRE_Int *B_int_i = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_HOST); HYPRE_BigInt *B_int_j = NULL; HYPRE_Complex *B_int_data = NULL; HYPRE_Int B_int_nnz; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; hypre_ParCSRCommPkg *comm_pkg_j; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i; HYPRE_Int num_procs; void **vrequest; hypre_MPI_Comm_size(comm, &num_procs); jdata_send_map_starts = hypre_TAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); /*-------------------------------------------------------------------------- * B_ext_rownnz contains the number of elements of row j * (to be determined through send_map_elmnts on the receiving end) *--------------------------------------------------------------------------*/ for (i = 0; i < B_ext_nrows; i++) { B_ext_rownnz[i] = B_ext_i[i+1] - B_ext_i[i]; } /*-------------------------------------------------------------------------- * initialize communication: send/recv the row nnz * (note the use of comm_pkg_A, mode 12, as in transpose matvec *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_A, B_ext_rownnz, B_int_i + 1); jdata_recv_vec_starts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts[0] = 0; for (i = 1; i <= num_recvs; i++) { jdata_recv_vec_starts[i] = B_ext_i[recv_vec_starts[i]]; } comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgNumRecvs(comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs(comm_pkg_j) = recv_procs; hypre_ParCSRCommPkgRecvProcs(comm_pkg_j) = send_procs; hypre_ParCSRCommHandleDestroy(comm_handle); /*-------------------------------------------------------------------------- * compute B_int: row nnz to row ptrs *--------------------------------------------------------------------------*/ B_int_i[0] = 0; for (i = 1; i <= B_int_nrows; i++) { B_int_i[i] += B_int_i[i-1]; } B_int_nnz = B_int_i[B_int_nrows]; B_int_j = hypre_TAlloc(HYPRE_BigInt, B_int_nnz, HYPRE_MEMORY_HOST); B_int_data = hypre_TAlloc(HYPRE_Complex, B_int_nnz, HYPRE_MEMORY_HOST); for (i = 0; i <= num_sends; i++) { jdata_send_map_starts[i] = B_int_i[send_map_starts[i]]; } /* note the order of send/recv is reversed */ hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = jdata_send_map_starts; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = jdata_recv_vec_starts; /* send/recv CSR rows */ comm_handle_a = hypre_ParCSRCommHandleCreate( 1, comm_pkg_j, B_ext_data, B_int_data); comm_handle_j = hypre_ParCSRCommHandleCreate(21, comm_pkg_j, B_ext_j, B_int_j); /* create CSR */ B_int = hypre_CSRMatrixCreate(B_int_nrows, B_int_ncols, B_int_nnz); hypre_CSRMatrixMemoryLocation(B_int) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(B_int) = B_int_i; hypre_CSRMatrixBigJ(B_int) = B_int_j; hypre_CSRMatrixData(B_int) = B_int_data; /* output */ vrequest = hypre_TAlloc(void *, 4, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) B_int; vrequest[3] = (void *) comm_pkg_j; *request_ptr = (void *) vrequest; hypre_TFree(B_ext_rownnz, HYPRE_MEMORY_HOST); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ExchangeExternalRowsWait *--------------------------------------------------------------------------*/ hypre_CSRMatrix* hypre_ExchangeExternalRowsWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *B_int = (hypre_CSRMatrix *) request[2]; hypre_ParCSRCommPkg *comm_pkg_j = (hypre_ParCSRCommPkg *) request[3]; /* communication done */ hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); hypre_TFree(request, HYPRE_MEMORY_HOST); return B_int; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixExtractSubmatrixFC * * extract submatrix A_{FF}, A_{FC}, A_{CF} or A_{CC} * char job[2] = "FF", "FC", "CF" or "CC" *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixExtractSubmatrixFC( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, HYPRE_BigInt *cpts_starts_in, const char *job, hypre_ParCSRMatrix **B_ptr, HYPRE_Real strength_thresh) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); //HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); hypre_ParCSRMatrix *B; hypre_CSRMatrix *B_diag, *B_offd; HYPRE_Real *B_maxel_row; HYPRE_Int *B_diag_i, *B_diag_j, *B_offd_i, *B_offd_j; HYPRE_Complex *B_diag_a, *B_offd_a; HYPRE_Int num_cols_B_offd; HYPRE_BigInt *col_map_offd_B; HYPRE_Int i, j, k, k1, k2; HYPRE_BigInt B_nrow_global, B_ncol_global; HYPRE_Int A_nlocal, B_nrow_local, B_ncol_local, B_nnz_diag, B_nnz_offd; HYPRE_BigInt total_global_fpts, total_global_cpts, *fpts_starts, *cpts_starts; HYPRE_Int nf_local, nc_local; HYPRE_Int row_set, col_set; HYPRE_BigInt *B_row_starts, *B_col_starts, B_first_col; HYPRE_Int my_id, num_procs, *sub_idx_diag, *sub_idx_offd; HYPRE_Int num_sends, *send_buf_data; /* MPI size and rank*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); row_set = job[0] == 'F' ? -1 : 1; col_set = job[1] == 'F' ? -1 : 1; A_nlocal = hypre_CSRMatrixNumRows(A_diag); /*-------------- global number of C points and local C points * assuming cpts_starts is given */ if (row_set == 1 || col_set == 1) { /* copy cpts_starts first */ HYPRE_Int len; len = 2; cpts_starts = hypre_TAlloc(HYPRE_BigInt, len, HYPRE_MEMORY_HOST); hypre_TMemcpy(cpts_starts, cpts_starts_in, HYPRE_BigInt, len, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); if (my_id == (num_procs -1)) { total_global_cpts = cpts_starts[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); nc_local = (HYPRE_Int)(cpts_starts[1] - cpts_starts[0]); } /*-------------- global number of F points, local F points, and F starts */ if (row_set == -1 || col_set == -1) { nf_local = 0; for (i = 0; i < A_nlocal; i++) { if (CF_marker[i] < 0) { nf_local++; } } fpts_starts = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_MPI_Scan(&nf_local, fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); fpts_starts[0] = fpts_starts[1] - nf_local; if (my_id == num_procs - 1) { total_global_fpts = fpts_starts[1]; } hypre_MPI_Bcast(&total_global_fpts, 1, HYPRE_MPI_INT, num_procs-1, comm); } if (row_set == -1 && col_set == -1) { /* FF */ B_nrow_local = nf_local; B_ncol_local = nf_local; B_nrow_global = total_global_fpts; B_ncol_global = total_global_fpts; B_row_starts = B_col_starts = fpts_starts; } else if (row_set == -1 && col_set == 1) { /* FC */ B_nrow_local = nf_local; B_ncol_local = nc_local; B_nrow_global = total_global_fpts; B_ncol_global = total_global_cpts; B_row_starts = fpts_starts; B_col_starts = cpts_starts; } else if (row_set == 1 && col_set == -1) { /* CF */ B_nrow_local = nc_local; B_ncol_local = nf_local; B_nrow_global = total_global_cpts; B_ncol_global = total_global_fpts; B_row_starts = cpts_starts; B_col_starts = fpts_starts; } else { /* CC */ B_nrow_local = nc_local; B_ncol_local = nc_local; B_nrow_global = total_global_cpts; B_ncol_global = total_global_cpts; B_row_starts = B_col_starts = cpts_starts; } /* global index of my first col */ B_first_col = B_col_starts[0]; /* sub_idx_diag: [local] mapping from F+C to F/C, if not selected, be -1 */ sub_idx_diag = hypre_TAlloc(HYPRE_Int, A_nlocal, HYPRE_MEMORY_HOST); for (i = 0, k = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i == col_set) { sub_idx_diag[i] = k++; } else { sub_idx_diag[i] = -1; } } hypre_assert(k == B_ncol_local); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_buf_data = hypre_TAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); k = 0; for (i = 0; i < num_sends; i++) { /* start pos of elements sent to send_proc[i] */ HYPRE_Int si = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int ei = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); /* loop through all elems to send_proc[i] */ for (j = si; j < ei; j++) { /* j1: local idx */ HYPRE_Int j1 = sub_idx_diag[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; if (j1 != -1) { /* adjust j1 to B global idx */ j1 += B_first_col; } send_buf_data[k++] = j1; } } hypre_assert(k == hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); /* recv buffer */ sub_idx_offd = hypre_TAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); /* create a handle to start communication. 11: for integer */ comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_buf_data, sub_idx_offd); /* destroy the handle to finish communication */ hypre_ParCSRCommHandleDestroy(comm_handle); for (i = 0, num_cols_B_offd = 0; i < num_cols_A_offd; i++) { if (sub_idx_offd[i] != -1) { num_cols_B_offd ++; } } col_map_offd_B = hypre_TAlloc(HYPRE_BigInt, num_cols_B_offd, HYPRE_MEMORY_HOST); for (i = 0, k = 0; i < num_cols_A_offd; i++) { if (sub_idx_offd[i] != -1) { col_map_offd_B[k] = sub_idx_offd[i]; sub_idx_offd[i] = k++; } } hypre_assert(k == num_cols_B_offd); /* count nnz and set ia */ B_nnz_diag = B_nnz_offd = 0; B_maxel_row = hypre_TAlloc(HYPRE_Real, B_nrow_local, HYPRE_MEMORY_HOST); B_diag_i = hypre_TAlloc(HYPRE_Int, B_nrow_local+1, HYPRE_MEMORY_HOST); B_offd_i = hypre_TAlloc(HYPRE_Int, B_nrow_local+1, HYPRE_MEMORY_HOST); B_diag_i[0] = B_offd_i[0] = 0; for (i = 0, k = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i != row_set) { continue; } k++; // Get max abs-value element of this row HYPRE_Real temp_max = 0; if (strength_thresh > 0) { for (j = A_diag_i[i]+1; j < A_diag_i[i+1]; j++) { if (hypre_cabs(A_diag_a[j]) > temp_max) { temp_max = hypre_cabs(A_diag_a[j]); } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { if (hypre_cabs(A_offd_a[j]) > temp_max) { temp_max = hypre_cabs(A_offd_a[j]); } } } B_maxel_row[k-1] = temp_max; // add one for diagonal element j = A_diag_i[i]; if (sub_idx_diag[A_diag_j[j]] != -1) { B_nnz_diag++; } // Count nnzs larger than tolerance times max row element for (j = A_diag_i[i]+1; j < A_diag_i[i+1]; j++) { if ( (sub_idx_diag[A_diag_j[j]] != -1) && (hypre_cabs(A_diag_a[j]) > (strength_thresh*temp_max)) ) { B_nnz_diag++; } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { if ( (sub_idx_offd[A_offd_j[j]] != -1) && (hypre_cabs(A_offd_a[j]) > (strength_thresh*temp_max)) ) { B_nnz_offd++; } } B_diag_i[k] = B_nnz_diag; B_offd_i[k] = B_nnz_offd; } hypre_assert(k == B_nrow_local); B_diag_j = hypre_TAlloc(HYPRE_Int, B_nnz_diag, HYPRE_MEMORY_HOST); B_diag_a = hypre_TAlloc(HYPRE_Complex, B_nnz_diag, HYPRE_MEMORY_HOST); B_offd_j = hypre_TAlloc(HYPRE_Int, B_nnz_offd, HYPRE_MEMORY_HOST); B_offd_a = hypre_TAlloc(HYPRE_Complex, B_nnz_offd, HYPRE_MEMORY_HOST); for (i = 0, k=0, k1 = 0, k2 = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i != row_set) { continue; } HYPRE_Real maxel = B_maxel_row[k]; k++; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { HYPRE_Int j1 = sub_idx_diag[A_diag_j[j]]; if ( (j1 != -1) && ( (hypre_cabs(A_diag_a[j]) > (strength_thresh*maxel)) || j==A_diag_i[i] ) ) { B_diag_j[k1] = j1; B_diag_a[k1] = A_diag_a[j]; k1++; } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { HYPRE_Int j1 = sub_idx_offd[A_offd_j[j]]; if ((j1 != -1) && (hypre_cabs(A_offd_a[j]) > (strength_thresh*maxel))) { hypre_assert(j1 >= 0 && j1 < num_cols_B_offd); B_offd_j[k2] = j1; B_offd_a[k2] = A_offd_a[j]; k2++; } } } hypre_assert(k1 == B_nnz_diag && k2 == B_nnz_offd); /* ready to create B = A(rowset, colset) */ B = hypre_ParCSRMatrixCreate(comm, B_nrow_global, B_ncol_global, B_row_starts, B_col_starts, num_cols_B_offd, B_nnz_diag, B_nnz_offd); B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrixMemoryLocation(B_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixData(B_diag) = B_diag_a; hypre_CSRMatrixI(B_diag) = B_diag_i; hypre_CSRMatrixJ(B_diag) = B_diag_j; B_offd = hypre_ParCSRMatrixOffd(B); hypre_CSRMatrixMemoryLocation(B_offd) = HYPRE_MEMORY_HOST; hypre_CSRMatrixData(B_offd) = B_offd_a; hypre_CSRMatrixI(B_offd) = B_offd_i; hypre_CSRMatrixJ(B_offd) = B_offd_j; hypre_ParCSRMatrixColMapOffd(B) = col_map_offd_B; hypre_ParCSRMatrixSetNumNonzeros(B); hypre_ParCSRMatrixDNumNonzeros(B) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(B); hypre_MatvecCommPkgCreate(B); *B_ptr = B; hypre_TFree(B_maxel_row, HYPRE_MEMORY_HOST); hypre_TFree(send_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(sub_idx_diag, HYPRE_MEMORY_HOST); hypre_TFree(sub_idx_offd, HYPRE_MEMORY_HOST); return hypre_error_flag; }
theta2h.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "compearth.h" /*! * @brief Computes h from dip angle theta as in Equation 24c of * Tape and Tape, 2015. * * @param[in] n Number of points in array * @param[in] theta Dip angle \f$ \theta \in [0, \pi/2] \f$. This * is an array of dimension [n]. * * @param[out] h h of Equation 24c \f$ h \in [0,1] \f$. This * is an array of dimension [n]. * * @copyright MIT * */ void compearth_theta2h(const int n, const double *__restrict__ theta, double *__restrict__ h) { int i; #pragma omp simd for (i=0; i<n; i++) { h[i] = cos(theta[i]); } return; }
pio.c
/* * pio.c: parallel input/output and CPU msp compute * * Created on: 2015-3-5 * Author: qiushuang */ #include <omp.h> #include <mpi.h> #include <math.h> #include "../include/io.h" #include "../include/dbgraph.h" #include "../include/msp.h" #include "../include/hash.h" #include "../include/bitkmer.h" #include "../include/share.h" #define USING_MPI_IO #define THREADS_MSP_OUTPUT THREADS_MSP_COMPUTE // parallel output threads should be the same number of parallel compute #define THREADS_MSP_META THREADS_MSP_COMPUTE // parallel output threads should be the same number of parallel compute #define THREADS_WRITE_GRAPH 128 #define MAX_IO_THREADS 1 #define MSSG_ROUNDUP 0.1 // should be set higher when each processor only contains a small number of partitions #define READ_RATIO_ROUNDUP 0.002 extern long cpu_threads; int read_length; // set the inital value in: init_input!!! static ull rid = 1; //read id with initialization to be 1, global to uniformly identify all reads; static uint unit_size; // unit size of one encoded read (without read id), set the inital value in: init_input!!! extern int cutoff; extern int mpi_run; /* for debug: */ int last_flag; int filter_number = 0; //static evaltime_t lds, lde; //extern float ldtime; float readfile_time = 0; double read_ratio; double mssg_factor = 0; ull * max_msp_malloc; extern int * dflag; extern int * queue; ull * read_size; size_t total_file_size_worker = 0; // total read size of a worker on an input file size_t file_size_offset = 0; // current file size that has been read of a worker MPI_File input_file; FILE * input; FILE * output; FILE ** mspout; length_range_t h_range; /******** input & output ********/ static seq_t * write_buffer; // buffer to write data to output file static ull write_offset; static ull write_size; // data size allocated for the write buffer /******** msp output & input *******/ static msp_meta_t * msp_meta[THREADS_MSP_META]; // msp output meta data //uint max_num_kmers = 0; //get the statistics when doing minimum substring partitioning //uint max_num_spks = 0; //uint max_spksize = 0; //uint max_num_kmers = 75609096; //hg7-512 data; used for initializing and testing, updated at the end of msp //uint max_num_spks = 7029665; //uint max_spksize = 68416697; //uint max_num_kmers=824616557; //bbb-512 //uint max_num_spks=60774697; //uint max_spksize=647034176; uint max_num_spks = 66774; uint max_spksize = 989232; uint max_num_kmers = 744293; ull total_num_edges = 0; ull distinct_edges = 0; ull total_num_vs = 0; int biggest_partition = 0; static uint spksize[NUM_OF_PARTITIONS]; static uint numspks[NUM_OF_PARTITIONS]; static uint numkmers[NUM_OF_PARTITIONS]; /* definitions of sequence information */ int table[256]; // lookup table for encoding data int check[256]; // check table for filtering illegal data static char rev_table[4] = {'A', 'C', 'G', 'T'}; #define INDEX(a, b) ((a) > (b) ? 1 : 0) #define sum(result, arr, n) { \ int i; \ for (i = 0; i < n; i++) \ result += arr[i]; } #define prefix(result, arr, n) { \ int i; \ for (i = 0; i < n; i++) \ result += arr[i]; } void init_lookup_table (void) { int i; for (i = 0; i < 256; i++) { table[i] = check[i] = -1; } table['A'] = table['a'] = 0; table['C'] = table['c'] = 1; table['G'] = table['g'] = 2; table['T'] = table['t'] = 3; table['N'] = table['n'] = 0; check['A'] = check['a'] = 0; check['C'] = check['c'] = 1; check['G'] = check['g'] = 2; check['T'] = check['t'] = 3; } void get_rev (char * read, char * rev, int len) { int i; for (i = 0; i < len; i++) { rev[i] = rev_table[read[len - i - 1] - 'A']; } } /* This function read one line to the str and return the length ('\n' included if it existed in the line), * or return 0 if the data is illegal */ int get_one_read (char ** pstr, offset_t * read_offset, size_t end) { int num_of_char = 0; int count = 0; // count number of illegal characters /* get one read -- be careful of illegal memory access if last line of data is abnormal */ // *pstr += *read_offset; if (**pstr == '\n') { (*read_offset)++; (*pstr)++; return 0; } while (*(*pstr + num_of_char) != '\n') { if(check[*(*pstr + num_of_char)] == -1) { ++count; // *(*pstr + num_of_char) = 'A'; } ++num_of_char; } if (count > CUTOFF_N || num_of_char != read_length) { *read_offset += num_of_char + 1; *pstr += num_of_char + 1; return 0; }/* illegal read: skip this line */ return (num_of_char + 1); } int get_one_read_2lines (char ** pstr, offset_t * read_offset, size_t end) { /* get one read -- be careful of illegal memory access if last line of data is abnormal */ if (**pstr == '+' || **pstr == '-') //must be fastq file: skip two lines { while (**pstr != '\n' && (*read_offset) < end) { (*read_offset)++; (*pstr)++; } (*read_offset)++; (*pstr)++; while (**pstr != '\n' && (*read_offset) < end) { (*read_offset)++; (*pstr)++; } (*read_offset)++; (*pstr)++; return 0; } if (**pstr == '>' || **pstr == '@') //skip one line and get one read { while (**pstr != '\n' && (*read_offset) < end) { (*read_offset)++; (*pstr)++; } (*read_offset)++; (*pstr)++; } int num_of_char = 0; int count = 0; // count number of illegal characters while (*(*pstr + num_of_char) != '\n' && (*read_offset + num_of_char) < end) { if(check[*(*pstr + num_of_char)] == -1) { ++count; // *(*pstr + num_of_char) = 'A'; } ++num_of_char; } if (count > CUTOFF_N || num_of_char != read_length) { *read_offset += num_of_char + 1; *pstr += num_of_char + 1; return 0; }/* illegal read: skip this line */ return (num_of_char + 1); } void skip_one_line (char ** pstr, offset_t * read_offset) { if (*(*pstr - 1) == '\n') return; while (*(*pstr)++ != '\n') { (*read_offset)++; } return; } double my_round(double number, unsigned int bits) { long long integerPart = number; number -= integerPart; unsigned int i; for (i = 0; i < bits; ++i) number *= 10; number = (long long) (number + 0.5); for (i = 0; i < bits; ++i) number /= 10; return integerPart + number; } // return number of reads / read size double estimate_num_reads_from_input (char * filename, int read_length) { FILE * input; if ((input = fopen(filename, "r")) == NULL) { printf ("Error: cannot open input file!\n"); exit (0); } int count = 0; char buf[2048]; char * ptr; offset_t roff; int i; int total_len = 0; for (i=0; i<128; i++) { int len; if ((len = strlen(fgets(buf, 2048, input))) == 2048) { printf ("Error in input file! please check it!\n"); exit (0); } total_len += len; int read_len; roff = 0; ptr = buf; if ((read_len = get_one_read (&ptr, &roff, 2048*1024)) != 0) // if ((read_len = get_one_read_2lines (&ptr, &roff, 2048*1024)) != 0) count++; } printf ("read ratio before return: %f\n", (float)count/total_len); read_ratio = (double)count/total_len; read_ratio = my_round (read_ratio, 3) + (READ_RATIO_ROUNDUP); return read_ratio; } int finalize_input (void) { fclose (input); return 0; } int finalize_mpi_input (void) { return MPI_File_close (&input_file); } int finalize_msp_input (FILE ** mspinput, int world_size) { int i; for (i=0; i<world_size; i++) fclose (mspinput[i]); return 0; } int init_code (seq_t * hcode_buffer) { return 0; } void reset_code_buffer (seq_t * code_buffer) { memset (code_buffer, 0, sizeof(seq_t) * CODE_BUF_SIZE); } int finalize_code (void) { return 0; } int init_output (char * filename) { if ((output = fopen (filename, "w")) == NULL) { printf ("Cannot open output file %s\n", filename); exit (0); } write_buffer = (seq_t *) malloc (sizeof(seq_t) * BUF_SIZE); CHECK_PTR_RETURN (write_buffer, "init write buffer malloc\n"); write_offset = 0; write_size = BUF_SIZE; return 0; } int finalize_output (void) { fclose (output); free (write_buffer); write_offset = 0; write_size = 0; return 0; } int init_msp_output (char * file_dir, int num_of_partitions, int world_rank) { int i; mspout = (FILE **) malloc (sizeof(FILE *) * num_of_partitions); CHECK_PTR_RETURN (mspout, "init msp output file pointers\n"); char temp[FILENAME_LENGTH]; memset (temp, 0, FILENAME_LENGTH * sizeof(char)); for (i = 0; i < num_of_partitions; i++) { sprintf (temp, "%s/msp%d_%d", file_dir, i, world_rank); if ((mspout[i] = fopen (temp, "w")) == NULL) { printf ("Can't open mspout file %d\n", i); exit (0); } } return 0; } void reset_msp_buffer (seq_t * msp_buf, offset_t * offset_ptr, uint mspid, uint part_buf_size) { memset (msp_buf + (ull) mspid * part_buf_size, 0, sizeof(seq_t) * part_buf_size); offset_ptr[mspid] = 0; } int finalize_msp_output (int num_of_partitions) { int i; for (i = 0; i < num_of_partitions; i++) { fclose (mspout[i]); } free (mspout); return 0; } void set_length_range (int k, int read_length) { // length_range_t range; int ave = read_length / AVE_NUM_SPK; h_range.l1 = 0; h_range.l4 = ave; h_range.l2 = ave / 3; h_range.l3 = ave / 3 * 2; h_range.l5 = h_range.l4 + (read_length - k - h_range.l4) / 2; // return range; } /* return the number of runs to process the whole input file */ int init_input (char * filename, int rlen, int world_size, int world_rank) { if ((input = fopen(filename, "r")) == NULL) { printf ("Error: cannot open input file!\n"); exit (0); } fseek (input, 0, SEEK_END); size_t file_size = ftell (input); size_t filesize_per_worker = (file_size + world_size - 1)/world_size; if (filesize_per_worker <= world_size) filesize_per_worker = file_size/world_size; size_t file_start = filesize_per_worker * world_rank; size_t file_end = file_start + filesize_per_worker; if(file_start > file_size) { file_start = file_size; } if(file_end > file_size) { file_end = file_size; } total_file_size_worker = file_end - file_start; int nstreams = (total_file_size_worker + BUF_SIZE - 1) / BUF_SIZE; //maximum number of streams fseek (input, file_start, SEEK_SET); read_length = rlen; unit_size = (read_length + 3) / 4; printf ("WORLD_RANK %d: number of streams : %d, unit_size of an encoded read: %d\n", world_rank, nstreams, unit_size); return nstreams; } size_t read_file (char * read_buf, int world_rank) { if (file_size_offset == 0 && world_rank != 0) // skip a line if necessary { fseek (input, -1, SEEK_CUR); fread (read_buf, 1, LINE, input); int offset=0; while (read_buf[offset++] != '\n') // skip a line { if (offset >= LINE) { printf ("error in reading an extra line!\n"); exit (-1); } } fseek (input, offset-LINE, SEEK_CUR); file_size_offset += offset; } // begin reading a bulk of file size_t read_size = fread ((char *)read_buf, 1, BUF_SIZE, input); if (total_file_size_worker <= file_size_offset + read_size) // end of reading file { int offset = 0; char *ptr = read_buf + (total_file_size_worker - file_size_offset); while (ptr[offset] != '\n' && offset < file_size_offset + read_size - total_file_size_worker) { offset++; } total_file_size_worker += offset; // point to the end read_size = total_file_size_worker - file_size_offset; } else { char * ptr = read_buf + read_size; int offset = 0; while (*(--ptr) != '\n') { offset++; if (offset >= LINE) { printf ("error in backing an extra line!\n"); exit (-1); } } fseek (input, ptr + 1 - (read_buf + read_size), SEEK_CUR); read_size = ptr + 1 - read_buf; } file_size_offset += read_size; return read_size; } int init_mpi_input (char * file_name, int rlen, int world_size, int world_rank) { MPI_Offset file_size, file_size_per_worker, file_start, file_end; if(MPI_File_open (MPI_COMM_WORLD, file_name, MPI_MODE_RDONLY, MPI_INFO_NULL, &input_file) != 0) { debug("Worker %d: can not open file %s for read!\n", world_rank, file_name); MPI_Abort (MPI_COMM_WORLD, -1); } MPI_File_get_size (input_file, &file_size); printf ("world rank %d: file size got: %lu\n", world_rank, file_size); file_size_per_worker = (file_size + world_size - 1) / world_size; file_start = world_rank * file_size_per_worker; file_end = file_start + file_size_per_worker; if(file_start > file_size) { file_start = file_size; } if(file_end > file_size) { file_end = file_size; } total_file_size_worker = file_end - file_start; int nstreams = (total_file_size_worker + BUF_SIZE - 1) / BUF_SIZE; //maximum number of streams // fseek (input, file_start, SEEK_SET); MPI_File_seek (input_file, file_start, MPI_SEEK_SET); read_length = rlen; unit_size = (read_length + 3) / 4; printf ("WORLD_RANK %d: number of streams : %d, unit_size of an encoded read: %d, total_file_size_worker=%lu, " "file_start=%lu, file_end=%lu\n", world_rank, nstreams, unit_size, total_file_size_worker, file_start, file_end); return nstreams; } size_t mpi_read_file (char * read_buf, int world_size, int world_rank) { if (file_size_offset == 0 && world_rank != 0) // skip a line if necessary { MPI_File_seek (input_file, -1, MPI_SEEK_CUR); MPI_File_read (input_file, read_buf, LINE, MPI_CHAR, MPI_STATUS_IGNORE); // fseek (input, -1, SEEK_CUR); // fread (read_buf, 1, LINE, input); int offset=0; while (read_buf[offset++] != '\n') // skip a line { if (offset >= LINE) { printf ("error in reading an extra line!\n"); MPI_Abort (MPI_COMM_WORLD, -1); } } MPI_File_seek (input_file, offset-LINE, MPI_SEEK_CUR); // fseek (input, offset-LINE, SEEK_CUR); file_size_offset += offset; printf ("WORLD RANK %d: offset skipped: %lu\n", world_rank, offset); } // begin reading a bulk of file size_t read_size; if (total_file_size_worker <= file_size_offset + BUF_SIZE) // end of reading file { read_size = total_file_size_worker - file_size_offset; if (world_rank != world_size - 1) { MPI_File_read (input_file, read_buf, read_size + LINE, MPI_CHAR, MPI_STATUS_IGNORE); int offset = 0; char *ptr = read_buf + read_size; while (ptr[offset++] != '\n') { if (offset >= LINE) { printf ("error in reading an extra line!\n"); MPI_Abort (MPI_COMM_WORLD, -1); } } total_file_size_worker += offset; // point to the end read_size = total_file_size_worker - file_size_offset; printf ("world rank %d: read_size = %d\n", world_rank, read_size); // MPI_File_seek (input_file, (offset-LINE), MPI_SEEK_CUR); } else { printf ("world rank %d: read_size = %d\n", world_rank, read_size); MPI_File_read (input_file, read_buf, read_size, MPI_CHAR, MPI_STATUS_IGNORE); } } else { MPI_File_read (input_file, read_buf, BUF_SIZE, MPI_CHAR, MPI_STATUS_IGNORE); char * ptr = read_buf + BUF_SIZE; while (*(--ptr) != '\n') {} MPI_File_seek (input_file, -(read_buf + BUF_SIZE - ptr - 1), MPI_SEEK_CUR); // fseek (input, ptr + 1 - (read_buf + read_size), SEEK_CUR); read_size = ptr + 1 - read_buf; } file_size_offset += read_size; return read_size; } /* Encode one read with 2 bit per character, length for one read: (read_length + 3) / 4 */ uch bitcode (seq_t * code_buf, seq_t * line_buf, uch len) { uch i; for (i = 0; i < len; i++) { code_buf[i / 4] |= table[line_buf[i]] << ((3 - (i % 4)) * 2); } return ( (len + 3) / 4 ); } /* test this: */ uch bitcode_reverse (seq_t * code_buf, seq_t * line_buf, uch len) { uch i; for (i = 0; i < len; i++) { code_buf[i / 4] |= (3 - table[line_buf[len - 1 - i]]) << ((3 - (i % 4)) * 2); } return ( (len + 3) / 4 ); } static int encode_kmer (unit_kmer_t * kmer, seq_t * read, int k) { if (k*2 > (KMER_UNIT_LENGTH * KMER_UNIT_BITS)) { printf ("kmer length exceeds the limit!\n"); exit(0); } int unit_length = k*2/KMER_UNIT_BITS; int i = 0; int j = 0; for (; i<unit_length; i++) { *kmer = 0; int j; for (j=0; j<(KMER_UNIT_BITS)/2; j++) { *kmer |= table[read[i*(KMER_UNIT_BITS)/2 + j]] << (KMER_UNIT_BITS - 2 - j*2); } kmer++; } if ((k*2)%KMER_UNIT_BITS) *kmer = 0; for (j=0; j<((k*2)%KMER_UNIT_BITS)/2; j++) { *kmer |= table[read[i*(KMER_UNIT_BITS)/2 + j]] << (KMER_UNIT_BITS - 2 - j*2); } return unit_length; } /* decode encoded sequences (either reads or superkmers) */ uch decode (seq_t * dec_buf, seq_t * read_ptr, uch len) { int i; for (i = 0; i < len; i++) { dec_buf[i] = rev_table[(read_ptr[i / 4] >> ((3 - i % 4) * 2)) & 0x3]; } dec_buf[i] = '\n'; return ((len + 3) / 4); // return number of bytes of encoded string } char * get_min (char * read, char * rev, int k, int p) { int i = 0; char * pstr; char * rpstr; char * minpstr; char * rminpstr; pstr = minpstr = read; rpstr = rminpstr = rev; for (i = 1; i < k - p + 1; i++) { pstr++; rpstr++; if (strncmp (pstr, minpstr, p) < 0) { minpstr = pstr; } if (strncmp (rpstr, rminpstr, p) < 0) { rminpstr = rpstr; } } if (strncmp (minpstr, rminpstr, p) <= 0) { return minpstr; } else return rminpstr; } uint compute_msp (int t, int p, int k, int num_of_partitions, char * read_buffer[], ull read_size, uch * d_msp_ptr, char ** rbufs[], uint * rnums[]) { omp_set_num_threads (cpu_threads); #pragma omp parallel { //****** test number of threads ******* int nths = omp_get_num_threads (); int thid = omp_get_thread_num (); if (nths != cpu_threads) { printf ("ERROR!!!!!! NUMBER OF THREADS: %d\n", nths); exit(1); } int turn = t; ull msp_malloc = max_msp_malloc[turn]; ull max_num_ms = read_length - k + 1; // float time = 0; ull time = 0; evaltime_t start, end; // printf ("id: %d, num of threads: %d\n", thid, nths); //******* Be careful: read_size may not be divided by cpu_threads! ********** size_t read_size_per_thread = (read_size + cpu_threads - 1) / cpu_threads; if (read_size_per_thread <= cpu_threads) read_size_per_thread = read_size / cpu_threads; char * read_ptr = read_buffer[turn] + thid * read_size_per_thread; if (thid == cpu_threads - 1) { read_size_per_thread = read_size - read_size_per_thread * thid; if (read_size - read_size_per_thread * thid < 0) printf ("ATTENTION!!! calculate read size per thread error!!!\n"); } uint rnum = 0; int len; offset_t roffset = 0; // offset_t coffset = 0; if (thid > 0) skip_one_line (&read_ptr, &roffset); //* if the thread reads starting at the middle of a line, then this line will be processed by its predecessor, thus it skip this line * rbufs[turn][thid] = read_ptr; // Store the start position of each read buffer area for each thread //******* initiate msp variables ********* char * read; char revs[read_length]; char * minpos; char * search; msp_t d_msp; uint num_of_reads = read_size * read_ratio; uint num_reads_per_thread = (num_of_reads + cpu_threads - 1) / cpu_threads; if (num_reads_per_thread <= cpu_threads) num_reads_per_thread = num_of_reads / cpu_threads; // ull msp_malloc = max_msp_malloc[turn]; ull usize = max_num_ms * sizeof(msp_id_t) + sizeof(uch) * max_num_ms + 1; ull align_size = sizeof(msp_id_t) - sizeof(uch) * (max_num_ms + 1) * num_reads_per_thread % sizeof(msp_id_t); d_msp.nums = d_msp_ptr + (usize * num_reads_per_thread + align_size) * thid; d_msp.poses = d_msp.nums + sizeof(uch) * num_reads_per_thread; d_msp.ids = (msp_id_t *)(d_msp.nums + sizeof(uch) * (max_num_ms + 1) * num_reads_per_thread + (sizeof(msp_id_t) - sizeof(uch) * (max_num_ms + 1) * num_reads_per_thread % sizeof(msp_id_t))); size_t read_size_end; if (thid == nths - 1) read_size_end = read_size_per_thread - 1; else read_size_end = read_size_per_thread; while (roffset < read_size_end) { if (rnum >= num_reads_per_thread) { printf ("maximum number of reads exceeds the initial set up! please reset the input buffer!!" "rnum = %u, num_reads_per_thread = %u\n", rnum, num_reads_per_thread); exit(0); } if ((len = get_one_read (&read_ptr, &roffset, read_size_end)) == 0) // if ((len = get_one_read_2lines (&read_ptr, &roffset, read_size_end)) == 0) continue; read = read_ptr; gettimeofday (&start, NULL); //******* COMPUTING MSP INFO FOR A READ BEGINS ********* get_rev (read, revs, read_length); int i = 0; uch num = 0; minpos = get_min (read + i, revs + (read_length - k - i), k, p); #ifdef LONG_KMER kmer_t kmer = {0, 0, 0, 0}; #else kmer_t kmer = {0, 0}; #endif encode_kmer ((unit_kmer_t*)&kmer, read+i, k); // d_msp.ids[rnum * max_num_ms + num] = get_partition_id_from_string (minpos, p, num_of_partitions); d_msp.ids[rnum * max_num_ms + num] = get_pid_from_kmer(&kmer, k, p, num_of_partitions); d_msp.poses[rnum * max_num_ms + num] = 0; msp_id_t old, new; old = d_msp.ids[rnum * max_num_ms + num]; for (i = 1; i < read_length - k + 1; i++) { search = get_min (read + i, revs + (read_length - k - i), k, p); kmer.x=0; kmer.y=0; #ifdef LONG_KMER kmer.z=0; kmer.w=0; #endif encode_kmer ((unit_kmer_t*)&kmer, read+i, k); new = get_pid_from_kmer(&kmer, k, p, num_of_partitions); // if (strncmp (search, minpos, p) != 0) if (new != old) { num++; // be careful: num may exceeds max_num_ms! if (num > max_num_ms) { printf ("number of %d-minimum-substring exceeds the predefined limit for output!\n", p); exit(0); } // d_msp.ids[rnum * max_num_ms + num] = get_partition_id_from_string (search, p, num_of_partitions); d_msp.ids[rnum * max_num_ms + num] = new; d_msp.poses[rnum * max_num_ms + num] = i; // test this minpos = search; old = new; } } d_msp.nums[rnum] = num; #ifdef DEBUG if (num >= max_num_ms) { printf ("Careful: number of superkmers exceeds predefined size!\n"); exit (0); } #endif //****** COMPUTING MSP INFO FOR A READ ENDS ******* gettimeofday (&end, NULL); time += ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)); roffset += len; read_ptr += len; // coffset += unit_size; rnum++; } // reads->offset[thid] = coffset; rnums[turn][thid] = rnum; // msp_time[thid] += time; } uint num_of_reads = 0; sum(num_of_reads, rnums[t], cpu_threads); // printf ("number of reads counted: %d\n", num_of_reads); return num_of_reads; } uint parse_data (char ** read_buffer, read_buf_t * reads, ull read_size, int turn, char *** rbufs, uint ** rnums) { seq_t * code_buffer = reads->buf; reset_code_buffer (code_buffer); // set element to 0! omp_set_num_threads (cpu_threads); #pragma omp parallel { //******* test number of threads ********* int nths = omp_get_num_threads (); int thid = omp_get_thread_num (); if (nths != cpu_threads) { printf ("ERROR!!!!!! NUMBER OF THREADS: %d\n", nths); exit(1); } //******** Be careful: read_size may not be divided by cpu_threads! ********* size_t read_size_per_thread = (read_size + cpu_threads - 1) / cpu_threads; if (read_size_per_thread <= cpu_threads) read_size_per_thread = read_size / cpu_threads; char * read_ptr = read_buffer[turn] + thid * read_size_per_thread; seq_t * code_ptr = code_buffer + thid * (CODE_BUF_SIZE / cpu_threads); if (thid == cpu_threads - 1) { read_size_per_thread = read_size - read_size_per_thread * (cpu_threads - 1); if (read_size - read_size_per_thread * thid < 0) printf ("!!! ATTENTION: read_size per thread for the last thread error!!!\n"); } uint rnum = 0; int len; offset_t roffset = 0; offset_t coffset = 0; if (thid > 0) skip_one_line (&read_ptr, &roffset); //******* if the thread reads starting at the middle of a line, then this line will be processed by its predecessor, thus it skip this line ***** rbufs[turn][thid] = read_ptr; // Store the start position of each read buffer area for each thread size_t end; if (thid == nths - 1) end = read_size_per_thread - 1; else end = read_size_per_thread; while (roffset < end) { if ((len = get_one_read (&read_ptr, &roffset, end)) == 0) // if ((len = get_one_read_2lines (&read_ptr, &roffset, end)) == 0) continue; bitcode (code_ptr + coffset, read_ptr, read_length); roffset += len; read_ptr += len; coffset += unit_size; rnum++; } if (roffset >= read_size_per_thread) { // printf ("thid: %d, roffset - read_size_per_thread = %lu\n", thid, roffset - read_size_per_thread); // exit(0); } reads->offset[thid] = coffset; rnums[turn][thid] = rnum; } // reads->buf = code_buffer; uint num_of_reads = 0; sum(num_of_reads, rnums[turn], cpu_threads); // printf ("total number of reads processed in parsing data for GPU: %u\n", num_of_reads); return num_of_reads; } void init_msp_meta (int num_of_partitions, double read_ratio, int read_length, int k) { int i, j; uint msp_meta_size = ceil(BUF_SIZE * read_ratio * (read_length - k + 1) * 2/ (num_of_partitions * NUM_OF_RANGES * cpu_threads)); printf ("msp meta size: %u\n", msp_meta_size); for (i = 0; i < cpu_threads; i++) { msp_meta[i] = (msp_meta_t *) malloc (sizeof(msp_meta_t) * num_of_partitions * NUM_OF_RANGES); CHECK_PTR_RETURN (msp_meta[i], "init msp meta array\n"); for (j = 0; j < num_of_partitions * NUM_OF_RANGES; j++) { msp_meta[i][j].idarr = (rid_t *) malloc (sizeof(rid_t) * msp_meta_size); msp_meta[i][j].lenarr = (uch *) malloc (sizeof(uch) * msp_meta_size); msp_meta[i][j].spkbuf = (seq_t *) malloc (sizeof(seq_t) * msp_meta_size * (unit_size+1)); CHECK_PTR_RETURN (msp_meta[i][j].idarr, "init msp meta id array\n"); CHECK_PTR_RETURN (msp_meta[i][j].lenarr, "init msp meta length array\n"); CHECK_PTR_RETURN (msp_meta[i][j].spkbuf, "init msp meta spkbuf error!\n"); msp_meta[i][j].size = msp_meta_size; msp_meta[i][j].spksize = msp_meta_size * unit_size; msp_meta[i][j].offset = 0; msp_meta[i][j].spkoffset = 0; msp_meta[i][j].num_kmers = 0; } } memset (spksize, 0, sizeof(uint) * NUM_OF_PARTITIONS); memset (numspks, 0, sizeof(uint) * NUM_OF_PARTITIONS); memset (numkmers, 0, sizeof(uint) * NUM_OF_PARTITIONS); } //***** set offset of one msp buffer meta information to 0 ******* void reset_msp_meta (msp_meta_t * meta) { meta->offset = 0; meta->spkoffset = 0; meta->num_kmers = 0; memset (meta->spkbuf, 0, sizeof(seq_t) * meta->spksize); } //******** expand one particular msp meta buffer by twice ******** void expand_msp_meta (msp_meta_t * meta) { meta->idarr = (rid_t *) realloc (meta->idarr, sizeof(rid_t) * meta->size * 2); meta->lenarr = (uch *) realloc (meta->lenarr, sizeof(uch) * meta->size * 2); CHECK_PTR_RETURN (meta->idarr, "expand msp meta id array\n"); CHECK_PTR_RETURN (meta->lenarr, "expand msp length array\n"); meta->size *= 2; } void expand_meta_spks (msp_meta_t * meta) { meta->spkbuf = (seq_t *) realloc (meta->spkbuf, sizeof(seq_t) * meta->spksize * 2); CHECK_PTR_RETURN (meta->spkbuf, "expand msp meta superkmer buffer\n"); meta->spksize *= 2; } void finalize_msp_meta (int k, int num_of_partitions, offset_t * max_kmers, offset_t * max_spks, offset_t * max_spksizes, int world_size, int world_rank) { int i, j; for (i = 0; i < num_of_partitions; i++) { if (max_spks[world_rank] < numspks[i]) { max_spks[world_rank] = numspks[i]; } if (max_spksizes[world_rank] < spksize[i]) { max_spksizes[world_rank] = spksize[i]; // max_num_kmers = max_spksize * 4 - k * numspks[i]; } if (max_kmers[world_rank] < numkmers[i]) { max_kmers[world_rank] = numkmers[i]; biggest_partition = i; } } for (i = 0; i < cpu_threads; i++) { for (j = 0; j < num_of_partitions * NUM_OF_RANGES; j++) { free(msp_meta[i][j].idarr); free(msp_meta[i][j].lenarr); free(msp_meta[i][j].spkbuf); } free(msp_meta[i]); } if (mpi_run > 0) { printf ("world rank %d: gathering numbers:::::::::::::::::::\n", world_rank); max_num_spks = max_spks[world_rank]; max_spksize = max_spksizes[world_rank]; max_num_kmers = max_kmers[world_rank]; MPI_Allgather (&max_num_spks, 1, MPI_INT, max_spks, 1, MPI_INT, MPI_COMM_WORLD); MPI_Allgather (&max_spksize, 1, MPI_INT, max_spksizes, 1, MPI_INT, MPI_COMM_WORLD); MPI_Allgather (&max_num_kmers, 1, MPI_INT, max_kmers, 1, MPI_INT, MPI_COMM_WORLD); } max_num_kmers = 0; max_num_spks = 0; max_spksize = 0; for (i=0; i<world_size; i++) { max_num_kmers += max_kmers[i]; max_num_spks += max_spks[i]; max_spksize += max_spksizes[i]; } printf ("WORLD_RANK %d: ----------------FINALIZE MSP META: max_num_spks %u, max_spksize %u, max_num_kmers %u, biggest partition %d " "----------\n", world_rank, max_num_spks, max_spksize, max_num_kmers, biggest_partition); } void output_msp_cpu (uch * msp_arr, char ** rbufs[], uint * rnums[], int k, int num_of_partitions, int wrt_id, int world_rank) { int turn = queue[wrt_id]; omp_set_num_threads (cpu_threads); #pragma omp parallel { length_range_t range = h_range; //******** test number of threads ********* int nths = omp_get_num_threads (); int thid = omp_get_thread_num (); if (nths != cpu_threads) { printf ("ERROR!!!!!!!!!set number of threads failure!!!!!! real number of threads:%d\n", nths); // exit (1); } char * read_ptr = rbufs[turn][thid]; int rlen; msp_id_t mspid; uch len; uch num; offset_t read_offset = 0; // rescan from the beginning of read buffer ull i, j; uint scan = 0; prefix(scan, rnums[turn], thid); uint local_rid = rid + scan; int local_k = k; uch * spk_nums; uch * spk_poses; msp_id_t * spk_ids; uint num_of_reads; ull max_num_ms = read_length - k + 1; msp_meta_t * meta_ptr = msp_meta[thid]; if (dflag[turn] == 0) // turn is from processing result of CPU { num_of_reads = read_size[turn] * read_ratio; uint num_reads_per_thread = (num_of_reads + cpu_threads - 1) / cpu_threads; if (num_reads_per_thread <= cpu_threads) num_reads_per_thread = num_of_reads / cpu_threads; // ull msp_malloc = max_msp_malloc[turn]; ull usize = max_num_ms * sizeof(msp_id_t) + sizeof(uch) * max_num_ms + 1; ull align_size = sizeof(msp_id_t) - sizeof(uch) * (max_num_ms + 1) * num_reads_per_thread % sizeof(msp_id_t); spk_nums = msp_arr + (usize * num_reads_per_thread + align_size) * thid; //******** be careful here, num_reads_per_thread may not be a precise estimation for each thread, in this case, thread access to partitioned buffer may cause error!!!!!!!!!!!!!! // spk_nums = msp_arr + msp_malloc / cpu_threads * thid; spk_poses = spk_nums + sizeof(uch) * num_reads_per_thread; spk_ids = (msp_id_t *)(spk_nums + sizeof(uch) * (max_num_ms + 1) * num_reads_per_thread + (sizeof(msp_id_t) - sizeof(uch) * (max_num_ms + 1) * num_reads_per_thread % sizeof(msp_id_t))); } else // turn is from processing result of GPU { num_of_reads = 0; sum(num_of_reads, rnums[turn], cpu_threads); // printf ("number of reads in output msp from GPU(s): %u\n", num_of_reads); msp_t mspptr; mspptr.nums = msp_arr; mspptr.poses = msp_arr + sizeof(uch) * num_of_reads; mspptr.ids = (msp_id_t *)(msp_arr + sizeof(uch) * (max_num_ms + 1) * num_of_reads + (sizeof(msp_id_t) - sizeof(uch) * (max_num_ms + 1) * num_of_reads % sizeof(msp_id_t))); spk_nums = mspptr.nums + scan; spk_poses = mspptr.poses + scan * max_num_ms; spk_ids = mspptr.ids + scan * max_num_ms; } uint read_num = rnums[turn][thid]; // printf ("number of reads processed in msp_compute of partition %d thread %d: %u\n", turn, thid, read_num); size_t read_size_per_thread = (read_size[turn] + cpu_threads - 1) / cpu_threads; if (read_size_per_thread <= cpu_threads) read_size_per_thread = read_size[turn] / cpu_threads; if (thid == cpu_threads - 1) { read_size_per_thread = read_size[turn] - read_size_per_thread * (cpu_threads - 1); if (read_size[turn] - read_size_per_thread * thid < 0) printf ("!!! ATTENTION: read_size per thread for the last thread error!!!\n"); } size_t read_size_end; if (thid == nths - 1) read_size_end = read_size_per_thread - 1; else read_size_end = read_size_per_thread; //********* cut reads into superkmers; process read by read ******** for (i = 0; i < read_num; i++) { /* Get one legal read from read buffer */ while ((rlen = get_one_read (&read_ptr, &read_offset, read_size_end)) == 0) {} // while ((rlen = get_one_read_2lines (&read_ptr, &read_offset, read_size_end)) == 0) {} num = spk_nums[i]; // number of superkmers for (j = 0; j < num; j++) { mspid = spk_ids[i * max_num_ms + j]; /* for debug only: */ #ifdef DEBUG if (mspid >= num_of_partitions) { print_error ("error in msp array id!\n"); while (1) {}; } #endif len = spk_poses[i * max_num_ms + j + 1] - spk_poses[i * max_num_ms + j] + 1; // kmern[mspid] += len; mspid = mspid * NUM_OF_RANGES + INDEX(len, (range.l1)) + INDEX(len, (range.l2)) + INDEX(len, (range.l3)) + INDEX(len, (range.l4)) + INDEX(len, (range.l5)) - 1; meta_ptr[mspid].idarr[meta_ptr[mspid].offset] = local_rid; if (j == 0) { meta_ptr[mspid].spkoffset += bitcode (meta_ptr[mspid].spkbuf + meta_ptr[mspid].spkoffset, read_ptr + spk_poses[i * max_num_ms + j], len + local_k - 1); meta_ptr[mspid].num_kmers += len; meta_ptr[mspid].lenarr[meta_ptr[mspid].offset] = len - 1; // set the most significant bit to be 0 } else { meta_ptr[mspid].spkoffset += bitcode (meta_ptr[mspid].spkbuf + meta_ptr[mspid].spkoffset, read_ptr + spk_poses[i * max_num_ms + j] - 1, len + local_k); meta_ptr[mspid].num_kmers += len; meta_ptr[mspid].lenarr[meta_ptr[mspid].offset] = len | 0x80; // set the most significant bit to be 1 } meta_ptr[mspid].offset++; if (meta_ptr[mspid].offset >= meta_ptr[mspid].size-1) { printf ("Expand msp meta happened!\n"); expand_msp_meta (meta_ptr + mspid); printf ("Expand msp meta spk happened!\n"); expand_meta_spks (meta_ptr + mspid); } } //* end of the read * mspid = spk_ids[i * max_num_ms + j]; //* for debug only: * #ifdef DEBUG if (mspid >= num_of_partitions) { print_error ("error in msp array id!\n"); while (1) {}; } #endif len = read_length - spk_poses[i * max_num_ms + j] - local_k + 1; // kmern[mspid] += len; mspid = mspid * NUM_OF_RANGES + INDEX(len, (range.l1)) + INDEX(len, (range.l2)) + INDEX(len, (range.l3)) + INDEX(len, (range.l4)) + INDEX(len, (range.l5)) - 1; meta_ptr[mspid].idarr[meta_ptr[mspid].offset] = local_rid; if (j == 0) { meta_ptr[mspid].spkoffset += bitcode (meta_ptr[mspid].spkbuf + meta_ptr[mspid].spkoffset, read_ptr + spk_poses[i * max_num_ms + j], len + local_k - 1); meta_ptr[mspid].num_kmers += len; meta_ptr[mspid].lenarr[meta_ptr[mspid].offset] = len; // set the most significant bit to be 0 } /* full read: take care of this case ! */ else { meta_ptr[mspid].spkoffset += bitcode_reverse (meta_ptr[mspid].spkbuf + meta_ptr[mspid].spkoffset, read_ptr + spk_poses[i * max_num_ms + j] - 1, len + local_k); meta_ptr[mspid].num_kmers += len; meta_ptr[mspid].lenarr[meta_ptr[mspid].offset] = len; // set the most significant bit to be 0 }/* store the reverse instead of forward kmer */ meta_ptr[mspid].offset++; if (meta_ptr[mspid].offset >= meta_ptr[mspid].size-1) { printf ("Expand msp meta happened!\n"); expand_msp_meta (meta_ptr + mspid); printf ("Expand msp meta spk happened!\n"); expand_meta_spks (meta_ptr + mspid); } read_offset += rlen; read_ptr += rlen; local_rid++; // global read id identification } } //**** finally write out msp buffers to files **** FILE * file; int i, j, t; omp_set_num_threads (MAX_IO_THREADS); #pragma omp parallel private(file, i, j, t) { int thid = omp_get_thread_num (); int io_th = num_of_partitions / MAX_IO_THREADS; int ios; if (thid == MAX_IO_THREADS - 1) ios = num_of_partitions - io_th * thid; else ios = io_th; int r; for (r = 0; r < ios; r++) { file = mspout[thid * io_th + r]; // fwrite (&kmercnt[i], 1, sizeof(uint), file); for (j = 0; j < NUM_OF_RANGES; j++) { for (t = 0; t < cpu_threads; t++) { if (msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].offset == 0) continue; fwrite (&(msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].offset), 1, sizeof(uint), file); fwrite (&(msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].spkoffset), 1, sizeof(offset_t), file); fwrite (msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].idarr, sizeof(rid_t), msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].offset, file); fwrite (msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].lenarr, sizeof(uch), msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].offset, file); fwrite (msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].spkbuf, sizeof(seq_t), msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].spkoffset, file); spksize[thid * io_th + r] += msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].spkoffset; numspks[thid * io_th + r] += msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j].offset; numkmers[thid * io_th + r] += msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES +j].num_kmers; reset_msp_meta (&msp_meta[t][(thid * io_th + r) * NUM_OF_RANGES + j]); } } } } sum(rid, rnums[turn], cpu_threads); } uint * prefix_sum (uch * lenarr, uint * indices, uint size, int k, uint * num_of_kmers) { uint i; indices[0] = 0; uint len; for (i = 1; i < size + 1; i++) { len = lenarr[i - 1] & 0x7f; *num_of_kmers += len; indices[i] = (len + k) + 3; if (len + k - 1 == read_length) indices[i] -= 1; indices[i] /= 4; indices[i] += indices[i - 1]; if (lenarr[i - 1] & 0x80) *num_of_kmers -= 1; } return indices; } uint get_superkmers (char * filename[], spkmer_t * spkmers, int k, FILE ** mspinput) { uint num_of_kmers = 0; uint num_of_spk; uint total_num_of_spk = 0; uint rid_offset = 0; uint len_offset = 0; rid_t * ridarr; uch * lenarr; // uint * indices; uint read_size = 0; offset_t mspsize; // size of superkmer string ull total_mspsize = 0; ull offset; // offset of reading input superkmer file size_t file_size[NUM_OF_RANGES]; int i; for(i = 0; i < NUM_OF_RANGES; i++) { if( (mspinput[i] = fopen (filename[i], "r")) == NULL) printf ("Cannot open msp file %s\n", filename[i]); fseek (mspinput[i], 0, SEEK_END); if ((file_size[i] = ftell (mspinput[i])) == 0) { // fclose (mspinput[i]); continue; } fseek (mspinput[i], 0, SEEK_SET); while (ftell (mspinput[i]) < file_size[i]) { fread (&num_of_spk, 1, sizeof(uint), mspinput[i]); fread (&mspsize, 1, sizeof(offset_t), mspinput[i]); total_num_of_spk += num_of_spk; total_mspsize += mspsize; offset = num_of_spk * (sizeof(rid_t) + sizeof(uch)) + mspsize * sizeof(seq_t); fseek (mspinput[i], offset, SEEK_CUR); } } if (total_num_of_spk == 0) return 0; ridarr = (rid_t *) malloc (sizeof(rid_t) * total_num_of_spk); lenarr = (uch *) malloc (sizeof(uch) * total_num_of_spk); // indices = (uint *) malloc (sizeof(uint) * total_num_of_spk); //**** Allocate read buffer memory **** seq_t * read_buffer = (seq_t *) malloc (sizeof(seq_t) * total_mspsize); CHECK_PTR_RETURN (ridarr, "init spk rid array malloc with file %s\n", filename[i]); CHECK_PTR_RETURN (lenarr, "init spk length array malloc with file %s\n", filename[i]); CHECK_PTR_RETURN (read_buffer, "init read buffer for getting superkmers with file %s\n", filename[i]); // CHECK_PTR_RETURN (indices, "malloc spk indices array in prefix_sum\n"); for (i = 0; i < NUM_OF_RANGES; i++) { fseek (mspinput[i], 0, SEEK_SET); while (ftell (mspinput[i]) < file_size[i]) { fread (&num_of_spk, 1, sizeof(uint), mspinput[i]); fread (&mspsize, 1, sizeof(offset_t), mspinput[i]); rid_offset += fread (ridarr + rid_offset, sizeof(rid_t), num_of_spk, mspinput[i]); len_offset += fread (lenarr + len_offset, sizeof(uch), num_of_spk, mspinput[i]); read_size += fread (read_buffer + read_size, sizeof(seq_t), mspsize, mspinput[i]); } } // prefix_sum (lenarr, indices, total_num_of_spk, k, &num_of_kmers); spkmers->spks = read_buffer; spkmers->ridarr = ridarr; spkmers->lenarr = lenarr; spkmers->num = total_num_of_spk; // spkmers->indices = indices; return total_num_of_spk; } msp_stats_t get_spk_stats (int pid, int world_size, char * msp_dir, FILE ** mspinput) { offset_t num_of_spk; offset_t total_num_of_spk = 0; msp_stats_t stats = {0, 0}; char filename[FILENAME_LENGTH]; offset_t mspsize; // size of superkmer string size_t total_mspsize = 0; size_t offset; // offset of reading input superkmer file size_t file_size; int i; for(i = 0; i < world_size; i++) { memset (filename, 0, sizeof(char)*FILENAME_LENGTH); sprintf (filename, "%s/msp%d_%d", msp_dir, pid, i); if( (mspinput[i] = fopen (filename, "r")) == NULL) printf ("Cannot open msp file %s\n", filename); fseek (mspinput[i], 0, SEEK_END); if ((file_size = ftell (mspinput[i])) == 0) { // fclose (mspinput[i]); continue; // return stats; } fseek (mspinput[i], 0, SEEK_SET); while (ftell (mspinput[i]) < file_size) { fread (&num_of_spk, 1, sizeof(uint), mspinput[i]); fread (&mspsize, 1, sizeof(offset_t), mspinput[i]); total_num_of_spk += num_of_spk; total_mspsize += mspsize; offset = num_of_spk * (sizeof(rid_t) + sizeof(uch)) + mspsize * sizeof(seq_t); fseek (mspinput[i], offset, SEEK_CUR); } } stats.spk_num = total_num_of_spk; stats.spk_size = total_mspsize; return stats; } uint load_superkmers (FILE ** mspinput, rid_t * ridarr, uch * lenarr, uint * indices, seq_t * read_buffer, uint total_num_of_spk, int k, int world_size) { // gettimeofday (&lds, NULL); uint num_of_kmers = 0; uint num_of_spk; uint rid_offset = 0; uint len_offset = 0; uint read_size = 0; offset_t mspsize; // size of superkmer string ull total_mspsize = 0; size_t file_size; int i; for (i = 0; i < world_size; i++) { fseek (mspinput[i], 0, SEEK_END); if ((file_size = ftell (mspinput[i])) == 0) { // fclose (mspinput[i]); continue; // return 0; } fseek (mspinput[i], 0, SEEK_SET); while (ftell (mspinput[i]) < file_size) { fread (&num_of_spk, 1, sizeof(uint), mspinput[i]); fread (&mspsize, 1, sizeof(offset_t), mspinput[i]); rid_offset += fread (ridarr + rid_offset, sizeof(rid_t), num_of_spk, mspinput[i]); len_offset += fread (lenarr + len_offset, sizeof(uch), num_of_spk, mspinput[i]); read_size += fread (read_buffer + read_size, sizeof(seq_t), mspsize, mspinput[i]); } } // gettimeofday (&lde, NULL); // ldtime += (float)((lde.tv_sec * 1000000 + lde.tv_usec) - (lds.tv_sec * 1000000 + lds.tv_usec)) / 1000; prefix_sum (lenarr, indices, total_num_of_spk, k, &num_of_kmers); return num_of_kmers; } void decode_kmer (kmer_t * kmer, seq_t * line_buf, int k) { int i; unit_kmer_t * kmer_ptr = (unit_kmer_t *) kmer; for (i = 0; i < k; i ++) { line_buf[i] = rev_table[(*(kmer_ptr + i / KMER_UNIT_CHAR_LENGTH) >> (KMER_UNIT_BITS - 2 * (i % KMER_UNIT_CHAR_LENGTH + 1))) & 0x3]; } } uint write_graph (dbgraph_t * graph, int k) { // printf ("++++++++++++write graph+++++++++++\n"); // uint num = graph->num; uint countn = 0; uint size = graph->size; node_t * nodes = graph->nodes; seq_t * line_buf = (seq_t *) malloc (sizeof(seq_t) * LINE); CHECK_PTR_RETURN (line_buf, "init line buffer for decoding kmer in write_graph\n"); memset (line_buf, 0, sizeof(seq_t) * LINE); // printf ("graph size %u, graph nodes: %p\n", size, graph->nodes); uint i; uch j; int sum; uint total_edges = 0; uint total_distinct_edges = 0; omp_set_num_threads (cpu_threads); #pragma omp parallel private(i, j, sum) reduction(+:countn) reduction(+:total_edges) reduction(+:total_distinct_edges) { int thid = omp_get_thread_num (); // printf ("write graph id %d\n", thid); uint local_countn = 0; uint num_edges = 0; uint distinct_num_edges = 0; uint size_per_thread = (size + cpu_threads - 1) / cpu_threads; if (size_per_thread <= cpu_threads) size_per_thread = size / cpu_threads; node_t * local_nodes = nodes + size_per_thread * thid; if (thid == cpu_threads - 1) size_per_thread = size - size_per_thread * (thid); if (size - size_per_thread * thid < 0) printf ("ATTENTION!!! size_per_thread error!!! %ld\n", size - size_per_thread); for (i = 0; i < size_per_thread; i++) { if (local_nodes[i].occupied == 0) continue; /* sum = 0; for (j = 0; j < EDGE_DIC_SIZE; j++) { sum += local_nodes[i].edge[j]; } if (sum < cutoff) continue;*/ if (local_nodes[i].occupied != 2) { printf ("error!\n"); exit(0); } for (j = 0; j < EDGE_DIC_SIZE; j++) { // num_edges += local_nodes[i].edge[j] & 0xff; num_edges += *((ull*)&(local_nodes[i].edge)) >> (8 * j) & 0xff; if (*((ull*)&(local_nodes[i].edge)) >> (8 * j) & 0xff) distinct_num_edges += 1; } local_countn++; /* decode_kmer (&(nodes[i].kmer), line_buf, k); write_offset += sprintf (write_buffer + write_offset, "%s\t", line_buf); for (j = 0; j < 4; j++) { write_offset += sprintf (write_buffer + write_offset, "%c\t%d\t", rev_table[j], nodes[i].edge[j]); } for (; j < EDGE_DIC_SIZE; j++) { write_offset += sprintf (write_buffer + write_offset, "%c\t%d\t", rev_table[j - 4], nodes[i].edge[j]); } write_offset += sprintf (write_buffer + write_offset, "%u\n", nodes[i].rid); if (write_offset + LINE * 2 >= write_size) { fwrite (write_buffer, sizeof(seq_t), write_offset, output); write_offset = 0; }*/ } countn += local_countn; total_edges += num_edges; total_distinct_edges += distinct_num_edges; } // fwrite (write_buffer, sizeof(seq_t), write_offset, output); write_offset = 0; free (line_buf); total_num_edges += total_edges; distinct_edges += total_distinct_edges; printf ("Number of distinct edges: %lu\n", distinct_edges); return countn; } uint gather_sorted_dbgraph (dbgraph_t * graph, dbtable_t * tbs, subgraph_t * subgraph, uint num_of_kmers, int pid, int start_pid, int np_node) { uint countn = 0; uint size = graph->size; node_t * nodes = graph->nodes; uint i; uch j; int sum; uint total_edges = 0; uint total_distinct_edges = 0; voff_t vs_offsets[THREADS_WRITE_GRAPH+1]; memset (vs_offsets, 0, sizeof(voff_t) * (THREADS_WRITE_GRAPH+1)); omp_set_num_threads (cpu_threads); #pragma omp parallel private(i, j, sum) reduction(+:countn) reduction(+:total_edges) reduction(+:total_distinct_edges) { int thid = omp_get_thread_num (); int nths = omp_get_num_threads (); if (nths != cpu_threads) { printf ("Error in setting threads for gathering dbgraph!\n"); exit(0); } // printf ("write graph id %d\n", thid); uint local_countn = 0; uint num_edges = 0; uint distinct_num_edges = 0; uint size_per_thread = (size + cpu_threads - 1) / cpu_threads; if (size_per_thread <= cpu_threads) size_per_thread = size / cpu_threads; node_t * local_nodes = nodes + size_per_thread * thid; if (thid == cpu_threads - 1) size_per_thread = size - size_per_thread * (thid); if (size - size_per_thread * thid < 0) printf ("ATTENTION!!! size_per_thread error!!! %ld\n", size - size_per_thread); voff_t offset = 0; for (i = 0; i < size_per_thread; i++) { if (local_nodes[i].occupied == 0) continue; if (local_nodes[i].occupied != 2) { printf ("error!\n"); exit(0); } int cf = 0; for (j = 0; j < EDGE_DIC_SIZE; j++) { cf += *((ull*)&(local_nodes[i].edge)) >> (8 * j) & 0xff; } if (cf < cutoff) { local_nodes[i].occupied = 0; continue; } for (j = 0; j < EDGE_DIC_SIZE; j++) { if (*((ull*)&(local_nodes[i].edge)) >> (8 * j) & 0xff) distinct_num_edges += 1; } num_edges += cf; offset++; local_countn++; } vs_offsets[thid+1] = offset; countn += local_countn; total_edges += num_edges; total_distinct_edges += distinct_num_edges; } tbs[pid].buf = (entry_t*) malloc (sizeof(entry_t) * countn); tbs[pid].size = countn; tbs[pid].num_elems = num_of_kmers; (subgraph->subgraphs)[pid].size = countn; (subgraph->subgraphs)[pid].id = pid + start_pid; inclusive_prefix_sum (vs_offsets, cpu_threads+1); omp_set_num_threads (cpu_threads); #pragma omp parallel { int thid = omp_get_thread_num (); int nths = omp_get_num_threads (); if (nths != cpu_threads) { printf ("Error in setting threads for gathering dbgraph!\n"); exit(0); } uint size_per_thread = (size + cpu_threads - 1) / cpu_threads; if (size_per_thread <= cpu_threads) size_per_thread = size / cpu_threads; node_t * local_nodes = nodes + size_per_thread * thid; if (thid == cpu_threads - 1) size_per_thread = size - size_per_thread * (thid); voff_t gather_start = vs_offsets[thid]; entry_t * vs = tbs[pid].buf + gather_start; voff_t offset = 0; int i; for (i = 0; i < size_per_thread; i++) { if (local_nodes[i].occupied == 0) continue; if (local_nodes[i].occupied != 2) { printf ("error!\n"); exit(0); } vs[offset].kmer = local_nodes[i].kmer; vs[offset].edge = local_nodes[i].edge; vs[offset].occupied = local_nodes[i].occupied; offset++; } } tbb_entry_sort (tbs[pid].buf, countn); total_num_edges += total_edges; distinct_edges += total_distinct_edges; total_num_vs += countn; double factor = (double)distinct_edges / total_num_vs; factor = my_round(factor, 3) + MSSG_ROUNDUP; if (factor > mssg_factor) mssg_factor = factor; if (pid == np_node - 1) { printf ("partition %d: number of vertices: %u\n", pid, countn); printf ("MMMMMMMMMMMMMMMMMMMMMMMMMMMMM MSSG FACTOR REPORT::::::::::::::::\n"); printf ("Number of distinct edges: %lu, mssg_factor = %.4f, mssg_roundup = %.4f\n", distinct_edges, mssg_factor, MSSG_ROUNDUP); printf ("MMMMMMMMMMMMMMMMMMMMMMMMMMMMM MSSG FACTOR REPORT::::::::::::::::\n"); printf ("TTTTTTTTTTTTTTTTTTTTTT total number of vertices counted in output: %u\n", total_num_vs); } return countn; }
GB_unaryop__minv_int8_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_int8_int16 // op(A') function: GB_tran__minv_int8_int16 // C type: int8_t // A type: int16_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 8) #define GB_ATYPE \ int16_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 8) ; // casting #define GB_CASTING(z, aij) \ int8_t z = (int8_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_MINV || GxB_NO_INT8 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int8_int16 ( int8_t *Cx, // Cx and Ax may be aliased int16_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_int8_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
fib-omp3.c
/* * BSD 2-Clause License * * Copyright (c) 2020, Alessandro Capotondi * 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. * * 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. */ /** * @file fibonacci.c * @author Alessandro Capotondi * @date 27 Mar 2020 * @brief Recursive computation of Fibonacci * * @see https://en.wikipedia.org/wiki/Fibonacci_number * @see http://algo.ing.unimo.it/people/andrea/Didattica/HPC/index.html */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "utils.h" #define F_30 832040LL #define F_40 102334155LL #define F_50 12586269025LL #define F_60 1548008755920LL #ifndef CUTOFF_DEF #define CUTOFF_DEF 30 #endif static int N; static int CUTOFF; #define SEPARATOR "------------------------------------\n" // Parse command line arguments to set solver parameters void parse_arguments(int argc, char *argv[]); // Fibonacci Golden Model - DO NOT CHANGE! unsigned long long fibonacci_g(unsigned long long n) { if (n < 2) return n; return fibonacci_g(n - 2) + fibonacci_g(n - 1); } // Run the Fibonacci unsigned long long fib(unsigned long long n) { if (n < 2) return n; if (n <= CUTOFF) return fibonacci_g(n); unsigned long long x,y; #pragma omp task shared(x) x = fib(n - 2); #pragma omp task shared(y) y = fib(n - 1); #pragma omp taskwait return x+y; } int main(int argc, char *argv[]) { parse_arguments(argc, argv); printf(SEPARATOR); printf("Number: %d\n", N); printf("Cutoff: %d\n", CUTOFF); printf(SEPARATOR); // Run Jacobi solver start_timer(); unsigned long long f_n; #pragma omp parallel shared(f_n) num_threads(NTHREADS) { #pragma omp single nowait { f_n = fib(N); } } stop_timer(); // Check error of final solution unsigned long long g_n; if(N==30) g_n = F_30; else if (N==40) g_n = F_40; else if (N==50) g_n = F_50; else if (N==60) g_n = F_60; else g_n = fibonacci_g(N); unsigned long long err = f_n - g_n; printf(SEPARATOR); printf("F(%d) = %llu\n", N, f_n); printf("Error = %llu\n", err); printf("Runtime = %lf ms\n", elapsed_ns() / 1E6); printf(SEPARATOR); return 0; } int parse_int(const char *str) { char *next; int value = strtoul(str, &next, 10); return strlen(next) ? -1 : value; } double parse_double(const char *str) { char *next; double value = strtod(str, &next); return strlen(next) ? -1 : value; } void parse_arguments(int argc, char *argv[]) { // Set default values N = 40; CUTOFF = CUTOFF_DEF; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "--number") || !strcmp(argv[i], "-n")) { if (++i >= argc || (N = parse_int(argv[i])) < 0) { printf("Invalid matrix order\n"); exit(1); } } else if (!strcmp(argv[i], "--cutoff") || !strcmp(argv[i], "-c")) { if (++i >= argc || (CUTOFF = parse_int(argv[i])) < 0) { printf("Invalid seed\n"); exit(1); } } else if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { printf("\n"); printf("Usage: ./jacobi [OPTIONS]\n\n"); printf("Options:\n"); printf(" -h --help Print this message\n"); printf(" -c --cutoff C Set task cutoff\n"); printf(" -n --number N Set the Fibonacci number\n"); printf("\n"); exit(0); } else { printf("Unrecognized argument '%s' (try '--help')\n", argv[i]); exit(1); } } }
task_untied_threadid.c
// RUN: %libomp-compile-and-run // REQUIRES: abt && !clang // Clang 10.0 discards local variables saved before taskyield. We mark untied // task tests that use local variables with Clang as unsupported so far. #include "omp_testsuite.h" #include <string.h> #include <stdio.h> int test_task_untied_threadid(int num_threads) { int i, vals[NUM_TASKS]; memset(vals, 0, sizeof(vals)); #pragma omp parallel num_threads(num_threads) { #pragma omp master { for (i = 0; i < NUM_TASKS; i++) { #pragma omp task firstprivate(i) untied { ABT_thread abt_thread; ABT_EXIT_IF_FAIL(ABT_thread_self(&abt_thread)); // Context switching in OpenMP. #pragma omp taskyield int omp_thread_id2 = omp_get_thread_num(); ABT_thread abt_thread2; ABT_EXIT_IF_FAIL(ABT_thread_self(&abt_thread2)); ABT_bool abt_thread_equal; ABT_EXIT_IF_FAIL(ABT_thread_equal(abt_thread, abt_thread2, &abt_thread_equal)); if (abt_thread_equal == ABT_TRUE) { vals[i] += 1; } // Context switching in Argobots. ABT_EXIT_IF_FAIL(ABT_thread_yield()); int omp_thread_id3 = omp_get_thread_num(); if (omp_thread_id2 == omp_thread_id3) { // Argobots context switch does not change the thread-task mapping. vals[i] += 2; } } } } } for (i = 0; i < NUM_TASKS; i++) { if (vals[i] != 3) { printf("vals[%d] == %d\n", i, vals[i]); return 0; } } return 1; } int main() { int i, num_failed = 0; for (i = 0; i < REPETITIONS; i++) { if (!test_task_untied_threadid(i + 1)) { num_failed++; } } return num_failed; }
GB_unaryop__identity_int8_uint64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_int8_uint64 // op(A') function: GB_tran__identity_int8_uint64 // C type: int8_t // A type: uint64_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ int8_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_CASTING(z, x) \ int8_t z = (int8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int8_uint64 ( int8_t *restrict Cx, const uint64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_int8_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
interpolate_op.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <string> #include <vector> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { template <typename T, size_t D, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>; using Tensor = framework::Tensor; template <typename T> static void NearestNeighborInterpolate(const Tensor& input, Tensor* output, const float ratio_h, const float ratio_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners) { auto input_t = EigenTensor<T, 4>::From(input); auto output_t = EigenTensor<T, 4>::From(*output); for (int k = 0; k < out_h; k++) { // loop for images int in_k = (align_corners) ? static_cast<int>(ratio_h * k + 0.5) : static_cast<int>(ratio_h * k); for (int l = 0; l < out_w; l++) { int in_l = (align_corners) ? static_cast<int>(ratio_w * l + 0.5) : static_cast<int>(ratio_w * l); for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels output_t(i, j, k, l) = input_t(i, j, in_k, in_l); } } } } } template <typename T> static void BilinearInterpolation(const Tensor& input, Tensor* output, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const bool align_mode) { auto input_t = EigenTensor<T, 4>::From(input); auto output_t = EigenTensor<T, 4>::From(*output); bool align_flag = (align_mode == 0 && !align_corners); std::vector<int> vy_n, vy_s; std::vector<float> vd_n, vd_s; vy_n.reserve(out_h); vy_s.reserve(out_h); vd_n.reserve(out_h); vd_s.reserve(out_h); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int k = 0; k < out_h; k++) { int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float d_n = align_flag ? ratio_h * (k + 0.5) - 0.5 - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; { vy_n[k] = y_n; vy_s[k] = y_s; vd_n[k] = d_n; vd_s[k] = d_s; } } std::vector<int> vx_w, vx_e; std::vector<float> vd_w, vd_e; vx_w.reserve(out_w); vx_e.reserve(out_w); vd_w.reserve(out_w); vd_e.reserve(out_w); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int l = 0; l < out_w; l++) { int x_w = (align_mode == 0 && !align_corners) ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float d_w = align_flag ? ratio_w * (l + 0.5) - 0.5 - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; { vx_w[l] = x_w; vx_e[l] = x_e; vd_w[l] = d_w; vd_e[l] = d_e; } } #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(4) #endif for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels for (int k = 0; k < out_h; k++) { // loop for images for (int l = 0; l < out_w; l++) { // bilinear interpolation T out_t = input_t(i, j, vy_n[k], vx_w[l]) * vd_s[k] * vd_e[l] + input_t(i, j, vy_s[k], vx_w[l]) * vd_n[k] * vd_e[l] + input_t(i, j, vy_n[k], vx_e[l]) * vd_s[k] * vd_w[l] + input_t(i, j, vy_s[k], vx_e[l]) * vd_n[k] * vd_w[l]; output_t(i, j, k, l) = out_t; } } } } } template <typename T> static void NearestNeighborInterpolateGrad( const Tensor& output_grad, Tensor* input_grad, const float ratio_h, const float ratio_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners) { auto input_grad_t = EigenTensor<T, 4>::From(*input_grad); auto output_grad_t = EigenTensor<T, 4>::From(output_grad); for (int k = 0; k < out_h; k++) { // loop for images int in_k = (align_corners) ? static_cast<int>(ratio_h * k + 0.5) : static_cast<int>(ratio_h * k); for (int l = 0; l < out_w; l++) { int in_l = (align_corners) ? static_cast<int>(ratio_w * l + 0.5) : static_cast<int>(ratio_w * l); for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels input_grad_t(i, j, in_k, in_l) += output_grad_t(i, j, k, l); } } } } } template <typename T> static void BilinearInterpolationGrad(const Tensor& output_grad, Tensor* input_grad, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const int align_mode) { auto input_grad_t = EigenTensor<T, 4>::From(*input_grad); auto output_grad_t = EigenTensor<T, 4>::From(output_grad); bool align_flag = (align_mode == 0 && !align_corners); for (int k = 0; k < out_h; k++) { // loop for images int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float d_n = align_flag ? ratio_h * (k + 0.5) - 0.5 - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; for (int l = 0; l < out_w; l++) { int x_w = align_flag ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float d_w = align_flag ? ratio_w * (l + 0.5) - 0.5 - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels // bilinear interpolation grad const T grad = output_grad_t(i, j, k, l); input_grad_t(i, j, y_n, x_w) += static_cast<T>(grad * d_s * d_e); input_grad_t(i, j, y_s, x_w) += static_cast<T>(grad * d_n * d_e); input_grad_t(i, j, y_n, x_e) += static_cast<T>(grad * d_s * d_w); input_grad_t(i, j, y_s, x_e) += static_cast<T>(grad * d_n * d_w); } } } } } template <typename T> class InterpolateKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input = ctx.Input<Tensor>("X"); auto* output = ctx.Output<Tensor>("Out"); const int n = input->dims()[0]; const int c = input->dims()[1]; const int in_h = input->dims()[2]; const int in_w = input->dims()[3]; std::string interp_method = ctx.Attr<std::string>("interp_method"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale = ctx.Attr<float>("scale"); if (scale > 0) { out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = out_size->data<int>(); out_h = out_size_data[0]; out_w = out_size_data[1]; } bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); output->mutable_data<T>({n, c, out_h, out_w}, ctx.GetPlace()); auto& device_ctx = ctx.template device_context<platform::CPUDeviceContext>(); math::SetConstant<platform::CPUDeviceContext, T> zero; zero(device_ctx, output, static_cast<T>(0.0)); if (in_h == out_h && in_w == out_w) { framework::TensorCopy(*input, ctx.GetPlace(), output); return; } float ratio_h = 0.f; float ratio_w = 0.f; if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("bilinear" == interp_method) { BilinearInterpolation<T>(*input, output, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, align_mode); } else if ("nearest" == interp_method) { NearestNeighborInterpolate<T>(*input, output, ratio_h, ratio_w, n, c, out_h, out_w, align_corners); } } }; template <typename T> class InterpolateGradKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input = ctx.Input<Tensor>("X"); auto* input_grad = ctx.Output<Tensor>(framework::GradVarName("X")); auto* output_grad = ctx.Input<Tensor>(framework::GradVarName("Out")); const int n = input->dims()[0]; const int c = input->dims()[1]; const int in_h = input->dims()[2]; const int in_w = input->dims()[3]; std::string interp_method = ctx.Attr<std::string>("interp_method"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale = ctx.Attr<float>("scale"); if (scale > 0) { out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = out_size->data<int>(); out_h = out_size_data[0]; out_w = out_size_data[1]; } bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); input_grad->mutable_data<T>({n, c, in_h, in_w}, ctx.GetPlace()); auto& device_ctx = ctx.template device_context<platform::CPUDeviceContext>(); math::SetConstant<platform::CPUDeviceContext, T> zero; zero(device_ctx, input_grad, static_cast<T>(0.0)); if (in_h == out_h && in_w == out_w) { framework::TensorCopy(*output_grad, ctx.GetPlace(), input_grad); return; } float ratio_h = 0.f; float ratio_w = 0.f; if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("bilinear" == interp_method) { BilinearInterpolationGrad<T>(*output_grad, input_grad, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, align_mode); } else if ("nearest" == interp_method) { NearestNeighborInterpolateGrad<T>(*output_grad, input_grad, ratio_h, ratio_w, n, c, out_h, out_w, align_corners); } } }; } // namespace operators } // namespace paddle
onesided.c
/* Copyright (C) 2011 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ #include "common.h" #include "onesided.h" #include <mpi.h> #include <assert.h> #include <stdlib.h> #include <string.h> /* One-sided wrapper to allow emulation; a good MPI should be able to handle * the version in this file. */ #ifndef EMULATE_ONE_SIDED /* Gather from one array into another. */ struct gather { void* input; size_t elt_size; void* output; MPI_Datatype datatype; int valid; MPI_Win win; }; gather* init_gather(void* input, size_t input_count, size_t elt_size, void* output, size_t output_count, size_t nrequests_max, MPI_Datatype dt) { gather* g = (gather*)xmalloc(sizeof(gather)); g->input = input; g->elt_size = elt_size; g->output = output; g->datatype = dt; g->valid = 0; MPI_Win_create(input, input_count * elt_size, elt_size, MPI_INFO_NULL, MPI_COMM_WORLD, &g->win); return g; } void destroy_gather(gather* g) { assert (!g->valid); MPI_Win_free(&g->win); free(g); } void begin_gather(gather* g) { assert (!g->valid); g->valid = 1; MPI_Win_fence(MPI_MODE_NOPRECEDE | MPI_MODE_NOPUT, g->win); } void add_gather_request(gather* g, size_t local_idx, int remote_rank, size_t remote_idx, size_t req_id) { assert (g->valid); #pragma omp critical MPI_Get(g->output + local_idx * g->elt_size, 1, g->datatype, remote_rank, remote_idx, 1, g->datatype, g->win); } void end_gather(gather* g) { assert (g->valid); MPI_Win_fence(MPI_MODE_NOSUCCEED, g->win); g->valid = 0; } /* Scatter a constant to various locations in an array. */ struct scatter_constant { void* array; size_t elt_size; void* constant; MPI_Datatype datatype; int valid; MPI_Win win; }; scatter_constant* init_scatter_constant(void* array, size_t array_count, size_t elt_size, void* constant, size_t nrequests_max, MPI_Datatype dt) { scatter_constant* sc = (scatter_constant*)xmalloc(sizeof(scatter_constant)); sc->array = array; sc->elt_size = elt_size; sc->constant = constant; sc->datatype = dt; sc->valid = 0; MPI_Win_create(array, array_count * elt_size, elt_size, MPI_INFO_NULL, MPI_COMM_WORLD, &sc->win); return sc; } void destroy_scatter_constant(scatter_constant* sc) { assert (!sc->valid); MPI_Win_free(&sc->win); free(sc); } void begin_scatter_constant(scatter_constant* sc) { assert (!sc->valid); sc->valid = 1; MPI_Win_fence(MPI_MODE_NOPRECEDE, sc->win); } void add_scatter_constant_request(scatter_constant* sc, int remote_rank, size_t remote_idx, size_t req_id) { assert (sc->valid); #pragma omp critical MPI_Put(sc->constant, 1, sc->datatype, remote_rank, remote_idx, 1, sc->datatype, sc->win); } void end_scatter_constant(scatter_constant* sc) { assert (sc->valid); MPI_Win_fence(MPI_MODE_NOSUCCEED | MPI_MODE_NOSTORE, sc->win); sc->valid = 0; } /* Scatter values to various locations in an array using MPI_REPLACE. */ struct scatter { void* array; size_t elt_size; size_t request_count; size_t nrequests_max; char* send_data; MPI_Datatype datatype; int valid; MPI_Win win; }; scatter* init_scatter(void* array, size_t array_count, size_t elt_size, size_t nrequests_max, MPI_Datatype dt) { scatter* sc = (scatter*)xmalloc(sizeof(scatter)); sc->array = array; sc->elt_size = elt_size; sc->request_count = 0; sc->nrequests_max = nrequests_max; sc->send_data = xmalloc(nrequests_max * elt_size); sc->datatype = dt; sc->valid = 0; MPI_Win_create(array, array_count * elt_size, elt_size, MPI_INFO_NULL, MPI_COMM_WORLD, &sc->win); return sc; } void destroy_scatter(scatter* sc) { assert (!sc->valid); MPI_Win_free(&sc->win); free(sc->send_data); free(sc); } void begin_scatter(scatter* sc) { assert (!sc->valid); sc->valid = 1; sc->request_count = 0; MPI_Win_fence(MPI_MODE_NOPRECEDE, sc->win); } void add_scatter_request(scatter* sc, const char* local_data, int remote_rank, size_t remote_idx, size_t req_id) { assert (sc->valid); assert (sc->request_count < sc->nrequests_max); memcpy(sc->send_data + sc->request_count * sc->elt_size, local_data, sc->elt_size); #pragma omp critical MPI_Put(sc->send_data + sc->request_count * sc->elt_size, 1, sc->datatype, remote_rank, remote_idx, 1, sc->datatype, sc->win); ++sc->request_count; } void end_scatter(scatter* sc) { assert (sc->valid); MPI_Win_fence(MPI_MODE_NOSUCCEED | MPI_MODE_NOSTORE, sc->win); sc->valid = 0; } #endif /* !EMULATE_ONE_SIDED */
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include <deque> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions FPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; void Act(SourceLocation PragmaLocation, PragmaClangSectionAction Action, StringLiteral* Name); }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value); // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispAttr::Mode> VtorDispStack; // #pragma pack. // Sentinel to represent when the stack is set to mac68k alignment. static const unsigned kMac68kAlignmentSentinel = ~0U; PragmaStack<unsigned> PackStack; // The current #pragma pack values and locations at each #include. struct PackIncludeState { unsigned CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<PackIncludeState, 8> PackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. The /// element type here is ExprWithCleanups::Object. SmallVector<BlockDecl*, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// A flag to indicate that we're in a context that permits abstract /// references to fields. This is really a bool AllowAbstractFieldReference; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// Whether we are in a decltype expression. bool IsDecltype; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the FP_CONTRACT state on entry/exit of compound /// statements. class FPContractStateRAII { public: FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } private: Sema& S; FPOptions OldFPFeaturesState; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getFPOptions() { return FPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. SemaDiagnosticBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class SemaDiagnosticBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op // in that case anwyay. SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; ~SemaDiagnosticBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First flush the underlying // DiagnosticBuilder data, and clear the diagnostic builder itself so it // won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. FlushCounts(); Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template<typename T> friend const SemaDiagnosticBuilder &operator<<( const SemaDiagnosticBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } }; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; void emitAndClearUnusedLocalTypedefWarnings(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Expr *E); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return !D->isHidden() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T) { return !RequireCompleteTypeImpl(Loc, T, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as a non-type, and an expression representing /// that name has been formed. NC_ContextIndependentExpr, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification ContextIndependentExpr(ExprResult E) { NameClassification Result(NC_ContextIndependentExpr); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_ContextIndependentExpr); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); DeclContext *getContainingDC(DeclContext *DC); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Uuid); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true); ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfOnlyViableOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfOnlyViableOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplate }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr(Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(E, nullptr, Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(ER, nullptr, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); // "({..})" // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// default constructor of a class will have, and whether the parameter /// will be const. ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD); /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, and false is returned. bool CheckConstraintExpression(Expr *CE); bool CalculateConstraintSatisfaction(ConceptDecl *NamedConcept, MultiLevelTemplateArgumentList &MLTAL, Expr *ConstraintExpr, bool &IsSatisfied); /// Check that the associated constraints of a template declaration match the /// associated constraints of an older declaration of which it is a /// redeclaration. bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old, TemplateParameterList *New); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(Decl *D); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(FunctionDecl *MD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbigiousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, AccessSpecifier access, QualType objectType); void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, SourceLocation TemplateKWLoc = SourceLocation(), AssumedTemplateKind *ATK = nullptr); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnDependentTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); // Concepts Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression, UPPC_Block }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, TemplateDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); VarDecl *getVarTemplateSpecialization( VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs, const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispAttr::Mode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, DeclaratorDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// FreePackedContext - Deallocate and null out PackContext. void FreePackedContext(); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = Ext; } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. unsigned DeclareTargetNestingLevel = 0; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckForDelayedContext = true); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckCaller = true); /// Check if the expression is allowed to be used in expressions for the /// OpenMP devices. void checkOpenMPDeviceExpr(const Expr *E); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); /// Marks all the functions that might be required for the currently active /// OpenMP context. void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse); public: /// Struct to store the context selectors info for declare variant directive. struct OpenMPDeclareVariantCtsSelectorData { OMPDeclareVariantAttr::CtxSelectorSetType CtxSet = OMPDeclareVariantAttr::CtxSetUnknown; OMPDeclareVariantAttr::CtxSelectorType Ctx = OMPDeclareVariantAttr::CtxUnknown; MutableArrayRef<StringRef> ImplVendors; ExprResult CtxScore; explicit OpenMPDeclareVariantCtsSelectorData() = default; explicit OpenMPDeclareVariantCtsSelectorData( OMPDeclareVariantAttr::CtxSelectorSetType CtxSet, OMPDeclareVariantAttr::CtxSelectorType Ctx, MutableArrayRef<StringRef> ImplVendors, ExprResult CtxScore) : CtxSet(CtxSet), Ctx(Ctx), ImplVendors(ImplVendors), CtxScore(CtxScore) {} }; /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); /// Called at the end of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, ArrayRef<OMPClause *> ClauseList); /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return DeclareTargetNestingLevel > 0; } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction( DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param Data Set of context-specific data for the specified context /// selector. void ActOnOpenMPDeclareVariantDirective( FunctionDecl *FD, Expr *VariantRef, SourceRange SR, const Sema::OpenMPDeclareVariantCtsSelectorData &Data); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, OpenMPLinearClauseKind LinKind, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation DepLinMapLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause *ActOnOpenMPFromClause( ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This is DefaultFunctionArrayLvalueConversion, // except that it assumes the operand isn't of function or array // type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign = false); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit, ImplicitConversionSequence& ICS); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion, bool &FunctionConversion); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); virtual ~VerifyICEDiagnoser() { } }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr); /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// A partial call graph maintained during CUDA/OpenMP device code compilation /// to support deferred diagnostics. /// /// Functions are only added here if, at the time they're considered, they are /// not known-emitted. As soon as we discover that a function is /// known-emitted, we remove it and everything it transitively calls from this /// set and add those functions to DeviceKnownEmittedFns. llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, SourceLocation>> DeviceCallGraph; /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be /// deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class DeviceDiagBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); DeviceDiagBuilder(DeviceDiagBuilder &&D); DeviceDiagBuilder(const DeviceDiagBuilder &) = default; ~DeviceDiagBuilder(); /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (DeviceDiagBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a DeviceDiagBuilder yourself. operator bool() const { return ImmediateDiag.hasValue(); } template <typename T> friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Indicate that this function (and thus everything it transtively calls) /// will be codegen'ed, and emit any deferred diagnostics on this function and /// its (transitive) callees. void markKnownEmitted( Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, SourceLocation OrigLoc, const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas declared inside __device__ or __global__ functions inherit /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ /// functions become __host__ __device__ themselves. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); void CodeCompleteAfterIf(Scope *S); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; decltype(DelayedDllExportClasses) SavedDllExportClasses; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); SavedDllExportClasses.swap(S.DelayedDllExportClasses); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getRawEncoding()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
random.h
/* * This file is part of Quantum++. * * MIT License * * Copyright (c) 2013 - 2018 Vlad Gheorghiu (vgheorgh@gmail.com) * * 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. */ /** * \file random.h * \brief Randomness-related functions */ #ifndef RANDOM_H_ #define RANDOM_H_ namespace qpp { /** * \brief Generates a random real number uniformly distributed in * the interval [a, b) * * \param a Beginning of the interval, belongs to it * \param b End of the interval, does not belong to it * \return Random real number (double) uniformly distributed in * the interval [a, b) */ inline double rand(double a, double b) { // EXCEPTION CHECKS if (a >= b) throw exception::OutOfRange("qpp::rand()"); // END EXCEPTION CHECKS std::uniform_real_distribution<> ud(a, b); #ifdef NO_THREAD_LOCAL_ return ud(RandomDevices::get_instance().get_prng()); #else return ud(RandomDevices::get_thread_local_instance().get_prng()); #endif // NO_THREAD_LOCAL_ } /** * \brief Generates a random big integer uniformly distributed in * the interval [a, b] * * \note To avoid ambiguity with double qpp::rand(double, double) cast at * least one of the arguments to qpp::bigint * * \param a Beginning of the interval, belongs to it * \param b End of the interval, belongs to it * \return Random big integer uniformly distributed in the interval [a, b] */ inline bigint rand(bigint a, bigint b) { // EXCEPTION CHECKS if (a > b) throw exception::OutOfRange("qpp::rand()"); // END EXCEPTION CHECKS std::uniform_int_distribution<bigint> uid(a, b); #ifdef NO_THREAD_LOCAL_ return uid(RandomDevices::get_instance().get_prng()); #else return uid(RandomDevices::get_thread_local_instance().get_prng()); #endif // NO_THREAD_LOCAL_ } /** * \brief Generates a random index (idx) uniformly distributed in * the interval [a, b] * * \param a Beginning of the interval, belongs to it * \param b End of the interval, belongs to it * \return Random index (idx) uniformly distributed in the interval [a, b] */ inline idx randidx(idx a = std::numeric_limits<idx>::min(), idx b = std::numeric_limits<idx>::max()) { // EXCEPTION CHECKS if (a > b) throw exception::OutOfRange("qpp::randidx()"); // END EXCEPTION CHECKS std::uniform_int_distribution<idx> uid(a, b); #ifdef NO_THREAD_LOCAL_ return uid(RandomDevices::get_instance().get_prng()); #else return uid(RandomDevices::get_thread_local_instance().get_prng()); #endif // NO_THREAD_LOCAL_ } /** * \brief Generates a random matrix with entries uniformly * distributed in the interval [a, b) * * If complex, then both real and imaginary parts are uniformly distributed * in [a, b) * * This is the generic version that always throws * qpp::Exception::Type::UNDEFINED_TYPE. It is specialized only for * qpp::dmat and qpp::cmat */ template <typename Derived> Derived rand(idx rows, idx cols, double a = 0, double b = 1) { // silence -Wunused-parameter in clang++ (void) rows; (void) cols; (void) a; (void) b; throw exception::UndefinedType("qpp::rand()"); } /** * \brief Generates a random real matrix with entries uniformly * distributed in the interval [a, b), * specialization for double matrices (qpp::dmat) * * The template parameter cannot be automatically deduced and * must be explicitly provided * * Example: * \code * // generates a 3 x 3 random Eigen::MatrixXd, * // with entries uniformly distributed in [-1,1) * dmat mat = rand<dmat>(3, 3, -1, 1); * \endcode * * \param rows Number of rows of the random generated matrix * \param cols Number of columns of the random generated matrix * \param a Beginning of the interval, belongs to it * \param b End of the interval, does not belong to it * \return Random real matrix */ template <> inline dmat rand(idx rows, idx cols, double a, double b) { // EXCEPTION CHECKS if (rows == 0 || cols == 0) throw exception::ZeroSize("qpp::rand()"); if (a >= b) throw exception::OutOfRange("qpp::rand()"); // END EXCEPTION CHECKS return dmat::Zero(rows, cols).unaryExpr([a, b](double) { return rand(a, b); }); } /** * \brief Generates a random complex matrix with entries (both real and * imaginary) uniformly distributed in the interval [a, b), * specialization for complex matrices (qpp::cmat) * * The template parameter cannot be automatically deduced and * must be explicitly provided * * Example: * \code * // generates a 3 x 3 random Eigen::MatrixXcd, * // with entries (both real and imaginary) uniformly distributed in [-1,1) * cmat mat = rand<cmat>(3, 3, -1, 1); * \endcode * * \param rows Number of rows of the random generated matrix * \param cols Number of columns of the random generated matrix * \param a Beginning of the interval, belongs to it * \param b End of the interval, does not belong to it * \return Random complex matrix */ template <> inline cmat rand(idx rows, idx cols, double a, double b) { // EXCEPTION CHECKS if (rows == 0 || cols == 0) throw exception::ZeroSize("qpp::rand()"); if (a >= b) throw exception::OutOfRange("qpp::rand()"); // END EXCEPTION CHECKS return rand<dmat>(rows, cols, a, b).cast<cplx>() + 1_i * rand<dmat>(rows, cols, a, b).cast<cplx>(); } /** * \brief Generates a random matrix with entries normally * distributed in N(mean, sigma) * * If complex, then both real and imaginary parts are normally distributed * in N(mean, sigma) * * This is the generic version that always throws * qpp::Exception::Type::UNDEFINED_TYPE. It is specialized only for * qpp::dmat and qpp::cmat */ template <typename Derived> Derived randn(idx rows, idx cols, double mean = 0, double sigma = 1) { // silence -Wunused-parameter in clang++ (void) rows; (void) cols; (void) mean; (void) sigma; throw exception::UndefinedType("qpp::randn()"); } /** * \brief Generates a random real matrix with entries normally * distributed in N(mean, sigma), * specialization for double matrices (qpp::dmat) * * The template parameter cannot be automatically deduced and * must be explicitly provided * * Example: * \code * // generates a 3 x 3 random Eigen::MatrixXd, * // with entries normally distributed in N(0,2) * dmat mat = randn<dmat>(3, 3, 0, 2); * \endcode * * \param rows Number of rows of the random generated matrix * \param cols Number of columns of the random generated matrix * \param mean Mean * \param sigma Standard deviation * \return Random real matrix */ template <> inline dmat randn(idx rows, idx cols, double mean, double sigma) { // EXCEPTION CHECKS if (rows == 0 || cols == 0) throw exception::ZeroSize("qpp::randn()"); // END EXCEPTION CHECKS std::normal_distribution<> nd(mean, sigma); return dmat::Zero(rows, cols).unaryExpr([&nd](double) { #ifdef NO_THREAD_LOCAL_ return nd(RandomDevices::get_instance().get_prng()); #else return nd(RandomDevices::get_thread_local_instance().get_prng()); #endif // NO_THREAD_LOCAL_ }); } /** * \brief Generates a random complex matrix with entries (both real and * imaginary) normally distributed in N(mean, sigma), * specialization for complex matrices (qpp::cmat) * * The template parameter cannot be automatically deduced and * must be explicitly provided * * Example: * \code * // generates a 3 x 3 random Eigen::MatrixXcd, * // with entries (both real and imaginary) normally distributed in N(0,2) * cmat mat = randn<cmat>(3, 3, 0, 2); * \endcode * * \param rows Number of rows of the random generated matrix * \param cols Number of columns of the random generated matrix * \param mean Mean * \param sigma Standard deviation * \return Random complex matrix */ template <> inline cmat randn(idx rows, idx cols, double mean, double sigma) { // EXCEPTION CHECKS if (rows == 0 || cols == 0) throw exception::ZeroSize("qpp::randn()"); // END EXCEPTION CHECKS return randn<dmat>(rows, cols, mean, sigma).cast<cplx>() + 1_i * randn<dmat>(rows, cols, mean, sigma).cast<cplx>(); } /** * \brief Generates a random real number (double) normally distributed in * N(mean, sigma) * * \param mean Mean * \param sigma Standard deviation * \return Random real number normally distributed in N(mean, sigma) */ inline double randn(double mean = 0, double sigma = 1) { std::normal_distribution<> nd(mean, sigma); #ifdef NO_THREAD_LOCAL_ return nd(RandomDevices::get_instance().get_prng()); #else return nd(RandomDevices::get_thread_local_instance().get_prng()); #endif // NO_THREAD_LOCAL_ } /** * \brief Generates a random unitary matrix * * \param D Dimension of the Hilbert space * \return Random unitary */ inline cmat randU(idx D = 2) // ~3 times slower than Toby Cubitt's MATLAB corresponding routine, // because Eigen 3 QR algorithm is not parallelized { // EXCEPTION CHECKS if (D == 0) throw exception::DimsInvalid("qpp::randU()"); // END EXCEPTION CHECKS cmat X = 1 / std::sqrt(2.) * randn<cmat>(D, D); Eigen::HouseholderQR<cmat> qr(X); cmat Q = qr.householderQ(); // phase correction so that the resultant matrix is // uniformly distributed according to the Haar measure Eigen::VectorXcd phases = (rand<dmat>(D, 1)).cast<cplx>(); for (idx i = 0; i < static_cast<idx>(phases.rows()); ++i) phases(i) = std::exp(2 * pi * 1_i * phases(i)); Q = Q * phases.asDiagonal(); return Q; } /** * \brief Generates a random isometry matrix * * \param Din Size of the input Hilbert space * \param Dout Size of the output Hilbert space * \return Random isometry matrix */ inline cmat randV(idx Din, idx Dout) { // EXCEPTION CHECKS if (Din == 0 || Dout == 0 || Din > Dout) throw exception::DimsInvalid("qpp::randV()"); // END EXCEPTION CHECKS return randU(Dout).block(0, 0, Dout, Din); } /** * \brief Generates a set of random Kraus operators * * \note The set of Kraus operators satisfy the closure condition * \f$ \sum_i K_i^\dagger K_i = I\f$ * * \param N Number of Kraus operators * \param D Dimension of the Hilbert space * \return Set of \a N Kraus operators satisfying the closure condition */ inline std::vector<cmat> randkraus(idx N, idx D = 2) { // EXCEPTION CHECKS if (N == 0) throw exception::OutOfRange("qpp::randkraus()"); if (D == 0) throw exception::DimsInvalid("qpp::randkraus()"); // END EXCEPTION CHECKS std::vector<cmat> result(N); for (idx i = 0; i < N; ++i) result[i] = cmat::Zero(D, D); cmat Fk(D, D); cmat U = randU(N * D); #ifdef WITH_OPENMP_ #pragma omp parallel for collapse(3) #endif // WITH_OPENMP_ for (idx k = 0; k < N; ++k) for (idx a = 0; a < D; ++a) for (idx b = 0; b < D; ++b) result[k](a, b) = U(a * N + k, b * N); return result; } /** * \brief Generates a random Hermitian matrix * * \param D Dimension of the Hilbert space * \return Random Hermitian matrix */ inline cmat randH(idx D = 2) { // EXCEPTION CHECKS if (D == 0) throw exception::DimsInvalid("qpp::randH()"); // END EXCEPTION CHECKS cmat H = 2 * rand<cmat>(D, D) - (1. + 1_i) * cmat::Ones(D, D); return H + adjoint(H); } /** * \brief Generates a random normalized ket (pure state vector) * * \param D Dimension of the Hilbert space * \return Random normalized ket */ inline ket randket(idx D = 2) { // EXCEPTION CHECKS if (D == 0) throw exception::DimsInvalid("qpp::randket()"); // END EXCEPTION CHECKS /* slow ket kt = ket::Ones(D); ket result = static_cast<ket>(randU(D) * kt); return result; */ ket kt = randn<cmat>(D, 1); return kt / norm(kt); } /** * \brief Generates a random density matrix * * \param D Dimension of the Hilbert space * \return Random density matrix */ inline cmat randrho(idx D = 2) { // EXCEPTION CHECKS if (D == 0) throw exception::DimsInvalid("qpp::randrho()"); // END EXCEPTION CHECKS cmat result = 10 * randH(D); result = result * adjoint(result); return result / trace(result); } /** * \brief Generates a random uniformly distributed permutation * * Uses Knuth shuffle method (as implemented by std::shuffle), * so that all permutations are equally probable * * \param N Size of the permutation * \return Random permutation of size \a N */ inline std::vector<idx> randperm(idx N) { // EXCEPTION CHECKS if (N == 0) throw exception::PermInvalid("qpp::randperm()"); // END EXCEPTION CHECKS std::vector<idx> result(N); // fill in increasing order std::iota(std::begin(result), std::end(result), 0); // shuffle #ifdef NO_THREAD_LOCAL_ std::shuffle(std::begin(result), std::end(result), RandomDevices::get_instance().get_prng()); #else std::shuffle(std::begin(result), std::end(result), RandomDevices::get_thread_local_instance().get_prng()); #endif // NO_THREAD_LOCAL_ return result; } /** * \brief Generates a random probability vector uniformly distributed over the * probability simplex * * \param N Size of the probability vector * \return Random probability vector */ inline std::vector<double> randprob(idx N) { // EXCEPTION CHECKS if (N == 0) throw exception::OutOfRange("qpp::randprob()"); // END EXCEPTION CHECKS std::vector<double> result(N); // generate std::exponential_distribution<> ed(1); for (idx i = 0; i < N; ++i) { #ifdef NO_THREAD_LOCAL_ result[i] = ed(qpp::RandomDevices::get_instance().get_prng()); #else result[i] = ed(qpp::RandomDevices::get_thread_local_instance().get_prng()); #endif // NO_THREAD_LOCAL_ } // normalize double sumprob = sum(result); for (idx i = 0; i < N; ++i) result[i] /= sumprob; return result; } } /* namespace qpp */ #endif /* RANDOM_H_ */
GB_binop__iseq_fc64.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__iseq_fc64) // A.*B function (eWiseMult): GB (_AemultB_08__iseq_fc64) // A.*B function (eWiseMult): GB (_AemultB_02__iseq_fc64) // A.*B function (eWiseMult): GB (_AemultB_04__iseq_fc64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_fc64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__iseq_fc64) // C+=b function (dense accum): GB (_Cdense_accumb__iseq_fc64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_fc64) // C=scalar+B GB (_bind1st__iseq_fc64) // C=scalar+B' GB (_bind1st_tran__iseq_fc64) // C=A+scalar GB (_bind2nd__iseq_fc64) // C=A'+scalar GB (_bind2nd_tran__iseq_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // A pattern? 0 // B type: GxB_FC64_t // B pattern? 0 // BinaryOp: cij = GB_FC64_iseq (aij, bij) #define GB_ATYPE \ GxB_FC64_t #define GB_BTYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ GxB_FC64_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) \ GxB_FC64_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) \ GxB_FC64_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_FC64_iseq (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_ISEQ || GxB_NO_FC64 || GxB_NO_ISEQ_FC64) //------------------------------------------------------------------------------ // 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__iseq_fc64) ( 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__iseq_fc64) ( 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__iseq_fc64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC64_t GxB_FC64_t bwork = (*((GxB_FC64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #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 GxB_FC64_t *restrict Cx = (GxB_FC64_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 GxB_FC64_t *restrict Cx = (GxB_FC64_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__iseq_fc64) ( 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) ; GxB_FC64_t alpha_scalar ; GxB_FC64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((GxB_FC64_t *) alpha_scalar_in)) ; beta_scalar = (*((GxB_FC64_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__iseq_fc64) ( 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__iseq_fc64) ( 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__iseq_fc64) ( 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__iseq_fc64) ( 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__iseq_fc64) ( 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 GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ; GxB_FC64_t *Bx = (GxB_FC64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; GxB_FC64_t bij = GBX (Bx, p, false) ; Cx [p] = GB_FC64_iseq (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__iseq_fc64) ( 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 ; GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ; GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC64_t aij = GBX (Ax, p, false) ; Cx [p] = GB_FC64_iseq (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) \ { \ GxB_FC64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC64_iseq (x, aij) ; \ } GrB_Info GB (_bind1st_tran__iseq_fc64) ( 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 \ GxB_FC64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC64_iseq (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__iseq_fc64) ( 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 GxB_FC64_t y = (*((const GxB_FC64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
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] = 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); } } } 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; }
kmp_sch_simd_runtime_guided.c
// RUN: %libomp-compile // RUN: env OMP_SCHEDULE=guided %libomp-run // RUN: env OMP_SCHEDULE=guided,1 %libomp-run 1 // RUN: env OMP_SCHEDULE=guided,2 %libomp-run 2 // RUN: env OMP_SCHEDULE=dynamic %libomp-run // RUN: env OMP_SCHEDULE=dynamic,1 %libomp-run 1 // RUN: env OMP_SCHEDULE=dynamic,2 %libomp-run 2 // RUN: env OMP_SCHEDULE=auto %libomp-run // The test checks schedule(simd:runtime) // in combination with OMP_SCHEDULE=guided[,chunk] #include <stdio.h> #include <stdlib.h> #include <omp.h> #if defined(WIN32) || defined(_WIN32) #include <windows.h> #define delay() Sleep(1); #define seten(a,b,c) _putenv_s((a),(b)) #else #include <unistd.h> #define delay() usleep(10); #define seten(a,b,c) setenv((a),(b),(c)) #endif #define UBOUND 100 #define SIMD_LEN 4 int err = 0; // --------------------------------------------------------------------------- // Various definitions copied from OpenMP RTL. enum sched { kmp_sch_static_balanced_chunked = 45, kmp_sch_guided_simd = 46, kmp_sch_runtime_simd = 47, }; typedef unsigned u32; typedef long long i64; typedef unsigned long long u64; typedef struct { int reserved_1; int flags; int reserved_2; int reserved_3; char *psource; } id; #ifdef __cplusplus extern "C" { #endif int __kmpc_global_thread_num(id*); void __kmpc_barrier(id*, int gtid); void __kmpc_dispatch_init_4(id*, int, enum sched, int, int, int, int); void __kmpc_dispatch_init_8(id*, int, enum sched, i64, i64, i64, i64); int __kmpc_dispatch_next_4(id*, int, void*, void*, void*, void*); int __kmpc_dispatch_next_8(id*, int, void*, void*, void*, void*); #ifdef __cplusplus } // extern "C" #endif // End of definitions copied from OpenMP RTL. // --------------------------------------------------------------------------- static id loc = {0, 2, 0, 0, ";file;func;0;0;;"}; // --------------------------------------------------------------------------- void run_loop( int loop_lb, // Loop lower bound. int loop_ub, // Loop upper bound. int loop_st, // Loop stride. int lchunk ) { static int volatile loop_sync = 0; int lb; // Chunk lower bound. int ub; // Chunk upper bound. int st; // Chunk stride. int rc; int nthreads = omp_get_num_threads(); int tid = omp_get_thread_num(); int gtid = __kmpc_global_thread_num(&loc); int last; int tc = (loop_ub - loop_lb) / loop_st + 1; int ch; int no_chunk = 0; if (lchunk == 0) { no_chunk = 1; lchunk = 1; } ch = lchunk * SIMD_LEN; #if _DEBUG > 1 printf("run_loop gtid %d tid %d (lb=%d, ub=%d, st=%d, ch=%d)\n", gtid, tid, (int)loop_lb, (int)loop_ub, (int)loop_st, lchunk); #endif // Don't test degenerate cases that should have been discovered by codegen. if (loop_st == 0) return; if (loop_st > 0 ? loop_lb > loop_ub : loop_lb < loop_ub) return; __kmpc_dispatch_init_4(&loc, gtid, kmp_sch_runtime_simd, loop_lb, loop_ub, loop_st, SIMD_LEN); { // Let the master thread handle the chunks alone. int chunk; // No of current chunk. int last_ub; // Upper bound of the last processed chunk. u64 cur; // Number of interations in current chunk. u64 max; // Max allowed iterations for current chunk. int undersized = 0; last_ub = loop_ub; chunk = 0; max = (loop_ub - loop_lb) / loop_st + 1; // The first chunk can consume all iterations. while (__kmpc_dispatch_next_4(&loc, gtid, &last, &lb, &ub, &st)) { ++ chunk; #if _DEBUG printf("th %d: chunk=%d, lb=%d, ub=%d ch %d\n", tid, chunk, (int)lb, (int)ub, (int)(ub-lb+1)); #endif // Check if previous chunk (it is not the final chunk) is undersized. if (undersized) printf("Error with chunk %d, th %d, err %d\n", chunk, tid, ++err); if (loop_st > 0) { if (!(ub <= loop_ub)) printf("Error with ub %d, %d, ch %d, err %d\n", (int)ub, (int)loop_ub, chunk, ++err); if (!(lb <= ub)) printf("Error with bounds %d, %d, %d, err %d\n", (int)lb, (int)ub, chunk, ++err); } else { if (!(ub >= loop_ub)) printf("Error with ub %d, %d, %d, err %d\n", (int)ub, (int)loop_ub, chunk, ++err); if (!(lb >= ub)) printf("Error with bounds %d, %d, %d, err %d\n", (int)lb, (int)ub, chunk, ++err); }; // if // Stride should not change. if (!(st == loop_st)) printf("Error with st %d, %d, ch %d, err %d\n", (int)st, (int)loop_st, chunk, ++err); cur = ( ub - lb ) / loop_st + 1; // Guided scheduling uses FP computations, so current chunk may // be a bit bigger (+1) than allowed maximum. if (!( cur <= max + 1)) printf("Error with iter %llu, %llu, err %d\n", cur, max, ++err); // Update maximum for the next chunk. if (!last && cur % ch) printf("Error with chunk %d, %d, ch %d, tid %d, err %d\n", chunk, (int)cur, ch, tid, ++err); if (last && !no_chunk && cur > ch && nthreads > 1) printf("Error: too big last chunk %d (%d), tid %d, err %d\n", (int)cur, ch, tid, ++err); if (cur < max) max = cur; last_ub = ub; undersized = (cur < ch); #if _DEBUG > 1 if (last) printf("under%d cur %d, ch %d, tid %d, ub %d, lb %d, st %d =======\n", undersized,cur,ch,tid,ub,lb,loop_st); #endif } // while // Must have the right last iteration index. if (loop_st > 0) { if (!(last_ub <= loop_ub)) printf("Error with last1 %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_ub, chunk, ++err); if (last && !(last_ub + loop_st > loop_ub)) printf("Error with last2 %d, %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk, ++err); } else { if (!(last_ub >= loop_ub)) printf("Error with last1 %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_ub, chunk, ++err); if (last && !(last_ub + loop_st < loop_ub)) printf("Error with last2 %d, %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk, ++err); } // if } __kmpc_barrier(&loc, gtid); } // run_loop int main(int argc, char *argv[]) { int chunk = 0; if (argc > 1) { // expect chunk size as a parameter chunk = atoi(argv[1]); } #pragma omp parallel //num_threads(num_th) run_loop(0, UBOUND, 1, chunk); if (err) { printf("failed, err = %d\n", err); return 1; } else { printf("passed\n"); return 0; } }
activate.c
#include "lib.h" #include <math.h> #include <stdint.h> #include <stdlib.h> void NEURALOPS_SYMBOL(rect_fwd)( size_t batch_sz, size_t dim, const float *in_buf, float *out_buf) { #pragma omp parallel for for (size_t p = 0; p < batch_sz * dim; p += 1) { float x = in_buf[p]; out_buf[p] = x * (x > 0.0f); } } void NEURALOPS_SYMBOL(rect_bwd)( size_t batch_sz, size_t dim, const float *out_buf, const float *out_grad, float *in_grad) { #pragma omp parallel for for (size_t p = 0; p < batch_sz * dim; p += 1) { float y = out_buf[p]; float dy = out_grad[p]; in_grad[p] = dy * (y > 0.0f); } } void NEURALOPS_SYMBOL(logistic_fwd)( size_t batch_sz, size_t dim, const float *in_buf, float *out_buf) { #pragma omp parallel for for (size_t p = 0; p < batch_sz * dim; p += 1) { float x = in_buf[p]; out_buf[p] = 1.0f / (1.0f + expf(-x)); } } void NEURALOPS_SYMBOL(logistic_bwd)( size_t batch_sz, size_t dim, const float *out_buf, const float *out_grad, float *in_grad) { #pragma omp parallel for for (size_t p = 0; p < batch_sz * dim; p += 1) { float y = out_buf[p]; float dy = out_grad[p]; in_grad[p] = y * (1.0f - y) * dy; } }
core_ssygst.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zhegst.c, normal z -> s, Fri Sep 28 17:38:23 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_hegst * * Reduces a complex symmetric-definite generalized eigenproblem to standard * form. * * If ITYPE = 1, the problem is A*x = lambda*B*x, * and A is overwritten by inv(U^T)*A*inv(U) or inv(L)*A*inv(L^T) * * If ITYPE = 2 or 3, the problem is A*B*x = lambda*x or * B*A*x = lambda*x, and A is overwritten by U*A*U^T or L^T*A*L. * ******************************************************************************* * * @param[in] itype * = 1: compute inv(U^T)*A*inv(U) or inv(L)*A*inv(L^T); * = 2 or 3: compute U*A*U^T or L^T*A*L. * * @param[in] uplo * If PlasmaUpper, upper triangle of A is stored and B is factored as * U^T*U; * If PlasmaLower, lower triangle of A is stored and B is factored as * L*L^T. * * @param[in] n * The order of the matrices A and B. N >= 0. * * @param[in,out] A * On entry, the symmetric matrix A. If UPLO = 'U', the leading * N-by-N upper triangular part of A contains the upper * triangular part of the matrix A, and the strictly lower * triangular part of A is not referenced. If UPLO = 'L', the * leading N-by-N lower triangular part of A contains the lower * triangular part of the matrix A, and the strictly upper * triangular part of A is not referenced. * * On exit, if INFO = 0, the transformed matrix, stored in the * same format as A. * * @param[in] lda * The leading dimension of the array A. LDA >= max(1,N). * * @param[in,out] B * The triangular factor from the Cholesky factorization of B, * as returned by SPOTRF. * * @param[in] ldb * The leading dimension of the array B. LDB >= max(1,N). * ******************************************************************************/ __attribute__((weak)) int plasma_core_ssygst(int itype, plasma_enum_t uplo, int n, float *A, int lda, float *B, int ldb) { int info = LAPACKE_ssygst_work( LAPACK_COL_MAJOR, itype, lapack_const(uplo), n, A, lda, B, ldb ); return info; } /******************************************************************************/ void plasma_core_omp_ssygst(int itype, plasma_enum_t uplo, int n, float *A, int lda, float *B, int ldb, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A[0:lda*n]) \ depend(in:B[0:ldb*n]) { if (sequence->status == PlasmaSuccess) plasma_core_ssygst(itype, uplo, n, A, lda, B, ldb); } }
egsolver.c
/*! \mainpage egsolver Documentation * * \section intro_sec User Manual * * ... to be done.... * * etc... * * */ /** \file egsolver.c * \brief File principale del solver. * * \todo Definire le strategie di aggiunta dei weights quando l'input e' un PG * * \todo Verifica del risultato * * \todo Verificare se serve gestire ulteriori statistiche * * \todo Sostituire uso deprecated di ftime() con altra soluzione * */ #include "egsolver.h" #include "cpu_solver.h" //#include "dev_common.h" #include "sorting_criteria.h" #include <omp.h> /** @cond NONDOC */ // non doxycumentati //PROTOTIPI da altri sorgenti: extern void checkDevice(int *deviceCount, config* conf); extern void checkCUDAError(const char *msg); /** @endcond */ /*********************************/ #include <zlib.h> // direct access to the gzip API // (ew!) global variable for the gzip stream. gzFile my_gzfile = NULL; int my_abstractread(char *buff, int buffsize) { // zlip usage, code from w w w . a q u a m e n t u s . c o m // called on a request by Flex to get the next 'buffsize' bytes of data // from the input, and return the number of bytes read. int res = gzread(my_gzfile, buff, buffsize); if (res == -1) { // file error! exitWithError("Error reading input (in gzread)\n", ""); } return res; } /*********************************/ /* Calcola il bound al numero dei loop. Se maggiore di LONG_MAX, warning e usa LONG_MAX-1 */ long aggiorna_max_loop(long Narchi, long Nnodi, long MGpesi, long maxloop) { char str[256]; long res = (maxloop); if ((res) < ((long)0)) { // default (-1) indica un numero max pari al teorico //CHECK OVERFLOW IN: res = Narchi*MGpesi+1; // if (MGpesi > (LONG_MAX-1)/Narchi) { // // overflow handling // sprintf(str,"%d * %d", Narchi, MGpesi); // exitWithError("Error too many loops: %s --> overflow\n", str); // } else { // res = Narchi*MGpesi+1; if (MGpesi > (LONG_MAX-1)/(Nnodi*Narchi)) { //TODO: sovrastimo il numero dei loop // overflow handling //sprintf(str,"%ld * %ld * %ld > %ld", Nnodi, Narchi, MGpesi, LONG_MAX); //exitWithError("Error too many loops: %s --> overflow\n", str); res = LONG_MAX-1; sprintf(str,"%ld * %ld * %ld > %ld --> using LONG_MAX-1:%ld", Nnodi, Narchi, MGpesi, LONG_MAX, res); printWarning("WARNING too many loops: %s\n", str); } else { res = Nnodi * Narchi * MGpesi + 1; } } return(res); } /*********************************/ void output_solution_singleline() { int idx; for (idx=0; idx<num_nodi; idx++) { printf("V(%d)=%d\t", nomeExt_of_nomeInt[mapping[idx]], host_ResNodeValues1[idx]); } printf("\n"); } void output_solution_onenodeperline() { int idx; // RIDONDA: for (idx=0; idx<num_nodi; idx++) { printf("%d : %d(%d--%d)[%d](%d)\t%d\n", nomeExt_of_nomeInt[mapping[idx]], idx, nomeExt_of_nomeInt[idx], nomeInt_of_nomeExt[idx], mapping[nomeExt_of_nomeInt[idx]], mapping[nomeInt_of_nomeExt[idx]], host_ResNodeValues1[idx]); } for (idx=0; idx<num_nodi; idx++) { printf("%d)\t%d\n", nomeExt_of_nomeInt[mapping[idx]], host_ResNodeValues1[idx]); } } void remap_instance() { int idy; int nomeInt, nodoDest, arco; configuration.shuffleSplit_index = 0; // contatore per numero di nodi nella prima partizione (utile solo se si usa EG_gpu_solver_OutdegreeSplit()) if ((input_gametype == GAMETYPE_PARITY) || (input_gametype == GAMETYPE_MPG) || (input_gametype == GAMETYPE_MPG_ARENA)) { csrPtrInSuccLists[counter_nodi] = num_archi; for (nomeInt=0; nomeInt < counter_nodi; nomeInt++) { // calcolo out-degree outDegrees_of_csr[nomeInt] = csrPtrInSuccLists[nomeInt+1] - csrPtrInSuccLists[nomeInt]; if (outDegrees_of_csr[nomeInt] <= configuration.shuffleSplit_val) { //conteggio dei nodi con outdegree leq della soglia per --outdegree configuration.shuffleSplit_index++; if (nodeOwner[nomeInt] == 0) { // se e' dell'owner 0 incremento counter_nodi0_1 counter_nodi0_1++;; } } else { // se non e' sotto la soglia e if (nodeOwner[nomeInt] == 0) { // se e' dell'owner 0 incremento counter_nodi0_2 counter_nodi0_2++;; } } } for (arco=0; arco < num_archi; arco++) { // calcolo in-degree nodoDest = csrSuccLists[arco]; inDegrees_of_csr[nomeInt_of_nomeExt[nodoDest]]++; } // printf("Degrees:\nNodo\t Out\t In:\n"); // for (nomeInt=0; nomeInt < counter_nodi; nomeInt++) { printf("%d \t %d \t %d\n", nomeInt, outDegrees_of_csr[nomeInt], inDegrees_of_csr[nomeInt]); } // // printf("\nindice :"); // for (nomeInt=0; nomeInt < counter_nodi; nomeInt++) { printf("%d \t",nomeInt); } // printf("\nIntofExt :"); // for (nomeInt=0; nomeInt < counter_nodi; nomeInt++) { printf("%d \t",nomeInt_of_nomeExt[nomeInt]); } // printf("\nExtofInt :"); // for (nomeInt=0; nomeInt < counter_nodi; nomeInt++) { printf("%d \t",nomeExt_of_nomeInt[nomeInt]); } // printf("\n"); // Riordina i nodi // mapping[nomeInternoSorted] = nomeOrdineLettura // revmapping[nomeOrdineLettura] = nomeInternoSorted mapping = (int *)malloc((1+num_nodi)*sizeof(int)); checkNullAllocation(mapping,"allocazione mapping"); revmapping = (int *)malloc((1+num_nodi)*sizeof(int)); checkNullAllocation(revmapping,"allocazione revmapping"); for (idy=0; idy < counter_nodi; idy++) { mapping[idy] = idy; } /** criteri di sorting dei nodi */ if (configuration.kinfOfParallelism == KINDPARALLELISM_OUTDEGREESPLIT) { // uso bucket w.r.t. outdegree: funzione EG_gpu_solver_OutdegreeSplit() // sorting prima rispetto a outdegree, poi rispetto a owner e se richiesto rispetto a SORT_<X> switch (configuration.nodesorting){ case SORT_N: printf("Sorting nodes w.r.t. owner (after split). \n"); qsort (mapping , counter_nodi, sizeof(int), split_prima0poi1); break; case SORT_O: printf("Sorting nodes w.r.t. owner (after split), then w.r.t. outdegree\n"); qsort (mapping , counter_nodi, sizeof(int), split_prima0poi1_outdeg); break; case SORT_I: printf("Sorting nodes w.r.t. owner (after split), then w.r.t. indegree\n"); qsort (mapping , counter_nodi, sizeof(int), split_prima0poi1_indeg); break; case SORT_OI: printf("Sorting nodes w.r.t. owner (after split), then w.r.t. outdegree, then w.r.t. indegree\n"); qsort (mapping , counter_nodi, sizeof(int), split_prima0poi1_outdeg_indeg); break; case SORT_A: printf("Sorting nodes w.r.t. owner (after split), then w.r.t. outdegree+indegree\n"); qsort (mapping , counter_nodi, sizeof(int), split_prima0poi1_alldeg); break; } } else { // caso in cui non si usa bucket switch (configuration.nodesorting){ case SORT_N: printf("Sorting nodes w.r.t. owner. \n"); qsort (mapping , counter_nodi, sizeof(int), prima0poi1); break; case SORT_O: printf("Sorting nodes w.r.t. owner, then w.r.t. outdegree\n"); qsort (mapping , counter_nodi, sizeof(int), prima0poi1_outdeg); break; case SORT_I: printf("Sorting nodes w.r.t. owner, then w.r.t. indegree\n"); qsort (mapping , counter_nodi, sizeof(int), prima0poi1_indeg); break; case SORT_OI: printf("Sorting nodes w.r.t. owner, then w.r.t. outdegree, then w.r.t. indegree\n"); qsort (mapping , counter_nodi, sizeof(int), prima0poi1_outdeg_indeg); break; case SORT_A: printf("Sorting nodes w.r.t. owner, then w.r.t. outdegree+indegree\n"); qsort (mapping , counter_nodi, sizeof(int), prima0poi1_alldeg); break; } } // printf("PRIMA VERS: "); for (idy=0; idy < counter_nodi; idy++) { printf("%d\t",mapping[idy]); } printf("\n"); for (idy=0; idy < counter_nodi; idy++) { revmapping[mapping[idy]] = idy; } // printf("SECON VERS: "); for (idy=0; idy < counter_nodi; idy++) { printf("%d\t",mapping[idy]); } printf("\n"); } // END GAMETYPE_PARITY || GAMETYPE_MPG ||... else { fprintf(stderr,"INPUT: CASO NON ANCORA IMPLEMENTATO\n"); } } //host_csrPtrInSuccLists; //host_csrPesiArchi; //host_csrSuccLists; void postparsing() { int idx; int idy; int idxInA = 0; int idxInB = 0; alloca_memoria_host(); alloca_memoria_device(); // popola i vettori host_csr...[IntSorted] ricopiando da csr...[Ext] e rinominando i nodi da 0 a N, in base al riordimanento determinato // nomeInt_of_nomeExt/nomeExt_of_nomeInt e da mapping[] // oltre a riordinare/rinominare i nodi si devono coerentemente rinominare gli adiacenti (le destinazioni degli archi) // OSS c'e' una doppia rinomina: nomeInt_of_nomeExt/nomeExt_of_nomeInt codificano la corrispondenza tra i nodi nel file (Ext) e // una rinomina che li rinomina da 0 a N nell'ordine in cui sono incontrati nel file (Int==nomeOrdineLettura); // Tramite mapping/revmapping invece si tiene conto del riordino // ( mapping[nomeInternoSorted] = nomeOrdineLettura // revmapping[nomeOrdineLettura] = nomeInternoSorted ) for (idx=0; idx < counter_nodi0; idx++) { host_csrPtrInSuccLists[idxInA++] = idxInB; host_csrSuccLists[idxInB] = revmapping[nomeInt_of_nomeExt[csrSuccLists[csrPtrInSuccLists[mapping[idx]]]]]; //printf("%d", revmapping[nomeInt_of_nomeExt[csrSuccLists[csrPtrInSuccLists[mapping[idx]]]]]); // almeno uno c'e' host_csrPesiArchi[idxInB++] = csrPesiArchi[csrPtrInSuccLists[mapping[idx]]]; //printf("%d", csrPesiArchi[csrPtrInSuccLists[mapping[idx]]]); // almeno uno c'e' for (idy=(1+csrPtrInSuccLists[mapping[idx]]); idy < csrPtrInSuccLists[mapping[idx]+1]; idy++) { // gli altri host_csrSuccLists[idxInB] = revmapping[nomeInt_of_nomeExt[csrSuccLists[idy]]]; //printf(",%d", revmapping[nomeInt_of_nomeExt[csrSuccLists[idy]]]); host_csrPesiArchi[idxInB++] = csrPesiArchi[idy]; //printf(",%d", csrPesiArchi[idy]); } //printf("\n"); } for (idx=counter_nodi0; idx < counter_nodi; idx++) { host_csrPtrInSuccLists[idxInA++] = idxInB; host_csrSuccLists[idxInB] = revmapping[nomeInt_of_nomeExt[csrSuccLists[csrPtrInSuccLists[mapping[idx]]]]]; //printf("%d", revmapping[nomeInt_of_nomeExt[csrSuccLists[csrPtrInSuccLists[mapping[idx]]]]]); // almeno uno c'e' host_csrPesiArchi[idxInB++] = csrPesiArchi[csrPtrInSuccLists[mapping[idx]]]; //printf("%d", csrPesiArchi[csrPtrInSuccLists[mapping[idx]]]); // almeno uno c'e' for (idy=(1+csrPtrInSuccLists[mapping[idx]]); idy < csrPtrInSuccLists[mapping[idx]+1]; idy++) { // gli altri host_csrSuccLists[idxInB] = revmapping[nomeInt_of_nomeExt[csrSuccLists[idy]]]; //printf(",%d", revmapping[nomeInt_of_nomeExt[csrSuccLists[idy]]]); host_csrPesiArchi[idxInB++] = csrPesiArchi[idy]; //printf(",%d", csrPesiArchi[idy]); } //printf("\n"); } host_csrPtrInSuccLists[idxInA] = idxInB; // ultimo riferimento /* Determino MG_pesi come la somma su tutti i nodi n del max tra 0 e l'abs() del * peso minore (puo' essere negativo) tra gli archi uscenti da n, * Quindi per un n, se tutti gli archi uscenti da n hanno peso positivo, si ottiene 0 * E' una maggiorazione (generosa) del peso massimo (abs()) che potra' avere un * qualsiasi ciclo negativo nel grafo */ int maxdelnodo; if ((configuration.algoritmo == ALGOR_EG) || (configuration.algoritmo == ALGOR_EG0)) { MG_pesi = 0; for (idx=0; idx < counter_nodi; idx++) { maxdelnodo=0; for (idy=host_csrPtrInSuccLists[idx]; idy < host_csrPtrInSuccLists[idx+1]; idy++) { maxdelnodo = MAX(maxdelnodo,-(host_csrPesiArchi[idy])); } if (MG_pesi > (INT_MAX - maxdelnodo)) { //Check overflow // overflow handling sprintf(str,"%d + %d", maxdelnodo, MG_pesi); exitWithError("Error too high weights: %s --> overflow\n", str); } else { MG_pesi += maxdelnodo; } } } avg_outdegree = ((double)num_archi) / ((double)num_nodi); double sqsum = 0; for (idx=0; idx < counter_nodi; idx++) { sqsum += (((double)(csrPtrInSuccLists[idx+1]-csrPtrInSuccLists[idx]))-avg_outdegree) * (((double)(csrPtrInSuccLists[idx+1]-csrPtrInSuccLists[idx]))-avg_outdegree); } stddev_outdegree = sqrt(sqsum/(counter_nodi)); } int main(int argc, char *argv[]) { struct timeb tp; double deltatime; int idz; static int nthreads=1; #if (defined(__CYGWIN__) || defined(__CYGWIN32__)) char stringa[256] = { 'j', 'a', 'c', 'k', '\0' }; #elif defined(_WIN32) char stringa[256] = { 'b', 'i', 'l', 'l', '3', '2', '\0' }; #elif defined(_WIN64) char stringa[256] = { 'b', 'i', 'l', 'l', '6', '4', '\0' }; #elif defined(__APPLE__) char stringa[256] = { 'm', 'a', 'c', 'u', 's', 'e', 'r', '\0' }; #elif (defined(__linux__) || defined(__unix__)) char stringa[256]; cuserid(stringa); #else char stringa[256] = { 's', 't', 'r', 'a', 'n', 'g', 'e', 'r', '\0' }; #endif /* SET config param reading command-line options */ setconfig(argc, argv); setstat(); //Calcolo soluzione printf("Process stats:\n\tUser: %s UID=%d\n", stringa, getuid()); gethostname(stringa, 256); printf("\tProcess: PID=%d running on %s\n", getpid(),stringa); ftime(&tp); printf("\tUnix time: %ld.%d (%lu)\n", tp.time,tp.millitm, (ulong)clock()); printf("\tCommand line: "); for (idz=0; idz<argc; idz++) { printf("%s ",argv[idz]); } printf("\n");fflush(stdout); ftime(&tp); deltatime = ((double)((long int)tp.time)); deltatime += ((double)tp.millitm)/1000; switch (configuration.computationType){ case GPU_COMPUTATION: if (configuration.deviceCount == 0) { printf("\nThere is no device supporting CUDA\n\n"); exit(EXIT_FAILURE); } else { printf("CUDA stats:\n\t%d CUDA devices detected.\n", configuration.deviceCount); printf("\tSelect device number %d name: %s\n", configuration.deviceid, configuration.devicename); printf("\tDevice compute capability %d.%d\n", configuration.capabilityMajor, configuration.capabilityMinor); printf("\tGPU clock: %.0f MHz (%0.2f GHz)\n", (float)(configuration.clockRate)* 1e-3f, (float)(configuration.clockRate)* 1e-6f); printf("\tDevice memory: %.0f MB\n", (float)(configuration.deviceProp_totalGlobalMem)/1048576.0f); printf("\tECC enabled: %s\n", (configuration.ECCEnabled)?"yes":"no"); printf("\tShared memory size: %.0f KB\n", (float)(configuration.sharedMemPerBlock)/1024.0f); int driverVersion = 0, runtimeVersion = 0; cudaDriverGetVersion(&driverVersion); cudaRuntimeGetVersion(&runtimeVersion); printf("\tCUDA Driver Version / Runtime Version %d.%d / %d.%d\n\n", driverVersion/1000, (driverVersion%100)/10, runtimeVersion/1000, (runtimeVersion%100)/10); } break; case CPU_COMPUTATION: #pragma omp parallel { nthreads = omp_get_num_threads(); } printf("CPU stats:\n\t ..TO DO..\n"); printf("\tCPU threads %d:\n",nthreads); // printf("\tCHUNK SIZE %d:\n",CHUNK_SIZE); // printf("\tMAX_THREAD %d:\n",MAX_THREADS); break; } /* Parsing del output del grounder */ printf("Parsing input (reading %s)...\n", (configuration.stdinputsource == 1)?"stdin":configuration.filename);fflush(stdout); parse_input(); remap_instance(); if (configuration.stdinputsource == 0) { gzclose(my_gzfile); } ftime(&tp); statistics.inputtime = (((double)((long int)tp.time)) + (((double)tp.millitm)/1000)) - deltatime; deltatime = ((double)((long int)tp.time)); deltatime += ((double)tp.millitm)/1000; printf("Parsing completed (parsing time %lf).\n",statistics.inputtime);fflush(stdout); printf("\nStart post-parsing...\n"); postparsing(); ftime(&tp); deltatime = ((((double)((long int)tp.time)) + (((double)tp.millitm)/1000)) - deltatime); printf("Post-parsing completed (postparsing time %lf).\n",deltatime);fflush(stdout); printf("\nInput stats:\n\tNodes: %d (%d+%d)\n\tEdges: %d\n\tMax node Id: %d\n",num_nodi, counter_nodi0, counter_nodi-counter_nodi0, num_archi, max_nodo); printf("\tMin out-degree: %d\n", min_outdegree); printf("\tMax out-degree: %d\n\tMax weight(abs): %d\n", max_outdegree, max_pesi); printf("\tAvg out-degree: %.3lf\n\tStd dev: %.3lf\n\tRel std dev: %.2lf\n", avg_outdegree, stddev_outdegree, 100*stddev_outdegree/abs(avg_outdegree));fflush(stdout); printf("\tLow out-degree: 0: %d \t1: %d \t2: %d \t3: %d\n", numLowOutDegree[0], numLowOutDegree[1], numLowOutDegree[2], numLowOutDegree[3]);fflush(stdout); // spostato dopo traspose in CPU solver: printf("\tLow in-degree: 0: %d \t1: %d \t2: %d \t3: %d\n", numLowInDegree[0], numLowInDegree[1], numLowInDegree[2], numLowInDegree[3]); /* RUN SOLVER */ printf("\nPreparing to solve...\n");fflush(stdout); /* predispongo eventuale timeout subito prima di invocare il solver. Cosi' si trascura il tempo di input e preprocessing */ timeout_expired = 0; if (configuration.timeoutOpt == SET_TIMEOUT_OPT) { install_alarmhandler(); printf("Setting %u seconds timeout... (not effective for some algorithms)\n",configuration.timeoutSeconds); alarm(configuration.timeoutSeconds); } fflush(stdout); switch (configuration.computationType){ case CPU_COMPUTATION: cpu_solver(); printf("------------------------\nTiming:\n"); printf("Parsing time: %lf sec \n", statistics.inputtime ); printf("Postparsing time: %lf sec \n", deltatime ); //printf("Allocation time: %14.6lf sec \n", statistics.alloctime/1000 ); printf("Solving time: %lf sec \n", statistics.solvingtime ); printf("Total time: %lf sec \n", deltatime+statistics.inputtime+ statistics.solvingtime); printf("Nodes per second: %lf \n", ((double)statistics.processedNodes)/(statistics.solvingtime)); //printf("Total time: %14.6lf sec \n", deltatime+statistics.inputtime+ (statistics.alloctime+statistics.solvingtime)/1000 ); printf("Threads used %d\n", nthreads); printf("------------------------\n"); break; case GPU_COMPUTATION: copia_dati_su_device(); printf("Use atomicCAS to avoid race conditions...\n"); gpu_solver(); printf("------------------------\nTiming:\n"); printf("Parsing time: %lf sec \n", statistics.inputtime ); printf("Postparsing time: %lf sec \n", deltatime ); //printf("Allocation time: %14.6lf sec \n", statistics.alloctime/1000 ); printf("Solving time: %lf sec \n", statistics.solvingtime/1000 ); //cuda usa diversa unita' di misura printf("Total time: %lf sec \n", deltatime+statistics.inputtime+ (statistics.solvingtime)/1000 ); printf("Nodes per second: %lf \n", ((double)statistics.processedNodes)/(statistics.solvingtime/1000)); printf("------------------------\n"); break; } if (configuration.algoritmo != COMPARA) { if (configuration.onelineout != NO_OUTPUT) { printf("\nSolution:\n");fflush(stdout); if (configuration.onelineout == YES_ONELINEOUT) { output_solution_singleline(); } else { output_solution_onenodeperline(); } } else { printf("\nSolution output omitted.\n");fflush(stdout); } } dealloca_memoria_host(); if (configuration.computationType == GPU_COMPUTATION) { dealloca_memoria_device(); cudaDeviceReset(); } ftime(&tp); printf("\nUnix time: %ld.%d (%lu)\n", tp.time,tp.millitm, (ulong)clock()); fflush(stdout); exit(EXIT_SUCCESS); } //*******************************************// void printShortUsage(char * str) { fprintf(stderr," For usage, type: %s --help\n", str); fflush(stderr); } void printUsage(char * str) { fprintf(stderr," Usage: %s [options]\n", str); fprintf(stderr," EG solving: Reads an instance and applies the selected algorithm.\n"); fprintf(stderr," Options:\n"); fprintf(stderr," --help -h -?\n\tShow this message.\n"); fprintf(stderr," --input FILENAME\n\tReads from FILENAME instead of using stdin. (Input can be in gzipped form. Default: stdin)\n"); fprintf(stderr,"\n Options to assign/modify edge's -weights:\n"); fprintf(stderr," --unit-weights\n\tAdd weights: w_i=1 for each node i. (Default: off)\n"); fprintf(stderr," --exp-weights\n\tAdd weights: set w_i=(-num_nodes)^p_i. (Default: off)\n"); fprintf(stderr," --rnd-weights [[L] U]\n\tAdd weights: w_i randomly chosen in [L..U]. (Default: off, L=-U, U=%d)\n",DEFAULT_ADD_RND_WEIGHTS_VAL); fprintf(stderr," --rnd-seed S\n\tUse S as seed for pseudo-random numbers. (Effective with --rnd-weights. Default: off)\n"); fprintf(stderr,"\n Solving options:\n"); fprintf(stderr," [--cpu|--gpu]\n\tChoose the computation type. Default: --cpu)\n"); fprintf(stderr," --deviceid I\n\tSelection of the I-th CUDA capable device. (Effective with --gpu. Default: %d)\n", DEFAULT_DEVICE); fprintf(stderr," --tb T\n\tSet T=2^n as the number of threads-per-block. (Effective with --gpu. Default: T=%d)\n",DEFAULT_THREADSPERBLOCK); fprintf(stderr," --eg [N]\n\tUse basic implementation of EG algorithm (node driven). Performs at most N loops. (Default: on, N=|MG||V|)\n"); fprintf(stderr," --eg0 [N]\n\tUse naive implementation of EG algorithm (node driven). Performs at most N loops. (Only effective with --cpu. Default: off, N=|MG||V|)\n"); fprintf(stderr," --shuffling N\n\tSelect kind of parallelism. N=1:vertex-parallelism. N=2,4,8,16,32:shuffle based (Effective with --gpu. Default: N=1)\n"); //fprintf(stderr," --threshold P\n\tSet threshold for switching between vertex-parallelism (%%Active>P) and 32-shuffle-based parallelism. (Effective with --gpu. Default: off)\n"); //fprintf(stderr," --outdegree N L U [T [D]]\n\tUse different parallelism for nodes with outdegree lesser-or-equal or greater than N\n\tL,U=1,2,4,8,16,32, select the parallelism: 1:vertex parallelism, K>1: K-shuffle based.\n\tApplies if the number of active nodes is greater-or-equal than T, otherwise uses D-shuffle based\n\t(Effective with --gpu. Default: off, T=%d D=%d)\n",DEFAULT_DEGREESPLIT_SOGLIA,DEFAULT_DEGREESPLIT_DOUBLE); fprintf(stderr,"\n Useful weird options:\n"); fprintf(stderr," --printdegrees\n\tPrint statistics about in/out degrees of nodes. (Only effective with --cpu. Default: off)\n"); fprintf(stderr," --onelineout\n\tSolution in a single text line. (Default: off)\n"); fprintf(stderr," --noout\n\tDo not print the solution explicitly. (Statistics are printed. Default: off)\n"); fprintf(stderr," --timeout [S]\n\tStops after 1<S<%d sec of GPU solving time (approx.). (Not completely implemented. Default: off, S=%d)\n", INT_MAX, DEFAULT_TIMEOUT_SEC); fprintf(stderr,"\n Profiling options to sort nodes:\n"); fprintf(stderr," --sort_n\n\tSorting w.r.t. owner (MAX<MIN). (Default)\n"); fprintf(stderr," --sort_o\n\tSorting w.r.t. owner, then w.r.t. outdegree\n"); fprintf(stderr," --sort_i\n\tSorting w.r.t. owner, then w.r.t. indegree\n"); fprintf(stderr," --sort_oi\n\tSorting w.r.t. owner, then w.r.t. outdegree, then w.r.t. indegree\n"); fprintf(stderr," --sort_a\n\tSorting w.r.t. owner, then w.r.t. outdegree+indegree\n"); fprintf(stderr," In case of conflicting options, the last one is used. Can be combined with other options such as --outdegree\n"); fprintf(stderr,"\nExpected input format: Nodes are consecutive naturals up to MAXNODE.\n Input format:\n\t[ARENA] MAXNODE [NUMEDGES] ;\n\tnode owner node:weight, ..., node:weight [\"string\"] ;\n \tnode owner node:weight, ..., node:weight [\"string\"] ;\n\n"); fflush(stderr); } //***********************************************// /* Processa opzioni: */ void setconfig(int argc, char *argv[]) { // SET DEFAULT PARAMS int i; struct timeb timeForRndSeed; configuration.computationType = DEFAULT_COMPUTATION_UNIT; configuration.algoritmo = DEFAULT_ALGOR; // flag per memorizzare che input si legge (stdin o file) configuration.stdinputsource = 1; configuration.onelineout = NO_ONELINEOUT; configuration.print_degree_hist = DEFAULT_PRINT_DEGREEHIST; configuration.maxThreadsPerBlock = DEFAULT_THREADSPERBLOCK; configuration.add_weights_mode = DEFAULT_ADD_WEIGHTS; configuration.rndWeightLow = -DEFAULT_ADD_RND_WEIGHTS_VAL; configuration.rndWeightHigh = DEFAULT_ADD_RND_WEIGHTS_VAL; configuration.rndSeed = NO_USER_RND_SEED; configuration.deviceid = DEFAULT_DEVICE; configuration.threadsPerBlock = DEFAULT_THREADSPERBLOCK; configuration.shuffleThreshold = DEFAULT_SHUFFLETHR; configuration.kinfOfParallelism = DEFAULT_KINDPARALLELISM; configuration.shuffleSplit_val = DEFAULT_DEGREESPLIT; configuration.shuffleSplit_low = DEFAULT_DEGREESPLIT_LOW; configuration.shuffleSplit_up = DEFAULT_DEGREESPLIT_UP; configuration.shuffleSplit_index = 0; configuration.shuffleSplit_soglia = DEFAULT_DEGREESPLIT_SOGLIA; configuration.shuffleSplit_double = DEFAULT_DEGREESPLIT_DOUBLE; configuration.max_loop_val = DEFAULT_MAX_LOOP_VAL; configuration.timeoutOpt = UNSET_TIMEOUT_OPT; configuration.timeoutSeconds = 0; configuration.nodesorting = DEFAULT_NODESORT; for( i = 1; i < argc; i++){ if((strcmp(argv[i],"--help") == 0) || (strcmp(argv[i],"-?") == 0) || (strcmp(argv[i],"-h") == 0)) { printUsage(argv[0]); exit(EXIT_SUCCESS); } else if(strcmp(argv[i],"--cpu") == 0) { configuration.computationType = CPU_COMPUTATION; } else if(strcmp(argv[i],"--gpu") == 0) { configuration.computationType = GPU_COMPUTATION; } else if(strcmp(argv[i],"--printdegrees") == 0) { configuration.print_degree_hist = YES_PRINT_DEGREEHIST; } else if(strcmp(argv[i],"--onelineout") == 0) { configuration.onelineout = YES_ONELINEOUT; } else if(strcmp(argv[i],"--noout") == 0) { configuration.onelineout = NO_OUTPUT; } else if(strcmp(argv[i],"--deviceid") == 0) { checkExistsParameter(i+1, argc, "--deviceid", argv); configuration.deviceid = myatoi(argv[++i], "--deviceid", argv); //atoi(argv[++i]); if (configuration.deviceid < 0) { fprintf(stderr,"\nERROR illegal parameter of option: --deviceid %s (specify a number identifying an available CUDA device)\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } } else if(strcmp(argv[i],"--tb") == 0) { checkExistsParameter(i+1, argc, "--tb", argv); configuration.threadsPerBlock = myatoi(argv[++i], "--tb", argv); //atoi(argv[++i]); if ((configuration.threadsPerBlock < 1) || (MY_HSTPOPLL(configuration.threadsPerBlock) != 1)) { fprintf(stderr,"\nERROR illegal parameter of option: --tb %s (specify a power of 2)\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } } // else if(strcmp(argv[i],"--threshold") == 0) { // checkExistsParameter(i+1, argc, "--threshold", argv); // configuration.shuffleThreshold = myatoi(argv[++i], "--threshold", argv); //atoi(argv[++i]); // if ((configuration.shuffleThreshold < -1) || (configuration.shuffleThreshold > 100)) { // fprintf(stderr,"\nERROR illegal parameter of option: --threshold %s (specify a value in [-1..100])\n\n", argv[i]); // printShortUsage(argv[0]); // exit(1); // } // configuration.kinfOfParallelism = KINDPARALLELISM_PERCENTAGESPLIT; // } // else if(strcmp(argv[i],"--outdegree") == 0) { // checkExistsParameter(i+1, argc, "--outdegree", argv); // configuration.shuffleSplit_val = myatoi(argv[++i], "--outdegree", argv); // if ((configuration.shuffleSplit_val < 0)) { // fprintf(stderr,"\nERROR illegal parameter of option: --outdegree %s (specify a positive integer)\n\n", argv[i]); // printShortUsage(argv[0]); // exit(1); // } // checkExistsParameter(i+1, argc, "--outdegree", argv); // configuration.shuffleSplit_low = myatoi(argv[++i], "--outdegree", argv); // if ((configuration.shuffleSplit_low != 1) && (configuration.shuffleSplit_low != 2) && (configuration.shuffleSplit_low != 4) && // (configuration.shuffleSplit_low != 8) && (configuration.shuffleSplit_low != 16) && (configuration.shuffleSplit_low != 32)) { // fprintf(stderr,"\nERROR illegal parameter of option: --outdegree %d %s (specify a value among 1,2,4,8,16,32)\n\n", configuration.shuffleSplit_val, argv[i]); // printShortUsage(argv[0]); // exit(1); // } // checkExistsParameter(i+1, argc, "--outdegree", argv); // configuration.shuffleSplit_up = myatoi(argv[++i], "--outdegree", argv); // if ((configuration.shuffleSplit_up != 1) && (configuration.shuffleSplit_up != 2) && (configuration.shuffleSplit_up != 4) && // (configuration.shuffleSplit_up != 8) && (configuration.shuffleSplit_up != 16) && (configuration.shuffleSplit_up != 32)) { // fprintf(stderr,"\nERROR illegal parameter of option: --outdegree %d %d %s (specify a value among 1,2,4,8,16,32)\n\n", configuration.shuffleSplit_val, configuration.shuffleSplit_low, argv[i]); // printShortUsage(argv[0]); // exit(1); // } // configuration.kinfOfParallelism = KINDPARALLELISM_OUTDEGREESPLIT; // // i++; // if (checkExistsOptionalParameter(i, argc, argv) == 1) { // int ttemp = myatoi(argv[i], "--outdegree", argv); // if ((ttemp < 0) || (ttemp >= INT_MAX)) { // fprintf(stderr,"\nERROR illegal parameter of option: --outdegree %d %d %d %s\n\n", configuration.shuffleSplit_val, configuration.shuffleSplit_low, configuration.shuffleSplit_up, argv[i]); // printShortUsage(argv[0]); // exit(1); // } // configuration.shuffleSplit_soglia = ttemp; // i++; // if (checkExistsOptionalParameter(i, argc, argv) == 1) { // configuration.shuffleSplit_double = myatoi(argv[i], "--outdegree", argv); // if ((configuration.shuffleSplit_double != 1) && (configuration.shuffleSplit_double != 2) && (configuration.shuffleSplit_double != 4) && // (configuration.shuffleSplit_double != 8) && (configuration.shuffleSplit_double != 16) && (configuration.shuffleSplit_double != 32)) { // fprintf(stderr,"\nERROR illegal parameter of option: --outdegree %d %d %d %d %s\n\n", configuration.shuffleSplit_val, configuration.shuffleSplit_low, configuration.shuffleSplit_up, configuration.shuffleSplit_soglia, argv[i]); // printShortUsage(argv[0]); // exit(1); // } // configuration.shuffleSplit_soglia = ttemp; // } else { // i--; // } // } else { // i--; // } // } else if(strcmp(argv[i],"--input") == 0) { (configuration.filename)[0]='\0'; checkExistsParameter(i+1, argc, "--input", argv); strcpy(configuration.filename,argv[++i]); // if ((inputsource=fopen(configuration.filename,"r")) == NULL) { // if (my_gzfile != NULL) { gzclose(my_gzfile); } // test vero solo se in precedenza ho letto un altro "--input": chiude altro file configuration.stdinputsource = 0; if ((my_gzfile = gzopen(configuration.filename, "r")) == NULL) { fprintf(stderr,"\nERROR in opening file %s :", configuration.filename); perror(""); fprintf(stderr,"\n"); printShortUsage(argv[0]); exit(1); } // else { // fprintf(stderr,"Reading from %s\n",configuration.filename);fflush(stderr); // my_gzfile = gzdopen(fileno(stdin), "rb"); // if (my_gzfile == NULL) { // exitWithError("Cannot gzdopen stdin\n", ""); // } else { // fprintf(stderr,"Reading from %s\n",configuration.filename);fflush(stderr); // } // } } else if(strcmp(argv[i],"--shuffling") == 0) { i++; if (checkExistsOptionalParameter(i, argc, argv) == 1) { int ttemp = myatoi(argv[i], "--shuffling", argv); //atoi(argv[i]); if ((ttemp != 1) && (ttemp != 2) && (ttemp != 4) && (ttemp != 8) && (ttemp != 16) && (ttemp != 32)) { fprintf(stderr,"\nERROR illegal parameter of option: --shuffling %s\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } switch (ttemp){ case 1: configuration.kinfOfParallelism = KINDPARALLELISM_VERTEXPAR; break; case 2: configuration.kinfOfParallelism = KINDPARALLELISM_2SHUFFLING; break; case 4: configuration.kinfOfParallelism = KINDPARALLELISM_4SHUFFLING; break; case 8: configuration.kinfOfParallelism = KINDPARALLELISM_8SHUFFLING; break; case 16: configuration.kinfOfParallelism = KINDPARALLELISM_16SHUFFLING; break; case 32: configuration.kinfOfParallelism = KINDPARALLELISM_32SHUFFLING; break; } } else { i--; } } else if(strcmp(argv[i],"--eg") == 0) { i++; if (checkExistsOptionalParameter(i, argc, argv) == 1) { int ttemp = myatoi(argv[i], "--eg", argv); //atoi(argv[i]); if ((ttemp < 1) || (ttemp >= INT_MAX)) { fprintf(stderr,"\nERROR illegal parameter of option: --eg %s\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } configuration.max_loop_val = ttemp; } else { i--; //configuration.max_loop_val = DEFAULT_MAX_LOOP_VAL; } configuration.algoritmo = ALGOR_EG; } else if(strcmp(argv[i],"--eg0") == 0) { i++; if (checkExistsOptionalParameter(i, argc, argv) == 1) { int ttemp = myatoi(argv[i], "--eg0", argv); //atoi(argv[i]); if ((ttemp < 1) || (ttemp >= INT_MAX)) { fprintf(stderr,"\nERROR illegal parameter of option: --eg0 %s\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } configuration.max_loop_val = ttemp; } else { i--; //configuration.max_loop_val = DEFAULT_MAX_LOOP_VAL; } configuration.algoritmo = ALGOR_EG0; } else if(strcmp(argv[i],"--timeout") == 0) { i++; if (checkExistsOptionalParameter(i, argc, argv) == 1) { int ttemp = myatoi(argv[i], "--timeout", argv); //atoi(argv[i]); if ((ttemp <= 1) || (ttemp >= INT_MAX)) { fprintf(stderr,"\nERROR illegal parameter of option: --timeout %s\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } configuration.timeoutSeconds = ttemp; } else { i--; //configuration.timeoutSeconds = DEFAULT_TIMEOUT_SEC; } configuration.timeoutOpt = SET_TIMEOUT_OPT; } else if(strcmp(argv[i],"--unit-weights") == 0) { configuration.add_weights_mode = ADD_UNIT_WEIGHTS; } else if(strcmp(argv[i],"--rnd-weights") == 0) { i++; if (checkExistsOptionalParameter(i, argc, argv) == 1) { int ttemp1 = myatoi(argv[i], "--rnd-weights", argv); //atoi(argv[i]); i++; if (checkExistsOptionalParameter(i, argc, argv) == 1) { int ttemp2 = myatoi(argv[i], "--rnd-weights", argv); //atoi(argv[i]); if ((ttemp2 < ttemp1) || (ttemp2 >= MAX_RAND_NUM) || (ttemp1 < -MAX_RAND_NUM)) { fprintf(stderr,"\nERROR illegal parameters of option: --rnd-weights %s %s\n\n", argv[i-1],argv[i]); printShortUsage(argv[0]); exit(1); } // due bound espliciti configuration.rndWeightLow = ttemp1; configuration.rndWeightHigh = ttemp2; } else { // un bound, intervallo simmetrico i--; if ((ttemp1 >= MAX_RAND_NUM) || (ttemp1 < 0)) { fprintf(stderr,"\nERROR illegal parameter of option: --rnd-weights %s\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } // due bound espliciti configuration.rndWeightLow = -ttemp1; configuration.rndWeightHigh = ttemp1; } } else { // nessun bound specificato (uso i default assegnati prima) i--; } configuration.add_weights_mode = ADD_RND_WEIGHTS; } else if(strcmp(argv[i],"--rnd-seed") == 0) { checkExistsParameter(i+1, argc, "--rnd-seed", argv); configuration.rndSeed = myatoi(argv[++i], "--rnd-seed", argv); if ((configuration.rndSeed < 0) || (configuration.rndSeed >= INT_MAX)) { fprintf(stderr,"\nERROR illegal parameter of option: --rnd-seed %s)\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } } else if(strcmp(argv[i],"--exp-weights") == 0) { configuration.add_weights_mode = ADD_EXP_WEIGHTS; } else if(strcmp(argv[i],"--no-weights") == 0) { configuration.add_weights_mode = NOT_ADD_WEIGHTS; } else if(strcmp(argv[i],"--sort_n") == 0) { configuration.nodesorting = SORT_N; } else if(strcmp(argv[i],"--sort_i") == 0) { configuration.nodesorting = SORT_I; } else if(strcmp(argv[i],"--sort_o") == 0) { configuration.nodesorting = SORT_O; } else if(strcmp(argv[i],"--sort_a") == 0) { configuration.nodesorting = SORT_A; } else if(strcmp(argv[i],"--sort_oi") == 0) { configuration.nodesorting = SORT_OI; } else { fprintf(stderr,"\nERROR unknown option: %s\n\n", argv[i]); printShortUsage(argv[0]); exit(1); } } int deviceCount = 0; if (configuration.computationType == GPU_COMPUTATION) { checkDevice(&deviceCount, &configuration); //sets: .devicename, .warpSize, .maxThreadsPerBlock, etc configuration.deviceCount = deviceCount; if (configuration.threadsPerBlock>configuration.maxThreadsPerBlock) { fprintf(stderr,"\nERROR illegal parameter of option: --tb (for device %d the number of threadsPerBlock must not exceed %d)\n\n", configuration.deviceid, configuration.maxThreadsPerBlock); printShortUsage(argv[0]); exit(1); } } if ( (configuration.computationType != CPU_COMPUTATION) ) { /* disattiva stampa degli histogrammi in/out degrees se non attive opzioni --cpu */ configuration.print_degree_hist = NO_PRINT_DEGREEHIST; } if (configuration.rndSeed == NO_USER_RND_SEED) { // usa un seed generato usando system-time ftime(&timeForRndSeed); configuration.rndSeed = (int)(timeForRndSeed.millitm % SHRT_MAX) + (int)((timeForRndSeed.time/2) % INT_MAX); } // altrimenti il default srand((uint) configuration.rndSeed); // se manca file input apri stdin (con possibilita' che sia gzipped ) if (my_gzfile == NULL) { // se NULL e allora non era presente alcuna opzione --input // fprintf(stderr,"GZopening stdin...\n");fflush(stderr); configuration.stdinputsource = 1; if ((my_gzfile = gzdopen(fileno(stdin), "rb")) == NULL) { exitWithError("Cannot gzdopen stdin\n", ""); } //else { // fprintf(stderr,"Reading from stdin\n");fflush(stderr); //} } } void checkExistsParameter (int i, int argc, char * msg, char **argv) { //if ((i >= argc) || (argv[i][0] == '-')) { if ((i >= argc) || ((argv[i][0] == '-') && (argv[i][1] == '-')) || (argv[i][0] == '|') || ((argv[i][0] == '-') && ((argv[i][1] == 'h') || (argv[i][1] == '?')))) { fprintf(stderr,"\nERROR missing or illegal parameter for option: %s\n\n", msg); printShortUsage(argv[0]); exit(EXIT_FAILURE); } } int checkExistsOptionalParameter (int i, int argc, char **argv) { if ((i >= argc) || ((argv[i][0] == '-') && (argv[i][1] == '-')) || (argv[i][0] == '|') || ((argv[i][0] == '-') && ((argv[i][1] == 'h') || (argv[i][1] == '?')))) { return(0); } return(1); } int myatoi(char *str, char *msg, char **argv) { char *endptr; long val; errno = 0; val = strtol(str, &endptr, 10); if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) { fprintf(stderr,"\nCONVERSION ERROR illegal or out-of-range parameter for option: %s\n\n", msg); printShortUsage(argv[0]); exit(EXIT_FAILURE); } if ((val < INT_MIN) || (val > INT_MAX)) { fprintf(stderr,"\nCONVERSION ERROR illegal or out-of-range parameter for option: %s (int type expected)\n\n", msg); printShortUsage(argv[0]); exit(EXIT_FAILURE); } if (endptr == str) { fprintf(stderr,"\nCONVERSION ERROR illegal or missing parameter for option: %s\n\n", msg); printShortUsage(argv[0]); exit(EXIT_FAILURE); } /* If we got here, strtol() successfully parsed a number */ //printf("strtol() returned %ld\n", val); if (*endptr != '\0') { /* caratteri spuri ... */ fprintf(stderr,"\nCONVERSION ERROR extraneous characters (%s) after parameter of option: %s\n\n", endptr,msg); printShortUsage(argv[0]); exit(EXIT_FAILURE); } return((int)val); } //***********************************************// //*******************************************// void setstat() { // SET DEFAULT VALUES statistics.processedNodes=0; statistics.solvingtime=0; statistics.alloctime=0; statistics.inputtime=0; statistics.device_usedGlobalMem=0; } //*******************************************//
luks_fmt_plug.c
/* luks.c * * hashkill - a hash cracking tool * Copyright (C) 2010 Milen Rangelov <gat3way@gat3way.eu> * * This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com> * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_luks; #elif FMT_REGISTERS_H john_register_one(&fmt_luks); #else #if AC_BUILT #include "autoconfig.h" #else #define _LARGEFILE64_SOURCE 1 #endif #include "jumbo.h" // large file support #include "os.h" #include <stdio.h> #include <string.h> #include <assert.h> #include <errno.h> #include "stdint.h" #include <stdlib.h> #include <sys/types.h> #include <openssl/aes.h> #include "sha.h" #include "sha2.h" #include <string.h> #include "arch.h" #include "johnswap.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "memory.h" #include "base64.h" #include "gladman_pwd2key.h" #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #define OMP_SCALE 1 #endif #include "memdbg.h" #define LUKS_MAGIC_L 6 #define LUKS_CIPHERNAME_L 32 #define LUKS_CIPHERMODE_L 32 #define LUKS_HASHSPEC_L 32 #define UUID_STRING_L 40 #define LUKS_DIGESTSIZE 20 #define LUKS_SALTSIZE 32 #define LUKS_NUMKEYS 8 #define FORMAT_LABEL "LUKS" #define FORMAT_NAME "" #define ALGORITHM_NAME "PBKDF2-SHA1 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define PLAINTEXT_LENGTH 125 #define BENCHMARK_LENGTH -1 #define BINARY_SIZE LUKS_DIGESTSIZE #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 4 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #if ARCH_LITTLE_ENDIAN #define john_htonl(x) ((((x)>>24) & 0xffL) | (((x)>>8) & 0xff00L) | \ (((x)<<8) & 0xff0000L) | (((x)<<24) & 0xff000000L)) #define john_ntohl(x) ((((x)>>24) & 0xffL) | (((x)>>8) & 0xff00L) | \ (((x)<<8) & 0xff0000L) | (((x)<<24) & 0xff000000L)) #else #define john_htonl(x) (x) #define john_ntohl(x) (x) #endif static struct fmt_tests luks_tests[] = { #ifndef _MSC_VER {"$luks$1$592$4c554b53babe000161657300000000000000000000000000000000000000000000000000000000006362632d65737369763a73686132353600000000000000000000000000000000736861310000000000000000000000000000000000000000000000000000000000000408000000104f386b50df3fcd9132589a934851faaff16709ff628ed0b628b0d7151b3600c0b3f95d8404a8b35fdf5dd6b6ff10f4c352fde11900010b1762663664393836622d633836352d343261622d616534662d6165313336633938383735360000000000ac71f3000430f5d9c39e349b48d7cf1771d9c152840b389a4353ff186436ec75cc397529ed40260000000800000fa00000dead0000000000000000000000000000000000000000000000000000000000000000000000000000008800000fa00000dead0000000000000000000000000000000000000000000000000000000000000000000000000000010800000fa00000dead0000000000000000000000000000000000000000000000000000000000000000000000000000018800000fa00000dead0000000000000000000000000000000000000000000000000000000000000000000000000000020800000fa00000dead0000000000000000000000000000000000000000000000000000000000000000000000000000028800000fa00000dead0000000000000000000000000000000000000000000000000000000000000000000000000000030800000fa00000dead0000000000000000000000000000000000000000000000000000000000000000000000000000038800000fa0$64000$16ZmSCXd0RPSNXdRfTOIrQHCXSDZypjONZk0Oa/f7c+MV25Uybp8nxhF1Ez3+C5H8cISxvHTq4uSMWrloHMk4i50+n8J9B5Zm1XxZ3eVm908kfxCDGOz3SRX52e/VV0YepVgzCwxEpuHQRPfL0df8j77TrMdAQGlnA7WGjpn3RLKAHVNzC/z1ISQzgdA/mHZEUUvrswqzXQ+uy6bAidLqPmHfbRzso1NFFGY+Qc/twTvWmM1yvxj6Ajl3Iko5+8TX9MwC60u+U8p8Bcg98RfNhYz4/EzJ465ZIn1dJCBGcdsn1Hhd8ibHw7iZ8E7Fob/ij4fzeh8MmpVWg2tnGIvoWCCa3HO2/96LykfPcEafQOVpClOBHHgCdi8NhhV7SgQmP08cf8LDZXIFL9c6bmDns99cWOyWByNaaPTQb/A752FAdhepwbJFK/1X7vycFs+pUY/7vmeW+uoYOxAuALHT4OeKgnzg15GvLmRKoyLueNy56i7kB1rYrIgjNfkWznOT377awIw4mGJ75NZwFAIG8mwTS4QQtcRHUFvuB8MmvihSwPcIrtV6F+TIz+8NZBaAd9m8kZf0eDwUInOdkKlZ78Fqr53o4gB9pmMD6TvOL8oLianIFK/mA6pTsstbCg36qauUYI274LtQRKyet15zTtqRl7MIW2yTxVImEZDpo2QUhYuMPgkmu1CHyMinpUahVHADvHGZaob9J2PLX2956Z9fKpZ74caeigL0mZ0nyV3x7+AlNeAI/VZ1dtObUPtheRb4/+h9D/k6dUckgnn+xMwfBg3woO1h4YajS6zPWFCAqL+RZk0F4tTtjkD2z36jiqbvqWAkDpySdTvrLqWRGxoV6R/TNy1Mc6XHqbJhJWbNfgnpqNEVIDbsKq86LJCO3G0PrUDbTzochlho5bLcX5ZXUR5Jp4NiAvs/nmUWdyoB3MlgW11OmEqJ/OW++h9bUj5jZAGE1ITaDiJ+Q2gq/lSUeiq/KaL1cS6w7AfKjBIFEBKuzIS65832CsnxCRGiIlDE6jCdZ1G4pp45AYsJMB89hwck7koSRSP69/MpErVWD59x5CrURE433QBAwNVW9Stn1Xb0p4FFrVyJy2EP6wx4M9L8/+xDHDEoOF/mByByKAKFdaod14Kka7ftfKHQ2gh85dv06iT6JfB8u4/HR27PHfGaZh+1OyWrO2FOSjXriZHbb4IpV+gjXoGUEJ2Qqbluj32liDKt1/HvSjjiRC2/R5a2fraVrHKmF1ZcuJMHFH/bMExTQYDsDa6fVBKpqeg0m7uYOO3ioIJoJ/VvBj9ZJwFkE6SSQwos4DaY50h674wLe1Ro+5p7z3CDlhE412XYgWKucIIY9GVcECrg3ghh/gR6WQVO8E2fJN99jAfGCuD162nSiqjTP0W6ghKeQsjKmhtXqPIp21NMq/O4A6nVSkCiOsSmm63IlmR4sjowhZfCEbYIewPBE0AFDuIm7ZMgqF8eIFX/jySxPduTWnwlmQki6B/lrqW1bb8fl6lfp7Ko1ZSj2hLerZ/dJGEsYIBzvL2yj/JlXSwzEdCfMkXQ8wvAZLlrvU3AHiZSeLCk0gVQsabCnQuaQDQgx2G+TeN0CKF+KCTGlIUbTS256wilxV6Dop12l3os8Kd4hDMt3IW5spWATBKKojypIKxWXXqyfObAP7S+c2fNqX3tMO2Qz/4LpyFSHte3MrjPbBd6XlNs2cj9zdqNEpPPeN6XqsdIZVRJ/esrcJ1TUHPYyH/rKJjBPMgi4ap8WObDdfg1HmJDWpvBD+YI/WrUoPxJdYSHpmMfjVlgykISwXdUWZdXgQqoLuXKzyNE4Rt0uQYJu3nH9KGAMPTrqfqSUDdyeTcVsHfMkrGcu18tcNip1qvFmL/e3LEk7zeVGeVtXJ0dKlm26P3w2I7xBltX2t/OQ8Utztqd8hgPHZYeFFurSUT6IHcD6VX4vrTDdq1RkrS6YHhJ14QseEzXcHMYBJq6gja2T7aDKm9yEQfwL1dkGmtDqaLtDoW2i8irPMvLAM6FnY4kfZubu7+IKMpHZPIt+x6WBCAXxbXZ1QHD6EKshVNaj+BNm696Z6u1C7EI5WQ5jSSnvoShrVxAQPievqoV12LEoqT9fMdMGBJrnKkZY+gVZsq3BoJ5njzm39M1/i2A4cpJJQEGwuf4vvgAsOKf2zk2spfkfAHhbVxAyB/cdd3nMBDEds1ow67lBzAT8ae+Lxam+EzszCuahpQWPPMXSBiTteqGjvJEflmzeD10Fxa/xEhPWXWkr2UgbGeI357VoaQ8g9WUabiHQRfNpTCd5yAwcsBZBFaQKfx6nYNxsRDR/Ii50zyIDuKj64Dwdwya38Ov3KOZFZ4q3SRi55dtFHpCa4sZL375h9OVIsoYoGxl4aWM2lsMQB4jOaVy8aFj1yMy3SB0KF0Rg+nHsn4OxjdwMDSFp4+hvW0r+/OArn1hZrQfsejmC57C5aVNRyw+9NIA3PmykTc1h+LHG1dTg20DCM88I2YgONs2PVajgBdXJDftzVB7N4S8icy3VH2dYDcO/J1jd56eQ4hnKnMzGAmtt61Zinx/kY/8qv7Kha8yoKiDbbVHJHkQZoTW3gKPc6FgK/FelQ5rUlqaWBOnsT6/PpzzQtckVkbapBUQdyIff8cascNGDvCwJB/ZFe68Yp5eIeyTQRZyzKOd2i3W1R2krthpDjS36xyON0Fi1DZIcE+llT0GKQMznIBLdDbwFcqMt8OCqcn2HRqvr/kH4AjCwnx+FCHbO6XH++cfXulwAFLqgEfRoD4Q/IoLCHPEM03ovBYQCZoWNIpGJpjhTQDp5EEI7cz6letF83rTK4HeQWizUEEoJjgC18nYK0SuX9XSo8we817I/KnPmX/DDNBzjp2W4xXQu8DtZgb/fe5r4urs4Mrx3xUWzlMZCE5NuF4toNh961PEXuVI4nb1TeXAbqmKz85ERsd+uWtncBe3MTxlcjrYGwggz7wUX81WIX2tN5tcXbYzK4W7A17p5VQNS3dDjPERMGTKl2rrP/eDw5GDPxXeSSX8oT+IT8Rr+77WnoV3hWNFzYEtDxXg31yvXyQXAPq0OJojfPgerHslIP9znP+ku/h/Xtkoi+nGno3+oeDdgplhb7dEIG00m4NK8dhQwX//fNCukJudYaux5xFX49n1teM0cGsqXdORKPLWWaxBlTiXPYno0xaeUHOifRcemjSSqB9pIfmNxSfsBkFnkHbmXPj/BD1S20Sr5+SE7hh3KixPjC7ohESHuipWBVEk7CYv8oFeV5EI1Tos5U9VQIAS3YqL8eSmXjrUMx6Vtp8zj4dY+J+RBUQ8Cz56km0c2uDxgmhzA3VVreXyD+0MUJN4ElBaRXe33wRkp0JQM2+Btdy5cBDRP7qVMpEjYndvSGZD+UBlaFTgLpSnvK79j/DOfHENTHirK+dknhhshDGpZZlONywfH55ffejiOiCEC9zzdvREKOjhrSfUSPWnGG0Rb5tuv0ldHkbb4YxO4JyFtKZJVygB8OlTY1BddEq61RRLpdoUlvsXlLeApWUNFAsuxM9md446iGNu/Rf3RoMxL0NzVmKZPo0gT+a0wW2CHEq7k/YvHMeg9gcRuvtBWSKUkqIgecaok/rlvZtOVJ1/EX0uRpxfkkTcy9I+MPLiKhZyqSsM8OwYjGHHOWSwrfu2ieCTEyVgqzebf6CFJs07k9/hn2CF8kbH4ewHzNJtvQE8To4VGmGGuf2lFuLQ4CqtWgxcLqhVZ0CW0ZzSCTVDeRXWqJSJifAdjQAcm53cX8I65dhXvNjD4zHyypgJAb7otbNyjuuzFS3TXCPOb9dd9/CAglgwiibaAxqX3C/Z5QBVo+nKm6iZeKRm7Rp5qm6I8xlYkatboUkDg84SFZJvxM0dpP3Fqv5eKkk6jRKq81hOz1VRw5htatwopRJpwI3YDcSc0JKT/PaQ7afMH9fAPKBl9+QIbdnFKIM34oxZei0WsEQdGAQeGDi5rH9fs3wl4Bb2OfUSsInrjJAy1rsxd2UUB3VfTlUZDckiGxVL0eISewKDHmQs2c+xGMbQZ1u5d/mrWbvA1fCGor6y0FWxcm6ysW5+oE0Ninkjtx3gsEBXK4bAQNlaqP+rSi4wh68VhdvLPFFOZO1u53jb4Lkc+wEN1V7EVBuNhR44TjEqQ5asXZbnWcFoJr1pIo9+9Hh0OHlRtz34zGNrtXgVDjdY9voLTdMCOvd9YaRFrOAWlmSwpMpgqEUHsg8T+9XXbWEcKVEPEvKLeCbLUSLgRF+EbpJ4ddIQxO4GDVr+FKrXKweY9A6XBhscAg6JyZ5IEnc1TxTR1Tmu/wSJnprBWcQ+KMdFEXbAFbkj2gsPhJjzJajWHWa13rKCrStu2cYwN41U8YswG4sHrRdMso63SUXX6eNIRVeaHvZyzPZX/4hzEVQ8YJzevhaIE7HfwLsVGmozNUOKdG7lBR7gKUmsO5yTfdsFmIkr4ylTEFzYQSMKhGvm9HK6o9C8ubc8/TZ1kwJzvxRoHcpFnIRq4rDDk49s4+yenQ0atmHVp+vR7vxErssKkJ6AhmJVXITy8G8tcnXvs9xDJBw6wj7ku8JYAjk/vBPNIDwhyQn5z0rbgr7MyAFFrE7LxGzCY2XpeGIubR2d0CQJN8v9LuNhPBJwUKriWfnFcWTQ82o99udMzuYUQojkdrIA+QIdiDnaJfOsySUNG5jYjGMFPoTQ8E3ROeP8Vi4v7QisMzZmXFq+8RYEENjelwSNZZvablrFSlXnjyrgeA+RaYsKOgmPEi2x0DZUXpB4GIiWHdD/yUVYa0pvKLhNIE/ZP7Bscz6bPK6OS73/MpW8I57PRLe1n9fA1tXc+sGAxKLNzkRCt2tDKSoGFxlYh8/cTnub6jJPuf+glMGBJPRa8ttxVoRqedCymGKKevg7wEMaNOjn+Iw2k5vm2ZeL+KO3eP3iAI0V+iLLJaozS1vazuFsfiKAzgPZc5VLypSzC9rgf2qeqpJlJvmS2OF/LjXTgj7lNTU6CwcYvJ0xzjOKhEoDf/EAhBYB0OKbJk3v5Wa+Odr7wAop9rS0RCj5luxhYL5RBeP/l5qPplrN8Hq890f6deUxOSHjbl0tiTluzZE/lo0Sreb7mmEx4OO8+F+2GBSWEtdaxsmnB0e7VNQG8hD9A9Cq48QAE4qX8vno3VKo7vvtGpOAlGAz3h2CTg9pKQ1TAGmmFQaa5JXZlFKGStti9H8oXrMXbXGz/2HmU306jwIxah7vBUOvRBoWS6+pIy8UNh2LKuS7UDkEGz9gBYTvAIA2tTZU+gFZFtrVfGERP4YAyxH/UayVMiSaU9B42oEUsml88Mv5bXRVtUbpF9OEjk1PVzG6XnVqCZDlxKkUo7bkV0sV84+XnTc9HrYnJMt0m5amB7DxWVIziewfHIauDP8ggTaGHwE1FYmDYKC+PsDqQipGHABCetYe23gmVc0DLFfZ3mAD/0jYXWVE1Dchn4txB/5dbupiZot/4cyuiFMNZOLw9UMDakSnTWjcXOV05mKJoHsFEedpVIgXtP/lSJW/cSOARLoGJxB942vZNlOeXHrCviMDxbzLU/E4mp5Og1WuNSOjOkyV+KICowmNXCzeWADvRcmQ2D4ehKE/g4gtCx+bahlSRSVD7qjKXed2D2w99+FjuA1Bga0PVs+LdWJwLZTIkvKwEr0LA1Ai0xlXpDPYxr5FZVJdQXTw20PiHMs8PFbnLBlz/+Q5zkZBOGeyd/j0NhgB4LVOUOkGS033TwIoYPbRq4qSN26QhDwcKjxlh/y8WSt4T4VpEbisvXyfcQ67wzPT3hmXYRZvlMvPQO8QQ+gm8pWqQ70csND9eXWLxufrm9MZJ0Al138IaAJpe6SzIuEAwh00x2DdjvTE6bY8OHEKoiSTv1vtXkVePeqNkEMEhr9XEs+aKa+hW5j2XngTfc70GXR8KkoDP/U2Nquhc9M3MElPJFZdjCn+ubm+2Z53SU1s88xDDXlXFJFW44eyJWW4rfOph9UiXmT6XRDVRxf3YSSB4bBtKxH8m32EQHz9V4g7kR4TactMeQ4nj/ng2LCSdl+HjdlVN6t+o7ZlEBt5MwAEMADHu5Zmv8ATVkfTFt7HUlEv2rdq0468BkBUE47TRI2gJ9S0MJe64iIgw14ZHMbyJvd3t2Uzqrwli7dVGaLiOnGcRKBkqW17GWzIhIQZvr22NPRa+tniYlxJu5rKCwED4Mc0cN8mTh0+cnDyaib3fYBBm1qzB8fbV3tO7zqfFRtBnh5TgFFldL0uy6sVIsiW5s4x+6jD5/ulXPMsl7j2Og71OKv1MsH2HGZU1M+h5Amyg1EWAgvqK8v7bENT3M0Qb0v5RP/ALz+am+LsZisiS034eOyxb+8OSOuL2oSFKUDEXMMRDJxTj9NawN+QoDMkX337A/7YKtrYclzfhsngmQf65oBisGBdO3aIcCYH/I5FdZjjfrTIs1BoLz2qdN51M7qkocXvz5o8d8Q9rhKxo6hFRkW799SKyoIgLFZnjt/Z5VEW/yNItehEcrbv2MCd5Rx+GqJC2I6MAV9QYmErsOsS9tRFWxFUB6WYWaton3sx7K2n1FAqQxZXuF3kExxyFlhVnbFhPwwNV/xQ7qEGSmjY625eSByrxajVpSRhdprn0b9j6BIADzXS6qOHsttS1iVN705oAzLvZLv/b3JtMYkTCu2XBRX8qsda/4tvCK+V/WXE9ZTutujmeKui+qkOJSa6Bh2m9pmUQuR534M4+Pkh3NCISZTL1rZdv6ADu3nHWDeo9dr8Fo7HbYllyR06D7Av4ekBfHb0APaKL3CV23Dtfc3+T7DVqte41HDbjxhGEwCW9Ak46bgtGqIkJiU5hMYRahSO2IGNsmxIwuq1xOei9f8e9Ml4ZdXPriTy+WxSva5e+BtNSv2UCrrZ507bxr+GHIyajKWnGa2So3izxzuBWcYsOKbQAKL1lhkdUwoiGgNBbrcQwkDLXd51bM2TWFSsMYBuBhLDQ/SGUPGOml8kN3D+cgKfds/yAHOTEfyIUJwHuJpSFs9u/mCHCt8mwVWAZwIViPx6yrqEgPsIjy03sZCS0IsM9HxNzZlPBRdEzzsqBavjjVVfqQ3ue9JyU31EtxfanhV3zFieey4h05cHSqvjicrSvQ2n82zW0AFgJ5UUiR1lCBtXdI5tKTFYxXh8cipP43jSXeNHShpfpx9pWS4uvyBdEKFJf+JzFI17zvlSP946SQalxccP6O+2Gw7VnKImZ+4db0ZTdwtTtv1JWgq5LcQaxtbZ8QthyYY+DlSBCjxFZ0R/2PuYGDApXvq8O4qY06+l16FX441l/VUTH/vUBYIPWsqZ27D1ReDe1ZviWRRBrrQ8LFY3zvX4Oqt6DUFpU96OvCgt4ABX1K6EjTgipb13l4mZ3tR/UAktUcCEEmpYet3gk0id8yVZMVSCghTdqSsfXcyKrRMmGiON1tTy4kb/zwbKkuY9OmD95pVFOd2FfyBYsY8Jbdb/W09YmV1cuWAWDXxRHcCw17vNmKwAQ/F0hC7FWwuuqYO1cswiuZUleXgOHexeJ/WzidCdfwCpamvfWjgSeFL2gF9XbNZICL/lBGVi7zFWVAbxGdL2+X1Xyb4xhaflFw1HPL6O1mbttBBN4qN1oNtZxjKTgfZ/XJcRM5agNzR+N74tAPW7wtyjEibF6NQGQ++1gx/hkcpmWAl0CYask4R9jRyaWdrfhSXLpA7RmQBcpz5v7K+hzlZ6StGxjUepbENVvIu836Ve6Zr+9d1zDqQeUjDfrT/4XWgd7VAu9ScZAHtMHaCeCx4L8oCw4AHzoYLK58KO4jCIL8+jnZUzLaIBO2dJ8S21FsLzd3zjgepzwzZSbOD7+bZY2KbBB7voUERg3byZPc0ZwTSak3e8Vhs/IXTqRnaOyIPvLGLbz9pomXp3+n7yO7ZQ2edhLN8dfAuwUXe8HAmMKF1EvPZ7MA8mt/PYw3eJbW8gjovVcnWm/uQGEaPBIj3b1a2A/E06GsMKu8gxoWwmF9xeZ8AJGNY2nwT+0vRo9eCaBhos/uZXAPhlRcyzPoQ0Lgj7ozf2lEDpG7tSwp46wh9XMEPW62v603MGChxPPeJk5hZqD2fmp+3voVrXKbsge8NphWKFxJy98XjCdAuGlgK6PB3P8I0/NrnQmBP9dQvEmj3tjvqf7YIbh2PYeO+VGd2Zt+Fh05RWmSIDOJ0dYyRA77/naqmEirNfs8Id8KNYkvGc37secVd6MM+IyioD2CRyyT//XgKK83OkKcPeF9ARxb7TsdNlBTG2xTqeD7LOZx3DFyM/icbKa0NSERfSut9IHeybVGqFlKJOPngcwq+ODJk1FWb/tkYJahkritxOKaA9Tv3RLLYL7zu6CYIzCFtb8xdbRfDRbCTcNFNOmgnsNaNw9EaPACzKlKdh0NiB/p7NitWnDy79UbX6aDvvU5+v7EccDxiS/QtbhLbE9Akvp33W9Nn0G/IMEWlthe7ZziF7zidLqzoxDZoFSvdaPZCMh4R0wrbRAL5MAEU1khx9NRqmNQGRI2eY6dcl9Ft134Jmg2Qvt60aZJCmU6HeeyihxPf9S3szbi4qKZHrqRYJb+aDE3+BLm4wX/u5bQg3UQ6nyN99m//CuCmtzoM+/nmNzD7aLAdWxuzxv4KnQzfwVwuvKzmWLQOr6sw7zK9FVZ6EyVa7iXsCaK1rafAWUk6JdFpxwIa0LcZvyRNwtn+VXF6jBg5/xjJddHEV6F7b+w5CgKNrW1tOi6qHf3RDvKx6iAiuEaE4toE9XN7EBSNPI9BT2Dvi2kNIADbfoAccQZSsA9pVVpFGZFfnINV7oa8SpYGVawIjUqW6QlTF0PeaEUv+IREJjQlQyBw5+BHhCY9xOn3RzT1XaOLxpZ3wpDmvZ02YbAH/YadOUEWVNYNobnqxdJcHqLRijxl8fb2HKzreomOL/w/cHVYUWWYu6BoK9iLOHsN4hIY2/scEREKk9r4N7rKuajbxs+SSZ1mkuLArMCJnev8whLbqFCF5qTNStARATU1rI4ZBDgfeGD+YW/JcxgHWAfkmsBc3ZcLWMvKEoX0qSQhstbsK1DEDoT4K/l+44sGZdkC29mM7Yf42Y7Ncm1d0VjMOZUGgN9SlC2d/AhxtoFMFoAWEFo4c/fBaj5MuWdsVRVB55dqfH+sZXiZl0QQeUJxya1rKfArAu8sdShwV06y/Oe8Gpjd8biF2Fmg40F4PdWnxW92orlF6yBYDuRX48KawMfMv8PE4/E92T3MUhe7X4wdUI1K3lfwkEkKyD0gjudimZQlXGJE7HB1a+Ozci0A4xysUJkXnkWsRl4kWPwYPBIhGoxWD2bJcWzTOJuTdcO+4dN3S3pnLMpQMxdUnAveaBCeX0xbepgSHhPIPy9OC9KNUw0L8CeqybUTSmIQXPJ7OvMtNbxQMdfquIxieZsC1Moa1MxV08MX7pc8ybhKDp8HoZpUH0JBnaOE13uYUZMcM9MQFEeq/Hwk1E+B5ZP3gOoTbidH/3jZaZHE7ldmKXihBHltLZLgjWsLwlQym8BHOpe1qy6r+JAFKdmy97Dm2d20wL4sAl3xMvmGFtb0QTc2GVEzovzitSG/w6hubuwRkY5Nkr8qV1KNbiPWj4BX/AaG9GfygVF8Y1vXW+81uxR/dN0vca4UcP4ctUx4wYFdpqsprBICfzMOaB1nl9KGfXUL6DVgJ+RfxqKvmDumLAInq/cCUbcabMEZK+8EPBSEuiiwFG7LmBqVsm1rgBZKLch73W6jJ0raGAANx7QWV7wfmGlWsmEMzFO0OX+rJRcyNWk1qPfnL+EC6yFGM8i0n5dUioRQFAL36yxlVMklOYvycryTY+99sZaaclIazAvhoyWc/fT60reJ7NcwSEIAB7UhtR+iuKEDBQwDKneKNiuvbwAA1mtubgkLLjBLMf1Syo6VzUPMFI9CW9D9eBsXhU8WYAVMQmm668+FpQgfa5em3tzw0/WUz7nky9LrN87+LjVBQB3cAMaV+pY6Rx7iJU6h+Aq/a6eO+uhGXBkOcNcJRShKQaiMr3s/Q9kxkgNX9+sAGZP/OvoFhTwYGP9MSS7tHH6XZMk4NqYnHrNR7md0S7TC2VPyVcP8r7bukAlAKqU2iAOGvCeOVUthHK4VtI3tvLQHm7cDxEopYUAq3OBNqIejmsZ05uwpTpFisfWcRYtuSX0VTeiqlkEANL1wcq1WAryA7YzXqu3af+wOzBk2psVHkyvTkeabiHkhYRPzEGQPOzGAwQMygZKUkSQ0CoqLeO5OpBblGpHokhkuDcIeM79VcqfKoIU8fJocyDex87rSnkrUAaIO/WDI+OU9TWBQTBl4Ui3V/ypoVEYi29CdovSoWRNdS8r2dYivVkIRaQ8XvNqNxEuH4cYXzpCY+Co2MM9wHHgn2EMiIGtpjU8aIft5lVSNvg+Cdpd/hMFkfukV6EkNiuRIBB9Doku7OFVj7Trqt3IN4mAvXqRItz3SedacGPU/ihGnYVq2+26BpRnBQzF95Ld8yvIzp6+vebplITsEWywUNIzQ29BO8iuMwKd66Grd2kxeknyMCS+gEAiLxYgB6yohNS4ZbE974Ttch6dgM7huGIrijVrHYEvlTk4gd9gL4uiuStAFrgWZpxUrJoXqsLCgVVmUgGm/AsGMDOrIePoPmrKP9mI+Nsbf11VzwYDoby7doWLs80seqFT8s0efUwesN8mZ5NfHapg9cGuGCvUM2CPq5trVJsHKN8itFLoIiD8Pzwd+KTSf6ZxAx3HrPGRQQuSmfjCXF+uPx9Mj0FIq5iymOh0gYeY6iSkl1YrQNiSS6STJmdIAivJJqbPrTQOZIttS0JejbXuiC62w2t4mnts0O2SL1x1iS7JoC4DD5ThCWCYZU98abcSWjYT6C9AADDfYQIMWTtNq1NCX7CaK3aEx1IY17+wxRjbdlE4adBavxxr3tMFra95tL+CjzTlRe6vA0Cy+HfqV6+9bHZjuG8wI+A8bbuv6ShKJv5f1DhGMZbkzZCMGE9llvm1epO+vgq/XdZNepu0YxyWnTfO0FTIITIenTNo7rKh1RPEEoycJxkdEyauoXAG0pGtQt/v8dxDszke0735gEWWsA77FkDwZfsMDva2V9agVmpTE2e0czoOubBuVpkIkqPVa6Y6DjfL4GYagCXZDzTmFFi/Zbl7C8nMmtX+60nddQRJgHyU0l0wmLMJbWHYa5M1pMfwG0pvrklo3XoGFn+0T+EpcF30z2CxE85/WnJJSuPzDvToylpt4nC4RihnCwT+5meGgIBnxa4udJ0DAQXD8hPJhoX1zkVIW35KcMY8pEnfb+dGySDtRzTzsaTsnzgnSG2ScxUToSRuzQ9BfHpb/nBTGCgoJMfmjQyrq2CZOsLGXngSvLpoP3OvVMhif9TnVZyqYxCJllf3VT926HZUzpI3Oohn/kotUn+4NZoZsFwrPU5Ljijnju8GOaDGfKniub1TKPHwCHLEv9IFEsF6lAajxxJFbm2cD4yr2a1ekHAp8/QZmHxyDEc5uCF7PdKnJZYdhpGPhvQIjS5O5zVytFd7huWFE07qwq9w/56dACZa1J6UQ/86GO0d2xGkc6goaBwebCJyHiF+iiOIdBsMjmwOCycwk4T4OjGovACooc4cwzwUYPtYFJ4591JUR2ICYZRZNtbR1xl1BZHRzePrQqE6AM57l++L4mX1T/OJDGUt66na7WJWIkpOONoZMTJGfHcs2nKrYe487t49eRYqat8fDtqED6fFXiRxLZnHxlEtNTCzmiY+WP0etwOM85SiJ52lGVEaXZ5KMcrZ1PIDBaQrTNTZ7RZftz/xpTGGXp4lweaE3VGSyjyrguo3IW/QcjydBiBr52rtqN6kEc1Le04a9ZlndHNxAE8UUyeKxTT2kucKGHYo/n6BCG+A97lNAA6HQTZBQ25ncFpz34eXjHcGpMJOlM4qomBkz2ek7P9Lyuw/cTI4oO3J/Bs19TIwiDlYsYIq3N7VeCj42aOxznUNblZJVEIcMzTyfzqfYlx1ATWyP0Gu7JkEF5CrrS//1ozo0G+J0vBLuVnUwMlifz+eeK40r92DxXU7F2UuFRPKQbH0S0TkKXLt044sUbxisLPTDPy+h02pj3JTzamavsBpVXS8mo5yRPUxjAuXMoEq7UfRb4q9R33GfQP25ir3ZZwnxWMi/85/WNmNXc3shKt2HLXOafdsvSBPkrJw/J6BDV59FAZySxJOvv0Sw0PqMXAymtL97Cze7Y1u8dIyuAv2FAWrmBp87JeeAl/+2krQmONbXbKLtpi5XMNhNs64QQvlM1XNP5oY8J1YU+1NTbV8++Rfl7XCFHmpWi1Rcc9FSPIm322dAYf2SLMu1xM9T9vy2qt7zN6eUe9VEKlTGAVip6PdIKCx138BV+LEEysefD+8s7LcSC049bxGy6qxVpxKMlqlzerU7kBKxFSQB8TFwRwC8wt1tAiqHpuJFpPjVgIrFBN/Di6zuzdT3JnaSwBe/Bmb7BjBX85+bK4CE21kdGiLCOhT1d5h9QExL47TV1R3ZuwapOb84iYYCnTdD3xUuHvMZ6W9WwY3N7qFTdpQtjPQLx3gTnIhIwYJ3JUBmiw1tIpPF4gCnt+td26lCV7Ab7Kp7JxNQT+6JT/CQQoOLGS+bhuYzu03xWfAmfFAibrNZGpBXJOfgYwnQwI5oQJlYT139wkzMP82Ige0U9QALgkLHjusvYh4iAlNRUslUgKmv6Gi+Y+jWPhWH0F1S/8jxMr/J2hOigb4LaXha1V3qmgK/STNE0kZ+6lgMIRnkumZDpRpSsFOPOCrai8ro94Z6t2Xlo0F6P9JVubNYhaPN14ZRMzj32pGaCMRTldK/NTOsKaUHfJtJ9lCrdbpEPd/Z0jZC5tblPsI8ciJA4kZffvTg4gMzb45dG2j8rb9qp8v/tnUIZPo79b6S/Bc7Po01pKgC0AzJObUhKYoxtu4PvXpyjqpOxMrM7eBgwLpOKq/qdBFFHKnYqQXPLyY8NoZiy30ctHMpS62iWHmuC+T3VGgKI6fXdGeCs0/PkAnAl+ASrm8Kcy0RUUgBtWPOuT1qB4E/bMMsDk19/3bAbFy4MucB/26jUv/tYEy09rQCKKhtLRQkjWcIAAmklOUCuor7SkyJfjgh+oUiHNzXUbSA88ZouS+TVASspb2+J2t9J5CWKYPeSbbPBr9XU8VlCTF/hqgKFppstYLPzKcvGffahA32ZLtGIS7J/WfItXkOfqltwQq4vgWB8kJ7pOyW410VLBS2EqW6Y5pVKrsABb1uSHejPJyiYKa2QPaRNoPCJbpillNsBLgzqHcHC3BzsrvDwcyUEhtx/E9PIXVnMehpAbsU/dHZvuCpHCldr7qbFwiAv9Ll1lIwyn89blYGqxTfbAHSPe8UklQjpnCQxm4EVUp983lWZLfBIadT0XkUEAWsidN7paRdS4EssHnaWIEA58+THc4z0jKP9g1cNNy9fxuOD6XCbVAgyFQljK3KaiYE8xxJInOcr31lLerVeb6dR70a3DotNuEtUo6ZzLRcNOkEOnUzWDymLRjrBb8Dqj0pYjYzWJGbpgTQH0JxeCXXhb+xzsz0/cvcZzMVYEB02uEzpB9C26hYk7dNlig+PrF+b1yR+yGZvuBzTrU41W1KahPAfNg6Yh4gjirZKZZ4B/yahzbsWNy88H2FL9U0a9oIMSFy+sSIHxP6Mod5wlrBTjodIg0rzzY762G4JyQmr4qlD/xdZB6Z8tdfkkUGQYbZDYZyT7uFuThmQKdgUe397UxLJPjZJ4+w4C7uK+LHDLD8wTeHYBre9yrdfPK0NbOh/NVZTIG0BSolpUij+3zKlUmFKOoUFenhQCJzAjxgWifL82w8z7JpG2R22OkFCaZZhQOaFLdEaxLUQNb1LvuqeH9X9T7xAgq1yPKA62skW+HQYeU0KbzoReY6m53sReRvfi+lp3p2GD+KnlNWMZMTeb1g63tzC2YkYCEHVkG6Geb/F3zz0s/GXSrv2bql72TKqvU4qduRwz9gsl1c08CQUkTXSXPXG7DBc1MxCcb81L9SOn0aLSsiQcudIuLmRQDkyIOjbN4sdEvReVztQ00jZQMr5oP3NFPbLtaYFuhb+75IM4kE0IPqshNpFbzlSN6GbDF7Hgu13jlkDFiVQus/7YRH6ZKiYzM6IUUadmQXaScAa7KpqNfip9XG16QaCN4CwAxrzPyOsibnNRDyT+hLvkfEAw6GtB8GEAqFftn9MXUfDQIfIT3rdhx0VHFoubL0DNn8EAhAW7O5FIc7ADs0LpkqgUApfVPl36U0DAseotGckdZnEqjsz/dPXcEwsF8ANz75OFFJ9AP5uCojPpLmmOajfuejwgZichQ2Q1Ggf2NZhPMSH38knQzpVzwORCXIOfrpOABf/T9RVddinqXkZn3I+00CKffbEb9qsXdV5IxT5lWOrjdBXgTWZhN0/vjZNnuj/hSDpCLrdCx4GWPlFl5LFED7CNHEgj5DlBnKOV3YEnoX4AvF80HwAsH1QR61tPjbc312wMpmES7B61om5hcH5QEmjvAaYjCUQ8FiMgfLrH52eet/gDqTNM45srYXSGgvAWdDwcRdQrsT4qaKID45e535iSJq8vWzcel2ylXuIfGSmyB6wW4LszHchuvMQfMvT9eoMFLOvU73ybEh0hX70WjFEswflHLIStL+vGJwk9q5R02HXNH73RFq9yg6k4n3YqKMSyeHXq1Wyibrlev3Ng1BRbanSdO54CAyU/Ae3aXFgnb/wNBo92TuEpmqI544lFThVV82j3k0+K6Wd4cxovKejPZIlcM9OsM6pjt3QJ1CSrVw8Ik90LxTw6vS+PcXfBW4H/4916fbBw+eSw1+sLVyS6Nr04w+doIoo5v+UWXwNO52Kbz7PodX0GKQZjQRokJyt4+eCVsOqDQW2bqTqG9zaVcKlszcQQ2EauHlTDNqPnunniad3AkGync62EIxWchS9jA1HKDL0yBNlGm23nOFadMDqaedw75KGjji0/xceoUoGuHDJfMfCCgA7fUVzOLXaar62miBAEsaK9qyWkqLxr/IgQufYpUOWVkL9e0ba5iDoN9l/CJmhw9JnG6ikyvInslMpJwZCLrWhzWU4kIF2GOG58cTn0pHS+g8/vsS3KSHmGe29DqszKzdRRvTTG+w+R9X7OUY9AGOUwSl5ooH8LYn1hzJLRDCHFE2PjxjohhwMzdK7mdKHYUENDBvVXPMCkph2elrw2zansUwuVP90I+W2t2AS0uyyvInaUrcPGQ1l2cQz5kc/+oWU2ah7lZqLJ8ibL66Tmjy7pYez8ReqZJDgHR7JTFFznD9AU0UT51lv1I46AhfUzXftHYeWOhYNgDlX1xMRAyCw4SP3KUDZlzADLMgwGpcPYatTaiyTdEjx7n/Xrc7I7GXKxIdARUAiShV9WOZp97rWvgOA+VJsbcUKPLE7bFtAarQ07HNyEQZZ7ulMkebiMb1SvRpuL5EMl5R9JDHn2b14oSee7/Ylsy+o4WActmB1oumc6nLrtKmRXFoeQv+VuItiv/vPeODdLC+lGSmn036XV6JGba7ShMdHqntjk9w1C+98dc38BtWUrMgaeDFj4wYWZOXxh8XPeywxJWf/xz7AjfyYnyzNOdiHk4FrKWF4jT6sP2ON5xV6QdgWPgHJGr/APSuBYRyaC20r2UcMNohYplHB1C9FKyR3n02nl7d64Fz32QA3YTKsl1b/GjMnuv2VU0h9/d07poE3gWd5QR/94vP0AZ3M2tkXyucQeOd68XQJl/2lwlxUnoXc+VbCQJutp+lbv4voyXyC/SOSEW9rQmDISqIIinYgWPZIEpfVBpE/BZ0gLMlg60j8nP+9zqg8xCkTI3ieLw7spioFHRYI8j/ixVYeXzzldPx2NrwD0KGLB9YmIZWQMsk/JJU8B3KOaqMCyIG0EpT7W9rgsvKRUryGacm7ts6Nii1qsuFNsIv3K7/VRCYCje88IcsY2YRPrVsyKbd20B5BnJsWvk7sGELZabZBxB0dW5dabYdM+RmQ7A9L/63YnGal7UC/awhCg3rvcZLgXnMXkojXIzeRgYP7VDoOBXJcOc3CJ9b4apQhUzBBzpjSrbzkLuaCsHF/mA766KgG/1juZc3becIjxAlViF+34cxBBfgP83pF3e4nSDCScoqOeKT0UsrR2RCjNGOC/5YzDmjqInbNtRmOPC9rPAHds0Srg8cak2kWBUgfI1SjvW88G6Fduy0qOXfIizvUUO9L5K99szEkYH+xxaGxvr4mxkzrXlR7WqZfnRxCbPmeGC8k9YOQOqLDM/cumaiLsNnAC26A7O4oG0R0YPlEg4vyooOiZ5kUxl/Cj3whkpIG0wgAUWlKwrmzaPCcm0JbWC1SMtO2/p5oEGo0T4y7naMe/dT0wldt/0qYUWnxFGjsnEtqXhpmb+LvuouoDPkZKt//aS6ktEcumKP7nmHM9RhktUK97a4egwISHkPLz6qgdMKscS5xtDeUgvhF5NBQ2GYhfAGAKZ4w/UUaHmTSc780XaGsPftMW+8I2/wDp9dWyKnqN73n3SZvnD/QNzj6waYBPSODVJco+wWXsLUfdttxuQjeGYJNA0LiWJx7d9CPoN+ZsMqIIV5tRFYbr/4LBoN+DWympp4IElgOu8Bds2IhUxaOh+jhfCymaLnDp4aEd5EZViJMwjnG1v2L8xwGvJykPiXy26yO7TfLk7Enbna0YwderDidA80m7oQXp3DKlt3Ph2zIYREWyBGtrRnbwujRUSYxGxHUXvvUUFRyUJ5s/OlUa03l8arV1dtK1Hwb9SRvjya58DEMeWu0uOk59gK5CTN0BhJ9MrrVgrzSWKOWsjsppQAp6PCnOc9+kB5n5Q3i5MkxxF5Y4vZcymgLtRl6y8nGMx8GoApSrlabBclMEu4kHFO3CE4dTX0wHr+fjQhQr9kgza3RNamTtMmpYYGJsaHGvxPAAvIB91sR5KAYMv1bW9S9Fn4ZAO84e6tjxoPkRtZPijtjoKVf8FHAjV8WaAPgQU27ouYgz/1CBvHobK12ZlUA29Iz+gNq6J8QmWWkl7Iobb8YluI+WNqx8Oku+ao/ds4Q/olGCd5SSAaYBm8RH7XGMLIIFz7zSKpK8vWDSGo11MFn6Y3BBwCFG/QAZbP9bg6MawpRp+167GcsN+eNFXxOlwjlrJUrBtvW/gBvc6AgzD+GLCLk/lW47CWx+gyiHXG9JEG8rbzfIS71uouTmU6XMto95tkPa9tq+oX+wp3KfU5WW4rtE12nHtK7MiJbo73vy+0HXJ/jMh3vGeJsoaV2IL8UtNhnVaQZso2fUC20NBEh7fC9yQhEXtGrhuskVR5ZuJI2/Xl27vvDj+XlTIlsC/bNdjrE8f2Pn5OiW3mClBsiXO2yjhU6v0pdOHPPkgxHMuCdZfN+auI9ozzPE8j7R0y7G9Ej0SlU9MpEHrAmHyzV4bm90ro2XStsYNtrMa9TFisr42KB3rWVnCokbVJ2JRBdjvxIZdH0tnGZg0ZrAIKydu8e4z2Xpu/vjxumVWqQxIkqZc6kBHYk1HNci6/WZBvY+GW2a6T/X8+j/JuBbGw2AIeMD0SP4b1taYIOeudWaESgMMyKM8K3Gi8XrNYDY21di/Ayminyr1aJRwwKU0kjQJEC+NqdwdyUTK2Re+kfwvHcisVXrGghNUMVGUtFzDVyocVI2oPnzSex/nLtetkkqdZ3ccm1scBMz0sqSifoj4scUHjQgtdacRwkYBgXoWDwW/RHx+qXfGYhn4Z2SbBm7Y/rrOYVrwoEflImaaXGKLC805822pbeG4BiWCmRTPsK2Xrwsqgh7lF22Q07AQR+4eXk7Ug6+DWWjl/g+RIeMllWua3DAFeYHM42QqSjxki41zbuHMQ3WUFqPuwj+gYSyP0Kd14kpROTlm08zLHXbdSvb7/UfBZHrJ7VhrXDpA57UouM/UXdXCW8lPOTwNU2COMeqRVoB55yER5rqEuVRN/NrYYfBwgQq/n03WcZkBg9B0OZ+SSa7MAv9oQ9wr9VxlJBlG1Ku7ZQXw/Scei2yT8hSGWJCNlkMPaAnUnUVWBVG/uVlpqqN4pVNOBU1d+hZdSXXIPC/nAB9u83ZGaA/L/PVdNtZAJm+4qg9EE32tdYOU27g/6L1dVzOOiwgNoh5ose6Bch4whVRgvo+xgYjs+MK3W+5uqA6oAaL/l9wg6O7KOK03FFy46yPuWRzoNsYurGSu7i5NZHVrbtxqx0GPOrzCtUmPI5VG8AeGA9nHRpks0LSLZNZWWBzisGquldys5qXzg1DGaarUJEalxVUHjPYDNVb8GPSh3Faer1s2M5One8aSnzJnk0AUykfgMjzh8qpKwydvLZfRGseLCp2Vr9wEqdnCp9KjkPe7K/9z7+khxdlGOuShQ5lLuyIJ0SJG0aXaXVkMkW1a6VRmMeUbaot7mmXUM2vK21GfGCEF9GBarYWT7J8i8ZlyiurWvozZHekZ9DWxZijvJU/TLMNGdox5N5I0x02ZUiBMrKO76latIf62U4lDWbTu64cHFaQI9by153+CNUJWlKxhrkS7HBNtJ6Pl+ZSCikf1pGls7uqmd5mjYoSrfL7NyRhvyo7lAZ4rrlHY7YIZYKfjuoWbBydcXICZx0bhZXb8D/uP0TiJZJLTlR5GD8F0bjwS4RXnSgdWlznmUIiF72/gupSmfSz5a7xqEi2q+Ql+l0AE0w+m2ZPWTa2UD5P12sxPKPwQvMRn82P6UY2r0sc74SRytpFn9uhhzXx+1oXLOnUxDe4BarPLAfQomOxXYtdecq3Au5+R/qleSuSvmlW9lzzg0jzb33TG4dvvDW//Ac2GMgPlHyCzjgq3LU1yCGUw7liBeKSlH3vjixZrzJgJaqQZ6IRtPEQmdj6peir/fUvZ+zMCpB8z4YbCHOa5fXmKsL2ZBhEv+Q9d/CCbG9GHJ2V8IXcmXDKwjFUlCFTxKDa1nyX1WUdJsawJHvTL5QtlfpqVYYkWHXxLDjda3nZYNV1vbFC5XV70fWGngx7Bc60xPA2cRIcV9kbB6eIsnWK7VTv+jjuVJsVnSpupKhlBd3QxWm5aJp7a+xmmCpqLXvvIZmEa143k1i+4y/Yvv9i0QJYrOLLq29sKN2wife+aBoClH0YM8fE+wwZIqnWgPYH8xjoiIilVBd6aw3rm/N6fPUX+s6/ZwSj43mtc6EyzNubGX0OSYkgugQgfHf2/SHIG9HmQRmLGGiHvUhYk78NFjN6EqFgLFSRxXiXqckCOus1oNIyMh3HEpnpPczCIlEY69fmO8VQsk7vBcS8FrBSDkuKL9jHieDiehxELsuuvByc15Our4DlAgc70gwCgQCqvimB3lXIVpIvebFKiotbTRypsCnXsdThaJ3FIUi3RpaGxT1dFSGcrJGNXuNwLUF4hKco49IFJQl3r365qxk/9Lz3sMFaUkIsMq5apHupdKQAy4Rne+WbAbQgWyq1QV4koEkhb/9YqH9/i75c/pQLUSdM+I9RIgSreRIla1aUnwfk7/rWMYVyIljf2XNo3GxYvxVneVdxfxkBRLalbUwcM6yqHnLh1/kCMOB7bt95UsfbkgKL0Sv3NMpDGLghSZrB1JNI+k/qOYwktQySU/sAivOvn7xCi0kSKRXoEj3imgTbtjhp5NzoGdpKUZfgK+zNT6gQHKvNecVEpGilp9M/RKx9QKnC47I7nubTltwLz8x+/f8JUrI3pTCvcd7h+ETznXiMtCnegtBW7F2dI62QPBKVxUr//pgg7zaKUJNYPefJ6U8TBfoTX7VHqsMRoqb8nz5IW2kuPWfRf7mJBYiiiIe29IPpZAIULU1HBGw72HYNj24H6xsq9rsvALSHbbLmcffjXSGwqy77EBCUJFzre/QAhi0w528viAMRZasp1vmp2O2VGtxSxVcWfYE2bFi+lTb3R6P3G7XSVLeRpDQ+tk7u4Fgj48fMjaqkirmWN5qMA6rVKojthNglkKTS1ltEbHWpcraZ5xDLOP26BX/JXPDiyClIEufIQq/ST6GrFb4PDRogENO3RssuNEVl/1dyb5dUcEvyT3PaB0qUe/6aPXhIWWr89EHsxZgR2B5nz6wDcckDcHo6v/jzEI66pWhAqPEYj5lvr14pWf9eah5nhOOPObGM5HZqj6AmxdS3e5MZnMC8apdgjWqQu/2MEuG1jfLtppHM9eetba/HxNj0ikGRCMQEXHqA0/l8iJMBWAd34wYB0msGsrXzdbCRD6d3JLsmLUnKIn3hMD3oj0ddRTjq89tx8huErvZYoD9Pp28mPhzPlLZkZKrPVi+F8EDDTxEaKNuvHNpHnrRQ0KSDdmeu+NuiMkiJguX5ygRIjwUuk+yLXrxq0kIDg3Tp2Ksa7wzt0Y2KDJZiqurpnsCk8GxkZbrQ6ZfyAjiFJ2oT9eT05Ku52xT7hy7mFgN+dM29bGt1xskqkt/bBSPP9VJ80kxCk6xDNDOe98QK6Q0zxQG269MEgtGBo/cCLx5iRdE6jlM1xPXj0OYvo9ZK534zlJTYiKzHVO5NKrWb7HCR9CPrOdXnCsARey0Uq72Vh1C26aqYs2iDL6SBsWTfHxmi2rZBsZFNtcbWv+yBg4ffT2YeBDNzB9dyNuGl6+Sv4e83zRudlEd8n/qZWCZPboq/6Wamx8HIHTmOSfwinu6PgeFHzmuotUSmqCW05YfwYHEhTOfhNvFxlHDvqHbXs5NmOD9CbHYtEMIRa4/rlwX/2ZHSpSuxnrAvQ+YknOizZr8i+kd5vP7EgxJ0NkiI3tSZO+CjsVl/vAP8I5p9eJPPBGKrt4F91eujpInPHvfFn2uiTgbnI0XSY/kxdEUt9QCHT5f/2otYLmSHTZtBQ5SSZymQlqpk6uU8YMUfffSxdAzHzjofORykySnMxqn26AlS2ivLFLvThqydlrH/HcBwKWZe5ALTq0TB59r9lnwnsLT1BrzEugEhxDkDl0pl4VLBD2MVt8tch9ZccPaJ9JaqrxdswO7ORC+7fJboykaTYqVcgai6my3MizjZEK3QuJq6foGuFsPnVRduG6SHZmUBSj0YUKGCYEpvxMnuv1zTLq54ZHjCFNaNnSa5NIWxkBRNhCDYnBDPSpXrAk9fOn+xJsqlMMigbtjnzLLv8nuLFW6jmyf7FwNLK0ChN7qeehHZPuMptQiIr/yrm1NtNnSth5s5jtjDWNWXxCe18MHX1vSLV9sYWMAZ6+ghM0V5WReOauXA5//gALI/ekd9g3I8StKZFBFRPfeDmeHRDB11PJ/9R3v1/Fmpfiflc+O1CWg6AKixBQbrG5nbU6zC6BFSe7/Xop6CGCiuBXLt7c4rjnjv+SOrk7MsnnkbzrNULUE4+ZchdEvGWQvYNJclz47m6eYbFLzdP/8GnRgdQWxMCCYOFZfN49CHh1/XfVC+N+VsB62MmgYovCDzXpqlvvdb8Fc7NBDXD51NnmH2sFpLzcfTHuUnc23dXOUCb3RnNrclNv0S8OvA0FaXq+ULbFNE9tBPt+m+THl4QrAomGQwP4oyFKUpN9u0L/vdHsytTr35mX+GD9eMR8AeUXAJfQK6x9XFW3ZCXcZakr97A/k+VX30FUqFyZrlfUOi0sXJqiodeK/IIPPwhvzRwocEWdZ+1LgUbCwBoyGxftDolP6xfq8t90RAzsa0jWMZA+t9y/seVG+6q6BnCKpuYWjEylKA9eoWLnzduYmMX16qw2fMW+Cfjg4CAmcA6jkDMY79GVx9Lq/Y6y++rttsxb5/KzSXo/hjYoRa02UQjJYDPslQWy3Mui+fNEKw1gB6/pOZo3LXqzHq8fS1ywLnVZRYshNVxxVvQ2GSTcRgG+Q7znU3SRD4Pmf/ukEC4yxZncJ4I6MbFedSogDzw7I91W9bd6RH2tc8rYUXU+pMbTU8wYSPilwQGxuIsYVMWck0wCsTGSNKdBgIGz3II0Y/nulRYxbaLyc8mng8BYoY5f8O61SLay6ykmx6PVZiROYF3WPVJgpfF2BVITO6/2TVbYo72kfui4auJF0nwiS6E9DR2kUS7uMHrbxuqlEDBIgRcUN8j3Vxv6nFbYLVRlFBjqTBtwnVDf8b3GB52p1p1g882RlOygrdqxlKDMu+dJffWdhK4UQVGnUU81Culy2oXn1nKPgeuKrjXDvql+uAtd4TvUnsSyYzsBoaQ/rDeNYmsQVuEJ144PcgJIIVNIqKt3VZytiKTVZ2OrXnYk1EH+iVxV7LfJFBzib2gxr10lAVNfgdxLXrgM/G50alnHPmwz1thREua1J9NjzwtcazfqvqElN1iw126c/MB3ldOzfks6zxJhC/PVxB1XDrYLqrdfiFBoFq7sys+kPoExz2Nv2yY6BhljH2bwGL5fYdgE+MgSusAsZzGfVMDfX880Llk7fQEj0VxYOtzLBrNHKJZphH0JvTFm5PaOi1c5jMJSTngPJXpdi0Rw9/bMvvVhL5yNdNMCqGsV261oW1qRn/BvHDGGE+rxh2cIQg7+qW733VV2Goibt82t5CYJ6/+Ha9X9QD10tnKjAjxjHLrjJYxesZ+ZNBS80ePQgSnyCS3NevZDnPfuhw2EejZoh9iM9XS31VenHDypmNLyl2lt7oT6vHqVhfO1za8yHuxoFUS52JYeK7JcPaFfQrQ5V/ISzxyT7x6kUDOVP4AdJxMUJIu4eFFg3I0+iJh8wz/3RBIA+y7mQsOiLD++5OebSolSfKCxDxUYw/swofn+b7FP1twfUO1rn1czaZbwRz6u1RjhJ6aUgr5bAse5IzBapEokEi61R8VMf1poMocQX2reaQpZL4JPrA8iHeVBowXVJP1L9e3VEXMEgsKoJbJ+DqSQD1WApTIZKOK12F2mmgSSiE4pzPQswZJr0RqB/QnyodFLjbuOEL+dofU1BrFQofgsvo1evEqsYHpMkP76E5SNCzojRaINZG6cGcX9ceTgUY/CDu3CxefygeZ/G9rTBYIAssYOSBpFILWiJSuNqubHnfIdgRoyMBxmyTo+P9bJ6dnVuCpqK2sNk/DcWzenwudeeN2z9M0V+4t8fHk/LuDQGUWojAQuDkLE6sHAC9klT3dXwiU5SQ1mJDjyeUhriH6sfogdGN9/eejBl2nao2tF2fk8J+1E7jPFvQb3+H9B2Erj/jHiwaklM6B03yAnglZ6fCiCO2c+gG3kFZMP4bTKu7EL3vAGuQWnYDzQOPTLAjcVrkFd8F7bceaBhWp9b9KyN5fm6PqFTcJkewoz57Wi01ay9n46H76lggjvHEgoUGWntC6iiauwF6x42Tf+QPt/tcyVXv1YQjUjdK/0XqwKtLwlA5Wwqn90swX3ja9tdZD5elCKa1FoKRsD2L51iUr8cqVNfCpCuVRwTZs7CAjoFOFSn+4xaSyP2g2yzqp01kfpSz6/Karih4JUPVmEBtNIkbUbiO62YrCfFucbLudmLZsxvicjz76JnWX7BIztB+RFAAlCDAEEUvAXj4h7KRjbGCbYSXFuO1Wfhp2EPr+JRXQgWxUdz8iFLUkzZ8/xg+1ZPrAMuSIW2CSF4nzafei2paLKbW1gqCiKY0nJs5s4lbd6tuX1kniR3IM+RmsfFio2rxl7gXtcnOPIxtuVrZCAWgnzLmItwooYECy345+4Dz3ZXJarkr3R1WTgmZrAZZAiLQU/yuAahmzAtaDEckFMuPeSsM/dNGkz9p/e/9nNKyNJ6crR+RdLW8ag6UAtxWT8IDyx5IWpqSIUXIWKwqXL/82Nw2nIq1mX2OKMLSgCWCqzTliJtyj39/xYJsJ5uHD3rLHb4ICYXe38wLZPxFFjVKJDkxYyP6t6cKMRdkkHYRcExDTgRryh3kQLfcZe9zMzAuGKuZSZFP9RWdh5q/uhaOelXF98XRf3noXmuA/x9foQZPv6jTDR6iSAScntce7onzi1k+JOenErVTsjUUdTbEuCRANdes6DVcrph29S2VcAjOJ8kWlqCqQJrMibXXmFOWYp0G4xtWVMhnceJvKwUyIz9ShwDg8BQxIkojOGcs9CR+7oOkwupMp7vasxqSPPPy3W9rKYWMOtEKcy0ENJcNgXJLhfkSY1UgBQGik+aHxHVCNyBF63m6d5XAIEByHGduxjIvhd37+jFwBqoFePEpsRUWR27JRI2OYTjiBT364IOLr5h0XH9PT6lWOiCruwPumZ2/xBgAsLEUAb+FHDU6chB5JCXXMnEloxZ2hvp4hn9BXvjg976kP5CHFaCFa7JL1DgDu77uQgb26h+dQYHQa5v17/hsLy5zwexZQ7qGonj1Y4bdyAYCOxNqfB5WqnXohpFZL0vhm0ZVUZ3Fd4gm7ESaErjPX1GLulaN9+fqSK2yV5SMT54YBvA9p7UTjZXU9Q4iRCWN6hs9nwN+sQ4N0K/uq9d/ObdrcdAgI3CMrWzoHfQZ9fVxG+OhZ3vnciGR3RODdJa/9/2yrKKeapvCu3tNxC6+evXKsy/+G2Lt9ogs3Dwz0vQJo3dnF2etfNqM3le3kT2WqtSPRCY6gr+Gc/HR1kJEFgLN7aMVZXTrGRBROCfvnwu93D3ZWjJYXcb43OZpf6HZTfKpWAk3TYWmtnAH1A5nFr4f/zsmxJLF1IrqCzsoTfZDlO/konJH/WcHd76wpWyEG+yeci30pdWizuSB5OylldffdfSLjXJheo89IJGXxmbYfE45+r4Wu1bs6JGJeQMEMgQqsq1qxodz8dV+MNk/5FGIralwhiNA7geurqMGlz7v8I7iEKj7yOc5srVtSGrv4B/31gII+eKwjrv/Bxq/bIySEtZRcOQDTNi7Cc4ljvCcW6ljK4mI6/p7LJJlilvzxIAaHR93+VfHXJOkm2uvRQR5ydgZ17EyL/HGnCsY+qSswAUcDRt5/5bBQ3AfR7TuyOvvu2UcWL+YqwwlZpoP0H03vwn/8ywGOBjEe8NrazyQ90TtJ0JoZeSOOVEf93MVDdQczcc8StxZU0Kbx2COhNVbAhrWI2szDikE2AtWgc6VLNAM/cA5x0oD3bzbX4/p2Cp5FGnu3qx635ROs8n/+KVu5dg9vXW1llRp4fc9KG37zhjOKu631NWkuOiR84IVY3WuIqAUUZJL+5bIrirOzQDHKAhKKuImq20GjOjk/WbuqTvrCB6Dku5ihDtJmkqAbK9FpP9u2Qm5kyn3zIshehJr7WgIgZo0LHWVTkrRszV6w1ixcRI1EXm/34OfKAJ6NRb3TVNA+iVIRdLLhiDXxzYvSDwwHrpG7fBvQyZw5LmTzLD0qcQOrJc2QmnEAPtpBNWCR2vwT4RHY1LBBjsdg3IjfCFjfTTd3jhvBI9NE8I4V4LpFuARdJ1cp/jp3XT5kaeAwpEFNG00uz44JioKfmG6zLcN3QfxB5V8ZNdKhoXUf1L7YDGh7haRjZCM/CGMQtCBmlpPi1dFGNItynXnHMnckTzIpGp6sOb1Ri5vs+R2GAk7jEcybAFmwsl5iDvmcj4RkNvvE6RuMN0pMMhOt799cCJFL2oM6xO1e6OqEzf+ouwQWhC5FZPuEnHdzJJOH3MbL3aM2aEjgFQfWr7jEnk+hZpjhisqTqWGh+QezjK/YgKAjgp/VrRSJd5zxhHs+3Iyj5gETQoCcEB+2jRVL38NCC7B9LOCI9LqEFnF+qqYVXonA55KlJiCVnW16EBG2hLccolccFV57I6fczqsVKYPjet3igNFutl0xgClIL7x6Z1qoRjNF3mlAxkrRv55p8SMoZuF+Psb+r/pYMGB5azPk8dLbsXRe9vvVWeNmKEbDB8OCt50c9E0gsO+tgYvtYVndXRtPgTOOFxm80u4gbZ9EGnfFRuWPQWzX1CZFi/vFc1rUL2QpDLrK+Sof9cV54WmeB2kUQnfkR34i73q+CP4ADmmvWhvU+Lhjcu8VFR2c/niPqPPMmNIOxWpd4k0BiXr0gwcSuUprUjtQeHGDCa6U4nMGcA3FMjiHph3KmXlHyuxYExeFOq8wxGoz3/QunWn+OsTbN4Q2X+5ltSwFdt/nSGS+xVBuUYcziv4ZHTNcvvY/8QaCiNugtdmEIqPg14BTxG8V3Sad0Ijc98U9QjMuMDUAtJUOr+Xd+9Wl1BrbmpW80x25iIgePU7K0H9Nj+CQmZZogpL0CzHbTx1Hesfz9KfdyBHm1vzuh0Io87Lok1+wWFhMAtOUYRehT6kck4M4zqENo0vWQZJE7Qlu5Do5OcyJjD4EBsev3RKYkdoINRGLPo5hoS16H/xwVMUk7lHnr2qya1lhX/j0GQSi3x3PH1nRzGAQGhyUTo2ogRQkVIbUBL2j4HmNEpFqbdPn7+qtKJ0yJxn99Tgkxj5F4UOiSR0GznYBhvvZwiviGOvMNm4ywFF+AlA2VMFI4GIh4TJcLZhj2H9olmhsEtP7G401HWLCPJ5r02PwD4MDRjt8biKQbbbn8y4hsjbAoPxpejZGE0T4h5oQAKCMFky/Qj6opLTfhW5IJJbCa8ur6aTUsYw/w9X0XBvtha21+7rgyH9+6ati9mv50VgPhBY/JButO2twDOzOULaTCoJ0ZoPOEAhdGtXtVeJNJiGWi8o1cV3fImcW+b1ibfFZm/cztvZ24Ewcfxar+rWeMQd+5DahoNG0wk+rq3ClZTKgBHzD5sI+qvT5yTat0LWoFrknZo4xMSOdfnbPpo62OC47VYzoYSKsf2h5jVCsV+jN2KOGvo2BZ6vgiGT6dmApNWqsQ/naqsfgoNm4/XtMeW/+YpfBzjAOa0zupPOj5d7P5x3Jno4H+B5YefTJBvZ8zgMdR9nI9kVH42auMCr71BDseAPlgXD3mKQ/bLAh3m6oGB542yp+y7WjwbeGZCJwntuLuxVI21o3CbbsPF3plfCYg742+jkUzrOS1xNZFBiCE7COgVHW3Y6DFPNlJufbpXt7tgEmr07EIwXj/Vq2XtkQ/vlB0JQktzYQXRt2zxIxXOWqPKLdN/TX2WXimNON9YqJ9KnbstOnZ/bWZJPaDAe4LLO90nP6yivuPLmWeiXjesuuHD58GkB02vxODVr0eTu5BNHOCUs2V72QYXdP3yfz/KsN5sW6jA52bxyikDrGRzV51aLZQ61a8AslnTynRAs+10y6do6/BFeEgEbtmKGzX5SntKGP3kerN88KFHpzyw+XB80Rua/txXyL+X1yeUqvadJ4gePROo/tiv68reGRW27MPuZFAP5RkPLJ3k661LwdaVjf05V4+EdL3tVY/jyhp32133l8o3qbQDftCfkgqaDNFQrjC8hLJ20yBClVLzMioSEJD5JTKrR6gYj4fpu+8sTpYaFRA+I4yGuzWsFlntJGmyxqsreuFTLtSjSyRkIhyYAx94IXpg2+7JbDqmy9Zfv+Q/syZJ24L6dowIgLapKTBAorw5BwCDaaBGg1dYHpZwGIkCc+C6GgtiKL+kZFwPO4ktXbLQ9Ws/qMZxltaC8b21LCOI5+A8LxE+ud+KAOMSYniGcjxzXKbQIYMmv+lW8cm8lXRlI8ZCXEOMeM8VS40yg4R7T1blVW0N3R8oVI5mainrLOeYnnkw+go8gusB1u9d2SoqK8dbMESBoFbGOT+maa4YB7YQ0QYJJMhuV6kk1OqfBmeal52VxQBkaQo2Dz9Da3geV2iV/it82BoViKqNQYdh7x07RPt1ftmksr1v9LWrZbUhg3cM/7Z/ClO2IQjvN2PYccmKJ9D3FFYQFyLsFsW5Kbae3SDGfvaIM/o+ndqXsbw98zKCm8PSzM5EWvsCfe59VopFByUqxNcjmYidarDIMRJ2DS7gJ0cXhG1lYalxWo4OMZYkW2iE+LBac7i13gwfrXGKjYHo+wsIGHGs0cJvu34u0KsjO+QzH7010wJ8XtKHrRgAWb7sWuNV08rtXdjejtSdoLXh/buqwFA1rcnHfQacnu2imkf0R9NPLgHbeoc6iScYCvLpeyuOgpfUpHYzQzf/gTtWf5pVZ4trTtKdvdHD87k8GwZ1iT+zeCcGWQNevOMzopje3kTKZyQmTAN1EvTW3L0nAzjS6Z3x8ojUsYM5dnjhltW4vy1nHw9AITCbmT7LvZZZXgQK+M6Cqj61v4Fk6G+vFh8DDlIcOkHcAs8nexI0QIh2r6J59Ok1a6h2gpgUF0hOiEREF0m/IvxntfsgVxwJcwmxQ/AMpnowlGtNPqHegs7/WTuzGoV5SmMoq94gLY5bT68CtvcidwGh0UCYrpf6AuKuvYXurjtRQEvH3pW3cGrYCG6Ci0IYT/pvQnLB17vilpQOCzvUOp0rudi+Id0u7VM0KOJsvLporNd1EolCDZ1JafFW3tjEPSTSsaWY3eCsEMfW11v6SOegUOXOgEoJw//96zAAazerYEjH0ruKPy7z3AsqbKU2Gd9El5lybZrbJIcIyjJSSHeca676yy4OYx3prCSAdwHy9VRWZgAYPvQMagIll4yYU367RGyZL/oQPNSpF5uDhEv7LNHt8t45ulQqyHc1Woyv9JEOmvXUFrNq9Yq4QOGeoZxEKvI/aKWAuEObRpoWVn+eaaGFlTU8L6e2mLQSYLSmbHcAJ/McawRtlBrLo/1GwmGLyZKSxYtAr9dDXvL/t2rbAZEsYElQjFXcxgFQ1PnXEhJPzmOSFc9bbWnJ8WqpWVxezJfzY1qzcxhI3/KvzYmwQS4FW0NOpcxDx96OtUAhjAJqEtAOLorpYdGt3iJhwvqDWhFZjSxSoVEuSal3IuVOhk0xPpdOD/EZ2yGfRvnW1d56IbhNpC9DqCN+GS1fO3lOw+nwaftpO1oz+7vtiQXoNMmdG08/N4T5PkOZJfSODG0EWHiAHkXtp3hvKorS2j5a/0H4n6QzNZ7yVWMOQEtgUd+2Kpu45sScpjGYF8I2/HY2qmlaV7TTtdwv2+0ivSckuVrhrrnz7ywINEyLki9mfR+6D8I+4aYBqu7dQ5uBxG7FB28MZ5tGNIA2z0zDz7m1zjPfK6044Go1y1FQfwSIW4pMYdi35FjVRgsCPJkim1JzBenoMsH+4dT6aPC2Nu1EN7eHt9seI4XbzlBCl+BTT49m69/dW27LCgbBkOqQwAn9DqJCR7JUZF6r+s676tZ/hIoLs3lbRJrU7JESgq+yYy/xj2gvnDW72fjXtCRO2kdhsQhNycWpzGyk1T+tkc01WmYI8Q2HSs1C9TBRM8MNGokvg8lmPJV3ougwJenJWynSVqs2HfGwbj+QglhqQYj07u0rGazcfMQtQMSHI05Vt9opoi6SOrsh4N7XfzPMNZZi1GGovVRSel7ZzHVHcF/OIYJQZXNRj1U+gUnyGntGY3XPfoel5Drgq8GgW7NPh8KmB1zpiux1I2avi+1F36os/gQVNoeithjhFRHkPkdltrdILVXOVg3+nRwLTE6AfTti7LEWMejqGse9eG2fxRGVkDJNnwg25pqDSa48TgvfY5izLabRSQWJhAlt8eYICNUAs1CN0b6Bq3crunJsNNYvvyDyorSqvEgK0faKORhi6YlOEy/F+qCYoV+WhvskL1i4EkgeQNelDUpHY+krSc3psY/cpXMZ9fFuxpBErCoIE5en3QorBIDA02U5MAsqmMmE6CwJSz9NP4tu/YXQjDJT7gXRluer+Pd02A9P7hutLUPXSPWDb3GXDFz0i64NC3M/EvntZV059ONDh/1ksEWA8E93eYuTyChERHFdvG0QY+8jreVp0WMmzB6n0IXqaLD1y4fTuKixXKg+1nF7jZ9z4yy83JA1TnyXbpr6Wfn9aqrniSRIDU7NtHGpMVN/nJrxQHovCXI6fFuHUfzFQWyfg4kfVuOfrVnHqcdlINWPEyVrdQrH5xp2Yhzy1GJfnL1xYbmLRUhJKF57xdSIJd70HfloUbZGGzODXGXTvOsDHncN7dBUsY85jG9aFgXUXVcs+ceeOWubJmMN/ax87RE6FwUuJKasN2XPo7cNdnLqB+/IFBDXDhibfPgMDp29tuDXxPT1qLU3UhjtORowD7FlWWrP6ZVXYDWgSHLU71BPwUOflO9c4deIpL9xTXKy0+XFM6ToypzfvjOQM0DkWI+FIAB3vuFVcc/GEBKabXWzSiKQ1RkQgGo4oETpQq2I74o82ga4dW6lV0+gbMPOGProtsg/XT1HQnf7kJjKD6j/Nc2roHcSt2J7EcZHpBjYdTwuEBmQitxGiRxeLkrxV7QcEkXTRJQiLYRs1r8Jmub5JLZCKBOdM0shsXjo6bMe5ndg+pEvpZaOjVdlbUUyW6Jfcjmgvz+8b8lS9r5S/nnNyjh6DiYTVV7EiRB020X91lqKuko9LM2LVC21z4rnf1XN5eHJAJtuZM5XfgCr/OYkp4UdAsirjZmuVz5HDW48TMmA4DMBDyEMEk336mkrrTKfRmv2jo7GXm5MpkJFgsY+OOUWgsxQiJHy9s/9xrhE1Tit7yw7zA7ioWYK9rsCS/DqIlMllanUDKE5+/HpaJ1yzCg2JoCi5PIjd2abKpebSnHoWjWkBwV7taOM/Phu3/BjiY53vPOlQNsbeM6U7AlJPny5Q4RUZ2OZY7eMwG62CBLtdMU7cCbortE7XdmTVqzpMJk8keuFOidV6vSF1Qz3z/UDLRhwjLq0U6RSwcpMFHnLLekqNxDal9TKVrWVMhtoiBGGV0NCCK+OeXGIAJx1usv/QKjGJ6seTYQM+ybulphjgNz9Co8pqwcUlxvvF2iFHgXbrDmeoPZZ79+ch0KfdI3fvFer5jFe6TX98zgh2Ea7QwRpTBtqCbV7/WDp2bdaT0qK6R5qBGnWd57iQLyyVuqPkc13RsS9pqv2ZxnJXu/ODGEB7Jcbu0XdPRGJQmI/x+wegb4MH8wQT+w1O9NUUSBHVUOM47hkKf/TQYu0Xm2X0PifIfJNsj7x51f7sYoHzYZg0bjAU92dj0fjm0zK+z/f6skhOZb9Wh1hGCmAEHrh46EWCc54881LX/zZUykiXA6ZzVl4zThXIhQlfaGjGLjsAj6laOUDv0POUyAo5lZ25OM66dHxqJy+IqvCeehUidkGmeb4NtMhjtOOcxkNBsA4kWdiDxzlSqOT/AkisBfwUC4ngTiBdNs+7dufFYfcHjdbxarp/Eh6dM+2wCrxWYa6yZjU29t/in29j7zdba1C2lUtwLr4NGm2WsJXw4UzpxE3/kplC7kL1v4tcqiH+eiWtbf9GNUlTL0hrTcoZEnkNbWv5ISBaD0NYKeobXqZPfQnm38nzgDicokYyVNHJmzcSzKhQnu57/x87p4k9YCdjJ5akg/+/I54rjwWyrlk/c59VqUV4sKokGI/e3QYzD70h9A/G6TIsBY7cQfOIGf0oVcM7Fs3aecUNTCncv5tXnJKScKrRBHJWiylvYtIM5aDQ946sYHkZI5uc6S8+9Nfdc4/tg/Q0i3A6ybSHZV4T256+J7pM//K7y5zxYSZK/6Qwhkha/QWTuwUlOLwNg++etcRZa61w6CA0pU9xQcfeS2a2tTN+g8PhfOeKVEII/AH4lG0mN2kJ9Ls5SsYox5Dkbc3IFLIRQdBq8lbby0AcU1p/bdC6Q7g9n6oHBhzGaLUIvR4yPQYOWhPUxr9zvxc+scm1zQnCxr3tNFXNJKi+6uPR0XRhEnLy1KSfcRat0clPer1gG1C8MqkAjVDM0wkKPObTs97dGQECDITZVx4da8F0+WxhoPz1r+HS1sMEECjHeaOxpVlNDr6VRkil2Hh1xS3cSV4xtFGWor9K9FtBa8H0qbuPqCZGKSmKtt1DlmUDK3Ck7E5Lh6Nu2Xt5EUaTiSfvqv+P+3AYVrncodQ7IxI4VNFyGuJ+paXKCxQtqoi+TY19fEqWkIbFK1fGVtQhtbZxGgQ6a8OHnJMJH/twefOogeHEIRTpqA0Pdn8uNfLYJzPTGUxOwdITw8DNQxdOwBIm3dNPXR89wiKAR7fCweHRmGR3NIgVTFo0onjXQIW45aATVjvEgtac5DCsGuPODzL3OKUA2VMDqvazMpK6OUq1TvOF5w9K8EiE6Uk5Akt2Fl5uACrySlLPw3x/pm/yAtX8gQ+HKkPHeUbBbhmSwpwmCM9W7JsxXrGk2nTi2CYTkAfw49vrt20JzFyMccnelNXdRFUi0Gw1Zd4fEB1Q+9D+rO7n2ZB9QXRk4OywynPrYha6TqroEKN9ZBpgFFCM7Sb68p6FWQEhsbBN0/3sVuyzYHctl4iakrciiPBABxja5/VNAV76UeG6Jo0BqhzDsx7OZY6Jb0I4NgHjZoP2cu88dhavQUcsoE2+Nm9GcdpW6FfE2b7ej/CpPuLFpprAIWAnfVTMsQtazIZkHUKDwZV1pXuSaEa+3Ytlztg1gqfQ0VZLxGLmVd33PKAHX0bDIvq820+Ty1tE0zPOwFXk86WQXBVKpHX+ICFtVfoAMJ13VbrQ2/nsE6dA/JzSIERaz/re/ytnT8mkCMK4JNC9U9e1EsHSms40bSODBoFjsiMzvPS7cnPj899CWztFcKWIXuZFGijIoTFFYXvMA9wND8Y6aidLkXE713/po8tl6XdhyJhAYfsS+qWxZNpHEZFAHGC7gLBcFoCmn1v0Y/6i0MgBIjRLaDyHE3lVavW7EMfAAqtKRS1jM6NKp2itFCSwhMrlcOUpfQAB32OpB7EK9VqxRl54PZSwVQmdmS8s2IgtgKLOQ4dAtNX13SRVBRah8bkJbYAqVDjHFAjobNmRpuL7btLbxUMrKhX/3mnbASRVQJ9j7yRKu2DH6V7ts+R6L60H+15YUeaM6vI7JQllFHcbZMPzKgpJof2ZkM01HlDfHwksEwShYpugPNuc7M/G1TbHZywE8bDx4f3j+3HFOAnivHNzy0n7a8VVAHKM+6VXFh+ZOVxC8NPxYCWEF6QJAQJJHpFM9Ioh8ExO1P0SMccZoYwtzVPjGMK93ek3Ie6uBVFABxRld24wt/DH1Dt4z2f5ABBt2sFMbR6/XniuxxmPjPma1DJnYSW+ikkzgeuWiCgW/Om6mnkYTIAS6/Pd8iBmcLq811alGUjf1JclUwis9yHWBNErx7rs12LUXcU2Knui7tw642l7IMH64Ql96viLwttrGnLoN1TbP5HlPeI4SWNBhPO1dU0sIHSZMvDUOW3giySdSVUSW4sHm7uP5YiGh9YI44g+V7pDFJQ84grWbxhMbE5aaKN0reQfOwCF1TCcRxRj3BkzRsW+rEx6HqykScruUKX26REo/ilN5FUqeELdbS7lNZj6vcv9jq1FhEF/LPA4+A0DU2TOLZqWH/BhRiWiaSrf4RIoTKgSX46zSAQzrEurHy+HCCNyFAOxExXREfCDAwU3UwOfkD44eh0QnmIbmQ7TYF+NQ1a2ffg1QShvRlju+4/hKqpPM1DuiR40UP9168b60jaxhmcJ5A7GWtf7vDH0cHcx9EYdTUWgwSHRyZqsPt0HBzrZstGqMxExgZq+cxHUudQ2FrIuWCgEjJMlW9jUfjOkiW+zqTa6lP0zAR2i3bPJCikzU4ktAoH0Bjvlq4Ut09jxd0DDya/TTLuDByhBlYB77Glupymmsr7Tp+KlN6nf7VCi6bUMY6+fRkN+6eM2wv+rudEOkSXJzMX7g8xSwF324AUHQNZSLQVsdl8tL2sEVt+tFNouTwIJJbVDKAPjQhLeTUDXr3Fzae4ghxT45atgxXD4l3Ty2tsZN0lvFqP9NHIXQcznjGsbcWkCCgPSQBFhmYgem953kZvOUymYPWq4eCrkKhuptmUiziMplA6aSsFtLKkMbgRKXd+jVolD4cdyYPM02PTInGORBb3qowseiyDFr3AxB509udpf8Gpq+kEcztfZzbTD2yzhU/oeR1HWyIaZzpKpKfkkw7oWhkbsFoeAG0YSiDGDkD/jAhkXzjlAy8XRCjs3YgDletmDw66ELxBrGPSKUDU4aIUzdshHHFkFQBW9CXNIbejJG/42vrq/HDeQFqKaqqvnvkpTgARLhSDIQAnmbSNlnYJ/TxVp6SdsH7eNjLbm3vDJqMz++emLy5LeXE8usvYfrUc/GW0q9QKtWCF9lBhuTkZdGQMIgE1QWN6lS/0wg5+xgnlngRUQY/5to0av1cxK/HMY9FLbk2PPinNwUSb9XyR8/vMmoe2hb5JO6cxORCsSAYOuuA5R9RnzV8joH2fhNit1KFzY6t94cnUm2jlTCSdFbMmoTGj/aAqGSLS8tOH8XqFA38F1HVjdfH9claGrQjFgLtWxiDPxlMJjCbP1s4i/DbmH383aRl19i7BqSZirAcHUdhYH20nh9zXVIQDV29OMlt2fEq/OSmCBEX2ZN28zd6hdm0d926x4Zj9q29unTo2xtfCnYPFx74mCv9ze4FtMaLoJklvy1ktD0kTN8vPe9e0wRd25ckHilZtdTG2W09Jfa6VOM5hFSS/TjFvWlZRAXWgXRHSXEe9FTBn0LzPc01u2bTAQ13I3+fQShppjrTUP155WJpP4Ek8FEIgMixPlWWeSZoHQG3WCqpRRndSZ7dc1dZefIhxB3CE0SefHx3lfuXcZiEMWWxwri/Uynx7OSbcZqK6kTIOraYM+AJ8m4QYXSMBd/qcrNWuflX71H/+AIkGAY3YoMr73PJBYtBDe2471PRdAiYhV8zMza1e4X+jz+Sn027NPhRFtNy4yt5WEwUBMdPT0Gj22O8S0w/+HP6TWKTmbHUniJvfcnjrYvXCcvSIjzG5gvENx0nITYC0fkFtblaON1T0foxSIKZ1MMOTtqC8UnKgHDdU4PXsKJe2cB6hziFtrAygP3//tib9etmG3MbTzSLX28AYqS5YYnCC9uQWwJY2W8oulg3lIfWEaZLpIW/sNUkgvNpOmojBx1ufHvxwg8v+DYw0YR5UWtx3uN97zvHe3xMN1phZsjepBpC9CvJvG+Mdio3z2Heeod/0fhlR00eMukcC9uPPuf8jy0iarnfQzzekNpi6w14UenKveqvhdVEs5JtfSQm2rVwZrS3cR4FqAdSBq/5fG4G2iZHx+V0ZePoyyhToMwrA1VXRNNSm6V1hAlvdODNRv/xaaQ06ia6uprEIfFjbnWsRPiNGS5jzx4tuJAthwUnPpvM8aWKwHuHrrJktvXQNIyDokN8tb8z9sTjh7n1R3wIIMNvrxJuqd9CtenOZU9djq3+6b31CaniF2GZt6acVzf9nDAPhqdZBzStZ4iOPy0BrR2aUQVBs6XWTjIgGiwC9qq1k7LXRBPtGSxJFXn4aNuGVb/pyO/vHL6OLvVm5I4uctcROyxRmAPlRQB3tgL93WCfP9rrqI9mxnoLIapZg7MqqR1XY9AMq6nzw0IZbvt3xIScW04aBa2bFYpzYFEIV5bWal8S1LCPY3qfs0wqAQ7pRtxOLhnPVwhA29v9ocxoqOTQZMXW2BvbLVr5mEAnak87wwxSEzzk+/ylnpP15nk9JL2lwqVIuRPTKQbiI4pRkackZdF1h4r6w9aYaOEHZtC08KWDiuRw0Tj1SO3pMNcjGkrqUA+AbEnSAmKFOSKMGXkhwj/PG1fCve5zEVEm1YXRfWzzLQjic9AAXZ+ng2bk0u+ZMfyOWyA9J+xZdA2Ci3Xdgoug2TCABf7bZcv4hr4j1gnfhMhj0u10tzLgn7gxrzjFSJJs7cWUR6npjL7hhIts/xR34VyBA8bov/nRdpRpCM/rOMPb6aBFKDVD/RG5A8E5yDL6ItYUanaXMhaQqFFNipjep1i8edaMwdOUGS//ztBp9XbagQkOxpX8fp9sk72xvJwARg5hdplbxdf6dEHORSSfDZy0RrBoqMVUj1Yn+WNQNwNCvQKA+qQXquGdXU1uTAmf0wk9We+XDqEzX3hgZ6nxVmv8yw4ur5oJZJS57soaiGSd72LQ8CfdjDDQdWeP4DlpkGdw/i9swqfEYe8S2C7JzJaP3tJmOYROdmmZYW1XjZkTSzazEn5jc9hkhi0keSjNi0B2/CfPxp6e51BmUk8oPuX78IGydqqPu9nIrbK7cSWRFZRgue8PZYs1xEucPZZvFkNRC6Ti1FAhXhwyn68AWZzQGBk14eyVjhnDyM4VRJnpieFzv2EeGRCZalkJBZqQ+yD1Zgudbw+cN44lAQL1qOcI9EWxu9diE5g1yyZZwM257r6k3gZ+Q+MIIf3Uk8+KFIQiod0VX6BYHqRQD3EMj8HZwAiRc3iH9Bxo68OyTT1uaN/C9ErChE1qp4q3EUdUp7InG21UUi6lK4K5/3azQ/KSPMDIY/cYEaIcrmhUXt+2AbryVUdhtiIpx49xajhnZPZrTV/6qNuFlHFQLNahFnZ25rH/b/a4KtYsTSZ5wHWG0V7zakrj50Fe52tOjgqgBofDqpstTQ7KKOez2NsOa7IMhPBGjTg5ylb9lVPUrE50K+G5aC6a3TAGxM+/HEHnCIAVDxeZ+Z77gwYYu9/qzNijyB0PvCv8JN0HVTJ+CXawnM7xCwHRTCQ2wJaynHUzO8EGSpp5xLFHQ4ImfO8dWAvwhyViQcobj0qrgEVvltMTcoFINe2648RdLLL7FTJebAYAFJfei6fXnPjYjoGJnuVRZBXuyy6FFps9M3cNnCMhI2y8Vcf3BHUJ8ds6IpAQc/X7C2Ib4U45fgEoFmAoSaEKa0qX7Pnc5fzelqA4fa5r67QsTqyRwiQkCPBHd5pEiZk390Eyy01+TsT2biaOIuVLj/HfCj8if87wKy+i0OlWjqOQVby217euyTLfuCa3AOKpSuJ7E5pQpJG/9ETnE9YAleLiEVIk9Rj/Fww3H4J+tKTQ39mYfXRGdPAuaBUXpjHVyjqmzfonzpoAU5UeqZRPr6sg0g4w79g26S4rN9SQB/Rl6zSdN0GXdyh9yyQDzje5vsmPC4mWms3tKuB1e9fKUNztptKG31RwJ8LS52ESdjvoDMXRi9cgHJD3c1dSSLnpgPkUs23aYfx1DJwUIsfQW5oaX4uT9vJuujzsxNgfEw0XgQrLWj9agT84dtKbsB2fOGbaqycfhPIKeUz45MoJyZx7bjLNHAUI21jprd5qcHVyvzDFy5bS30zK6ruVEogGkDPhwuxJ2Bxe7a4QprVJTel++I/uSsGrLVD1Ka/3M6XiwjVTvzUoNKB2uoOqQl21Mhfz1SwAsnL3ZyulB0ATw9JdP2wiUPlVGpkoELr/dchbrNPYjNux9ri9FoYEBdl97V/EpS7SBFoYqqLfv1quYb2ISI89ENIQAfBNICmSDN9gxJZRGAzTKdMAFImFajE7j4l9TzSdip7PDyHoSCgJRFE2NFq7q2ujBCFCkNNSPA8y1kBw2NZyky0N9RcTrYvwq1lv67iU2Kcw7sw5E9US7fXhC4yJGyaGD4iTtbvT/s8V3evwt3T/k3aArsKHS/UDf2qCSDMD6oBRHCOb8Gkfl8J0fOxr+F8X80oz/MeHB/RX/j8jBI/67IRN3W5kgFXetdPeJ+i+aVuy/RyQ7583q+Bj8ebJbKXnrA1U5k28En7wlixZ6qoGLby2ccKvgG06ADwzMpulhm/4B8+U3FGy6zWMSdBoBcVeHKgBKyGMOmOOvkQdddD/0B1AzjYzjO8iPBk+jeBY8e9Apwks1ZdB3ONgRr2nqdJnMlWOcLs0n7I++lOBCS6Qw9XqvrWU+K7be8fc9s3oFI5THYjI7Mrkc9b4S6CM+xen39XvQwyLe1vjIyHMmX63hvSkK6+z1to8xXi7VoeyU8kTsVf0CWOb9CkgEuu5Dzt79iWz+ci6pa3rwEjbhFloH5wsQ4+EUUiF2SbSbmyaVikTY9FZwzPKvmrQoDgbudbqpDCzHQsIP9sK8/kBbeId5FKGz5FeraUyJbAdgWZ9zWi6G+UID471k6l/pBwwhcLpWtvtL8yY0HiZkLsS9rRDACJXZuvm/LWpYnRYbe/jvduvImviSjB6pOB9v2+zkRIDgd0pRVo+C9gNQ/gvtfmtWTM+FMrPC1OGMtTUS+ghh1XaOU/xJv2ry1nG+dujBPespEw7CZmlj/USgq0VxPvfBUvAWSvlA+fuuZ6scqj6pSsusaeKLwOlrxK6ah+YSsa/KmyGLNPBysSTCTlPEEkHsU5CN/tH/EBd2lKDwd2MZtHRNiceQpzCqiUS4Qt15qHhwVDeQJZGTzHZXnTvZWRwzT2bgiGQADlYRGR6c7sKWduncaPEuZbjY76wmnKfjKuHWzQjl9XkN4A6L/S/8ZjDmKgWxZ15ayV1raddaryHrxEGgP67WzSXfRO7gqlHFrZFV6Q1ITXjaTtYdmgU8MaP+VZLgfdhilB1pCFAtGBZy5VlTzF7Ne6Gx8SQd+Rf/g+hQaA04PBgdAHsaYQ++6u0CenhfaQgHHYxzGd8B9wuK5fZBrRQEAubLbnQxX6jwdJZnLbFEOoUyGwI5EbHTIr4nnLFEpYFHo5RX1CMBXRGbkeyxaf52nZrrs+nWF1otWiHf9yzEY/4d/pLlaeIEubQziIeyWZkcYzQRZvHUxhnk4rZo7/FzdDEcvORPGtgc/yZ8xQooL0iJO9IaGsYQeu/UVxWhik86+YLFZ54vIVGcoLdeZfO1pPk3MZK1B7E+KdMhQ0IHEp0+Lm4fZ4CTyv9VjUjrhDQOS4aXXHuPG51Q6wHwFYi4Muh0mvAytjFR/UfW8cFlvkspE9RZUUOa6yzx7TtIj263pAyx0M4UGea/0KxWQiUC7FNq0JCIhy/2WeB24ABSiRD0IEGTaNJltZ98fbZjf0pnKWxcJ7CBPcv57Cc+k49UVkt6n90kqoKHiRW8jkJ4qlvsesy7Gh3UMn/mjwKoKE2aHflAoAARYbcXfPwQ9JQ0NHfqqVm5xPGfrkEf2AEXDiZKea2nIRRSI09ilmymFOtFo8yYKen5C++Q2u7AjgOUdpSymO+KxsosOp1WkdAzmvsZA7VM37K7UGQwdl0nHq4Le4ifNDo6G/KUxBYo8bTfDNFpF04/PQCOHzh1bwtkDu6lj2am1e6EP0LU238MvP4acki9RiBfA86Y2UrIfglDr4GAaCQ1frJ+2Dtf6tUX9f0m1JQ6S7OrBkyebojYGom6zcciAQc+dmSVUslHCPa/Vok3Ylz5jcwza2qD3VP0q4XoHeaD3+xQUz1X1j4ArdhOxlryRYRy9Lxd53GAbIgjRH4/GTD81to1MM7eQc86pUQA7savQLGScER8PYCKv8vQ6e/IJIS3bjH54Ge/qIMAlFMww9noMw5UDuUtR0HDKcxhIzRsv/Jz1hHzxCyW1+ACNMbefNx4+AdT7t18orklHEoDH99RYZ1WfpPhE4JRboF1dZ+TzDD08XIMt8OIg7fich81GO8nqbGvcISH6cjXhyH+ecPmnMnWrHMRwdgZDHNJyjqIyd57F274xitxREy8TmhStoyr8x3DNAEUdv8vNhm7baDvfJB9qHzC+PsFjDf1s5kKxQdLC3xLN75staSZW+LmAJpxbcJXTeVwQaz3gomdyxyoq6NQTGcjH0kWHTwtPZ4LNfTfbEp+oeGL3bnx0qwOQ+G7jvfO9WMr6ZmQ8WDzrPjKdBtWK28QqJnV7OztVLq4S7hKGYCfeUTlQ3jAbJajVgLR1INE1ugkvjGYY4aHozRiBWDSyoUlYXlpYFRuDYtRtUljkc5BK3XwXmqyH+bddN/brGQNmQbXwv42c1rYbzeiisnuo9O25Y6eORTyQ9bT8KVwE2UTdznQl3B4eD7QvyMI2lfvcuGcfkwHMEghJzqAI/oW4R2BvKHwi/+AwSsptoH9LZz6QCejPvYCYHEwfs3/qmKlqWZBS4uieEeC64oZdrMU5l74xU0zR+u/dtlzzTcT0atIuycyesGrL9X5klgrgW2JNnIoSg8hO0wNJZ/ZP2kvGOj8Ix4dH9AzL/jW68BZ+9AfFnNzsqbBtKfcoxkNGT1mvaMNUb+8gw5qGcSrEK5Oe9UUDkfZ1CaOrzuNNuLLmaVfLoQlh67P7TXPmNG4BYwzZDZMan5o4BQKjUbO5hVijRuD+SsGrAeJiOLjh9691HLNRnVgfHQ8eDGXHipmV/G/nshRYDbs32Awky9Z1CMcOFgSjSQtjRgHSoshozvgGUAzCmd9aZULSzrecibVCDQqW7fdBl+gU5GL10rw7WtzT00Fb9qky0WkZB4iUfmbCUP1b2Ru1Hpk981f5N0mNzj51lsvucTOSdYeh3jkbM91keHCFugEbXEFIZEuFPSy1fAuxVjOzcqaAACbdBAXZImCyI5pbV3mxGf5Zx+IWA+GiSkO6MO9W7bKLqhZb6icrL8t/9isRxKJm0EDM3D73Jm4CSZJqJmtJ1kDuOMiYYP/+b2mxBjK+2GzBLFJPqHIQw8B6NKMNjreaVkx0UXh740k4HNQlOXRXCSsJ+sTX+c0tZNfsw7srgPKYtVqAZwzV+sPl8csIWW0XXBhNyJJGo7YLhmNnBT3orLddnhd/pkorvQWkfXgpcNA1Bl7arHnphygHgB22KwNlUHzTdNhyRrsC2kH33R3nratYlE4NxrWqE9bSws6ASSjn1ZsftXqaCqnuoa6Uu2k+bwv4fpPDx7l7lO93DjXuMQR1ykFRBgvxNLPg+rMS8V+B2WctAjlTCr6J3vpwEBakxZ/19pakAUgkZAs9tpkKXWo1heqLNlLGWazlGxmDsFBzoDQ3fVMLLrvVfcsRW1wm8fyoUYkiq0aYVx2WUbBVfkoOE+Ib5NkI93K/7HFerOQU8v1GWmeSs3xqMRHV/5zM7PHzuxRQef3Dyuz6FGASDYoVBRLVo1UIGboOO8Tbk2i4QuKbLbLIIg8cKmucGnmgM+/9jlqptpwi4eDoEKq0FqtH0TmGovr/QLl1q0C02KaRrj5SjTPHPKU/LCN7DMki1fPAJWCUCEhpW7lWs+K6Xlxh/GxoJrxlkq/OLiKWFhRo6+ndcs60oX10YRricYlmEUQNfXynJt7aE1+a7slW1nzUHO2wWmV4iO0cS9umbU/G24ROPF9rRjLCNVggNzL26nbDnWEqMGArYFR0Xz6IhJFjjhsRHT7mrc1BPi0qAPZbEHHEetPsl548r6OiapnkTm9rArrNZR9NgwjHbW/VEnsNhsqTAXkqv4TN6CU7f12NZJZoMuDz/zriJrnsHtMNqeRmZ+kqujbN4kivCXxa+ZE3Q4/thz0bScg4VlG2DxoTuPbuMPQC158bKpHldbvcR+PV6Acj/5CZoCdutMwE3NlYvjnDrANGgS07A+1/izceJ5+H0ujWeh/B7Z7mA2xMuzkIWSfScbJ3R3wmfS4/1iloYtGwjvPSqGvUtfycycyrpgQqE/pPYP0P8ufK5+NOGNuzkBe4ELXfBToHB9UmW67o4kKqJlL2GdYIq+TzNZfggfn7sq02xnyC0ClY9S8n+OeFGCfY/WwF0oQmwBzxmy8wHwcntqQX9G6IKOX9AwQ90jkZGAjV8fj1fp485hga5N9/aZ6YDM0awrv1g8NbDYHX3pa5j/L64jtAzEjQlzF5lZtLAp57ypqW6VP8bUyr6ljiu+aLe1Bdzpa0ygGHeR9GotoiwDB7XORFe4DiCW1OB7M18yJ2W1S9M4QLXO3AXJsHHPFIszNANMx1eflAqtFgFVXDZub1aOcSWb2g/2Bn8TD85s2vMM60jPFafg6g1emDCt5VVIZYgUcssqQWHXG08ZNzSoasTgRpGQpJYYK8ExiH8mle4pVCAvRXn1wlh9Z1y24Mz3Ou4216KRBjz+kMQg4r5KLAWMbYNvN1EdgncCfOZuo4kSoVGbs7AbdXc2hf4MsRe+jownw4kkcXzGXzQ7EvgKUJsx4Umk1noGbOQ54GCLc7LLXdc/Q/FLhzD/aluJKXamEHm45exFygihmGZdCN0yELxgza0maRExjSub56Tn0IgZL16s7FJfEAuL6I37l83OsH6I33r6exnyWdabVHKo0YWEAshVc2Iq5OMu1zSEeGxCl3MuRmKLKKWRD11mATtH5NG0Aa+ZfSAyJvFFd9gKOdBtp7YEBF4ZtuNlNRYLSJqw8YhS0X0Y/SUD5AI7hzuJNJbhzKdR8eH1PXwm+pxm+yu+1VqZJO6kMObjsDC3MPMGLQzANHhvruZPDlbNWNX7ZqnOZxGOrzH50nAQofbkOUny0+qRhTW/k/Y9FN4fmd1IoFgZ7Ul+75V9P3jlXvje0H/LjtcAw2Q3EE3Ghbkwc/TVPdNUH6i1iSee8VfmsFls4vli5aSIipcXDaCOJXU9rOX9RwK+4gIZ4Mz8YS55TggdZm+uelFytMl6ufW+6ps7kYRizqJny6YUFkNvRqN19/ZOPPGBwYt0+x/5ohNVAJ5T9QikDba23ad9nxW4qgHqAiQbJHZaU2cxaj315Ox1MBtubSS7XMQoItdHoy5LogdipXS2dQyj2myuLh/MbOGWSDvM+bwLx4AyG9oK81Tzt+U2vWJvXUkFCBiQA2EZSy3Fwu2clUgRlLTMInQL3mvF6nXm/ocKZaiCcuNyfiHsyYvB5y5narKnHj4rFtY7io69WYmrQVHQFfHHWDxmnEVPlZ0mpbnmsjZvv++vW1oHLEnlbqpsLWp51050+PTelYPGEm2mTthLYZ41MYyKOioG9SHoP09GjIcqOBdxMvorU0ORgdd5Ul2qWQi2+LmdXncfdOY3ZD2ELbDtS0dkldr/8MYbm2b2GtrgVQeBBj8kf72DzuKM7qaF0LuiE8iRVUvZJyzkinGP0lJ6VA7+tNkYArHAbHaFlFjWSu5jF2nlUc3Ghop2QoMVM/Dz7D97jtzpalRvjglEhneAW42ggHtWQf/emG/xl2wwA+mOO/uKqxra2qhtR1lkLSWXak6wukXxOqHXWjuroIQHQgZhOttS2saf3ecRVC/WQou5wfMjbns8ew5Jy4B9pNXfG9jTtxMRZd08gEV/yth6lOczVzaeF7cpE8wLFYTSc0wJUMMCjo863K+cAZeOZAnQJDPxwvdq1Gw/qkfKHnizy2QGnAbr+ZOts8qUNrWhOArOBrZ3P3LuNQ87O2Xs4CB6+wc9F/EEQ1DF1CTU5OXtY6tGOsnif35K2+inB9itG3YYMDa6q8tEXc0DlbPwR+qvCkvfAGs4S6rdxQnBcRE84NvXQbZq9slMR9nKCSgfdjlypMO6QV1NOsERb/zV8+cPD1XIg1jd2UaeiBB82jPRtrvFXIFEsIw/iTAxJnXkoijmdPpu5A5Bp2qYaskB0AX/PD9/lGI4izNLbxdyf9ABGtiegUDMWusd0ub6gJVAYXswnoEEUEmThm+K+6Tg54HnLenby+EjvqUdPuPaKTJ62gR9EZY4bN2A5GzVNWm+rQ7XrIkSY78GjJ2bmLCmQjZ3HageMNBi7jrJHCNp1ah+XBZtEcLngmyMT9SMwGxtvlRWthl50lI1hZ+eOOqx4xJdV1rHTIUuNN0z0INcs6Wtz85w/FxDWqHXUGuOhFnESMnTArsxknCHwh9S0ay+k04ok+wSSmnRDpJvRtfQ3ndSilmOGahje8+0KAe7EMw/ImzBJVudttcfGRc9yBLx1oA+fBvb/BWljGPkXHymVwk6HlwKGmg9hvluQxa9e8L95gM7lAEzHODaBsXUVw+gahmUTH0fWagZPHn5MoMZzAgnN3Z6pmfxtLSMOkRan53lhvF4LlTdw2bu1MuPcXJHchu4ywbGa6oOtbcpyogYTe5aYb1aF+RwAL2dlpysPrH5dNKmr1BsVYn+kZP34KHljeNNXL+AQLXftu3orwKmGoy3k7VJ17etjmO46OGT/v4bAyz1aW0pIzwTDhb55rr7EGWlW7xp73Ch/CUUrJP2o+5VwdkYEhgRlJ1FgdpJjV4vci0TnfcVrWrMIXX1uyPhXNfap1+im7va/ltHXrVSKEZau+5Xjg951NSV+xCZnMTuZ8pAKxygZspekEWhdXjppYwn3WgSb5Jdcp/z31TSWOzH1c6Zmzmlvxj6iZ3QFIdYZqrsO2nbFej/0ujbTjvQJFNWQWr8uXpY4zFjDtvBSa63B5Rh92bHSlPxlZWNj5bzXkT7u3rx2AdsKz5+yj8ovRzVnUGDlePHwzR9YnKinQodB5RZgk6DP6DFAFsSkP6RAc+fq6oJEimuZLNqfEH+W+DDICy5mD6VlCr5PAWbYMosJ/WUGXdpmvGBEGd9SzpSYmx3VJj17SCM/+7SglKGmgApfXrCOfNns+FprTkpsEsOU+/IgwGBtwglseVoYgAuHgqDI4CnilBIbqc2cRLpdLjrUG4xIGaMOfiY/q5OmTP7a1t2CGFAbhkgWz47U3raHmBgrupoVxjIV4xwz+mpXCh1GuMZWIcTB1UA++5l0Cc8Ayy1C7tKb/uPqsR0xQMMp4zdF/Tdv7+W543HverKZbpn+prBUd0MvoZ9fE1hFRNY8z7UILFk08RFCydIV4mkzADMYexvq8HsN6lz7+dKcscvVq+Jn/E2euebQZgYN63wg9LZt8qZzASehzKT69FmAjFunAZ3UDvWlNJKjaw0NjtoM0PYxGRbD/O/I+yPji4d6fl47Erw4xxNfJ+JZi//jHafZCOhvqZK52l1cfURjn9jXW7/nn1BAl2DUHrsOPHN/dMrDFIcj04wes3z1SE7bJKeVluU2Ux20KAIxUcuGflVxf+KNPs8kFYAirpfrk8wUTOwkjnErQp5dgYlE52AJhtDEZoBhSw/JIyQHtyEHWTEMEtoBGxPph56gqXC5KOpM1JmXA21IO0jQ6HxHANDhJEdgr2QxhTJazuSxR5mwMFAeDPH8+YOkFuOzKS3VDXMc0sqS3iLaCHydPJny6QL28Um0D01pcrCyNnU4clPl8QgvuYa90tp/7XdQlIaIe2zldCUkc6dA18jb3Moa213laZiTE/tru4mm1KNpF+4zb5x35MsX1rz4u7qQoIUCImRlLMv6pVo+koY6l+ta9+c6r6db/TekHOQCX3qoFWDgh/Glqr06TnXktJ57xvkYSnm6BEFxiBjTQaKcySgyMSqiPzoL0K7sfBxoBKwr2TwgfC2KOEmI0v9Y26J/lydQwBLnk8HYrht4fnmD9bvMT8uP0IXJPUwzGNkO4ZdRLZDBtsJfzKctOv4QwUL7qrOQiSvY2DigFeOV5jnG33GZVtt4dvcOdsOBeo7EVIAUKTuqjge/6/Yti235RdHsWhddpAVP8HHgHS+s3wcGFXz2kSGcAr20gRvBGBAvodoAaBjxi1/3lBmFuaWlSnAS3Lt3QPkD5NtErfkVmUUXIqpdD83MiNO4men+m34wVrg1/4u9xP96oStgGgqJgaCI/pw6cZkCcNbJgwGd48heVLHbWreNbc3R+TWjRc1h9p0W/vTUBdeJ0jh0/hfan6PNK9fFdZQ5PyH5ACRB+A/fB9jUSxTzNff4W6iL0BarCW/iLeo/NN+2jugN7h3CVzkkpTpKGAy9OD+IZsNuWAom4ByhHgwJr/x/XU/dTSkthwJsxwDrwNuINg1e8MpvtzhCyvG6bfhUoKtpQ2pVa1zvV9gQnMBhnQwYD3xb1zJpH6xIJjyPll6CbruuwkIjwEjnYI+TA4ewt2Dk1U5dk8ATUipSkWUoZRsayVDIDKeiW0ZETocRNbyvQYAI8m8G2erkWM2tFzpWR0Aia8EAId5jDB11e+huN6JPD6Fj/JR3WBtgi5FpFY41WuzXr74tJ9g8xwrUOCiyaAGGyCXsQ4uI+dV4AziCYVbRtbg6pFgK+ku7EOtpocafQru3qiB9rWRAAH2KqNoEZEZClBuQuiV2W0b/XpzSirCO3Lo5uTm+f29nEqCZMjLe04zV1Y12N/AuzojWjR85DUTKOT31Qs5IIUmEmO/k+bkwZhFdA/y7OUx5T5yl+AwqZxosFq0Fi6PWr4u/0Df2Sth9jk5dG2loetHCO9GMd6zV751U4Hr9jFikaiF6gPzsNjZkjIxM5MmFhRzuinKOAJDbKL9Bji4gGo4hCkxjVNxDeyxRdkVg0relmUHPITkSiSRbBuQqH1EDfLHSIaCvfj2YjgX941uR809XlGknPEpo68Zm+LcimXhj18gROrNS1wfM8IbZ6bB8DzO2GYOSxiCw44SNOkQ2lGocD41zNGQs0paWmMZyK30ACYB5+iN0L/9M8c7/tIg/4e9UKBfH6LCOpUaZ8ADr3m0XwzTxw44E8Av62qZkmk7DcImlcSwQKS7Rati20dDn/1oNafvoUQOizCh369m7E2DnczE4yhhaQSkrhiKAKloRID8k/7bJ/WGO47YXVZgFue1jbeztwcdUi4OT/5RkHcSXl9mDWzJcatPzgLfk4uxXd0eBKGVRC3dlXIiEYTrvtBWmN5dVM9U6OXID9gdq6eGLZebmxACYst8CPdpfEsZkfHvbyta11DMUmMIo9U6l2MGk963dG87fRKSQj97rDVE5HBPfvppci1NfdmNmnXgJg2CUXUerAV39J3+93sz7Sa+5/CG4RveCzecmNnbgqVaP8hmEO2yYhjnso/le8XlRF3r+ALeMZjkMeIUmVMDrMRzAGsUQTctlvB+PN+0+yHYTmk7ttOxHl0ZITRxIjmaUkOgc8mLO42in0bmHy4Ty1FRHhiwzjSIethf50uYu/cUCeb/tMDoGDrP73Qu/WBGw5vm1fl0n0KOClTSYPGCy3T8RiubsQ7f84U8g5C2DHTUmYNJ9uT0dZPJWKkM8WKXGk1jplpQt+IJY1VzEv23gE83n1zESYmA02W9SatGlbZbajYEjcPLQnjz9r9oVxEzny1Y+6kMQqK6BGb5TYUqYIsxsfpYWOjuvhPnRkDOlgw+/g1ZIdelA+/BmmIMMMfv2cw0BodxptkA1iNmbaNarUQTEbPtd4PVt+UGkchKs2ueDAH9pV5W0lMFhs5HuZSJ1eOPcRd+ejSstLU99nenpxmSispl5MXIPMHNA1MGVkCgcL6pu88c9LV1vA65KJDVu9ayzuQkhrEM9LNSELr2tauvaOusdnDC7mcB1phhh7bhc6d3sMnJOWDC/iuSW+XOGR9RPeu6kJbrR9pCH4yd6BrtBSsEzC2iVE6gSiNINHtLBbGkx71NKBssb7v9dVHuB1/usYwE8GSwVK5YsAqi/3ROJrW78bF0zar0eJ+XqrDkb0dSeD0LGqpft3L86vZc3aSWMI+YPuzHUVI4y64chi4Yq9Oqi4CvWUmW8gMMH+ZlEYu2jMnrZfqAXmpjIXdVX3oR4M7mxQ8SOCrU2lRgnl1GaTJOYBk/6egAMcw0W9ero0SLecvG+9MtE+oGxqv7tLR8+yVfE9TELFCJ/sF/pyCUtQV3ouISim2q1xnnJteVWAygO2vsgF5tEEyBavBa4kyNRfSgQ/VcwKSRyPb06YCm5QwMs5UxcZC8aLRT9m+HL//Exo0coATtyhH7IcWGGRvSwkJoIStJS+4OZbYL/Gwb3JHSu4zz1JivZG3iY0HrZAxTnyEYdnhVnFmh0gdC7XepOlHxejBq+pvKAr0DmqVafb2gPSM+kSssOa17QsLSo3NFF22lmMjnN6kyNi1iuewByOEqFORjzKBXqnqM8rw0j4TfjEMUD0n6VlhvHKTufy38eLR5eIdA+AciZQ9mFfeS536fMHFQLaG3GhC7WeUTyAVF5cx69hSCbyyQVEs/1T/dXx/l7dYQ2e9jnv+1FGmvpXOVQD4xJHYQvjeDRf732RFEYmy3xBrFa0DoiDs2vH/7YW+mT64W5RA1LOXSz1Nx9JQFy2s9Y/67vzShOyjF+WFgxxmiA00f/5QqyTTRidMSeqWvtAF8T+bzKKx3rhN4yvgxTt2SCsBgqct5V6pMICdwIofNK7M9dQBAHr1jLYHMOAg4bmcuCXd6gAcns+TwrqRy/mSKLEdWvJoujmTWheBY5Pgd+jWsC/BHRarfCPTgJobs5aF8rfWJ0VVAFpdVNKIPlqTJPYAniVQfZVqlVrWGkujKXb6bv8k3NGRoaui8szyhjMzI8q398gEtExB3InUlo2AxXKZ9oKjctjZ6UAQW0s8Usl5W3M70Hlib2Y9KJqMy+V9RCvWrQDStwlOmHccoauYog5kXQ3h0dztz1qS+tY3i/gTM7pO4V8vmzlkrb9aKrPv2vUtsLfegTKXkBX1s9CWhcMbx+Ip3GgihQV9r4j9E7kLOUg9g77kXvZyf8PRpVbEnTHZ17KlBnkn80Dd/1Wrz2qTi+721p8fV1GPQgN6/1vthjVjCfJtmLLLB+Cw+NqZWcZE9lL8RDBrvLW3DzFSAcmoldyPQfvLjtGR2sdzTxv+NSu5yxLrAI2hyT9iUUtVDGmbSRUsgQTbmobLgcpLdWGjD+Pt5WqA6we1tDGJ1sjufVCKAuiQFK0w5yDkpj7xnB8HO9yPU2LLYhcsR3erOOG8JPdFI7M62YF8+sX2ic5WucRir1mPBanh2E9Zq2fKeK5Pn4BUJQMCFQ3q3TJ2DC2KlKhePE7Mq3+cuxNlJkNd0psU3ym0JV+qb4rqyJRe+EWSHXfpccz6LF4pZ5YYycWokBkh/jOrCtKSfyGF+WP8TkV7f1+voPDb/gwLEg+lcViq5/TlpekEk0s23k+X6DXJBsfNEkNvVuusPUcidhUxyImB0WiIufwbyCx5UpdDBKw4oVFhzmlRX+6KDYBeIJkFhiPGdG3NqfzJ79XoWMWM8WpV0pbiLuaKvXTm4gezouOcPTzA1hycH/aNQ5wxKCQo8l/QhGlD8D6QXcW/LRSSVG1ZRoADVfegGQ8oLWJZJlMfJCbbCQ8fO5lsZMDYv9CgVkyGMF/qpS8aCLIkaKY1lbjT7aqu+6UetLZakynhPsXT1LYymnD/YMcDdCdqs1D5P71rl0jkf+u3pvJzAY3sB7K9OCVFHLgFXWl2OI8u3HAliVUPwtwLQt9xAIKoHlF5PXbl90H66bYRlCVO5XDltZMj2KyfgYaTLV7Ny4GMPlwO5sq4sGokMa1OHdR2SjkWTZQYrpJhg1Zlg7KUZyzwQfZNUVcqRQZsRRyAlyICWiKbP38oWGqBJOXgVK1Bm+1nsDSAZkETgrDCWFlm7X9dPBhieSNedWKKc4V0fwSSQXvkOfY0kZsonQh5ZB6jTT/xcbeB9kbO/9Y0iPH9YrOhKyKR1kvWchSEA/V3W694kCq1r8D8N56l09capE3NLNHO8j9gn0adQt3b+HJVQZhFqT4xMerX05tsp8DJuj6w10oUvp9qFJLIjz/8CW183QwIbm6yHSCkTw1NiBOau85fT1x6pdsMqWhCsSIrUmA8BsQ2JZS8ZhonZ06Nxw2OtSVWpmBUHyppBT6mHoXPL/NgMGdnS+bNEWh9gazRvkfR4DhLdly8M4zi/Q2KcCjT9/Q1UMpqalwC9l9e0avcW4eblmzACSu8qa1A6vgvtW0qss1tb4mjYL54b8+T09aP46nNnDdUaoxYhuYzh/nDFCPeY18pqu9+cVtqewFZJQb3Yyb4UYOURSo+6NnVgLH6Yka7kiueVJ9zXJGE0IAz8LzgwDJhQck6+PaFC4dm8d9+ovIO/gXB7g1LPjTT6O5FIJvg+x7/b4fGCT40j+t4etozxJFUaNMZoNy0J1SFNVZUYZB1puEXfJpm6Ux8ru6BRaZBChKiM9kE7OIuTkweRP9aXYfCz3q3E5T/DYFHpxQsonIOAZXc2m4PVeNTdpt8WsQs+P1lyhWS+aAeNtBNzGCiCEYztHX2+pIBdgM7pjBjpXlZRy2RhnGSDz4BEOYbzOQvoj4rKsik4Ov0Ji8hEmvy/jvTvqAVjnBffGFUewWNfnQ8WljkX5gFhWLmZ8YpZgoG0iefC/dMoASdEavN/iZK3dK4lD+b1JUGY+MOHQDTTr03tLZ8y7KuXaOYPFyLmW3eex2rtvovzJaLNjMjXS1T6F63hEDp7ckfQi+GVKhKxr5tXLtFNlI/emYai1FIws0+5RjKLYuj41oOVXuyi6igxAfOh9tfm2gLMxRMqT7NnMP2HnkQiFVbAXqds/6FN/TXZsJK5oafZElMcAiOrcLrsds+yoen8REv7ItVeuB9af8zIr7E1fEsYMM4H8VyAVpUWpcQg6+mCOwlTGqOyDU3i82AeUR7OMJgJ7f7pu8KgxCrOua63JjAVfJha6IGHrGvog5WBjoY+yOjgUCwTytDJSSOBZJtx7L6IdZcSwZJnvDhOhuKCNY6DxPFTPEluvcMTmUS/VZzDzSqvKWPr7QoYsvqo0RVjvtL+Jo/99L3b80dFnc44/36u5U2wEKN8sSDsmzIh91W3fz7sPrkrkGBkm7zbFMdBN/SjOg3yi8nMDED5dNsBotAlMU9ACXiGPj4EtTwhr8IBkFF4L9ByYIWPM4Scwt7gl/LZYGiTd1EawYorQrTRq+Ecz292fZn1gZQrgs85z8H20xFv79Wx5sDa/ltyUh/JnOLFNfnaFlKKdiYJ5nPSn5jLsq9H3NEuqjsLlgVX79Sf7lrumvpMOVKzprFwqHNraRwh/H02hA2QvaMJhBaxwdncdgyqE2Rx8QRSZtvTNaLx0hK9hRaM3PMMrlxjBmiRARenS93g/dBLe+4bP4s3vquEpWFLV1NVPacH5lQ/p46zLgQJMl/6DmqDn6mGHDR5DHcUQ6x4peqp29FCD6URHbBClf1E35O0hSUchgvk3hGjL19DMPUHhnXHULyIxYXlB0eEhqw7XGK8OxMNHOGgijCsKIO7I4u53+msToNLRjYLZiAyEgWBtJVg25HXfgB8WkKZFgP7nMoSrckB1z+X7cWM8P5wfzMDLuwYvETbSsvccaV3m0EXmeaych17jmIyV7bTrdcAmhunmO4jNH9FprwH0g7eRnUlon3ipZihwe6FthGl3sN3ubPqaXl6Vttkt5dncaTyKOoY3ZKjoSLFu5JZBhkbvpiuUpsvmQpQJybMeqq7jwOUvKTmDlnbrcv8agLFst0iGVs2xR3ekPHOJvoglLd9VPuLclpgwf5Ogb9SxocLXZeLHQJrdWVafmx00nDtF9B31lrTkkzZNt72jgGL8EsPh5QUTku5MlUa2rxC8H3Sfl5xVYCzO6PaTSHTeXY8gC0/W3qj6xRAXuxeF3Fnn4UtYV8ruxrZo9BwRtRGrw/wxUQCvNwfXtTQndOl7hcOnS4dQo+t2Yr36KXr+iL9AINTDJDt9S/soCX7FT0cpWCyhQCuZp4y726N7WjpeUnUItZp08RFshqyxiPz0cbgXsqf/TetXcLfZBdPYYShvt78WxJKIW7M6aSin4W4ExHh+5BnJLiMawBRLLCARbohNmLZwGizJjXAv4Fdzp3bMcKAdlLkvAVVgjp3XIqhT/ZAG7CQXRxLHNsduSbg9jZ+0eVEIswoJV+g3VC0p9si95PJMlRJNJHU4CQucOgcdwbK3vDu0NWAdA1sUUFnxsioE1WTi1SH9nIxwXIqZstbY+LXLfSxKFpfeUAjXx+/dipGCGSSZipQSnP66CF4NNYgTpq+b7rsf7EzzfOORUzJljlANAngDJet0s2lFL6RHQNLIJgdjw29I6Z3cND6i8hlcnBdVlKWGfLHbpiW3kFs4mcvtCymneZx/fcu3NRfjtyRmsAq4GbhDopj+Q0yVvmMISq8KgoOSz+ogB544xDz7VviIoJymIrTign/RCBNieRt3xpcdcKIWWZQ0UX2exLmqKPQclor6qjhcnwHdpzsZlrfDHjlnXJfPOJtG48NT9z6r+yA8A/wlA96LvB1c1y4RXH7p3ZZ5Zh6XYdYQ4hnA0WPvAsdUs+zOlEhiirnLpjZU9tiKCq2q4tibe9CR2KQ0nYypUSfvm/KrFn31Qno77NFBOLB2okYThmdrXOaEaW/KvBzgo57mptOZItOSfB7zSjo381SyTSuN6i2bAG0BiWFMzXNGObazl0tZ8EVQouVOG9HAQAumYeVNU0B0o8lx1pRpP+KPK6j9BYXxGzea6j4MhNYsWfuaTnrV/jCLj6tSwnFlfwwsXMBUQR05CTBJ71qGz6Uoc93XrcNlcrOX9rJwLbSCSpknzYapoNyfOPQXqqyfLHPX8T+H+0pmA+kFf1ABOccw2K+6pdk7LmzFrnaPxugsRJKjbyZSL1muMXdJ51122Z2Zfk3bEyN/P+XmdrqSPQSymWppHA3XdskLPf7DG0UcPMR1ZfJ3mpcMebXknVKz65Nplzw+dB4jHPsCOwy571OLhjj6ZF0JgMKZpWN4a8FihLjUsQO2AlRcjySjcAp20JiCxwxX9JHowqv8Tu6C/LqsIlwxajyFicZ08A49OEmI8YrBcwIO/y534epzdjKXSa4FGCHtuzh8w2b3vZVEKMRypFwxMHeFbo3SK3TphIgs+oAszp/Z1Yom2WT0SH651MnG5MrVKtv7f+KENpfKoPlfD7WtroOKQulXV46Ihs0yCOwUBL45qyMLa7W7yCpBfXjoJ15uyGIrsmjQsXTmO2xTke3ioBzI9MG7/SSTx465/jlkE6ACoLNlU8mWsfHLm4Xv9EB8w6oZdBGxuityCr2WHfynJsX/KTKx1jTGpLD0t8/7KMG0yStwktWoTSOueZAlSoDy1d2llnUaJO2EPJVpVCFpLeTSoGl2ZuLzNxPyhSTGtD4n5GyNtMYDu3IxB3I5eN9c1/msAOXOpxuttglfrx8vogz287aNq+/QucSBW/eljJ2G8MegqspJ+qJULogIQwkUAp45qkFBGWlcEqNhv4JCf2fjFymdDl5J5MkV6qhNatk1vr0Q/QcZzXbMDSJiNdNKvNu0D/gIl3c/5uThCk2U65cRm9RFU+DtsO3Wjyj6Bn9hlIM1jfy8gs9r2DQgnvqnw2am9cgBNfNFtVeTTP2TqRoekphHnOJSERZcVqTcu3wzWrAj6KjfvUra8l4oykrQXeoc5EIhAzCkwjJHp8CWPwXU/AJj6em47BLacPoHTU1RffC5hvilu2qrl9+i10VNw2cXy77a5J4dbPlbNx0C+c7mzw0Uwjf+h1CxyMTKMSdMgZN4u5Sexy0DKMHTOBzsGzM0ngfOg8Jn6e/q8Sr0YomB0TCt9KkBe5y4hIEJEBRvJ9TYIx4xP/fBPG3LjFoUu7eD1HEhsRbm6yhYlKXFh1QvVby2Jne810DUIcOa3Po854eHLVk6QCWVLfEsEQs9COWAWR54AjPcS1vgnoMssF4KbKbYyaDmU1gkI01Lsu/AfT+PJ1Bmxo5Gk2e9qBbD82EqUnFlZ/e4ghpGVZ8+3mEfXmb598T/vsd3NiPPyG09IoLxACGkZNn7JtDg6bSmpY46naRg8MXvTedQC4QlxUOtkT9S50dpV6pN2bFtqDyWtX2d/aPa6OHgtRD3nmTi3tOcKkktNrfCB3rbf9Esj3jmOECBgSdydkWQpxK8R1WpdsCV2/hXKO73PKFoECmIBdFzlOWrtSLqknErDJPgZry+2+SISKEqN8zqPUBUMok3jYr13JMOWUjuD8wgxTL76G2XLRV/VaIAMLaBdMGzPQZNlKe/Nd1WCgqu3AvJyj6AJDcfB13Fy4DuyEYltBIGVSJGoNWQyLsgDqGwEZcJjwqR2cOjdLRuVWCWC7UvJwhYnUkeZfhdLFg6HUmNvM58CirvFlmicI4D1ssSxKLcvKtVhxYfbmZvW3N2/YGZMjKeasdDD30I7ZeGdhfTYfjaBqDYxQ70Va5e356s02T0/qlD7r5jt8nMCgduiM+qBGjDQnoptk3MacuwGVKtIs39O7ENkmnArzqDnQhar2y324n7xb8h1xSf1QSLIbACPB2scQHOiOmlc9Y4zsr9MoNC8MigIspKrzF1RxPxzgTuSXiEZSGVq4BOwHAcvttb3ioK0CR3zrkrQ6g+060Q8+NxRIguTA76/KFUQ+8BAkq8W0lwAcsB7NZMsa6KiBaBIxdloUivhC/nXU0dccygqhE+vN0yr2FwDAMbeL6o7Ol8s732eYWgei5K6GByZhXdzVDHzLXsK20KMEmMzvXyEwTiJ8fJ/rJCtmbsIB1i/6vN04hRD1Agt9ZYzGIgPp7sn1oqQg650L9jUbxa8mFjWIbpXdwePE5N22+YpYWJLq+Ung963yorPtcliHbOHrxmMIY70NX7rLKGRO+5waEa7rlZ8wwcNg2Pt5R8WeVpZePXq/ChOI1uY04WQKc7RWFP0IrFj+MMmUTa66hTlL5Cn358UOFXEnc5AEydZ1JFoDwYRdJ/cglMJ51aJnS2wxwy+WFfe/pkbKB+qv9P7M3xekNdHq4zhjNiNsL7UirgsN2dzG5DHxr+Xo/q1qnjZbqm8maZU8VXd5/26Yao9uqmfb9OmG01EEZgpetjfCWXOVQSmhdclIJyeOlbyOs+YpHeOB+yYh5Slsxne8fj2y9YOTXfaF87fEBp4lBVeheHuTvDaR7vM9maFA7+oOa3ogib8xKaC8EsLzWEqirzm0sHSlxUfp9bQ9Wj9nmRYy6UmnTNTICKcko46EsY3NAHs/sFSeKj2mz3GXeAIRS4xuP4ZBMSzZ7K65pu44MwOgZb/xE1svS1+BDOBPTtqbaK84lWktO15zU1B5GdaDR1EpX0Te4VFFvpxXV5vadwcXdvSbKtiGlDSPVt8kiwbd0z7hrnpZh11nD2X4/BLvb9tdbR9IbvNnSlSe0G90Ho1bWaufisXZuEYkuKmXLs1Hx/1N8gFd0KayeI4xTQvy3I2NpMtLSC+9du0vIm5JMetDuQp/3oWCUfpOeFHPuAiAMhXoCrjLromk97gjChaR6sk8VwRhEizIjvmMhbp3ve308AMjng9beHYiijw6YF83fOTIqfSMroGTRaSUykfE7ToVq+tSFkrkPBS5R7bYNV3orsYd0AKvuAqxOt8j4vqPIL1OTNbMTkQpTOqstf3mnE1gEjW9Lz5PgMp/+/hVZUrMuFRtEpcibY06s2KaY+xP856/fIbwVtif8yeI8Q/IZFSUhPlyWdaLt7MwmVpx5/2zpsFSA8ODgU1ctiNBqn2ZyAQnvk7ZhsBm4o3/k07pQTLpvLsfVhB5KOYwavjtvrRCqzChob6pTqdj7Z2yHd8SrRcf+6faIdEpw0f8H+jTRp0ER60Nx6oxegBC5zKe8sNr1wtNBjqAKgjloH6dmCPGoEowpeAO0xF/INVXQOfoXkX4jV/bY4GWQCNXVHQFGE1gRP0R0ubxhmd1Iq65gLXwIrOJkrrXwm+936kWQ6CZdNC9MyXd0RfkA2P0yZ01hfd29kIHD+4SEIh6vqpPUuOydjNBmBgSwBFgLI9d+Wp94NVzNVkvpCk8gtnwbu5vIUzfB+ZxHLK5eXS1n0Qua8n9rWzuIVZK8tqHupXQp4G3R3mXqZXerkmLFINTNvWzV+K2dVmHd+ITPDYsSQCakQ2ByUSVknEZDzzfON0996My47V0dh38Nz5yfTL936TYmBHCYZLpGvXrg70HjPfp7oV589axLolTdOMCzKXTxvcuNE3JJm+WL2VNBJmTVptPdhsEQ0bnJmMfdkH+xHc5u60F0oyvxv2YQEoFbJc1Z9/8K2uAi4XBYhKneuzNzWUxV4rLnajzvrPMvncKe6axTNFZF/OShPMOZ5XayVMOWH1fC6bm6rWbbVSmLuajiCngbjr3URcwcqfZn93W+XahLBTA8eC/J/RUWVqouhzfW4maI6J1zHt9083CiI+raayR9OcpGRaO27RPDZghT6Ra8bzGyqtUccOidLaTT01rXElziNhlo3uR+euTOY6bqh7g5bNRaQf75ti5SJFgS09bsnlv5AWtt4kfdJa5g1dkZ9nxbwk8L1vDuUIFdf3ii/suew2WgzkAXE5ZAaTLq/vVtUN5Z8Tpzua7VDHZOMPrp+c89P0h4dYcre3PGsiqeJfdZeF0q2Sc2Pru85535frZy8ZPMgJ7fvhtpDDBdJGUiD2NOOV8taEua987qIaaKpby0A4bW/IuXxDB6cm47vhzVg6flpmvbMB8gM0nDxsWoRxBBCNYxvsl5a9UaBQzkid4NqHdSZGFhAduKxg2VKgvVRzkTA2LBNl1QBAd1YKB4aN3XZHpovtGGG5nnXD+HWTFiSLrruqt7tz9b0xNl+KJXBbzq+nMZUKoS9aFqSl5h5DpGwSsL6VSE8LrBfhqOrtdf+Xa5fQXiTkJgwrrvmnA6kWovnENkOBFD843BAPBV4Xj0opHpzagyQQfytqqLqtZMIsIOkXC5xSPA5JQcFbmFvOAueJ1+Te9XZ/7MxsjrOGf/01wWdpVcBnH9GjPianq5l/+2e4QTpsGPWRR4HdWj+FrMxNeSBq6Iker4FCFXUfV3jiwB+zS4Qcxo2AEDQYya6dl2mFGnZUfok3bpada8jcq4ElcVQ5YoyhLlzHlfl3UlpYeP99GbnsHlEkAu90+5mhhbomJryOb0hTg80Nv9+Wyl5zet7p837wg7AOIrAPW3+PMu29Za0xUsMewWh9vRlH91iCkTiBQw45QgtGetsSSar2yAJOqCwavvD28hJNcjg/yshyz5LnpWGKtDRYpcpnywpRKr3r7mGkMkdNZdyHsRxUAhb8NN8stnnKjU1lI24OME+TyfX8cq2PuRte5lFnj+BmumzX1/QnF+Y6P6kCFILR0IuhBHww8BJ3jjlNMn/MyZS1dAum8qY9pISl53JKF+r0QCXw9B0QiyskAnSzNUfbETk/eVorFx4DXvcSUCN3V71REWunTS1XB2tcJFa8STxusC/SVKl4qhFiDfhE4WrsrCEDlDoMC3PAd48Z2iQMSUaeZWa3fMuuLVIBUaBuoblb9+1PK0OYNZnbxkMMEjTHKvkC/DLzDsIo22suSafUbagig809hbJz/axYP/MxScfK/achErzYKChemofD0c0FenluFqUDBiNCegd53NtCYUm8hPFWYigqfK1t8Uo34WIDCUX74g/unT4mFzCIkYBCdw5i76sSMq8IpUZbR+eSMpsgBHwiNjbsu/8kwyncXj8XYsVt6tkEfZYbvPMpe41kGbeRM/MkwN252um/ms2J9sWuE8cUgbty/u/1YWGnkOyFby4/Fx4VYZSxrtiMUs8bxWtMcX2yqBJTm42cPlDLpIfuYiGAt+50QPc1NlHKaKjUD2fQBTYfFVKjhlU0azXxd8UvE53d8DkAtAom5kez0YMklzswR2kQS1IN67ymnnGs4ifQI7s/4De0B10nCppSMOf4kNaLJYwDLs5JWOslUPFSAFwfT/LnEnEjohaKOeiVQsB8iEsV5HaIN3DfsIztUJQM/AaaBF1XHZjLCkSVEYaEebVzvuP6tfGqCC5yrKOSePaFyGqvPKqW+xNj/W1bjVP0Ipm1vh0hT1J9kLp0lyUr+nCtGlXd2xBAtfYyPYIZiOP0wzEE3ettxa7AI3iIMEO0DUiZ2583WJNTN25xGeQhO8G9gC28HHlxhla77tjhjTJ4TLG09OLLG2J+nxrMthsfRQtTRb0wGbuK2RZhUp4OqUKqhwgZ2m/lLNqJiCAr56SG/mP85iovOsFOPuMyIxbOdwo9XDR7JUzPqgqRVM5O6wVopV/hB3BZLpxAtsV12gc6vos+9mEHCZs99u+FBm5e98+9LDVRzE3tIh9IrqGhpPbNr0OtJLUwF1DoQ3E/m+L5X2oNBCc0//+XLWf2iOvWYwjrftys2pSgxa2CVKNPcbe75hAt0HgR+Id1FoDAswamEhi+7RPEZh+JPfHu7mEv9y8AydG2igEQaXg8kqvRJmi16p+7V5DeMQK4A3Re1JeFmLTemi9x7Y34bC0nespUMH26odZt+tY0nb4hQFNs4VxtE/dO1y3dq36jmgiLVidBctMPxDy30Od1wfTqO48A5GPQzq/DgTZ/SiHjkeMatZ6vBWAHe+RWi7X6a+qQfEtX8etPE5s0l6FZ53CQW+3VPfddDsvNJJuWFDuevXlsShlPR/I+EYawJTGbu1GzoklWoDYxJfW/dZXy6Hmt1t8MAiwNDRI8OHmrBQOmYZ8VxZg/N5WLTV7m5gChsca5mYRXdQ2J4nP7MBktLAWGry/+8w7OKxE5BBBlSEyTUY5L+f9CE1tZ2jT1JkJD3UCadUm3eerFJU5tzi37zgZN5uPZUbjwxI5KB+SwWoCClazcJBj3KGcERsuhzg5WbRA7PBE7us/jfbeXUpjgx8lzQniWN6Z6g+7B5VFQqc7uxl1CSdp0+YYSh+nBwve+ZrrPiCMPJbVlocL6X2LRK0dx5DFtCcxsWFFybhtLwAzOc/ILy7bRNXm6pJcv/W2k7ybrIncO+CDNSTOas8TUR2hloj4gSu5cHpPDVH3aEa+1JZXuPdR4TTiD6wwO89txvrbaCUF4Uyp3ml6i5FZTDBOS47asNXEHB6zlV4lrUWJfTTPF/5lEWVROu7J8es+rFQ3fe4g5Nwm16Brj4vWD+1l/UkL6sYTxCydk7JHdgmgWn4JQZHY4t7ssoQqYJTxdRFCpTRQwjYT475GPcMn3RUrBbkqJ1puOZeeBdTaVGv0PJA/9kc01Wmrl/XY2C+EPXEKJ6+JXMbrHrJEnPzCq6griYpBHdv2+7fllTImd7cU34rIkJSMFyZBqY+dgjDruvNzV90kHqOvSw3lSGwWwTg2b87ChlP9aTypjmoX/t+q4Flwryeo0Xtg5JyxHOKltK3s62w0730Ke48D9v/z4BXbEInXS/1XfcrZnQ74b10/d0r8ReMmTLhuAHRhqc2+vxko5MwZl81UMqSQjca78KsJ12G4bmj8nzWx8juvSCstWVK+mn106UzvT+WEvrwy4nMugMWmtiGUU+GMc9mi8Lt4nEY0gYNSFFw6wmtKNyjI5/flsBB0iWi1yH9M5nF/d74tziISP8w12BMw2m6hcE2jVeQve8JfDiSo9Ch/crv5URyKWD9pndXz1qWKJ8FFHJE3AanRjqQ/41cP4/Y8iZRFPWX3NeqX99U70k0i9Q+4dS95jq5Vhzo1Wpbitv224qtMdO2+lNB1eo53f72aEr1KX+66JgfVpPrpSx9eHuGv/t5DGEYCpTbQXslspow0QAGnbuz99Lg3tS2hA6C1qa7sDLlHKJFKRdEm52H2GurnMixbbfpgxu6jm0ZkBfMluKKa1ZSYR4/6mR1fD1cG54/X55d9xEZyGCOdq/5uUQF+FVWu3ZBMCxyEWqIWWWCh9P8u9j0J2Hw5ajgMENdQmyBSfWd5e9ydGWUUNCiGEah7YPFkk6AhXC+dvIfx/m7PmHZMFghlAP2e/qXXeyvddJbyADFimEOsppUf/mL0KjuvvFePpdUfcr8UWRZkLn90fRe7Pq8dvJ3lT32ulGgK6iShkXK/8i8OPxznCEza896IhFdx+by6bEDmyDVvSs2odWBqxM8atmpR0DRGRLvUyMf6zBNVe1Jvk/WVTqSVYh5uR0Qd83Tlmr1oRKacatzJAsuuFfwxQCju+zE3BTxy/riNeTquDMAt9u2zFU3iBnLat/Ro4Rq6iRRJ6Wzv3tYFCEEmXTMADwnl4QC4RhmC2/DBeDq+FV++ULWLpzQXH/hFfm09s7vGJq+4ADXgFNbuHMj9U+90B45T5YonjypAoAABjC0OknbFHbyf/95EtsOB6Ao67KmmAt9rg2NfSpxZqagvn7cXB9sL7GsymrPkPde+HfvHfKGp0ELpep1N179VXD/4xgrH1R/y6EFcrFIJC5ipr7IeF4tXe29KQQslUVSc/LC33kzg90E+53hx+YghOer7hfvMFuHNC8te32vfwtaRCDUFyvYnFgCvrOnaWrheGGlxVXYQ94MWgyJ87CzCUqyTnzyIvANd72tssicn3HCvtNPJiAG295mgYGn7eSNvMU0uN7tnInowEj2pSwTWSm70lX4fx4EwOJNYhx2Pc1LT9+Lo+DdeOpSNQP69kD7fVM33pauXky8jNF2bt2ufKDa0JiGoUbKFJBxYlwSpL/3xI9nPmkt89lf8o6VKjQz42mXZGiwNyV9z6K7zeMVvBDcfsOHyl8iLCpRmRT6sYV9T4zt8cSA9F/OelwJTi1qeh0Hgu5UqhE7KlHZrW8leub4siKskxwzt3ZhaCjNyzP5R8D9enEdfLje7DZ3Nrt8L25014fHZRUPUyhGI2Q6UHiYbPjlKDfBMoxHmN7/JKDT68ZlqG8A0WsesV10cJG6GL7LYlrrvANvTpFYTtm/3NdLDwEL59TNe0F6ZEotVbbXsi9gb4p4T5e0L7GtXBr+w2e2TYbr+o6cybSi9wha3Wt+jXu55oEpKqumu0o/+J1VLxLY5sQSHJV4xHkfpL2YksUV5nfSY5nA917cM5pte9x1k7gZFsCS1pm4P0a6TxDqfS7a+y7PoCJ5h8/prRZWqU2eLUCwEyw5uQ0jH7dDNeAc2042kCB5NIuW4u+WjSAo6euoHNQ36ImNnQgsSBmSmqtBBGXL6+scY6l4LZHIqm6Zc4I/731Sn7poCCf5SKFYK4I2L0ejikAEAZAChva5wVmECT6b04teB5pQXmfbjGgUFO+X8ONTtD/k+WC8jAQe42835x2H01eDg04YFQ+N5Og5ogc/QOT0RSl2c8xXZWp5w+at8OgZGLNqzxCgxYePoLdRRE3sgmo5+hEGf57u6ZgV4aduvtoA8JPcpR9RSDKDfrFwcJOnZ4fJUvuknmbynRWm9MmAh0dCaFEJgoG2bv33AYsi3QIz2+FOIFKEdlWD4Q+48j9t5cSqVxGVHesXsdXd8j9LABanWKVmyChxmjiMcvKgQvZxR10XjVX0wDnMCBwUzxSlJO0SCwgWtCrpEO1/amHNIwQI44LIADDRXjmDlK3KWMS/RS/hr+0ZcMnZ1FbYUaB9w8ZWO3rntmFsMdS/CmAELpJyV5kDWBwAo83CmDJHcXeaau8J2EHzI4vBEnGVnDpImHWPp/c4MZ3VqXCG65OANIo6xqHaiaiDdo2Ex/D355gHBLM3FCDWGFDYIpqDPjUNMn9T4JpT6i+C6WIz91W+BDIyIfu6k3Wq0LMM24VNaHp2zmyemPgSV12w37wgEsPTSXREFi73I5F55IJuyGa+t6V4ppjQCoM7mp00+YH6XZOZO4Rgo+UXyvTscNbgUq/xrM1rqHGyOJYmOYrwa4J2+XJIe40wOSJ4tzw0Azv8KoCe11aDUPU0MhGwmU5kN1p4K6MneoQuO513sN3WxtPeXzL0hAeXNzRc2p1JMSER+lG4w+qh9F+gtWFQ8SF3OkIMaHSCuBF4rsup3qtEWj1cWRQsEGPGd5/LKPjATAZrAAmJm0g5x/pkaT1HX3tVBeKzWveOiX+9E7CUYitoNsZWWYWk9bioCm4kpiogpXyCF28rh+aOoVMoh0iC5DvG+YJmuTve2P212xBaWZFtR8EfMRx8RbY4bWROnIai/h+ntBl1czARBB2eQC1xQ1svfHOaa1NLsqVe/1tpAsI6meYXwGjwXRdxRJ6J3J7baro0/nmOV90xjTOo5W6lcEGM5iD5/DAMBvixE2dkrQIGB/7LVBJq53YoN8fXL2rmES6GzSS3N4oedVTV4jk2CM6vCgyc6tpVbLtD0FEqbUzKd06tyZMSWEZE/dbV9iYdER5VZKviRzAotPvkaVL59rAIZ7cIpC8dOw7e0cKTzN7uXuxGgPTxrhTuJdm60RYIR88JBAZgd6ApdYvLwClVr6dpNrgLAPmzcqGI/1a2GYrnl+D+x74pvPBkFlIUpHgFQYlg7m0R7siaVkD7h7s1h0arYHrTUZgFPEQftoyHFeQZYhveGSbYmxr7ItBOmgRa9tLyrlrtiCf9uSRY81fIRh0Ly/J7G6g+slZ++nRVXnvtpxPCoycp+K2ZrtHHv5GICveuc5N3kAa5ds71sENtf47D0i2JP6Qr8ehV4Y+wNH1dPmA4dEU9Hq5B8KZNUEs35VR4smSAzOcOXyQCop9Xucwp0uSLbHyzu3WMm0dkIhifeHw71EHUA/H7gpxVZH0/z+sYwt5Mf0qKNP1NusxwnQmqB1ODgPjp0LZJu/8ETsKirP7gqF8QcI2HUPFDMh/vQpLc724oT6Bau8H9X90xo9qpDyBJoYcvA85ZWj3zm5A+oLezCrdwCkzIDaRvR0hoAdXXBmx/ZsHc5argdVzv2jCZhbM02IH2sE4FqqeifzzRf+dcXYG4FeWgq3s9WnIt7w3YjnRtbtuxQz6kdPQqjnW90/tQcocMxanpM9uPBumn0QnBVjydJq8HfWOeSqwSyogWNo8KSSPBSPiQUzoOEM3JCOlHz8IdBqpTNxIBNuUN/xtzdEO156AFN8UR5Kp6PlGONhH9oSBup2wGwITJb2e1k1XpvqOq/LVRj+3KqXoynxUK43xj3d6FLs3tTydIZjL3PRzlHtm/twMgH63lmtcrlHLaTc2YhC2i7tHABxBzu1McJqr9fB6iFQbDCh2saxKa8mCZGmjzAWzbxRevq+GbhDF/WtZz5CP+9kuFnIhTzmlvmM9iv48GKwhLbqbfQXb9Y7bEFlmVK0HtKx3kpse7s95wSLJAc4WRoarGRGB3oECb/adsRMCG6YqKx0CZcyuv9iDCAKubd0S73BC8t+GuejCCWmlSbMX2zmFUaGKStnSuXpJpUFwFq9WBXiP6hjCT1lBFY9SEf4NNgeZjurgdLUCeyCkiNCAOpdiocjkMSBJd8F3BbdTKDCHhY8spBYd3g0KekcztKgov9sGZ3AjVa8QqYsvYBcSZNG6gvBc2MPAgFjk6vnH/G1JKAa2Gx+QLRZVQ6NMWAPAzK6CqByZUkg3hupMuknHoS8bEgffzQOe4I9Z7GPIMyW3xKm1QRq1LnOy2k8zWyXAGldnwmGYx44WSvJ7yTl+/hTjfT99MoX3zgGd3Wi/MHhVN9arUB2nD83Vu8uONIn15YwtllPweh38jYxbvBJeUnYs0/tQeQE6C3C7rMl6t8WHuB1goaXnZU03Uiryc1DIP4G6CPdO0jj+5do9B4xtggXtuQPMZjPf0DLh6BDtpm4a8LrrBfUe7wzMyMAkhsxVbC+1OwK+CRlvNLKrSASgQDKFz76aGKNPdBc+IgrlphQnuNhn2LwUI+PGRezVTHG0wS46K6j3BieM8NTXdHp0C5bCnhQf5mNkReue7i81nmbqdrcQsdKrxa6jMDx5fBtgDq8a37efVosC+D5aGfKpFsjBHR1Gnala1sIrq5scxxsnTfkGbcS47LXhqNs5i+DrP4HXQZVXkbEt39qiJlfmfwR0FhiXjam9KV61IEwASm9HKlMleu4+V4eaqcwpDSPH+KFyo7qJ4cR7vGECQhlg/Cnjh47RosMVxdpXL38c9WGTyR9yfnkpuEbZ+g/PxfPQwJRqSvbyYmWxdLmTMvjKXlE4JjqiUoq92AscINPCqnkODZ6bu8HlYzSv2HIYGj6TNI311i2GK981zJW6jm/ek4JcStlmWxHbcT/MDNWKbLN5p4pgXZrdwgjiWCWU/V4Mrq23l4SvktwVFz1x4RhKf/rloqOX9ZoK58dyevpcaz+MSF9e6sH+1gC5V9G6GdBR9muVao1AwY7/I5UJ8/BX7uXcPpFxQmRbmyRsL9JOStrNn8Ds9arTGbGhDQwmvzehcJGlgHcSgy/ppRwiGxy5Q49aiFds7HAINNI7Mtu9ToCvIJzX0t8io0LKjAwrL7EafmAXAu8EjwA2TZoGPpzYgw4zhkqM74cxGEJ0IYVHwA4uYpej7RPzisvzk0DkhIt98YJo8PHt9bgjaz2mEaGJaxIWMXKGkkkyENRzIRVGwKcNqJ3R1LEK0oESMymWoKZ6vtu4LIMdfSSCAYYopEz0BOp6p+rdzd7uEigXYqGLg90zD5zeuxFAQCncVw+kSRmuKfQCdQX6IgyPqV001MMXqJ+0r/l5fvZZE6McFEyNz39Pjv0hBcg4tL5l9duDYC61KJ5SvwGfvIqWHbXViU0yptkPJOcBdGlJZHFvX5u3bC9xpw+rFMGDRfjLoHvMYIqHlf/62sTzWyUKkOM05qlcKNz3e5mKpEitWVpIwKNKlhgb48IDVPAmi6YevetAEICAWJbtRgY/hl+oQEnIx5w87R/VuqS+aKvGlb//2zvBXaC3L8hn2Q17u6hAPTYKCTyUCqsn/2GyTd7OHW8xNO0hoYVFJdcLb7mQLC44iYSdMQkJXlm2E8uUJFuvHdPQt25NbHEA1UUs+vGcoXJURosTRJkJypEOtldeD14NsqE76voVgGPtiMlJ7n9TmyiUJYz4FUxTseSos2C3NJi/Ew4Ey5awtWtEA+8Z3Y0qe6700c7ZvQGCaUGjSfQx3CTDroYXnGDRKMgHrHiSj7zjXI0SxpAw8t2uIaTHViGFv+zQlX/65PmF+xy33rN38R4ystuO4ynm86WTaPxnlE/94EfGW70LKad45A/A+kxek99n13Cu8NiQ+t0oZtYPw+1Zt4Ni1TxMvzKDsIQUvQD4vNLzktyAgwZGWYTd3YbpMXY5vj3movN6S1WM966DvbvO0h6F8FK/sx6PIIQdd4uiKA+YjdKeEROFcVei9yfjLLabJg+cr5LAbOYlH9/GgBQDDOpJPTCKZDGkT5W5uQpv5mzaM2E9tyJ6hrScE0hnyLftgT4yVebRqp9oZ+FPbVkptwYFK13Ogb+W0xeCmlsyExXgQ7L9a5+N29M/cCoa5/WZrDqO+lso9RZDqelY5N0/SO66vZC2gA01ZL93i6IUU6trEWjTSum65KWQzLYQOi7lGPO6GpEO3X+HaHbbnT/WSS3C1i37d73stE6B8y+7dBP0doOb+U2tvfrwdWt2XMo5PfBTW0SOzjfwvtvRYcxN4h16azUZMNljijTYL5icsSjNfD87y3gdfSIsWZgqNp/uW+oNEUI65UtmBfCPVXiX3OwXY148Pdh+AI2v5Uw0f0H5pmibbRpKFyC3f/mmmcAPCtk9U4YRrnZMzN4zLrCt3RHoR4T22BoSYNk0gw3MgR0QWFyA+G3trWLDeL2829dHmX947jwqHBt+AnPFC4NvpvnCenuePp5C4zBapQjIJkzQGkNNUHnUhB7a3MVUGyuYgHvPzfoJAR77P8e2Ye/8tXoH4rPvQmKKFZw/wcSlue+qeAXo0ktzlghLrqYOS7lOEin7u5CE2tfRn9ZgA5VwH/69JqBlS0TH+OPxx51tLE27n/xK0U7ohGKRsRV62gn5yAUrMAJCZKjGEygWqv0yFuXzHXDOFNVDRNWY3kduD6BjCtgf81qnwV5PmeMwBxg97Hw/hjxyckNh6kzaOD3IGzGrYz9wPXfF79879PoWziz2JQdTQ1bEc3GGDwziZcjt4nHoJUMjySTxMzIfO9MIrUvIhA+A/5POXsZyVni9eUJbY7gMn0fbkAXxs6jxTb0Su759rGYxsBGOG287LndzpfKn77Bjfayb3JHzC/vNcTZyH6MVtsr3BWZlCj4Ie1KhiQqeVESR/6NgUZoT0bdk0FguMlYRePr5xe/c1mZqtYG3rECLlfArqzjz+/p4LZOR2YZMCWpjmmHfAhyc9R01qzHeZ3QZXqWqVHu3gimYDSpvMq6Vo5FXlGJsoNWJZmYAiCW93AOVLUjZzedtpmqMNuaso0j1p6RynNu3JAv0JhWpBYuv1xpE2fHsG2qe8bhqSDU5qETGDbgpIxcsNviKGzWCHEezZvvgmBxd4mQ5wKhNnNBKVbeZSuXj/to5T9ZOF+u3Py9hI9Xe/TzXr78UYR06rrp1TySPWfbxY+qFQmP79JBeW73w5xwEpUZ6V/gsfDbigV/RPbDHsmWQH+YCqaHX2W8o0MrtyO2m9MXjXkGsYvRNEYIkZAHFwv86jmYHHOw+Ybw8kXwhPY7HAsw0jp/ZysAiLFwiE6/5cmtuMQISiSr9vIMzuIGMkWJRKe58zAYUjNfBhJ01PG2MSaOnV2gJenY/KJBnge/SOPNYxc2vJbtkSSvT4YqabQZBMw4r9LKEJO3XaYUePxo7pAj+4f/rtwWixWGjGuRaRRsJXrnfpdv5tuGZbb4mIua5Zk1H5Ntdyq30AltrLuW6exM11cvukZHPICFdeHxQ5OCZLawE2hmlPHadYp0eWRG4Wbh7HJbg0UlnzvP6UEjWP1oAimwnQcWlA5VH6bsKKe4daXAykJDSPbWlxElMMzfUfwJJtzHcmOSq2Cjcd3t8JYkTvlL2nT2PO48Rh1j6T16uKTi/xcqpcVkQv5zSIwfVlAEXy0psZMGZ10OCE3AFAzZp58cZh8MC06P/azxZh4JKb8eeSeIbxjxYDkCsG7wbqs6w+2FLOaviJEHzY2z8crLz4sytBi3G07DrFQB8miuEwdXoqyAPx0o14fLGFRlaF37cjRkjioWedwp3NIe7+e3v8KddQ7Enfdb6OfyBVGS9gDBkgNcXxmOC5bFUo7Vs/KzTxtJZsFg/lVp7HpLIAs1Y5nnIzrDbXgtQgkz1HH+ZdJYtlV1UFJ5ytsFX6YDDG1J7Aqh4WbxvPMYlUhtsLjppHx90DeJacKMQFdgOFndX4wl9WD77S+rOZGxPYmG9zeQElpBIQSA+AV65ITAYELGmj2x8PY+aIzuvNoG9/dsdWCZgmWJVxUBtavAzB9te7tUOL8ROTIgWe6vTccdc8VurlhTM4X0kQ8MXswadcX2JiVtCAxyt8DHOOOK3BgnHHJbjgrCj3epn+bgqbIjuNCe9QPgexJX8gKK9XJt9TqEFDF9Hk759zJw2U3Y5s2/WbqY1CM/tpIkqNsM19v0hYcxmgyoT8WZx19ghz7oKqC+x7WZGP8OP1YTpYz+3pyUD4Bf6eJF3Dh60EI5WpIzMpK010YV34lscxKJ+n5m7Qr0T8kT4PcWELOPV7hQkAzs2KUubGFZxD68BMOsvYpVWzt61Fkr/n+LgqQN7JNoR2J5c63r8PTvVwktxzk50L2gSl9K23IVZI6MRQJZYspryrKmLW+5kTi7PCOn/0uQPtmAePzpTJ8DmYm8Kzd+rnP7lVba95TNvt7bx30zUbcPvstVVFb17bf8RZ3pvzwX1NExWovfiTq1pduJbNo6BlQ4ARLE2712O3689b+p6DKyDtvv8ruvhhZCdjORb2N0XME5zazJFJnXqabNIr6Q15GTf09t7MIheTOfkOHAM1vN34lDkZBh6Z6Z9De+0Xxsq3hC1gJAYwpRafO4BhLom1KpK9C9Z+7qImRt5o0QEmVfVGXgbEuaz/dME3XHdq1MBdW9cn5kWcQIpvSLFru3fJUylfgskckqR3iIkjsofrDPLTuFrXAgb+jMjN4qUkiIv0sbt86MHFkJ4riVcIhcjiMJfNvalZng5ILiNM2Zc5J10BS3RAoN8P5XRrVx1wykVsTCHsuy96D9BCeXqocG4rv0cqd0dA5a2OUQso2jWRuGiiMnwHhQ1vD5Skl/kcDSFIdDlCObPopo8sePQK/K10dkPOsa8yYmEfv3InWmMgvxwG0IsBo5X6VDp2xpmArI9NyzWGHDl624IBY1XvLlBKXXoY3dzj8o2bUhXWBS42xnXb4mgH3MWyEsal7RDtTHyjhVkSSvUSPY+R3Cp8gidEqc2H6+m7Bzq9b+3qeNzaY1uhdAhFzl6y5u6j+Ft49mKhLd1AM9R6UWYJhfmXA9udN2h0axpUxew+hccjmwcrfhsCeRlWLn+SzzFZAhHl9G7OJ/Lz5gHeXCQiSSUK4y5VjYPSM7aM6KYIUB2lTVWAdXByjNA7HKCDKrYX7IP5ZurygQS/7nR0YToiyYJ9cAJML7j2GiUUdzywTeUwyB99hYYfDfxIFKdeCynxsxsrz6NnmaqkwJIbQXfQ6B3CbsVO/EWDBS/7ogX04L/visbgkpcv1+Lj4WRjKyB+tUhELzkNjBIx5V9x5/SfoY8vH1cVofN9uwOxU/YwWq9S9GCmUDgKWi9WNAv9W4+2oQMmWviBp25dNnqy8y/MU/2Epj40vAvMXTAX5iw9//W8PJqbmOwzbywCl1463cnXXw1Hu6/Kj/Z5G6xcvn3FmxCg8mSWezj+zMtpUC4fiqQgQ0YLm4EjU7ZOy5xerq0VyYPX1jbm1XFRoiRzOvmsUXmq39wAPtPXldTbpdJ1acKVH97Sm6vJ0n1LQeeAvuC+EheCi/VqT3cx6LItjL5S75lXZLYal+vnh9LChnjja3kdZV+Z5MCI4PBWgYeVAGA7AcPPw+3XUb72SN6NuXNiiKoWmzn/iKt6X/ZhzcD7yxAduWmSfwPxSZDhdfN4AO1cjwXgKZw0KAcUioZCM4h1SO6GRDIJGlMsq/MLUKZLxcN2+GbT9kROf8kTOx5MrjyKedw2+SPezPhbLHdxSyajABTmXQIAoQSE4cNJvymZAKxfz/zOy0aD2+vl6vZgl0KfGNImi1uJxcxZrdGmGphyzW0noDPdt96a9dJ16d2KGgAuOqB31WAem5WzwcWVRPcdm4dWN4681PIxqzz5HVjz+MDBfhrtTWHdRRy/3H74nZ3NpluBqEgDaD7PPyDxYrM27GrgwUvsZiuwgl1zWhoDCJX+cfoLqcWpntjXhkvfQnPCR6QP5HNwKAMEzOi7RHBFBEHn1nawoeSOkKR7AtafvNEs/ntD3UmDsb0fDHIjkHlnq/fS5Vj0WLdgkBSUN2pDtNZhD3sedRTeP02BI9ZCbhNpqPaXbcPqqAiUMfEyIYLgemLvTLWu9fDtOdC4qI6MC2S2loluQIoLAbP27peUWpQPvlrre1t6+JXQtt0Tl//5zZPm9IM2lSZ6k8seWK3S4TZXQA/JNuvx271TAdhMF3EBYfykqj8j0JfGeHmzOi0z03z/lor95p/uhbq+8PF9N1qmEivKU9DJYqW0ynJVKhIUoFB4BwSrGSeB8uobXBF4UbXwnF+9LhCn8HOUpFnwP4vJTXcSSDZeMu9pBNEBEl2NCJrw7B3FLjMelIp8LLk1i+4a2XkGEW+2VYwV3LsYmiux9wHwqSa5ybQOg2taPQR8MFjw63wWA3htIZ9ruPR10TfuAgLDp/PQyVjvJOCP/WzTKh3da8XCfy+TqezE7W4GVEBp+YhKuw2a81EhJzdO1RpbRbYwcC/cJGyf/1Ur1SUrUx4tQhGMtkck2+RAVT3WpVfe5tT8yfdf3NYTVD6Ve5xFde7j6Drm/yi2UsSmS8KVhyWbYYImH4tHhZBj/rDDpUqow9WLxl/HUw3yviDEhcmppkvLxWvQDu9yuJYu04C2TYTJT1O5yYnTttm1tra83H+ZyID5cDUVjlmrQ8dJYKD40LI6qd7CEgUrxRoZ5wg10j82GvqOxClUTWTXoHssLUWav0SAcZcZfDnyXWr1J4kSD55sgYxX291vNKcq0b8f1HwWHoqVxn2qGTS0qNeVK/368QgJo5AYOfxhRY6PHX4cc8EuvZDRUABUtVcb5TUo/bhOcjERaECiRg7xdmpS9LTz684mXHpwRb/chHJt7C4Nw/stqIeWiVT3HV1vTs4lHTGlX2a62f+PQJqZcd1OKcfkuTJm78vRxIdvgE+17I+wBzGh7FiM5ksVeXUWxBGoZ10AIIWt6zlU1OJrzSPPBWWoIojyrdIwdEXKFC9HqvyvRzPbvJTxJN+7QKre3P/dolhl8EuhY3LDMXS89WfT72ZJsb359l2QCjDpD5NoJA6auaR1VK1gNKiVY2BV0s2RdoMwkJv6jDzONRSAhI1//wB2dWc1NZkNtJbu9fkq3WyeCPyYihAxK6GlEEaZddQcL1nSc/0f+9FVvxMUhAGyhrUkb41cuOpv/lTMnMA0oegRiPPIXusWKq9Xd/ZJ55dY4mrhJmHnx5vX0+amGvl1ZPELvU2oeKgBW3HqEsOYhRSRCYkXg2ixJ60JC/RPZuNCUP/zp2lC4kpOoZsuHOBe22AG1FECIYSmDn+r1oCdynNS4EhdKXSIy9vxH9or+st2kcOZIg5MSVQayVY+VovzKN0MKMHVfbV+FNlsC1fa3ZhldUOnMpf0yiqoqZEYz1twTd+wqOsicp+AZBHx++Wv3Yga4AZ6AVgc/sEEXftV7NBbBB7M5F+Y7/YnTYN7l+2h2r218G0uw6b9HfJqdZ5wQT197ODA534t8jwTor/u2MpVwpVoqrZWyNl+a2m8epLUVM7x5WOAl5iglbFo0mrO6N3acMGUYpJQeQfaCVBH9Lef6FIT3dSbEwIcttMs6CwWdA5JKzDmKKj1LoNwKyisLIrw14wElpsDvLKcsTEf2oMjD9Seehs/tjwcK2mIF16YirF3KDCJr/E8KW7qwtrwyGaRE0HCsbHpIzc0xeY2c1XUkynqaB5VOSmbaR6/8cxrfxJFfKZQN7OUeMiJkct5Pe9QsgXjFRseQuYEZj0ckV1XkwGmSCipl1jFv4iWKMzeJ84El5ZGxceVANdYBcq5aWOb+nRbqEVkqLOKmi0b0O87m28wW6e3QvwUxQqXZ7I+cYOgGK4dIBbEP78d/fSLZTcTW9zeS94mnM/+rw8Y5iOnTW8SkXN3vgA46b2h3bI91cFcRF5xSOVy1vUG6QlRS70it9j64sOINcJU/HHkAUcw4nVCuwYrW8qF81ySHcb87J2E5h5N/tjC5p5DgJvChUWlMgQb2FO815tLBFlpBMJW1VX99xcabSQp+2NUBj/8n2a+FyHa7Qj2WFImynZICjMBMTyuglbvb927fodJ153dlhIHGnJtYDOU3MwN7YAIwSEyEGbO+Z264IfK8XhNn2G4h0Xf4n55Fv7ulAEG6ut2xaFK4uyX9sJeWeejMhcICmWsosUy4b1brDTXl0kTpaGWGaXwTMsNBYQSZp36ABmp3Dx3AXOYO//j0nyEHSKa0v5UN4r559lvheAa5+hjqABEZJ1ORNtLgmFcLa/4/lLajmKdOQAsI7p3483axTUV11gSAhN5n0+plIvf63ZlpH5EJ3W9cxsCsOngZiRXIqEAciZP9Oq7a2gMq21Fxvhs85QMByTtiqxwFHjcrqPaX4LCSKqvBBMpkXJiXeH0F9X+cTNV87I0xFJmgXUU95eYy8DnRI6JyWHzHYk48bwz1On3RKkMj76/WnEOFsC5rBRKQCzQOCfdWC9tYVC9F/hYfKTV1IdaFzKFqlj0gAi/p0rnGKwadW0FRTDAwyIPeBN2tx4rHSXfYhx9HwfNBoyuLtCZwyENwyFAGBYC6sDZQqIxczxvRcYlLwADYKyAmr8L/TWa6eUzkWj/Zo9m6VoRjk1r8qC3+8clp/PCNROBDXRs3dpJLQGjHVzK2EpXEVckgBoh6FsG+vc8WBeMuSM3KqPV9aPw8Q8UY9ySPy+L84qJev2Ro8DlcOJ50waayxzIsSV687tl7O8MfyOCJEwZfz8prjpnW+DDqIk1uc72G/tiq60s41zPXJxsF9oVHXW1mWPmHrzZny4vcTGlhjVlC4cQ0glFovoalADgsDvcM8J33MA6nmrSPHe+Iu+bRIGH+uGnnLF0+zIr9M49C77aQWuHl/ZaHww1Wj0Ww6gxAm25pAoiQ1yXjvhPDclvP+GVk3GmyUA7H7K/Y+GfpiAEWUZn48aIbxWyTrcTbTufncuc2i0LuVRvPPcKjoGHpjQcSEPOHK1OSqxDn69hTzT+jfyrxjcP0JIreBHnUpMDJYFwwD+uB94fAjwwvmmStAkfezB+RmqIUR7s6pbKPjfP4L/jQVxray+4ijVrq9sd2pBYExkCTWykqeiyLhZpBdpOtjeMQ3RvrrmBQ5sNehsdkrQwBBK9PVajxbC+sZSLkZtyVvmkDItw2rgA5/6urYXFVKt45U4Kpjg+WqmnmDf1i0ufs2iENTphScLBfWRhboYs/mpn0+SfCa/GvWMHrGxAVK/Ry/E063x/aJwr2fRhFC2XKpyYmTT1ln7YA73x0NEpi4ZvoLl5KdwWXZjvsmSbewPVC/XgMH3aA5K0wRLfa7gdQzG8phQ2k9CypsAO3X09a/3K4i8Sj9teku0HqcT0Hiw4SKChHxcve3eH+6KXc6E3khZaGOJajsG81xA7KlSHEgYLjWbfnZXKmJEiXL8myaRW08dczjaFGan1/qZBHv+4iR0ay9exsJNKXxz6yLC1S8dNCgoUXiDidh6kD7R7GqCmMvRVcvR+0CS6I4tgjmANxBUs/tmu1Ushf1bqhKp/3/XYOeXSxXpF7Y9AYM1XN5Ql6j1JADTstb2LuEBnHE3M3fQB/F0rtxfh27lw6LdBRBE1PAGYGNZ2aa+ypnV3XjlATG71AoGqYBeGxX1XYAiOMOuPPF0K7IMQ0PILHzW+9YO7hiC2ka6zZSxuLbnGJVEzSLmg/xMHVWPzwKCO4WRPCW66Fu9EJ4pMRxDh2tez/v8L1QhljyJoDc04pc9wYDOWRD+P+nvhSKcjpWqhfQanczpiAVGcGC4RiYqoU6QArb5eX4ms/+1oiHFT7a7EuQy3MrGq62WJmZJCXzNLr4zGJNycnVi/vFQrDQU9g9V01Hla/88cSwSObvlT27lh5rm1HgqIRUZHlYq2XhKKyTh4cOD5Hd41X5YmfaaqyOeeAZRtF5pu04Ii3A5WHg1m5usxpWEpZIXOqZ9/zLpB0h7+US/notWNXv0+cv1XINgPNxQVEWCyQXf84GsQ1cDpVCFigReisRtMQ6S2UrzBsF4427t2UEnST2CKALDIrFJzTEv/YPCKXdGWHPytvMJqkFghya10GnuJjNUMtoUIt4DD9JuK+HdYhZ5I7l3UzTlKqdolDej4swPruxt6/ePr6gxWcaeA8EzwftTGVtHH5XYIUMpnJah6CUK/DawjS5YQMAO+WM9WSJDMeIRYkCxjxbNqDORYlY40nbaaZomlSLKbR4u64964R3Q7SfGQ7FcaSEJqF9R3zhGRRYwxU4AAuXEJx/P42NZPFzMQJpb/OH5Fv9U76j3Q71X6Enn+KqZIcGfR1jnBMUw/kIlY4FIbAVRjnKgz4IlTXEYjHlINuMVkPSV73Y0onFISXW7U/jLLbBDPsww30OlKmd4TNk7FZ235t7VjqBoF86IusSCoyxf4KA3fr0WZhjArm3SG1HXXHp3L66G9ZYayi29D1MTrCJpeAMO0Ygqms5ah40CYnpzdDptPgT4ZJs2OZDsDnCD8L2fRtd0EE7xzhdFHNK1iLhJFSMid2+p/7YxPRjwlAm5ufG0zbq7aUEoHq4Yx4+HyOOkG8MOq3pUH5uhLKvqXyq9oGGr8Z4KNJwi/3DAqGvv+nlQ6VvWQYxKk4TJHFuK+i5DLmy7EnLoA5fSsP5mXNIrdE5i1tl8lgdd+ImnCF1SFXbc+22aZCciI+YjJXdG3eC7i2LFgR2cPvFrt4mHybwa8pjO0wcDb4kr8hBCTo120VQx9W9HFRnNooHvAy58IDJgYW2Q4xVSrMxSc9BECIsnoZPFTzbcQZqtudJTaD6rNyrfksnRfR4GO3puh7IlIlzEy90oVd8LewFJMEB5rVRgVLEGl2H33nwwNIqSE+a1gVPoy8G+II0VrwUIzfN+f0wHkSOqFZO7GJJVT5tSd4gvyfVnwtN7oREoGkJEX4NFSBR2lzeuhHLmIwSXi/F6+I95kLXKQFRP+sWPyYshb33bZvhraXGkmyQ3mkwYUOUPSn/x8UhYMSrI7mAnc0+5Kg3WzE3Mh/fQTslwvilbx5KPM3C5yIu5iMFWWqCtAw/EKxI5gTtv+fht0eGbdxReXBMyhWTWe1YJs/pw4SjMYDAkkTTnN10DprLQdVQrSwqqotaG8vgw9wmo3Ebu4rHMGiNOF3pF3M308cVWPrkYfCd0zoMqdTBZL17CXpv274i6ZRB12ncqzSflLAfth3Ph/0+W6vNJhLRipilH9Q1bN0MmN06AA1BVmP1sIJgmiyKpekVAH7LnZVbHkuWLkedLQWUz5irasWOjrU82griy5PPtjwjOA056RvQLjOS3s8P4LFH6sgqleeC7XnEtYBCRgeEmDVVjrhXfmCJ51qbAaHg8ctWiT55P5tItQzjyQ402/0u0fiKuWjE2SIixlIUm8kfAkjE9ZmL4FxajhPrRPjcpSD+EWFyXE6cqNmt1EcJumHIWczPkH+4iUeyVKCqOSi41YBWGZ+K2/ZTmc4tt8o9KT1mhAI543+bGwAAqkLZtoliKTLhOBWQvAkm4MI5JEmEYytgy4cn/qdpQIu+6SJoNqLt4jx3DWeo4Gz6+tOUNjltEguDFkV+uPQkAWpDvB23vydmYpx4d8hHdzCVpzxvTQk0R4+NrW9Vx0/a6/WuKYpyBvh357z+jg6lCM7kHyJfsstLRA2EIuAm2P6jZJQpSmESMQW040gfpN7RzMPVwKhK616+B5y0P+nvBG3qcUiSjH8W/WaFYnoxDdS8W7zEAcDZ4//2f5JsooR4MmBeWhEwqYKmmYkdaj54I90tZj9M5Bsc6rLPV/cJNbdUVlK4Kx3H6WeaO9GoprHzbcwQuA7OuQgLoU0z/KvoafdTYRMvza4c8Dy5/tDFz0jxRm5iFTFb7HUIlobW0jLxtqpyGXxMdinKvlNmWqRQnkNbA7zr1JAU7LoeOrFdenE0V+seVq8JgcVeH1+ZvfvNToONjdJJ9tMHNn3dzB6uesglbXHHK7Tj+uEneIOncYugm8BdDSeYv0OE4ULHpAR4GH52h84axg0fLx1NZnReyopZnfRXYI9MYdRewXnyr4S+CTM/i+XAVEwiLvAljFOISu0rxWtVjTBZH94dHDLyh2rXTWUwZHuXHFmNlVFilrz2a6NzqRy1wXCm2BesU+pcLw7sJdJTkIEzYvvf5Bqand4AJeCki9k4nKk8hdgHm7yH7zkpJCwbMHkm3jzsDZwOaxsRns3ijspj25TnuNKQPNd5/1d6kWx3HPnZZ1mmBkdSoRVE8tsqVS1/RF9yXjUggAQH8BQ464tWqGqlHkQd3Wfrj9sUQSWCULm4lwIlde28Wa8Iq+KgET3sAXEF84zNuJD9mJ8RGuZ2aD+uCnkGBM4a7b7w4iR12b1ebmtGHLNoLlNQoXgHf819nX/nzJPMRpE3/2q7PeHGt2V9e1WokmSrtQBwkweFJrKb5WvTbGwrmUsoreCa6ArkFv/ZY3/Y9UWthlArgj0DFnNzjI6wYrZ7WRNsFX/7TdM32rkHLAk3z5yx5ryLyStX6LTYBCbQDRFDqiepwESlNPb5Iwkob05A84aEJVTRKsga/qYYUIxwXpmdqZ25i8KiwMZpzghFLDjDhAoDOneIqQdxLaUOiKq43jRdH1tfCVZjaF0FmD9MImLOZc9lU8v6Ti0oEkzATqkGB6hncFMCmsAfQFg3h4ZNyZfn3b2SMmfkB9V0fl83NUXXzKBInblxiOzxX9pGG6Xpj7gbDEG2ijbDWtN47GO7gabqRgvjeusH4++g4uJA1HrofnB1oJCUYlaUnt6NkXzy+doylOusGaQDnjGq20vdlVSMzvhHrL3bfrLe1HG6y1rsNVnv67wA92vCnGVj4ZhcZPZxS+riGLDJ2R8MP5nEqXrQn7XzSJdt7kq5+Mch/WzxAidp9nfqt0TtxR0VBcb2V8l+Nx7rsGwk3cMFlB7DT72IuOveOzWm6J+maOUQYDMQQc6DpUQoE1Wf2h1k9Q6LvxK0ifSa/oJ7WTArcHKRZpJHtsOf5c7gftixOFwLY6V9kJWpoFBmi6KiD2pnQQF8ZqoMw9ge0cMvDd63rKhILqjJKgktXklUg10TY2SZwYWUsq2EKfwHHhEJ4WnzrYLZ4tfLIKPRfKU7hqQzi17WBJ3qt45bd7FUIXTH8N+hWf1lPTEQo5DgOBqd9n9csF5SFJpJ7iLsLGySe7fq/BDlrtSn3/9TG4kPzV9ldlWbTFQumIWxuTZ5HPiHH+e8M/XnmX/E6DcjFBu3gwA1+X8vkY9yDSgb8T0nWgStoFZp0AYUXD9G98xBxzstc+mUS3wLmZd4lbM/i5nbfla+np1dbExZkWchk3tqYGcjFAeF/FKvA/NelFJN9dFFUPan12pgtSyGbiOVKJbp3605ErJiM9n8KCsRna6t88AtLZI5zKgEXK1aVwSj/m7UaPr+pwMlynyMSs2ELyM+IyPGOM86XizMAhhBrNR5I6oeiuXrDsZXTXkwBLz0jYF2MiA5tQw1v39DZCSfuquZzLjwbLgYvKXQG/lCksVHJbn4LArFKcflp6AcU6xVj6F4/EKBzSH22G91BNQtnO/FHrGi2C+5YwbLQld2BR/wJZFGI79oKKd7QvM4uh2dsbhPiSHpO9tW8DnNvD/UYeTkXnnPgjyKcw+f//M5Syi9MKRL4j/q7MGqdVQ+qZhEZUVMHMJPxWSwMDnbnVwiLFTzcae3+Xz9WtFI/fqC1gFb0JjT/of/XQVQRZdq7jcqUJAeOPkaJcQOwuuVN6uC+rDfYr8p8/9EB0GwiGjVPwgZX245FXu0W/CPx3FIcwGiDbdv4uz7P4HPXFbEjAvoveGJ7Q6ee2dxd5bIczXOlXzayxQ9PhIVbrpieO9ECUFuDXKalJWQP0VAM4h+LSDRH7TJPW0PNnNOJM9Rz024DNlUFtY4uaY1W0lsmC7RkMCB83cSxcgR16HFOdIKgx169WsD1pZTCGkB0BTWoJUXe9RFTyz1LLwKIo8mGN6WihRErhDqpyK8Z1ixleE9xtUvS2wiwLTSlAmUp17X1edxRl/vSPKdxd+Szky8Ho+7YpJwgxTQuwA4WiWg77BbBb3kBGFgKxEmtOzM1jX5gpPKYZKDm/v4zsu7tfVbAGvdPoCdgDqTMdKuvOCljW78HZfp5ruat9+6mRyafpdOep3cwmMjd7yb0vPOB3AZeF6g8wrhpx6Zy5cy6aBFlP4zgFkFcey9iefoeQZ6aiVqFWsFnVs7AbEXHlJcXEeUhxalGVccs30G+QnVhs9rbmK/yT3Yrb8WJEqOUfF7U+XnHj3n8T5/F9rhGsYqCSzrC0SMrpvJAUu8bac/+4aeRWNyDWeeZb+c0aXxDGwszCl3krNtd/LAroIpNXZJnruupBWS8a4vhdrJnvhqpl3H5kKc936XTO3On8RZJlQZSi7JoLrmjfgs6rklCZAzf2TWIWtWOJcO0JjUtbhHr1zJ9/kZcIr5gViccLyfJk2C4TiuspuOHzVAKku1ZxnJWnmPrq3/AOmZ86fljd+TUCPdzCM7ts20O6HejxLRwzehwPWzXj0DkC34/ruY3Um6BTYVD3R+CEsFnYS7emx1wukXeFQvfqNt6063orbaNCaMC6zfczF4IQqtiu5RNy3/IfCn1N/NQ6/FXunedaUragXK6oSHRNCO5l85kw8ekGDk3253D6PI2wOKapCfwS32fYT96810rOJUBnmKWxZ/XDSQPpFl1dfF5ZjhCbN9MB/jMDCYYdBbPnEmxBLM/6yM71wdchPMynS3xYswVGpvCtOHqf38lEmH6PQs50rtiFQMeaHLVxsM9qkj2brs1zEv4VktZo9jO/HlTEqNpfzptlo6Oq04/P8cMxquKotbp2TKkMtSJbRzzTz8zMP7lBmQ8fASZYRCb5YjHtl0fIgIDVbBBTGLneEkjFkZRHMXAfg3BRyNStqPSm52DeaQGOwh1z4TF0XM7zOHBK7wVJPovod6LX7kHYz5jHk3qtsYkV2t5RPydnNY9e3+z5MdF0QMuNpYfmSIkgrWD84wAKY4y8+jsawEUfFpjmjOQb9t9fBOolu5mD4niu1w3d8Dep6wwl/7WXriXaZZGcka0iFdJEefQGSZt4pZ5REsMVgVrp7P4bAD0+QyAPMa0YjGvREQFjhnK/WOB/noxb23/pIzhbgZjS5S4HbGdpFQM+sICEyUAOFEdv6ttRTITOmM3tt2cEFjlWHoCvPjHrwrW7DUiRvxvUIaXzH7qvbH1ZBDoqy++W/G+77CQ5NJOsWQLM55cjcbEuZGa4y9IiNm/pnE2DG+HC60gTuRkApQzUA2BNhiArSqLy5KwcNZowBNgfMUDJVvsUs14qbUKhE6jY/xPNZpGNStSzAGkxBYb5yq3nYSI9O/qIj7WhaMBKAYBvxN2KwAgYqIeXkeg0TRRu3LwQUF9yFTRgtEC4eVvHKeslYMKburVEcdcko0TjY7WmI6gnjAQ2/9eaZPnRC2ZIit6IyQNsBJzIvBg/LZ7NOH00Nv/kx41w/IggijTLCDQWC9OiwikTSWR3QhG5wSpm2E7JFqnHL+cCgpHUtgkInv5rgpZpZPKbBFHjxSeduYe7pbfkk/rIGKL0bqFgyQvLtqincmHkyua/0eeSKcNbDRUuPq2A9XAHtJlcYttJDKAF7xtTnneOwsb73wtREpF5UASkHdJF/WoWR0OL1E/AXOgO+61aPjAgCilQIK6YPZ8Ocarz9gZF1r3P8IIviF/CLLLX/aH5Nnu97xg+09bSZKgD+HF9GzEwG1XvzvcKW/Go6hDgPTP2aCA+Rw9enqPV6IKhJC6dU0WOgBcLNiaJ8S7vAxTw4KT7gU4TD72gKQyG8KjMhdFCYAEV90KgULcrFmTmN8OdIusfWXazU6SF5B4z3BZ/lrNheM83egxHdifcktk+WshOG5IsU+xgMo2xSASHd/q4FIrzSAO7qm8/AhXYeRYBCNDPk6ekkvtygu/hnFiCq0Fr+jPJPHg7J2nww44rfm1eQMxUka183lrdhOOpYwf3AOJIvHyF/PbPu8ZIom26wo+ukni9rCz/Ch2OpGqGNDG2W6EobSIKwic1prYeBycaLPK+AtgY366A2cfsl0hoqg4ePI7yw++bV1546VPVsXOplLfRnyGvRhjkr84wa5k09g4J6/60N9U5axC75TJmdPzhoiiBcrNrrBJenehk4Ek0D78oDG5q4tE9iIVXRgZRwwiLwzhDJ/vrcWzitK2Y3D5UOqN3i+6fd3lyXEToKjboGeo5cv/uEtV9wBGQzkjphBnJPvHwM2E7WSw5bxIiWKJfJZuvNAJR6nLKbeYJmBcnGHtJCwPZ6xbk1byoRZG1tBuJWB/Xbkp7ixx5iUa7kEzOvhHs8a5YWZawYWzgYyqd3Ur2xfEr4Z+n1qI1geDt6+XMEY/jOOPcJaqf6DX4zCcu2p/smR43tPa4CEfZVb6Oxg5q3c4iigxp5f95JKf3se/PKhiKnVS946Zg+wkqn8Dh0fRFgpp75bVuB+5UdUba9OJ+d6h4DgP8AilseWnqemL0maLBUCDEpiKctoJXkZtuO5MsJNSKxLsykanpUJPN0xiGbugkoyN4mEiJma/BJTkmkiXSm00DEylNn7urXQOCYkiHPsEJK/8MLiOFRSivI40x/BmIMZXRjcVmgC/NcFiI1Y5xArjc5BbAwQhk+GH4dt+yaVP664J13alQZQRATPYgzzkylYW/wZKzwFpMcB6mijjzkjZ/ZpeSSZRE7OdINMGAV+z3cm/Ak+BF7jCOCtSUQi/VrgV44kQGrzDVvTBeF2C6iy6qlvpjuDiUstQ8VvBvw2Tf8olzJ/Ij8+5eCs+ThjEaxEoRgFa468eXkcb7HtIebEtyuW+DEIAkDBrkuYXXVjftzCwiRvRuNoBmHZ1OFYAdp3KGi5JFvohe9KAY+1u5Ac4efcZgpjqCSyLqDl5+4WGhcFsIM41P93U2XGN4LmtVXuzxXzUKgQjt2TGTfovnzPC6SiuQVSHUexdQL1QnNMp7QtCkoszAXaswGPaWthcW34PL+xD3B3hzXDsBZSyHdiNrinrQ4aNpX+xLl5X5ET3L+P1vA0AdqNZ7/W4tve6KEGtwSlRkvg4dYRYU6oweSad9zu71t0t8CV9L0NE9nss0Pf3CEr6RAYUdI48dXM9VSMtmsKyF9ZT9+NtPtJuyhvrltG/qgV4iLOyi9+TqomKMMHThwcHn1hLtmE9LiR1c2OnAuO3U5lGiQ7hoLe1mycwOqsvLF3sf7kr7m5wcyQtQ0FwFieRZ8wjd8gXscpztngLuRczNZapCyEkBDVc920lGT9hu1PgKRHlHJasqJlQ9mikcHSLPJtpgVfIK3ZQGPAbk9xzRpuvOcSkFlWHI/ZK9EjLNU25oiKPchZSEiDBDk43X3ZmP4cwptmsp8MO2C3CI79xrlxejgM13oCC3mYtTWgHUbQvf7QcQbGmPD4OynQOy6nrGYkhK5gsWt3QEaCe3pt+iGfP90LZUSB0JK8kmk2DxYBXw/gyAm3scixiFZ/lPvrsJR2X1dU/EUKP4QDpV2cdi1sWY66qdu3wbPuFHr/L4Q/oRU6GngSK1MagY2WyB1R+O/x8Hb83qcXKbljZnVK9GcGLXVR+QWovlBDSl37z8Ae+upfrGpJAXhGdf+2e76Olukg/Nq3Y0/yXBn/JqJPWjfblhI4rKQBTHBpwBgW8zknsOOGg7bIGARZLLVMMmBUQEk9dHBcBQRka8lHVHrhoZJD+D5HTcCF643XADhcLkMjyG6lo/NmsPyO6QCBJe7GXTr9/6PcT7SlHrAH8uZmwTdRYkiD0QsoHotDWuNNwUQKamww818uKl/GJryuIN+pXm6gwNgpl67usuGQQX8+yZnzMgmJT9OVV0uVN4j/gkoxr01CbYiFZ8/lid3yZpqW09MxFFHzRHKyofAMOkTXX7vInHqVuHPSOAxb6ekNkudl8NN7Fefr5qCGT+uFEPT/S0SdmV12ceIi9PZpTfS6GPL1NiPsduCAniCsmlegddMeY3djOjKNeg4cm6j/YpRBqflyBtgPJkX4T7e7G8SYSORq5xjee0Nibq0eIoinhlQDooopA6ODIq1QgQ6GKUuFj/X0huPkMsfdvHCTCtWraW1zPUOeDmhg7ztrNzMUMCpg/XlBdMPZbFlGzv2WjiE4ZpIbavg1eMIa979ZMvRNxA48G+oFUIZErSEi0oYRlGFyYO/QJUB0ukhmzfPjZOuOteuFuEKng3DejMv35BOZ8eAR2OF9iQGE16gIHu9WjVwg1hJPpef0iVRS61Wp7rl0lsGGYggbfb+cca8m7I/RFZBqnybapUp/F9ZsSZ3Pb/9qYMgEu19JStsPhGz1gbVyL2muTs6TyO5QkeqHt1eqyGq/oby9FXUrO9RXXAw9zxtgVoMnXKdvjpF/wfJyvPxAKeW7p0x6tQfyb7n9LLdrqPUyYyJjVb3xvQ7ps5hQtgCs9aS3sMpDg2bAXrp6lROL8u4nReEXWb55vly4cryfwZQd7wr5jb7WV+emcSK/t5X23F8DbVzDMMVOClKS316BmYSmzyO88RSpsGoLznPLY49HH8OYbbvX/5icbG2frDZyXKepvPVWL8sG6qZyoggu8LdZP4e87o+uX/KZB2u2LCirOL90OuCsKInC1pvjn9b+1aQ5mOdqfxyClqBRjOd8edkgr0Yopb56uQHq16oCltw4KIj82HHMMTBvLKfYGLD5GyC3rCH0lmKADOQMajjyrlq6XY4wgBaf1O77CkG1M8ClSA7wCA0+f6TjGYoOFpUSOFo9H4b0ulrIKWhJ5/HpGmWmn8DmLS1X+dSkEo379YmjaUlPrlY6ZBEMEJB4gM7/T4OGRIx/f1oPwNvyq+LU90Afu7XeiSjZP4uH4ew3OLTfpmkps+KF/qVXY3x9WJPA5byv7BU1H4h9mMN9i0hrUzrsjzAGA0uyg/IyrTNbL53IXQQ+V7vXnXqbCpowvG01fTyBJWfrBCHVx0Ypdide0xW3E9IHZ2gEmvjLovwWXSudDyFS+yGGahUWJK8nHLJzJx43vNsrixHTIhxiIOW79ThC2MX5Yjjd54E+9c+kuIlemEQeO0OeWf4xGc1XMZf3lHlODKmmWqWETcSfojvZ7eMKvB1gd1mTkodIO2ycCQPkrhiz9Dertw+7fk9mh/MVdaFVjiYc0zRPWl1YF3FxEhBNWiVz5QPFMmCDLGmrjl55k1xCUDsiLBiSGW2jS9cQz01DNT5MFi20I4Mhil3sC+NhNIPBTEV3urOcBoH0uTtKqRBnO6+BfvxLSHkaZ6g2x1S2AwGzNULa00VEJeIspvB0FFON1QlVFcqXt2xSvuIJvH8PtUQZ/SVSNvs+hT0r0VC/TQS/QpA9t5hdd20FZAyw7pPf13N/AvYpGybVeMtoOvy7wd9xHqmJf8swndgdrXRZ/y2qgr3kSwtSpbdapJWSho6cmSyCLQIeyBTsDF2rgC0egJZT7ad8TvdbS253faoWzV+hXT3iwoV2j+4dnPlBQzyRHgFpTnZpZ1E5GXzDACKr6OfvO7t0/cJfNa+0xUKfqlEHwTpQ2iyTdeyXBp9rYRsPB9CBzg86CHVJvzO0oo7pQ7RoXLdfHJfDmANQxCbeehU6sity1GzWM9AAyBJhaLMzBCvJvJ6QNjRZyEzPcxDblvTfmHJKu1Gtj+Uy+C3Faz6IoOk5RV8PsLIAWbR4JwW1QrHRUL9+DPRl685nyuCL1lHaAALMOxRoZjUt8JAhDzjNCJC10RPi/ajRBuaKhaTeLZD0F3mn6zbLVDj6eQMFvbFkXODtvinQmJlVwNHKMxUz3CCqP11ogPJij5PQtoTjQIvXWvsBt32DRtH7Tyziwt8ityRo3sOFOjIqz0/VBfuJwjZdbUfMkOax7OlXsDxTIMXA29p/6uNQcYy6kWnVREnMKlHGSuVB5ThZUswU24CQvM4oOBkHftvKfOn6p/cmwH5CvN621gs2DAXBc2oxIUh8OS17cyYuqlxHM0yqxqW/CFbNR0U0Y1u1sQCSnfu89Cay34x0ZjMdr/I0v/aDrQNtQRHVi2WEXG1PsHypubeWCcu64NmEzRYEIdvwVaaEkDlG8yuwq0Gag15yDxtfVHEdCG5GdwIx6YVvyQbfbOGJFiTvfKLTLv/fflrtzZoQqXucgCstrihOxPB3rMB4ukk3iygd7juri4J+Vlem6aHxsBGzws0m3+teiTz2wpxBQAJORrqAZ1B63WLsOaTRLbV4lyoIHTnoDKx7/IGrndNu3f0bnU8lc1mWatkM00riVLD/IcYPBPphR4Ru0e3XerZYeXIz6lxcgIYZZIDTWl0TyYt3ib/u/itOdMXhl0SC3JHOq4+ihZ/uV2K9qJdSI6trHuNss8dMlA5UI5N6GODZWNDP9bckC70/X0V7UC3O78PoJJ1G+fj49of18Xo4MtUf6hLsQwiRNrwJPfghFCSTqda07Vd072//ZwrMHlWvtJRKXCZ5KprKCYjgxAovdCg9q6jh/qNV5iXC5RMRDc37gtJ3vwRN1Q60pqCB+QktLWe//+5rsWcb/IihMK/bftGZQDCXKfPRjM3xdINpWUei10m8tYEIwhFZwTwOoFhefkqJhMwbHqwMNeK+79EogWWWJeXbyk/0kkWIrFJiALngRQ7nBPSjwHvjyPka8fgojoT1g3LzHXxBpF31TvJestOlWIpnZJ+zkUsLu7VlPDXaeNnIdScQLtwHK5ADy4m7my++JMGlGuJOnFwg67rQYHGoPBaRCkpL1sPfJ2oG8qydasb9QcnMwQgl8na4kzxJCFSuf/JWkztVX1VoZ7D/c8Ihm9e6aMlESnR0+ikEp8O+nPtj12vZPatOjqzYFwlCPpUUvMOyjHgb0IEXfU/GTVNjrCi2m1G/n/YZJEuDc8M0MlrR0j6hf1OXjWuLMjaHCMrqb2bGh7QWc0uAO8R1tgaYcnLzScOXRmILeXNDpk7NgXO8gv4+UNNaXZ8rNNM+jz6RBchJyuXDnUTpXksGMwgojMNrrsH1T6jMQTUCRSGgnAdDl04pEqKbXhXXcWy85pANMj3G4KSgIomQCcVawjFZEBYLAgI73+vQGlDKpBQ7ZuiN7RYkdDE/Z1HL6kItAlmSKLf58B6p9MzYP4MzqLhY8rZOnQ+JJljreqaaSFXBvgPSJc2ciVDYFM8OSePmoPGROS0sB5hkO5/c1Pe6r8b5I8N5Sx7J8bY62/nAJuNHb+FWud1MNjlUIPReVGjz/txpfCDrXo29iy2r1AeWLxd0etaHBQL6YLbQgNjptctN2p+JtZQfPLjKkhmKE1c/NeoZzMlECtPrx7+cvUpgxrYzCu8nw3Qt4GFO4zVKQdDTQCSXrFjxyHlnQ48ZAnGTvTKEOqezoIq6frjKnHpJ7JsLrgRjz3L9tA430f9xQFdOnfVbO4EjPGH/ssapWAUlXwLQ8jkFnWgJRs8Vi8tRQ7BAMhX9YpjAsirWyVnjoisH/oWp6pUL1Qt3xQ8V61Yl1FAlsr2oNIjCLyZpCnVBMatXq8qrpn6USuA/cf+rjZ3Tx5N1VbgoKvtgPm1V4JZESAwX+a6Vld8XjZ7TEzzlu3pTXUfF/blvcwx30PtE5b/rwyX4tfFDujuhtJxZccWoTuJsyh4nl+NTJR1gn4YFjLEfEJnjqwN513fCim6xp35Q0dicxZOCLsQ2FHPLHG6Zy9NqEMAT3cUWqSbUn5OoR30ADYSbZe5xiNdOloFvW6nRp1Z47jLRuJsGR80bcw76wzp2HnXAgwkD7IwrJVDvcACDFjECdDBuh0ASsed4jhC1VE4NA/0sJHn/wDI5TNSe9R9rvHAu+u/vKt2ZHRlJSST60flTuvgNalBiZ203wbXhOF6gbw8Yzo6OgLDQdY7oPcefNoE+ChtK8PV45v+zLdwdWkojhLA0HAxuHY0zkiuQudNrVFySYkLQdHkSUVGctPCd8t4xY7y4gGSZ6cixUcQjId4AqjrMns3cRko9sX4ixLahOXpj/PJMMYZ0bRLq0POwGJrQn+C4h29ZKPYfQlYRTQPmZWibVbvoEXYWrPMPs5CRT9U/qWKY/CofYrdOQnBO/8Uhw9Ht6H16T8m6tiwj9lcf5DwW7l9+Z7QX0XqQsDGOFsM/joV/vwuFRSn/CYiiAhg3H2NDJQhTzUbgTfUd1vJJQj5t8ck8qhbWdLtWxjhAeKcNuwY7zspQOGAv+Ysb9ibo/Vtfj5+h3ist8hsrm2iVuvgsjEarCbbWeaQHRcS0abKcLfctV4ZDEcr0J+fVGZ0AOhvIF1mZimiM0WLZVHf90BJcyWOA8vL8PfVc4DfO9LJ0WtKHYTSuEDmnuyfJa5z60hQRh5F6MOSTHDmBdOw3x5as1TIx0LfnKTv9gfXTCHEwQPcw52xGEYitrR3HPJ+Y06zJXBfzLB0nVKMa4JVuVH/HSkDXNCc+KzAirsuzRZwPQPKHXC3CEyFilcociUGXk9yQ8qpBDTmGX9iDbib8J8DPiMk8yHzsLWa0FJJ0PKxAhObsDKAcAgOI3bS/23oEIBJCT1BMpaLNbCjU4JMXLsikVm56hQu1gFRE1p5k/qo+p13ed0JD1Zr5WjC+Ldt0Kawv4E9ZXLdiZAax8kqIemjqSCyftzYgygagEsxBSpBFcuWkMnpdqTe4DT7aBXBc8G/hGJjzLegDk7P/b1ANlGPgaDkTAzBNSmqrtOesxyoD0fUpdCkdXGQAL5T/BqYImbFM5k1NtbUipT5kXpPjtVZw7tqAcmxTJS0UuNQtySDg9JEKM68TefbHKcJcsHywJP2WWrA9LAPTAAG0kCHcF2XgWle5KG4xq0ih/u15bGzLDNm5enk9OQqBfaNxVkeh/uaaVm0Zc0vMeou8dZSVdFFo98LP+p1DqYQi4aKWmmSWEe1IMS7GgxsE0TAGAzu4U31jWnL21qSylq7zb/ChG9N42F+fApbqoWvuKbIUJ63bT3PpBQwJ1nyqK8CaIIm9TeYhgWisYOL7Y6wWUnVTzIVPGBDD/mZ2jzSmvNxP2I1jpruqdetCjSjXVCJhxbuDhQk2L+0yeb+81PoeFVIus/6eL/+VN1kiq+rXnGZAXyb3Zdh+bIXbeCfJHOwWlJdR/7XpMsoSGhiAeqeA==$4f386b50df3fcd9132589a934851faaff16709ff", "!@#$%^&*"}, #endif {NULL} }; /* taken from LUKS on disk format specification */ struct luks_phdr { char magic[LUKS_MAGIC_L]; uint16_t version; char cipherName[LUKS_CIPHERNAME_L]; char cipherMode[LUKS_CIPHERMODE_L]; char hashSpec[LUKS_HASHSPEC_L]; uint32_t payloadOffset; uint32_t keyBytes; char mkDigest[LUKS_DIGESTSIZE]; char mkDigestSalt[LUKS_SALTSIZE]; uint32_t mkDigestIterations; char uuid[UUID_STRING_L]; struct { uint32_t active; uint32_t passwordIterations; char passwordSalt[LUKS_SALTSIZE]; uint32_t keyMaterialOffset; uint32_t stripes; } keyblock[LUKS_NUMKEYS]; }; static struct custom_salt { struct luks_phdr myphdr; int loaded; unsigned char *cipherbuf; int afsize; int bestslot; int bestiter; char path[8192]; } *cur_salt; static void XORblock(char *src1, char *src2, char *dst, int n) { int j; for (j = 0; j < n; j++) dst[j] = src1[j] ^ src2[j]; } static int diffuse(unsigned char *src, unsigned char *dst, int size) { uint32_t i; uint32_t IV; /* host byte order independent hash IV */ SHA_CTX ctx; int fullblocks = (size) / 20; int padding = size % 20; for (i = 0; i < fullblocks; i++) { IV = john_htonl(i); SHA1_Init(&ctx); SHA1_Update(&ctx, &IV, 4); SHA1_Update(&ctx, src + 20 * i, 20); SHA1_Final(dst + 20 * i, &ctx); } if (padding) { IV = john_htonl(fullblocks); SHA1_Init(&ctx); SHA1_Update(&ctx, &IV, 4); SHA1_Update(&ctx, src + 20 * fullblocks, padding); SHA1_Final(dst + 20 * fullblocks, &ctx); } return 0; } static int AF_merge(unsigned char *src, unsigned char *dst, int afsize, int stripes) { int i; char *bufblock; int blocksize = afsize / stripes; bufblock = mem_calloc(blocksize + 20); for (i = 0; i < (stripes - 1); i++) { XORblock((char *) (src + (blocksize * i)), bufblock, bufblock, blocksize); diffuse((unsigned char *) bufblock, (unsigned char *) bufblock, blocksize); } XORblock((char *) (src + blocksize * (stripes - 1)), bufblock, (char *) dst, blocksize); MEM_FREE(bufblock); return 0; } static int af_sectors(int blocksize, int blocknumbers) { int af_size; af_size = blocksize * blocknumbers; af_size = (af_size + 511) / 512; af_size *= 512; return af_size; } static void decrypt_aes_cbc_essiv(unsigned char *src, unsigned char *dst, unsigned char *key, int size, struct custom_salt *cs) { AES_KEY aeskey; unsigned char essiv[16]; unsigned char essivhash[32]; int a; SHA256_CTX ctx; unsigned char sectorbuf[16]; unsigned char zeroiv[16]; for (a = 0; a < (size / 512); a++) { SHA256_Init(&ctx); SHA256_Update(&ctx, key, john_ntohl(cs->myphdr.keyBytes)); SHA256_Final(essivhash, &ctx); memset(sectorbuf, 0, 16); memset(zeroiv, 0, 16); memset(essiv, 0, 16); #if ARCH_LITTLE_ENDIAN memcpy(sectorbuf, &a, 4); #else { int b = JOHNSWAP(a); memcpy(sectorbuf, &b, 4); } #endif AES_set_encrypt_key(essivhash, 256, &aeskey); AES_cbc_encrypt(sectorbuf, essiv, 16, &aeskey, zeroiv, AES_ENCRYPT); AES_set_decrypt_key(key, john_ntohl(cs->myphdr.keyBytes)*8, &aeskey); AES_cbc_encrypt((src+a*512), (dst+a*512), 512, &aeskey, essiv, AES_DECRYPT); } } static int hash_plugin_parse_hash(char *filename, struct custom_salt *cs, int is_critical) { FILE *myfile; int readbytes; myfile = jtr_fopen(filename, "rb"); if (!myfile) { fprintf(stderr, "\n%s : %s!\n", filename, strerror(errno)); return -1; } // can this go over 4gb? cs->cipherbuf = mem_alloc_tiny(cs->afsize + 1, MEM_ALIGN_NONE); if (!cs->cipherbuf) goto bad; // printf(">>> %d\n", cs->afsize); readbytes = fread(cs->cipherbuf, cs->afsize, 1, myfile); if (readbytes < 0) { //free(cs->cipherbuf); fprintf(stderr, "%s : unable to read required data\n", filename); goto bad; } fclose(myfile); return 0; bad: fclose(myfile); if (is_critical) { fprintf(stderr, "\nLUKS plug-in is unable to continue due to errors!\n"); exit(-1); } return -1; } static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static void init(struct fmt_main *self) { static int warned = 0; // extern struct fmt_main fmt_luks; #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_out = mem_calloc_tiny(sizeof(*crypt_out) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); /* * LUKS format will need to be redesigned to address the issues mentioned in * https://github.com/magnumripper/JohnTheRipper/issues/557. * This will require a change in john's hash representation for LUKS format. * The redesign will happen after the next official jumbo release. * To avoid having to support the current LUKS hash representation forever, * just print a warning that the hash representation will change in future releases. * * So far, no "official" jumbo release supports the LUKS format, currently only * users of bleeding-jumbo may have used LUKS format. These users should be able * to re-run luks2john and retry the passwords that have been stored for the current LUKS hashes * once the redesign of john's LUKS format implementation has been completed.) */ if (!options.listconf && !(options.flags & FLG_TEST_CHK) && warned++ == 0) { fprintf(stderr, "WARNING, LUKS format hash representation will change in future releases,\n" "see doc/README.LUKS\n"); // FIXME: address github issue #557 after 1.8.0-jumbo-1 fflush(stderr); } // This printf will 'help' debug a system that truncates that monster hash, but does not cause compiler to die. // printf ("length=%d end=%s\n", strlen(fmt_luks.params.tests[0].ciphertext), &((fmt_luks.params.tests[0].ciphertext)[strlen(fmt_luks.params.tests[0].ciphertext)-30])); } static int ishex(char *q) { while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q; } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy; char *keeptr; char *p, *q; int is_inlined; int res; static struct custom_salt cs; if (strncmp(ciphertext, "$luks$", 6) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 6; if ((p = strtok(ctcopy, "$")) == NULL) /* is_inlined */ goto err; is_inlined = atoi(p); if (is_inlined) { if ((p = strtok(NULL, "$")) == NULL) goto err; res = atoi(p); if (res != sizeof(struct luks_phdr)) goto err; if ((p = strtok(NULL, "$")) == NULL) goto err; if (res * 2 != strlen(p)) goto err; if ((p = strtok(NULL, "$")) == NULL) goto err; res = atoi(p); if ((p = strtok(NULL, "$")) == NULL) goto err; if ((p = strtok(NULL, "$")) == NULL) goto err; if (strlen(p) != LUKS_DIGESTSIZE * 2) goto err; if (!ishex(p)) goto err; } else { if ((p = strtok(NULL, "$")) == NULL) /* path */ goto err; q = p; if ((p = strtok(NULL, "$")) == NULL) /* mkDigest */ goto err; /* more tests */ if (hash_plugin_parse_hash(q, &cs, 0) != 0) { MEM_FREE(cs.cipherbuf); return 0; } MEM_FREE(cs.cipherbuf); } MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int is_inlined; int res; int i; int cnt; unsigned char *out; static struct custom_salt cs; unsigned int bestiter = 0xFFFFFFFF; size_t size; ctcopy += 6; memset(&cs, 0, sizeof(cs)); out = (unsigned char*)&cs.myphdr; p = strtok(ctcopy, "$"); is_inlined = atoi(p); /* common handling */ p = strtok(NULL, "$"); res = atoi(p); assert(res == sizeof(struct luks_phdr)); p = strtok(NULL, "$"); for (i = 0; i < res; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } p = strtok(NULL, "$"); res = atoi(p); cs.afsize = af_sectors(john_ntohl(cs.myphdr.keyBytes), john_ntohl(cs.myphdr.keyblock[cs.bestslot].stripes)); assert(res == cs.afsize); if (is_inlined) { p = strtok(NULL, "$"); size = (strlen(p) + 20) / 4 * 3 + 1; cs.cipherbuf = mem_alloc_tiny(size, MEM_ALIGN_NONE); base64_decode(p, strlen(p), (char*)cs.cipherbuf); } else { p = strtok(NULL, "$"); p = strtok(NULL, "$"); strcpy(cs.path, p); hash_plugin_parse_hash(cs.path, &cs, 1); } for (cnt = 0; cnt < LUKS_NUMKEYS; cnt++) { if ((john_ntohl(cs.myphdr.keyblock[cnt].passwordIterations) < bestiter) && (john_ntohl(cs.myphdr.keyblock[cnt].passwordIterations) > 1) && (john_ntohl(cs.myphdr.keyblock[cnt].active) == 0x00ac71f3)) { cs.bestslot = cnt; cs.bestiter = john_ntohl(cs.myphdr.keyblock[cnt].passwordIterations); } } MEM_FREE(keeptr); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[LUKS_DIGESTSIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1; for (i = 0; i < LUKS_DIGESTSIZE; 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] & 0xf; } static int get_hash_1(int index) { return crypt_out[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_out[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_out[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_out[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_out[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_out[index][0] & 0x7ffffff; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } 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++) #endif { unsigned char keycandidate[255]; unsigned char masterkeycandidate[255]; unsigned char *af_decrypted = mem_alloc(cur_salt->afsize + 20); char *password = saved_key[index]; int iterations = cur_salt->bestiter; int dklen = john_ntohl(cur_salt->myphdr.keyBytes); // printf("itertations %d %d %d\n", iterations, dklen, cur_salt->bestslot); // Get pbkdf2 of the password to obtain decryption key derive_key((const uint8_t*)password, strlen(password), (const uint8_t*)(cur_salt->myphdr.keyblock[cur_salt->bestslot].passwordSalt), LUKS_SALTSIZE, iterations, keycandidate, dklen); // Decrypt the blocksi decrypt_aes_cbc_essiv(cur_salt->cipherbuf, af_decrypted, keycandidate, cur_salt->afsize, cur_salt); // AFMerge the blocks AF_merge(af_decrypted, masterkeycandidate, cur_salt->afsize, john_ntohl(cur_salt->myphdr.keyblock[cur_salt->bestslot].stripes)); // pbkdf2 again derive_key(masterkeycandidate, john_ntohl(cur_salt->myphdr.keyBytes), (const uint8_t*)cur_salt->myphdr.mkDigestSalt, LUKS_SALTSIZE, john_ntohl(cur_salt->myphdr.mkDigestIterations), (unsigned char*)crypt_out[index], LUKS_DIGESTSIZE); MEM_FREE(af_decrypted); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], LUKS_DIGESTSIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], LUKS_DIGESTSIZE); } static int cmp_exact(char *source, int index) { return 1; } static void luks_set_key(char *key, int index) { int saved_key_length = strlen(key); if (saved_key_length > PLAINTEXT_LENGTH) saved_key_length = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_key_length); saved_key[index][saved_key_length] = 0; } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_luks = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 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, #if FMT_MAIN_VERSION > 11 { NULL }, #endif luks_tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif 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, set_salt, luks_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 */
pr58756.c
/* PR libgomp/58756 */ /* { dg-do run } */ /* { dg-additional-options "-msse2" { target sse2_runtime } } */ /* { dg-additional-options "-mavx" { target avx_runtime } } */ extern void abort (void); int d[32 * 32]; __attribute__((noinline, noclone)) int foo (int a, int b) { int j, c = 0; #pragma omp parallel for reduction(+: c) for (j = 0; j < a; j += 32) { int l; #pragma omp simd reduction(+: c) safelen(1) for (l = 0; l < b; ++l) c += d[j + l]; } return c; } __attribute__((noinline, noclone)) int bar (int a) { int j, c = 0; #pragma omp parallel for simd reduction(+: c) safelen(1) for (j = 0; j < a; ++j) c += d[j]; return c; } __attribute__((noinline)) static int baz (int a) { int j, c = 0; #pragma omp simd reduction(+: c) safelen(1) for (j = 0; j < a; ++j) c += d[j]; return c; } int main () { int i; for (i = 0; i < 32 * 32; i++) d[i] = (i & 31); if (foo (32 * 32, 32) != (31 * 32 / 2) * 32) abort (); if (bar (32 * 32) != (31 * 32 / 2) * 32) abort (); if (baz (32 * 32) != (31 * 32 / 2) * 32) abort (); return 0; }
convolution_para.c
/* Generated by Cython 0.15.1 on Mon Feb 11 15:34:00 2013 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #else #include <stddef.h> /* For offsetof */ #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #if PY_VERSION_HEX < 0x02040000 #define METH_COEXIST 0 #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) #define PyDict_Contains(d,o) PySequence_Contains(d,o) #endif #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PY_FORMAT_SIZE_T "" #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) #define PyNumber_Index(o) PyNumber_Int(o) #define PyIndex_Check(o) PyNumber_Check(o) #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) #endif #if PY_VERSION_HEX < 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) typedef struct { void *buf; PyObject *obj; Py_ssize_t len; Py_ssize_t itemsize; int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #endif #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif #if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_VERSION_HEX < 0x02060000 #define PyBytesObject PyStringObject #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytes_CheckExact PyString_CheckExact #define PyBytes_FromString PyString_FromString #define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyBytes_FromFormat PyString_FromFormat #define PyBytes_DecodeEscape PyString_DecodeEscape #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyBytes_Size PyString_Size #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_Repr PyString_Repr #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #endif #if PY_VERSION_HEX < 0x02060000 #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_VERSION_HEX < 0x03020000 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) #else #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) #endif #if PY_MAJOR_VERSION >= 3 #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) #else #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) #endif #if PY_VERSION_HEX < 0x02050000 #define __Pyx_NAMESTR(n) ((char *)(n)) #define __Pyx_DOCSTR(n) ((char *)(n)) #else #define __Pyx_NAMESTR(n) (n) #define __Pyx_DOCSTR(n) (n) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #define __PYX_HAVE__cconvolution_omp #define __PYX_HAVE_API__cconvolution_omp #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif /* inline attribute */ #ifndef CYTHON_INLINE #if defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif /* unused attribute */ #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || defined(__INTEL_COMPILER) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ /* Type Conversion Predeclarations */ #define __Pyx_PyBytes_FromUString(s) PyBytes_FromString((char*)s) #define __Pyx_PyBytes_AsUString(s) ((unsigned char*) PyBytes_AsString(s)) #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #ifdef __GNUC__ /* Test for GCC > 2.95 */ #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* __GNUC__ > 2 ... */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ > 2 ... */ #else /* __GNUC__ */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include <complex> #else #include <complex.h> #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "convolution_para.pyx", "numpy.pxd", }; /* "numpy.pxd":719 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t */ typedef npy_int8 __pyx_t_5numpy_int8_t; /* "numpy.pxd":720 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t */ typedef npy_int16 __pyx_t_5numpy_int16_t; /* "numpy.pxd":721 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "numpy.pxd":722 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< * #ctypedef npy_int96 int96_t * #ctypedef npy_int128 int128_t */ typedef npy_int64 __pyx_t_5numpy_int64_t; /* "numpy.pxd":726 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; /* "numpy.pxd":727 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; /* "numpy.pxd":728 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "numpy.pxd":729 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< * #ctypedef npy_uint96 uint96_t * #ctypedef npy_uint128 uint128_t */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; /* "numpy.pxd":733 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< * ctypedef npy_float64 float64_t * #ctypedef npy_float80 float80_t */ typedef npy_float32 __pyx_t_5numpy_float32_t; /* "numpy.pxd":734 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< * #ctypedef npy_float80 float80_t * #ctypedef npy_float128 float128_t */ typedef npy_float64 __pyx_t_5numpy_float64_t; /* "numpy.pxd":743 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t */ typedef npy_long __pyx_t_5numpy_int_t; /* "numpy.pxd":744 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< * ctypedef npy_longlong longlong_t * */ typedef npy_longlong __pyx_t_5numpy_long_t; /* "numpy.pxd":745 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< * * ctypedef npy_ulong uint_t */ typedef npy_longlong __pyx_t_5numpy_longlong_t; /* "numpy.pxd":747 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t */ typedef npy_ulong __pyx_t_5numpy_uint_t; /* "numpy.pxd":748 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "numpy.pxd":749 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< * * ctypedef npy_intp intp_t */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; /* "numpy.pxd":751 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "numpy.pxd":752 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "numpy.pxd":754 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t */ typedef npy_double __pyx_t_5numpy_float_t; /* "numpy.pxd":755 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "numpy.pxd":756 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /* "convolution_para.pyx":7 * * DTYPE = np.double * ctypedef np.double_t DTYPE_t # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ typedef __pyx_t_5numpy_double_t __pyx_t_16cconvolution_omp_DTYPE_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif /*--- Type declarations ---*/ /* "numpy.pxd":758 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; /* "numpy.pxd":759 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "numpy.pxd":760 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cdouble complex_t */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; /* "numpy.pxd":762 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #define __Pyx_RefNannySetupContext(name) __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #define __Pyx_RefNannyFinishContext() __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif /* CYTHON_REFNANNY */ static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /*proto*/ /* Run-time type information about structs used with buffers */ struct __Pyx_StructField_; typedef struct { const char* name; /* for error messages only */ struct __Pyx_StructField_* fields; size_t size; /* sizeof(type) */ char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject */ } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ #include <string.h> void __pyx_init_nan(void); static float __PYX_NAN; #define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/ #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif Py_ssize_t __Pyx_zeros[] = {0, 0}; Py_ssize_t __Pyx_minusones[] = {-1, -1}; static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/ #ifndef __PYX_FORCE_INIT_THREADS #if PY_VERSION_HEX < 0x02040200 #define __PYX_FORCE_INIT_THREADS 1 #else #define __PYX_FORCE_INIT_THREADS 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if defined(_WIN32) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); #if CYTHON_CCOMPLEX #define __Pyx_c_eqf(a, b) ((a)==(b)) #define __Pyx_c_sumf(a, b) ((a)+(b)) #define __Pyx_c_difff(a, b) ((a)-(b)) #define __Pyx_c_prodf(a, b) ((a)*(b)) #define __Pyx_c_quotf(a, b) ((a)/(b)) #define __Pyx_c_negf(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zerof(z) ((z)==(float)0) #define __Pyx_c_conjf(z) (::std::conj(z)) #if 1 #define __Pyx_c_absf(z) (::std::abs(z)) #define __Pyx_c_powf(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zerof(z) ((z)==0) #define __Pyx_c_conjf(z) (conjf(z)) #if 1 #define __Pyx_c_absf(z) (cabsf(z)) #define __Pyx_c_powf(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); #if CYTHON_CCOMPLEX #define __Pyx_c_eq(a, b) ((a)==(b)) #define __Pyx_c_sum(a, b) ((a)+(b)) #define __Pyx_c_diff(a, b) ((a)-(b)) #define __Pyx_c_prod(a, b) ((a)*(b)) #define __Pyx_c_quot(a, b) ((a)/(b)) #define __Pyx_c_neg(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero(z) ((z)==(double)0) #define __Pyx_c_conj(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs(z) (::std::abs(z)) #define __Pyx_c_pow(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero(z) ((z)==0) #define __Pyx_c_conj(z) (conj(z)) #if 1 #define __Pyx_c_abs(z) (cabs(z)) #define __Pyx_c_pow(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); static int __Pyx_check_binary_version(void); static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, int __pyx_lineno, const char *__pyx_filename); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *); /*proto*/ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *, PyObject *); /*proto*/ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *); /*proto*/ /* Module declarations from 'cython.cython.view' */ /* Module declarations from 'cython' */ /* Module declarations from 'cconvolution_omp' */ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_16cconvolution_omp_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_16cconvolution_omp_DTYPE_t), 'R' }; #define __Pyx_MODULE_NAME "cconvolution_omp" int __pyx_module_is_main_cconvolution_omp = 0; /* Implementation of 'cconvolution_omp' */ static PyObject *__pyx_builtin_xrange; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; static char __pyx_k_1[] = "ndarray is not C contiguous"; static char __pyx_k_3[] = "ndarray is not Fortran contiguous"; static char __pyx_k_5[] = "Non-native byte order not supported"; static char __pyx_k_7[] = "unknown dtype code in numpy.pxd (%d)"; static char __pyx_k_8[] = "Format string allocated too short, see comment in numpy.pxd"; static char __pyx_k_11[] = "Format string allocated too short."; static char __pyx_k__B[] = "B"; static char __pyx_k__H[] = "H"; static char __pyx_k__I[] = "I"; static char __pyx_k__L[] = "L"; static char __pyx_k__O[] = "O"; static char __pyx_k__Q[] = "Q"; static char __pyx_k__b[] = "b"; static char __pyx_k__d[] = "d"; static char __pyx_k__f[] = "f"; static char __pyx_k__g[] = "g"; static char __pyx_k__h[] = "h"; static char __pyx_k__i[] = "i"; static char __pyx_k__l[] = "l"; static char __pyx_k__q[] = "q"; static char __pyx_k__Zd[] = "Zd"; static char __pyx_k__Zf[] = "Zf"; static char __pyx_k__Zg[] = "Zg"; static char __pyx_k__np[] = "np"; static char __pyx_k__DTYPE[] = "DTYPE"; static char __pyx_k__numpy[] = "numpy"; static char __pyx_k__range[] = "range"; static char __pyx_k__zeros[] = "zeros"; static char __pyx_k__double[] = "double"; static char __pyx_k__xrange[] = "xrange"; static char __pyx_k____main__[] = "__main__"; static char __pyx_k____test__[] = "__test__"; static char __pyx_k__ValueError[] = "ValueError"; static char __pyx_k__convolution[] = "convolution"; static char __pyx_k__RuntimeError[] = "RuntimeError"; static char __pyx_k__cconvolution_omp[] = "cconvolution_omp"; static PyObject *__pyx_kp_u_1; static PyObject *__pyx_kp_u_11; static PyObject *__pyx_kp_u_3; static PyObject *__pyx_kp_u_5; static PyObject *__pyx_kp_u_7; static PyObject *__pyx_kp_u_8; static PyObject *__pyx_n_s__DTYPE; static PyObject *__pyx_n_s__RuntimeError; static PyObject *__pyx_n_s__ValueError; static PyObject *__pyx_n_s____main__; static PyObject *__pyx_n_s____test__; static PyObject *__pyx_n_s__cconvolution_omp; static PyObject *__pyx_n_s__convolution; static PyObject *__pyx_n_s__double; static PyObject *__pyx_n_s__np; static PyObject *__pyx_n_s__numpy; static PyObject *__pyx_n_s__range; static PyObject *__pyx_n_s__xrange; static PyObject *__pyx_n_s__zeros; static PyObject *__pyx_int_15; static PyObject *__pyx_k_tuple_2; static PyObject *__pyx_k_tuple_4; static PyObject *__pyx_k_tuple_6; static PyObject *__pyx_k_tuple_9; static PyObject *__pyx_k_tuple_10; static PyObject *__pyx_k_tuple_12; /* "convolution_para.pyx":10 * * @cython.boundscheck(False) * def convolution(np.ndarray[DTYPE_t, ndim=2, negative_indices=False] A): # <<<<<<<<<<<<<< * cdef int m = A.shape[0] * cdef int n = A.shape[1] */ static PyObject *__pyx_pf_16cconvolution_omp_convolution(PyObject *__pyx_self, PyObject *__pyx_v_A); /*proto*/ static PyMethodDef __pyx_mdef_16cconvolution_omp_convolution = {__Pyx_NAMESTR("convolution"), (PyCFunction)__pyx_pf_16cconvolution_omp_convolution, METH_O, __Pyx_DOCSTR(0)}; static PyObject *__pyx_pf_16cconvolution_omp_convolution(PyObject *__pyx_self, PyObject *__pyx_v_A) { int __pyx_v_m; int __pyx_v_n; PyArrayObject *__pyx_v_B = 0; double __pyx_v_c11; double __pyx_v_c21; double __pyx_v_c31; double __pyx_v_c12; double __pyx_v_c22; double __pyx_v_c32; double __pyx_v_c13; double __pyx_v_c23; double __pyx_v_c33; int __pyx_v_i; int __pyx_v_j; Py_buffer __pyx_bstruct_A; Py_ssize_t __pyx_bstride_0_A = 0; Py_ssize_t __pyx_bstride_1_A = 0; Py_ssize_t __pyx_bshape_0_A = 0; Py_ssize_t __pyx_bshape_1_A = 0; Py_buffer __pyx_bstruct_B; Py_ssize_t __pyx_bstride_0_B = 0; Py_ssize_t __pyx_bstride_1_B = 0; Py_ssize_t __pyx_bshape_0_B = 0; Py_ssize_t __pyx_bshape_1_B = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyArrayObject *__pyx_t_5 = NULL; long __pyx_t_6; long __pyx_t_7; long __pyx_t_8; long __pyx_t_9; int __pyx_t_10; long __pyx_t_11; long __pyx_t_12; long __pyx_t_13; long __pyx_t_14; long __pyx_t_15; long __pyx_t_16; long __pyx_t_17; long __pyx_t_18; long __pyx_t_19; long __pyx_t_20; long __pyx_t_21; long __pyx_t_22; long __pyx_t_23; long __pyx_t_24; long __pyx_t_25; long __pyx_t_26; long __pyx_t_27; long __pyx_t_28; int __pyx_t_29; int __pyx_t_30; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convolution"); __pyx_self = __pyx_self; __pyx_bstruct_B.buf = NULL; __pyx_bstruct_A.buf = NULL; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_A), __pyx_ptype_5numpy_ndarray, 1, "A", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_A, (PyObject*)__pyx_v_A, &__Pyx_TypeInfo_nn___pyx_t_16cconvolution_omp_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_bstride_0_A = __pyx_bstruct_A.strides[0]; __pyx_bstride_1_A = __pyx_bstruct_A.strides[1]; __pyx_bshape_0_A = __pyx_bstruct_A.shape[0]; __pyx_bshape_1_A = __pyx_bstruct_A.shape[1]; /* "convolution_para.pyx":11 * @cython.boundscheck(False) * def convolution(np.ndarray[DTYPE_t, ndim=2, negative_indices=False] A): * cdef int m = A.shape[0] # <<<<<<<<<<<<<< * cdef int n = A.shape[1] * cdef np.ndarray[DTYPE_t, ndim=2, negative_indices=False] B = np.zeros((m,n)) */ __pyx_v_m = (((PyArrayObject *)__pyx_v_A)->dimensions[0]); /* "convolution_para.pyx":12 * def convolution(np.ndarray[DTYPE_t, ndim=2, negative_indices=False] A): * cdef int m = A.shape[0] * cdef int n = A.shape[1] # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2, negative_indices=False] B = np.zeros((m,n)) * */ __pyx_v_n = (((PyArrayObject *)__pyx_v_A)->dimensions[1]); /* "convolution_para.pyx":13 * cdef int m = A.shape[0] * cdef int n = A.shape[1] * cdef np.ndarray[DTYPE_t, ndim=2, negative_indices=False] B = np.zeros((m,n)) # <<<<<<<<<<<<<< * * cdef double c11 = 2.0 */ __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyInt_FromLong(__pyx_v_m); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = PyInt_FromLong(__pyx_v_n); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_4)); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_4)); __Pyx_GIVEREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_bstruct_B, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_16cconvolution_omp_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) { __pyx_v_B = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_bstruct_B.buf = NULL; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } else {__pyx_bstride_0_B = __pyx_bstruct_B.strides[0]; __pyx_bstride_1_B = __pyx_bstruct_B.strides[1]; __pyx_bshape_0_B = __pyx_bstruct_B.shape[0]; __pyx_bshape_1_B = __pyx_bstruct_B.shape[1]; } } __pyx_t_5 = 0; __pyx_v_B = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; /* "convolution_para.pyx":15 * cdef np.ndarray[DTYPE_t, ndim=2, negative_indices=False] B = np.zeros((m,n)) * * cdef double c11 = 2.0 # <<<<<<<<<<<<<< * cdef double c21 = 5.0 * cdef double c31 = -8.0 */ __pyx_v_c11 = 2.0; /* "convolution_para.pyx":16 * * cdef double c11 = 2.0 * cdef double c21 = 5.0 # <<<<<<<<<<<<<< * cdef double c31 = -8.0 * cdef double c12 = -3.0 */ __pyx_v_c21 = 5.0; /* "convolution_para.pyx":17 * cdef double c11 = 2.0 * cdef double c21 = 5.0 * cdef double c31 = -8.0 # <<<<<<<<<<<<<< * cdef double c12 = -3.0 * cdef double c22 = 6.0 */ __pyx_v_c31 = -8.0; /* "convolution_para.pyx":18 * cdef double c21 = 5.0 * cdef double c31 = -8.0 * cdef double c12 = -3.0 # <<<<<<<<<<<<<< * cdef double c22 = 6.0 * cdef double c32 = -9.0 */ __pyx_v_c12 = -3.0; /* "convolution_para.pyx":19 * cdef double c31 = -8.0 * cdef double c12 = -3.0 * cdef double c22 = 6.0 # <<<<<<<<<<<<<< * cdef double c32 = -9.0 * cdef double c13 = 4.0 */ __pyx_v_c22 = 6.0; /* "convolution_para.pyx":20 * cdef double c12 = -3.0 * cdef double c22 = 6.0 * cdef double c32 = -9.0 # <<<<<<<<<<<<<< * cdef double c13 = 4.0 * cdef double c23 = 7.0 */ __pyx_v_c32 = -9.0; /* "convolution_para.pyx":21 * cdef double c22 = 6.0 * cdef double c32 = -9.0 * cdef double c13 = 4.0 # <<<<<<<<<<<<<< * cdef double c23 = 7.0 * cdef double c33 = 10.0 */ __pyx_v_c13 = 4.0; /* "convolution_para.pyx":22 * cdef double c32 = -9.0 * cdef double c13 = 4.0 * cdef double c23 = 7.0 # <<<<<<<<<<<<<< * cdef double c33 = 10.0 * cdef int i,j */ __pyx_v_c23 = 7.0; /* "convolution_para.pyx":23 * cdef double c13 = 4.0 * cdef double c23 = 7.0 * cdef double c33 = 10.0 # <<<<<<<<<<<<<< * cdef int i,j * with nogil, parallel(): */ __pyx_v_c33 = 10.0; /* "convolution_para.pyx":25 * cdef double c33 = 10.0 * cdef int i,j * with nogil, parallel(): # <<<<<<<<<<<<<< * for i in prange(1, m - 1): * for j in xrange(1, n - 1): */ { #ifdef WITH_THREAD PyThreadState *_save = NULL; #endif Py_UNBLOCK_THREADS /*try:*/ { { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_10, __pyx_t_6, __pyx_t_28, __pyx_t_25, __pyx_t_30, __pyx_t_14, __pyx_t_19, __pyx_t_22, __pyx_t_13, __pyx_t_18, __pyx_t_26, __pyx_t_17, __pyx_t_9, __pyx_t_7, __pyx_t_29, __pyx_t_23, __pyx_t_12, __pyx_t_20, __pyx_t_27, __pyx_t_11, __pyx_t_16, __pyx_t_21, __pyx_t_24, __pyx_t_8, __pyx_t_15) #endif /* _OPENMP */ { /* "convolution_para.pyx":26 * cdef int i,j * with nogil, parallel(): * for i in prange(1, m - 1): # <<<<<<<<<<<<<< * for j in xrange(1, n - 1): * B[i,j] = c11 * A[i - 1,j - 1] + c12 * A[i + 0,j - 1] + c13 * A[i + 1,j - 1]\ */ __pyx_t_6 = (__pyx_v_m - 1); if (1 == 0) abort(); { __pyx_t_8 = (__pyx_t_6 - 1) / 1; if (__pyx_t_8 > 0) { __pyx_v_i = 0; #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_j) firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) #endif /* _OPENMP */ for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_8; __pyx_t_7++){ { __pyx_v_i = 1 + 1 * __pyx_t_7; /* Initialize private variables to invalid values */ __pyx_v_j = ((int)0xbad0bad0); /* "convolution_para.pyx":27 * with nogil, parallel(): * for i in prange(1, m - 1): * for j in xrange(1, n - 1): # <<<<<<<<<<<<<< * B[i,j] = c11 * A[i - 1,j - 1] + c12 * A[i + 0,j - 1] + c13 * A[i + 1,j - 1]\ * + c21 * A[i - 1,j + 0] + c22 * A[i + 0,j + 0] + c23 * A[i + 1,j + 0]\ */ __pyx_t_9 = (__pyx_v_n - 1); for (__pyx_t_10 = 1; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { __pyx_v_j = __pyx_t_10; /* "convolution_para.pyx":28 * for i in prange(1, m - 1): * for j in xrange(1, n - 1): * B[i,j] = c11 * A[i - 1,j - 1] + c12 * A[i + 0,j - 1] + c13 * A[i + 1,j - 1]\ # <<<<<<<<<<<<<< * + c21 * A[i - 1,j + 0] + c22 * A[i + 0,j + 0] + c23 * A[i + 1,j + 0]\ * + c31 * A[i - 1,j + 1] + c32 * A[i + 0,j + 1] + c33 * A[i + 1,j + 1] */ __pyx_t_11 = (__pyx_v_i - 1); __pyx_t_12 = (__pyx_v_j - 1); __pyx_t_13 = (__pyx_v_i + 0); __pyx_t_14 = (__pyx_v_j - 1); __pyx_t_15 = (__pyx_v_i + 1); __pyx_t_16 = (__pyx_v_j - 1); /* "convolution_para.pyx":29 * for j in xrange(1, n - 1): * B[i,j] = c11 * A[i - 1,j - 1] + c12 * A[i + 0,j - 1] + c13 * A[i + 1,j - 1]\ * + c21 * A[i - 1,j + 0] + c22 * A[i + 0,j + 0] + c23 * A[i + 1,j + 0]\ # <<<<<<<<<<<<<< * + c31 * A[i - 1,j + 1] + c32 * A[i + 0,j + 1] + c33 * A[i + 1,j + 1] * return B */ __pyx_t_17 = (__pyx_v_i - 1); __pyx_t_18 = (__pyx_v_j + 0); __pyx_t_19 = (__pyx_v_i + 0); __pyx_t_20 = (__pyx_v_j + 0); __pyx_t_21 = (__pyx_v_i + 1); __pyx_t_22 = (__pyx_v_j + 0); /* "convolution_para.pyx":30 * B[i,j] = c11 * A[i - 1,j - 1] + c12 * A[i + 0,j - 1] + c13 * A[i + 1,j - 1]\ * + c21 * A[i - 1,j + 0] + c22 * A[i + 0,j + 0] + c23 * A[i + 1,j + 0]\ * + c31 * A[i - 1,j + 1] + c32 * A[i + 0,j + 1] + c33 * A[i + 1,j + 1] # <<<<<<<<<<<<<< * return B */ __pyx_t_23 = (__pyx_v_i - 1); __pyx_t_24 = (__pyx_v_j + 1); __pyx_t_25 = (__pyx_v_i + 0); __pyx_t_26 = (__pyx_v_j + 1); __pyx_t_27 = (__pyx_v_i + 1); __pyx_t_28 = (__pyx_v_j + 1); /* "convolution_para.pyx":28 * for i in prange(1, m - 1): * for j in xrange(1, n - 1): * B[i,j] = c11 * A[i - 1,j - 1] + c12 * A[i + 0,j - 1] + c13 * A[i + 1,j - 1]\ # <<<<<<<<<<<<<< * + c21 * A[i - 1,j + 0] + c22 * A[i + 0,j + 0] + c23 * A[i + 1,j + 0]\ * + c31 * A[i - 1,j + 1] + c32 * A[i + 0,j + 1] + c33 * A[i + 1,j + 1] */ __pyx_t_29 = __pyx_v_i; __pyx_t_30 = __pyx_v_j; *__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_B.buf, __pyx_t_29, __pyx_bstride_0_B, __pyx_t_30, __pyx_bstride_1_B) = (((((((((__pyx_v_c11 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_11, __pyx_bstride_0_A, __pyx_t_12, __pyx_bstride_1_A))) + (__pyx_v_c12 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_13, __pyx_bstride_0_A, __pyx_t_14, __pyx_bstride_1_A)))) + (__pyx_v_c13 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_15, __pyx_bstride_0_A, __pyx_t_16, __pyx_bstride_1_A)))) + (__pyx_v_c21 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_17, __pyx_bstride_0_A, __pyx_t_18, __pyx_bstride_1_A)))) + (__pyx_v_c22 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_19, __pyx_bstride_0_A, __pyx_t_20, __pyx_bstride_1_A)))) + (__pyx_v_c23 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_21, __pyx_bstride_0_A, __pyx_t_22, __pyx_bstride_1_A)))) + (__pyx_v_c31 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_23, __pyx_bstride_0_A, __pyx_t_24, __pyx_bstride_1_A)))) + (__pyx_v_c32 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_25, __pyx_bstride_0_A, __pyx_t_26, __pyx_bstride_1_A)))) + (__pyx_v_c33 * (*__Pyx_BufPtrStrided2d(__pyx_t_16cconvolution_omp_DTYPE_t *, __pyx_bstruct_A.buf, __pyx_t_27, __pyx_bstride_0_A, __pyx_t_28, __pyx_bstride_1_A)))); } } } } } } } } /* "convolution_para.pyx":25 * cdef double c33 = 10.0 * cdef int i,j * with nogil, parallel(): # <<<<<<<<<<<<<< * for i in prange(1, m - 1): * for j in xrange(1, n - 1): */ /*finally:*/ { Py_BLOCK_THREADS } } /* "convolution_para.pyx":31 * + c21 * A[i - 1,j + 0] + c22 * A[i + 0,j + 0] + c23 * A[i + 1,j + 0]\ * + c31 * A[i - 1,j + 1] + c32 * A[i + 0,j + 1] + c33 * A[i + 1,j + 1] * return B # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_B)); __pyx_r = ((PyObject *)__pyx_v_B); goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_bstruct_A); __Pyx_SafeReleaseBuffer(&__pyx_bstruct_B); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("cconvolution_omp.convolution", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_bstruct_A); __Pyx_SafeReleaseBuffer(&__pyx_bstruct_B); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_B); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":190 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; int __pyx_v_t; char *__pyx_v_f; PyArray_Descr *__pyx_v_descr = 0; int __pyx_v_offset; int __pyx_v_hasfields; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getbuffer__"); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "numpy.pxd":196 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ __pyx_t_1 = (__pyx_v_info == NULL); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; goto __pyx_L5; } __pyx_L5:; /* "numpy.pxd":199 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "numpy.pxd":200 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * * ndim = PyArray_NDIM(self) */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "numpy.pxd":202 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); /* "numpy.pxd":204 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { /* "numpy.pxd":205 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; goto __pyx_L6; } /*else*/ { /* "numpy.pxd":207 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ __pyx_v_copy_shape = 0; } __pyx_L6:; /* "numpy.pxd":209 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); if (__pyx_t_1) { /* "numpy.pxd":210 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); __pyx_t_3 = __pyx_t_2; } else { __pyx_t_3 = __pyx_t_1; } if (__pyx_t_3) { /* "numpy.pxd":211 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "numpy.pxd":213 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ __pyx_t_3 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); if (__pyx_t_3) { /* "numpy.pxd":214 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); __pyx_t_2 = __pyx_t_1; } else { __pyx_t_2 = __pyx_t_3; } if (__pyx_t_2) { /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; /* "numpy.pxd":217 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); /* "numpy.pxd":218 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if copy_shape: * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "numpy.pxd":219 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ if (__pyx_v_copy_shape) { /* "numpy.pxd":222 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); /* "numpy.pxd":223 * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); /* "numpy.pxd":224 * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ __pyx_t_5 = __pyx_v_ndim; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "numpy.pxd":225 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); /* "numpy.pxd":226 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); } goto __pyx_L9; } /*else*/ { /* "numpy.pxd":228 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL */ __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); /* "numpy.pxd":229 * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); } __pyx_L9:; /* "numpy.pxd":230 * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; /* "numpy.pxd":231 * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); /* "numpy.pxd":232 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); /* "numpy.pxd":235 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef list stack */ __pyx_v_f = NULL; /* "numpy.pxd":236 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; /* "numpy.pxd":240 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "numpy.pxd":242 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ __pyx_t_2 = (!__pyx_v_hasfields); if (__pyx_t_2) { __pyx_t_3 = (!__pyx_v_copy_shape); __pyx_t_1 = __pyx_t_3; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { /* "numpy.pxd":244 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; goto __pyx_L12; } /*else*/ { /* "numpy.pxd":247 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ __Pyx_INCREF(__pyx_v_self); __Pyx_GIVEREF(__pyx_v_self); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = __pyx_v_self; } __pyx_L12:; /* "numpy.pxd":249 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == '>' and little_endian) or */ __pyx_t_1 = (!__pyx_v_hasfields); if (__pyx_t_1) { /* "numpy.pxd":250 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == '>' and little_endian) or * (descr.byteorder == '<' and not little_endian)): */ __pyx_v_t = __pyx_v_descr->type_num; /* "numpy.pxd":251 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == '<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_1 = (__pyx_v_descr->byteorder == '>'); if (__pyx_t_1) { __pyx_t_2 = __pyx_v_little_endian; } else { __pyx_t_2 = __pyx_t_1; } if (!__pyx_t_2) { /* "numpy.pxd":252 * t = descr.type_num * if ((descr.byteorder == '>' and little_endian) or * (descr.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ __pyx_t_1 = (__pyx_v_descr->byteorder == '<'); if (__pyx_t_1) { __pyx_t_3 = (!__pyx_v_little_endian); __pyx_t_7 = __pyx_t_3; } else { __pyx_t_7 = __pyx_t_1; } __pyx_t_1 = __pyx_t_7; } else { __pyx_t_1 = __pyx_t_2; } if (__pyx_t_1) { /* "numpy.pxd":253 * if ((descr.byteorder == '>' and little_endian) or * (descr.byteorder == '<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L14; } __pyx_L14:; /* "numpy.pxd":254 * (descr.byteorder == '<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ __pyx_t_1 = (__pyx_v_t == NPY_BYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__b; goto __pyx_L15; } /* "numpy.pxd":255 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ __pyx_t_1 = (__pyx_v_t == NPY_UBYTE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__B; goto __pyx_L15; } /* "numpy.pxd":256 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ __pyx_t_1 = (__pyx_v_t == NPY_SHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__h; goto __pyx_L15; } /* "numpy.pxd":257 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ __pyx_t_1 = (__pyx_v_t == NPY_USHORT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__H; goto __pyx_L15; } /* "numpy.pxd":258 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ __pyx_t_1 = (__pyx_v_t == NPY_INT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__i; goto __pyx_L15; } /* "numpy.pxd":259 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ __pyx_t_1 = (__pyx_v_t == NPY_UINT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__I; goto __pyx_L15; } /* "numpy.pxd":260 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ __pyx_t_1 = (__pyx_v_t == NPY_LONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__l; goto __pyx_L15; } /* "numpy.pxd":261 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ __pyx_t_1 = (__pyx_v_t == NPY_ULONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__L; goto __pyx_L15; } /* "numpy.pxd":262 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ __pyx_t_1 = (__pyx_v_t == NPY_LONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__q; goto __pyx_L15; } /* "numpy.pxd":263 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ __pyx_t_1 = (__pyx_v_t == NPY_ULONGLONG); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Q; goto __pyx_L15; } /* "numpy.pxd":264 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ __pyx_t_1 = (__pyx_v_t == NPY_FLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__f; goto __pyx_L15; } /* "numpy.pxd":265 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ __pyx_t_1 = (__pyx_v_t == NPY_DOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__d; goto __pyx_L15; } /* "numpy.pxd":266 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ __pyx_t_1 = (__pyx_v_t == NPY_LONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__g; goto __pyx_L15; } /* "numpy.pxd":267 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ __pyx_t_1 = (__pyx_v_t == NPY_CFLOAT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zf; goto __pyx_L15; } /* "numpy.pxd":268 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ __pyx_t_1 = (__pyx_v_t == NPY_CDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zd; goto __pyx_L15; } /* "numpy.pxd":269 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ __pyx_t_1 = (__pyx_v_t == NPY_CLONGDOUBLE); if (__pyx_t_1) { __pyx_v_f = __pyx_k__Zg; goto __pyx_L15; } /* "numpy.pxd":270 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_1 = (__pyx_v_t == NPY_OBJECT); if (__pyx_t_1) { __pyx_v_f = __pyx_k__O; goto __pyx_L15; } /*else*/ { /* "numpy.pxd":272 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ __pyx_t_4 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_8 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_8)); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_4)); PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_t_8)); __Pyx_GIVEREF(((PyObject *)__pyx_t_8)); __pyx_t_8 = 0; __pyx_t_8 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L15:; /* "numpy.pxd":273 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "numpy.pxd":274 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; goto __pyx_L13; } /*else*/ { /* "numpy.pxd":276 * return * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = '^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); /* "numpy.pxd":277 * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = '^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; /* "numpy.pxd":278 * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = '^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; /* "numpy.pxd":281 * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, * &offset) # <<<<<<<<<<<<<< * f[0] = 0 # Terminate format string * */ __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; /* "numpy.pxd":282 * info.format + _buffer_format_string_len, * &offset) * f[0] = 0 # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ (__pyx_v_f[0]) = 0; } __pyx_L13:; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":284 * f[0] = 0 # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pf_5numpy_7ndarray_1__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__"); /* "numpy.pxd":285 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); if (__pyx_t_1) { /* "numpy.pxd":286 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) */ free(__pyx_v_info->format); goto __pyx_L5; } __pyx_L5:; /* "numpy.pxd":287 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ __pyx_t_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_t_1) { /* "numpy.pxd":288 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ free(__pyx_v_info->strides); goto __pyx_L6; } __pyx_L6:; __Pyx_RefNannyFinishContext(); } /* "numpy.pxd":764 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1"); /* "numpy.pxd":765 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":767 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2"); /* "numpy.pxd":768 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":770 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3"); /* "numpy.pxd":771 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 771; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":773 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4"); /* "numpy.pxd":774 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":776 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5"); /* "numpy.pxd":777 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 777; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":779 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; long __pyx_t_10; char *__pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring"); /* "numpy.pxd":786 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "numpy.pxd":787 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "numpy.pxd":790 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ if (unlikely(((PyObject *)__pyx_v_descr->names) == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = ((PyObject *)__pyx_v_descr->names); __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; __Pyx_XDECREF(__pyx_v_childname); __pyx_v_childname = __pyx_t_3; __pyx_t_3 = 0; /* "numpy.pxd":791 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ __pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (!__pyx_t_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected tuple, got %.200s", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 791; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_fields)); __pyx_v_fields = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "numpy.pxd":792 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - (new_offset - offset[0]) < 15: */ if (likely(PyTuple_CheckExact(((PyObject *)__pyx_v_fields)))) { PyObject* sequence = ((PyObject *)__pyx_v_fields); if (unlikely(PyTuple_GET_SIZE(sequence) != 2)) { if (PyTuple_GET_SIZE(sequence) > 2) __Pyx_RaiseTooManyValuesError(2); else __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(sequence)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); } else { __Pyx_UnpackTupleError(((PyObject *)__pyx_v_fields), 2); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF(((PyObject *)__pyx_v_child)); __pyx_v_child = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_v_new_offset); __pyx_v_new_offset = __pyx_t_4; __pyx_t_4 = 0; /* "numpy.pxd":794 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ __pyx_t_4 = PyInt_FromLong((__pyx_v_end - __pyx_v_f)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyNumber_Subtract(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyObject_RichCompare(__pyx_t_3, __pyx_int_15, Py_LT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { /* "numpy.pxd":795 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == '>' and little_endian) or */ __pyx_t_5 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_9), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "numpy.pxd":797 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == '>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == '<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_6 = (__pyx_v_child->byteorder == '>'); if (__pyx_t_6) { __pyx_t_7 = __pyx_v_little_endian; } else { __pyx_t_7 = __pyx_t_6; } if (!__pyx_t_7) { /* "numpy.pxd":798 * * if ((child.byteorder == '>' and little_endian) or * (child.byteorder == '<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ __pyx_t_6 = (__pyx_v_child->byteorder == '<'); if (__pyx_t_6) { __pyx_t_8 = (!__pyx_v_little_endian); __pyx_t_9 = __pyx_t_8; } else { __pyx_t_9 = __pyx_t_6; } __pyx_t_6 = __pyx_t_9; } else { __pyx_t_6 = __pyx_t_7; } if (__pyx_t_6) { /* "numpy.pxd":799 * if ((child.byteorder == '>' and little_endian) or * (child.byteorder == '<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "numpy.pxd":809 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< * f[0] = 120 # "x"; pad byte * f += 1 */ while (1) { __pyx_t_5 = PyInt_FromLong((__pyx_v_offset[0])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_v_new_offset, Py_LT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!__pyx_t_6) break; /* "numpy.pxd":810 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 120; /* "numpy.pxd":811 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "numpy.pxd":812 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1); } /* "numpy.pxd":814 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_10 = 0; (__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize); /* "numpy.pxd":816 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ __pyx_t_6 = (!PyDataType_HASFIELDS(__pyx_v_child)); if (__pyx_t_6) { /* "numpy.pxd":817 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ __pyx_t_3 = PyInt_FromLong(__pyx_v_child->type_num); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XDECREF(__pyx_v_t); __pyx_v_t = __pyx_t_3; __pyx_t_3 = 0; /* "numpy.pxd":818 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = ((__pyx_v_end - __pyx_v_f) < 5); if (__pyx_t_6) { /* "numpy.pxd":819 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_t_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_k_tuple_12), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L10; } __pyx_L10:; /* "numpy.pxd":822 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ __pyx_t_3 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L11; } /* "numpy.pxd":823 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ __pyx_t_5 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L11; } /* "numpy.pxd":824 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ __pyx_t_3 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; goto __pyx_L11; } /* "numpy.pxd":825 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ __pyx_t_5 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L11; } /* "numpy.pxd":826 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ __pyx_t_3 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; goto __pyx_L11; } /* "numpy.pxd":827 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ __pyx_t_5 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L11; } /* "numpy.pxd":828 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ __pyx_t_3 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; goto __pyx_L11; } /* "numpy.pxd":829 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ __pyx_t_5 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L11; } /* "numpy.pxd":830 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ __pyx_t_3 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; goto __pyx_L11; } /* "numpy.pxd":831 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ __pyx_t_5 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L11; } /* "numpy.pxd":832 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ __pyx_t_3 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; goto __pyx_L11; } /* "numpy.pxd":833 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ __pyx_t_5 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; goto __pyx_L11; } /* "numpy.pxd":834 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ __pyx_t_3 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; goto __pyx_L11; } /* "numpy.pxd":835 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ __pyx_t_5 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L11; } /* "numpy.pxd":836 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ __pyx_t_3 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L11; } /* "numpy.pxd":837 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ __pyx_t_5 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_5, Py_EQ); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L11; } /* "numpy.pxd":838 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_3 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L11; } /*else*/ { /* "numpy.pxd":840 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ __pyx_t_5 = PyNumber_Remainder(((PyObject *)__pyx_kp_u_7), __pyx_v_t); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_5)); __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_3)); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_5)); __Pyx_GIVEREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L11:; /* "numpy.pxd":841 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< * else: * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L9; } /*else*/ { /* "numpy.pxd":845 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ __pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_11; } __pyx_L9:; } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "numpy.pxd":846 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "numpy.pxd":961 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("set_array_base"); /* "numpy.pxd":963 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); if (__pyx_t_1) { /* "numpy.pxd":964 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< * else: * Py_INCREF(base) # important to do this before decref below! */ __pyx_v_baseptr = NULL; goto __pyx_L3; } /*else*/ { /* "numpy.pxd":966 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< * baseptr = <PyObject*>base * Py_XDECREF(arr.base) */ Py_INCREF(__pyx_v_base); /* "numpy.pxd":967 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base # <<<<<<<<<<<<<< * Py_XDECREF(arr.base) * arr.base = baseptr */ __pyx_v_baseptr = ((PyObject *)__pyx_v_base); } __pyx_L3:; /* "numpy.pxd":968 * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< * arr.base = baseptr * */ Py_XDECREF(__pyx_v_arr->base); /* "numpy.pxd":969 * baseptr = <PyObject*>base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ __pyx_v_arr->base = __pyx_v_baseptr; __Pyx_RefNannyFinishContext(); } /* "numpy.pxd":971 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base"); /* "numpy.pxd":972 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ __pyx_t_1 = (__pyx_v_arr->base == NULL); if (__pyx_t_1) { /* "numpy.pxd":973 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< * else: * return <object>arr.base */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; goto __pyx_L3; } /*else*/ { /* "numpy.pxd":975 * return None * else: * return <object>arr.base # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } __pyx_L3:; __pyx_r = Py_None; __Pyx_INCREF(Py_None); __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, __Pyx_NAMESTR("cconvolution_omp"), 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_u_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 1, 0, 0}, {&__pyx_kp_u_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 1, 0, 0}, {&__pyx_kp_u_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 1, 0, 0}, {&__pyx_kp_u_5, __pyx_k_5, sizeof(__pyx_k_5), 0, 1, 0, 0}, {&__pyx_kp_u_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 1, 0, 0}, {&__pyx_kp_u_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 1, 0, 0}, {&__pyx_n_s__DTYPE, __pyx_k__DTYPE, sizeof(__pyx_k__DTYPE), 0, 0, 1, 1}, {&__pyx_n_s__RuntimeError, __pyx_k__RuntimeError, sizeof(__pyx_k__RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, {&__pyx_n_s__cconvolution_omp, __pyx_k__cconvolution_omp, sizeof(__pyx_k__cconvolution_omp), 0, 0, 1, 1}, {&__pyx_n_s__convolution, __pyx_k__convolution, sizeof(__pyx_k__convolution), 0, 0, 1, 1}, {&__pyx_n_s__double, __pyx_k__double, sizeof(__pyx_k__double), 0, 0, 1, 1}, {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, {&__pyx_n_s__range, __pyx_k__range, sizeof(__pyx_k__range), 0, 0, 1, 1}, {&__pyx_n_s__xrange, __pyx_k__xrange, sizeof(__pyx_k__xrange), 0, 0, 1, 1}, {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { #if PY_MAJOR_VERSION >= 3 __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_builtin_xrange = __Pyx_GetName(__pyx_b, __pyx_n_s__xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_n_s__range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_n_s__RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants"); /* "numpy.pxd":211 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_k_tuple_2 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_2)); __Pyx_INCREF(((PyObject *)__pyx_kp_u_1)); PyTuple_SET_ITEM(__pyx_k_tuple_2, 0, ((PyObject *)__pyx_kp_u_1)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_1)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); /* "numpy.pxd":215 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_k_tuple_4 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_4)); __Pyx_INCREF(((PyObject *)__pyx_kp_u_3)); PyTuple_SET_ITEM(__pyx_k_tuple_4, 0, ((PyObject *)__pyx_kp_u_3)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_3)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); /* "numpy.pxd":253 * if ((descr.byteorder == '>' and little_endian) or * (descr.byteorder == '<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_k_tuple_6 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_6)); __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); PyTuple_SET_ITEM(__pyx_k_tuple_6, 0, ((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); /* "numpy.pxd":795 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == '>' and little_endian) or */ __pyx_k_tuple_9 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_9)); __Pyx_INCREF(((PyObject *)__pyx_kp_u_8)); PyTuple_SET_ITEM(__pyx_k_tuple_9, 0, ((PyObject *)__pyx_kp_u_8)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_8)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_9)); /* "numpy.pxd":799 * if ((child.byteorder == '>' and little_endian) or * (child.byteorder == '<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_k_tuple_10 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_10)); __Pyx_INCREF(((PyObject *)__pyx_kp_u_5)); PyTuple_SET_ITEM(__pyx_k_tuple_10, 0, ((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_5)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); /* "numpy.pxd":819 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_k_tuple_12 = PyTuple_New(1); if (unlikely(!__pyx_k_tuple_12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_k_tuple_12)); __Pyx_INCREF(((PyObject *)__pyx_kp_u_11)); PyTuple_SET_ITEM(__pyx_k_tuple_12, 0, ((PyObject *)__pyx_kp_u_11)); __Pyx_GIVEREF(((PyObject *)__pyx_kp_u_11)); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_12)); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is a quiet NaN. */ memset(&__PYX_NAN, 0xFF, sizeof(__PYX_NAN)); PyEval_InitThreads(); if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_15 = PyInt_FromLong(15); if (unlikely(!__pyx_int_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initcconvolution_omp(void); /*proto*/ PyMODINIT_FUNC initcconvolution_omp(void) #else PyMODINIT_FUNC PyInit_cconvolution_omp(void); /*proto*/ PyMODINIT_FUNC PyInit_cconvolution_omp(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_cconvolution_omp(void)"); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #ifdef __pyx_binding_PyCFunctionType_USED if (__pyx_binding_PyCFunctionType_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4(__Pyx_NAMESTR("cconvolution_omp"), __pyx_methods, 0, 0, PYTHON_API_VERSION); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; #if PY_MAJOR_VERSION < 3 Py_INCREF(__pyx_m); #endif __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_module_is_main_cconvolution_omp) { if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ /* "convolution_para.pyx":1 * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * cimport cython */ __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyObject_SetAttr(__pyx_m, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "convolution_para.pyx":6 * from cython.parallel import parallel, prange * * DTYPE = np.double # <<<<<<<<<<<<<< * ctypedef np.double_t DTYPE_t * */ __pyx_t_1 = __Pyx_GetName(__pyx_m, __pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetAttr(__pyx_t_1, __pyx_n_s__double); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyObject_SetAttr(__pyx_m, __pyx_n_s__DTYPE, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 6; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "convolution_para.pyx":10 * * @cython.boundscheck(False) * def convolution(np.ndarray[DTYPE_t, ndim=2, negative_indices=False] A): # <<<<<<<<<<<<<< * cdef int m = A.shape[0] * cdef int n = A.shape[1] */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_16cconvolution_omp_convolution, NULL, __pyx_n_s__cconvolution_omp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (PyObject_SetAttr(__pyx_m, __pyx_n_s__convolution, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "convolution_para.pyx":1 * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * cimport cython */ __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_2)); if (PyObject_SetAttr(__pyx_m, __pyx_n_s____test__, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; /* "numpy.pxd":971 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { __Pyx_AddTraceback("init cconvolution_omp", __pyx_clineno, __pyx_lineno, __pyx_filename); Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init cconvolution_omp"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* Runtime support code */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* CYTHON_REFNANNY */ static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { PyObject *result; result = PyObject_GetAttr(dict, name); if (!result) { if (dict != __pyx_b) { PyErr_Clear(); result = PyObject_GetAttr(__pyx_b, name); } if (!result) { PyErr_SetObject(PyExc_NameError, name); } } return result; } static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (!type) { PyErr_Format(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (Py_TYPE(obj) == type) return 1; } else { if (PyObject_TypeCheck(obj, type)) return 1; } PyErr_Format(PyExc_TypeError, "Argument '%s' has incorrect type (expected %s, got %s)", name, type->tp_name, Py_TYPE(obj)->tp_name); return 0; } static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; int is_complex; char enc_type; char new_packmode; char enc_packmode; } __Pyx_BufFmt_Context; static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case 'b': return "'char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'B': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'h': case 'i': case 'l': case 'q': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset; if (ctx->enc_type == 0) return 0; group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { /* special case -- treat as struct rather than complex number */ size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } __Pyx_BufFmt_RaiseExpected(ctx); return -1; } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %"PY_FORMAT_SIZE_T"d but %"PY_FORMAT_SIZE_T"d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; --ctx->enc_count; /* Consume from buffer string */ /* Done checking, move to next field, pushing or popping struct stack if needed */ while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; /* breaks both loops as ctx->enc_count == 0 */ } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; /* empty struct */ field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case 10: case 13: ++ts; break; case '<': if (!__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': /* substruct */ { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; } break; case '}': /* end of substruct; either repeat or move on */ ++ts; return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } /* fall through */ case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { /* Continue pooling same type */ ctx->enc_count += ctx->new_count; } else { /* New type */ if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; } ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; default: { int number = __Pyx_BufFmt_ParseNumber(&ts); if (number == -1) { /* First char was not a digit */ PyErr_Format(PyExc_ValueError, "Does not understand character buffer dtype format string ('%c')", *ts); return NULL; } ctx->new_count = (size_t)number; } } } } static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; } buf->buf = NULL; if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; if (buf->ndim != nd) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%"PY_FORMAT_SIZE_T"d byte%s) does not match size of '%s' (%"PY_FORMAT_SIZE_T"d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_ZeroBuffer(buf); return -1; } static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_Format(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { /* cause is unused */ Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); /* First, check the traceback argument, replacing None with NULL. */ if (tb == Py_None) { Py_DECREF(tb); tb = 0; } else if (tb != NULL && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } /* Next, replace a missing value with None */ if (value == NULL) { value = Py_None; Py_INCREF(value); } #if PY_VERSION_HEX < 0x02050000 if (!PyClass_Check(type)) #else if (!PyType_Check(type)) #endif { /* Raising an instance. The value should be a dummy. */ if (value != Py_None) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } /* Normalize to raise <class>, <instance> */ Py_DECREF(value); value = type; #if PY_VERSION_HEX < 0x02050000 if (PyInstance_Check(type)) { type = (PyObject*) ((PyInstanceObject*)type)->in_class; Py_INCREF(type); } else { type = 0; PyErr_SetString(PyExc_TypeError, "raise: exception must be an old-style class or instance"); goto raise_error; } #else type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } #endif } __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else /* Python 3+ */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (!PyExceptionClass_Check(type)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } if (cause) { PyObject *fixed_cause; if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } if (!value) { value = PyObject_CallObject(type, NULL); } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } } bad: return; } #endif static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %"PY_FORMAT_SIZE_T"d value%s to unpack", index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %"PY_FORMAT_SIZE_T"d)", expected); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { if (t == Py_None) { __Pyx_RaiseNoneNotIterableError(); } else if (PyTuple_GET_SIZE(t) < index) { __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); } else { __Pyx_RaiseTooManyValuesError(index); } } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); #endif if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); else { PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject* obj = view->obj; if (obj) { #if PY_VERSION_HEX >= 0x02060000 if (PyObject_CheckBuffer(obj)) {PyBuffer_Release(view); return;} #endif if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray_1__releasebuffer__(obj, view); Py_DECREF(obj); view->obj = NULL; } } #endif static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) { PyObject *py_import = 0; PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; py_import = __Pyx_GetAttrString(__pyx_b, "__import__"); if (!py_import) goto bad; if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; #if PY_VERSION_HEX >= 0x02050000 { PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); } #else if (level>0) { PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); goto bad; } module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, NULL); #endif bad: Py_XDECREF(empty_list); Py_XDECREF(py_import); Py_XDECREF(empty_dict); return module; } #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(a, a); case 3: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, a); case 4: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_absf(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(a, a); case 3: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, a); case 4: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_abs(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { const unsigned char neg_one = (unsigned char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned char" : "value too large to convert to unsigned char"); } return (unsigned char)-1; } return (unsigned char)val; } return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { const unsigned short neg_one = (unsigned short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned short" : "value too large to convert to unsigned short"); } return (unsigned short)-1; } return (unsigned short)val; } return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { const unsigned int neg_one = (unsigned int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(unsigned int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(unsigned int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to unsigned int" : "value too large to convert to unsigned int"); } return (unsigned int)-1; } return (unsigned int)val; } return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); } static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { const char neg_one = (char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to char" : "value too large to convert to char"); } return (char)-1; } return (char)val; } return (char)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { const short neg_one = (short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to short" : "value too large to convert to short"); } return (short)-1; } return (short)val; } return (short)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { const int neg_one = (int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to int" : "value too large to convert to int"); } return (int)-1; } return (int)val; } return (int)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { const signed char neg_one = (signed char)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed char) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed char)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed char" : "value too large to convert to signed char"); } return (signed char)-1; } return (signed char)val; } return (signed char)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { const signed short neg_one = (signed short)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed short) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed short)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed short" : "value too large to convert to signed short"); } return (signed short)-1; } return (signed short)val; } return (signed short)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { const signed int neg_one = (signed int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(signed int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(signed int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to signed int" : "value too large to convert to signed int"); } return (signed int)-1; } return (signed int)val; } return (signed int)__Pyx_PyInt_AsSignedLong(x); } static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { const int neg_one = (int)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (sizeof(int) < sizeof(long)) { long val = __Pyx_PyInt_AsLong(x); if (unlikely(val != (long)(int)val)) { if (!unlikely(val == -1 && PyErr_Occurred())) { PyErr_SetString(PyExc_OverflowError, (is_unsigned && unlikely(val < 0)) ? "can't convert negative value to int" : "value too large to convert to int"); } return (int)-1; } return (int)val; } return (int)__Pyx_PyInt_AsLong(x); } static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { const unsigned long neg_one = (unsigned long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); return (unsigned long)-1; } return (unsigned long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned long"); return (unsigned long)-1; } return (unsigned long)PyLong_AsUnsignedLong(x); } else { return (unsigned long)PyLong_AsLong(x); } } else { unsigned long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (unsigned long)-1; val = __Pyx_PyInt_AsUnsignedLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); return (unsigned PY_LONG_LONG)-1; } return (unsigned PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned PY_LONG_LONG"); return (unsigned PY_LONG_LONG)-1; } return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); } } else { unsigned PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (unsigned PY_LONG_LONG)-1; val = __Pyx_PyInt_AsUnsignedLongLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { const long neg_one = (long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long)-1; } return (long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long)-1; } return (long)PyLong_AsUnsignedLong(x); } else { return (long)PyLong_AsLong(x); } } else { long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (long)-1; val = __Pyx_PyInt_AsLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); return (PY_LONG_LONG)-1; } return (PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to PY_LONG_LONG"); return (PY_LONG_LONG)-1; } return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { return (PY_LONG_LONG)PyLong_AsLongLong(x); } } else { PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1; val = __Pyx_PyInt_AsLongLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { const signed long neg_one = (signed long)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); return (signed long)-1; } return (signed long)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed long"); return (signed long)-1; } return (signed long)PyLong_AsUnsignedLong(x); } else { return (signed long)PyLong_AsLong(x); } } else { signed long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (signed long)-1; val = __Pyx_PyInt_AsSignedLong(tmp); Py_DECREF(tmp); return val; } } static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_VERSION_HEX < 0x03000000 if (likely(PyInt_Check(x))) { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); return (signed PY_LONG_LONG)-1; } return (signed PY_LONG_LONG)val; } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { if (unlikely(Py_SIZE(x) < 0)) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to signed PY_LONG_LONG"); return (signed PY_LONG_LONG)-1; } return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); } else { return (signed PY_LONG_LONG)PyLong_AsLongLong(x); } } else { signed PY_LONG_LONG val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (signed PY_LONG_LONG)-1; val = __Pyx_PyInt_AsSignedLongLong(tmp); Py_DECREF(tmp); return val; } } static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); #if PY_VERSION_HEX < 0x02050000 return PyErr_Warn(NULL, message); #else return PyErr_WarnEx(NULL, message, 1); #endif } return 0; } #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; #if PY_MAJOR_VERSION < 3 py_name = PyString_FromString(class_name); #else py_name = PyUnicode_FromString(class_name); #endif if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%s.%s is not a type object", module_name, class_name); goto bad; } if (!strict && ((PyTypeObject *)result)->tp_basicsize > (Py_ssize_t)size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); #if PY_VERSION_HEX < 0x02050000 if (PyErr_Warn(NULL, warning) < 0) goto bad; #else if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; #endif } else if (((PyTypeObject *)result)->tp_basicsize != (Py_ssize_t)size) { PyErr_Format(PyExc_ValueError, "%s.%s has the wrong size, try recompiling", module_name, class_name); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; #if PY_MAJOR_VERSION < 3 py_name = PyString_FromString(name); #else py_name = PyUnicode_FromString(name); #endif if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, int __pyx_lineno, const char *__pyx_filename) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(__pyx_filename); #else py_srcfile = PyUnicode_FromString(__pyx_filename); #endif if (!py_srcfile) goto bad; if (__pyx_clineno) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); } static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else /* Python 3+ has unicode identifiers */ if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } /* Type Conversion Functions */ static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; #if PY_VERSION_HEX < 0x03000000 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; #if PY_VERSION_HEX < 0x03000000 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif if (res) { #if PY_VERSION_HEX < 0x03000000 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%s__ returned non-%s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { #if PY_VERSION_HEX < 0x02050000 if (ival <= LONG_MAX) return PyInt_FromLong((long)ival); else { unsigned char *bytes = (unsigned char *) &ival; int one = 1; int little = (int)*(unsigned char*)&one; return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); } #else return PyInt_FromSize_t(ival); #endif } static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) { return (size_t)-1; } else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to size_t"); return (size_t)-1; } return (size_t)val; } #endif /* Py_PYTHON_H */
sp.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB SP code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// //--------------------------------------------------------------------- // program SP //--------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #endif #include "header.h" #include "print_results.h" #include "read_memory.h" /* common /global/ */ int grid_points[3], nx2, ny2, nz2; logical timeron; /* common /constants/ */ double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3, dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4, dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt, ce[5][13], dxmax, dymax, dzmax, xxcon1, xxcon2, xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1, dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4, yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1, zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1, dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1, dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2, c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt, dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1, c2dtty1, c2dttz1, comz1, comz4, comz5, comz6, c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16; /* common /fields/ */ double u [KMAX][JMAXP+1][IMAXP+1][5]; double us [KMAX][JMAXP+1][IMAXP+1]; double vs [KMAX][JMAXP+1][IMAXP+1]; double ws [KMAX][JMAXP+1][IMAXP+1]; double qs [KMAX][JMAXP+1][IMAXP+1]; double rho_i [KMAX][JMAXP+1][IMAXP+1]; double speed [KMAX][JMAXP+1][IMAXP+1]; double square [KMAX][JMAXP+1][IMAXP+1]; double rhs [KMAX][JMAXP+1][IMAXP+1][5]; double forcing[KMAX][JMAXP+1][IMAXP+1][5]; /* common /work_1d/ */ double cv [PROBLEM_SIZE]; double rhon[PROBLEM_SIZE]; double rhos[PROBLEM_SIZE]; double rhoq[PROBLEM_SIZE]; double cuf [PROBLEM_SIZE]; double q [PROBLEM_SIZE]; double ue [PROBLEM_SIZE][5]; double buf[PROBLEM_SIZE][5]; #pragma omp threadprivate(cv,rhon,rhos,rhoq,cuf,q,ue,buf) /* common /work_lhs/ */ double lhs [IMAXP+1][IMAXP+1][5]; double lhsp[IMAXP+1][IMAXP+1][5]; double lhsm[IMAXP+1][IMAXP+1][5]; #pragma omp threadprivate(lhs,lhsp,lhsm) //kai int k1=0,k2=0,k3=0,k4=0,k5=0,k6=0,k7=0,k8=2,k9=0,k10=0, k11=0, k12=0, k13=0, k14=0, k15=0, k16=0; int main(int argc, char *argv[]) { pid = atoi(argv[1]); printf("pid = %d\n",pid); /* //kai // crucial_data(grid_points, "int", 3); // crucial_data(ce,"double", 13*5); crucial_data(u, "double", KMAX*(JMAXP+1)*(IMAXP+1)*5); crucial_data(us, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(vs, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(ws, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(qs, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(rho_i, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(speed, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(square, "double", KMAX*(JMAXP+1)*(IMAXP+1)); //crucial_data(forcing, "double", KMAX*(JMAXP+1)*(IMAXP+1)*5); crucial_data(rhs, "double", KMAX*(JMAXP+1)*(IMAXP+1)*5); crucial_data(cv, "double", PROBLEM_SIZE); crucial_data(rhon, "double", PROBLEM_SIZE); crucial_data(rhos, "double", PROBLEM_SIZE); crucial_data(rhoq, "double", PROBLEM_SIZE); //crucial_data(cuf, "double", PROBLEM_SIZE); //crucial_data(q, "double", PROBLEM_SIZE); //crucial_data(ue, "double", (PROBLEM_SIZE)*5); //crucial_data(buf, "double", (PROBLEM_SIZE)*5); crucial_data(lhs, "double", (IMAXP+1)*(IMAXP+1)*5); crucial_data(lhsp, "double", (IMAXP+1)*(IMAXP+1)*5); crucial_data(lhsm, "double", (IMAXP+1)*(IMAXP+1)*5); //int k1,k2,k3,k4,k5,k6,k7,k8,k9,k10, k11; consistent_data(&k1, "int", 1); consistent_data(&k2, "int", 1); consistent_data(&k3, "int", 1); consistent_data(&k4, "int", 1); consistent_data(&k5, "int", 1); consistent_data(&k6, "int", 1); consistent_data(&k7, "int", 1); consistent_data(&k8, "int", 1); consistent_data(&k9, "int", 1); consistent_data(&k10, "int", 1); consistent_data(&k11, "int", 1); consistent_data(&k12, "int", 1); consistent_data(&k13, "int", 1); consistent_data(&k14, "int", 1); consistent_data(&k15, "int", 1); consistent_data(&k16, "int", 1); */ int i, niter, step, n3; double mflops, t, tmax, trecs[t_last+1]; logical verified; char Class; char *t_names[t_last+1]; //--------------------------------------------------------------------- // Read input file (if it exists), else take // defaults from parameters //--------------------------------------------------------------------- FILE *fp; if ((fp = fopen("timer.flag", "r")) != NULL) { timeron = true; t_names[t_total] = "total"; t_names[t_rhsx] = "rhsx"; t_names[t_rhsy] = "rhsy"; t_names[t_rhsz] = "rhsz"; t_names[t_rhs] = "rhs"; t_names[t_xsolve] = "xsolve"; t_names[t_ysolve] = "ysolve"; t_names[t_zsolve] = "zsolve"; t_names[t_rdis1] = "redist1"; t_names[t_rdis2] = "redist2"; t_names[t_tzetar] = "tzetar"; t_names[t_ninvr] = "ninvr"; t_names[t_pinvr] = "pinvr"; t_names[t_txinvr] = "txinvr"; t_names[t_add] = "add"; fclose(fp); } else { timeron = false; } printf("\n\n NAS Parallel Benchmarks (NPB3.3-OMP-C) - SP Benchmark\n\n"); if ((fp = fopen("inputsp.data", "r")) != NULL) { int result; printf(" Reading from input file inputsp.data\n"); result = fscanf(fp, "%d", &niter); while (fgetc(fp) != '\n'); result = fscanf(fp, "%lf", &dt); while (fgetc(fp) != '\n'); result = fscanf(fp, "%d%d%d", &grid_points[0], &grid_points[1], &grid_points[2]); fclose(fp); } else { printf(" No input file inputsp.data. Using compiled defaults\n"); niter = NITER_DEFAULT; dt = DT_DEFAULT; grid_points[0] = PROBLEM_SIZE; grid_points[1] = PROBLEM_SIZE; grid_points[2] = PROBLEM_SIZE; } printf(" Size: %4dx%4dx%4d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Iterations: %4d dt: %11.7f\n", niter, dt); printf(" Number of available threads: %5d\n", omp_get_max_threads()); printf("\n"); if ((grid_points[0] > IMAX) || (grid_points[1] > JMAX) || (grid_points[2] > KMAX) ) { printf(" %d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Problem size too big for compiled array sizes\n"); return 0; } nx2 = grid_points[0] - 2; ny2 = grid_points[1] - 2; nz2 = grid_points[2] - 2; set_constants(); for (i = 1; i <= t_last; i++) { timer_clear(i); } exact_rhs(); initialize(); //--------------------------------------------------------------------- // do one time step to touch all code, and reinitialize //--------------------------------------------------------------------- adi(); initialize(); for (i = 1; i <= t_last; i++) { timer_clear(i); } timer_start(1); //kai // consistent_data(&step, "int", 1); // flush_whole_cache(); // start_crash(); addr[count_addr++] = &u; addr[count_addr++] = &us; addr[count_addr++] = &vs; addr[count_addr++] = &ws; addr[count_addr++] = &qs; addr[count_addr++] = &rho_i; addr[count_addr++] = &speed; addr[count_addr++] = &square; addr[count_addr++] = &rhs; addr[count_addr++] = &cv; addr[count_addr++] = &rhon; addr[count_addr++] = &rhos; addr[count_addr++] = &rhoq; addr[count_addr++] = &lhs; addr[count_addr++] = &lhsp; addr[count_addr++] = &lhsm; addr[count_addr++] = &k1; addr[count_addr++] = &k2; addr[count_addr++] = &k3; addr[count_addr++] = &k4; addr[count_addr++] = &k5; addr[count_addr++] = &k6; addr[count_addr++] = &k7; addr[count_addr++] = &k8; addr[count_addr++] = &k9; addr[count_addr++] = &k10; addr[count_addr++] = &k11; addr[count_addr++] = &k12; addr[count_addr++] = &k13; addr[count_addr++] = &k14; addr[count_addr++] = &k15; addr[count_addr++] = &k16; addr[count_addr++] = &step; ReadVarriable(addr,count_addr); printf("step = %d\n", step); printf("k1 = %d\n", k1); printf("k2 = %d\n", k2); printf("k3 = %d\n", k3); printf("k4 = %d\n", k4); printf("k5 = %d\n", k5); printf("k6 = %d\n", k6); printf("k7 = %d\n", k7); printf("k8 = %d\n", k8); printf("k9 = %d\n", k9); printf("k10 = %d\n", k10); printf("k11 = %d\n", k11); printf("k12 = %d\n", k12); printf("k13 = %d\n", k13); printf("k14 = %d\n", k14); printf("k15 = %d\n", k15); printf("k16 = %d\n", k16); for (; step <= niter+1; step++) { if ((step % 20) == 0 || step == 1) { printf(" Time step %4d\n", step); } adi(); k1=0;k2=0;k3=0;k4=0;k5=0;k6=0;k7=0;k8=2;k9=0;k10=0; k11=0; k12=0; k13=0; k14=0; k15=0; k16=0; } //kai // end_crash(); timer_stop(1); tmax = timer_read(1); verify(niter, &Class, &verified); if (tmax != 0.0) { n3 = grid_points[0]*grid_points[1]*grid_points[2]; t = (grid_points[0]+grid_points[1]+grid_points[2])/3.0; mflops = (881.174 * (double)n3 - 4683.91 * (t * t) + 11484.5 * t - 19272.4) * (double)niter / (tmax*1000000.0); } else { mflops = 0.0; } FILE *file; char result_file[MAX_FILE_PATH] = "/home/cc/cctlib/tests/recompute_result.out.jie"; sprintf(result_file + strlen(result_file), "%d", pid); file = fopen(result_file,"w"); if(verified) { fprintf(file,"SUCCESS,%d\n", step); } else{ fprintf(file,"UNSUCCESS,%d\n", step); } fclose(file); print_results("SP", Class, grid_points[0], grid_points[1], grid_points[2], niter, tmax, mflops, " floating point", verified, NPBVERSION,COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, "(none)"); //--------------------------------------------------------------------- // More timers //--------------------------------------------------------------------- if (timeron) { for (i = 1; i <= t_last; i++) { trecs[i] = timer_read(i); } if (tmax == 0.0) tmax = 1.0; printf(" SECTION Time (secs)\n"); for (i = 1; i <= t_last; i++) { printf(" %-8s:%9.3f (%6.2f%%)\n", t_names[i], trecs[i], trecs[i]*100./tmax); if (i == t_rhs) { t = trecs[t_rhsx] + trecs[t_rhsy] + trecs[t_rhsz]; printf(" --> %8s:%9.3f (%6.2f%%)\n", "sub-rhs", t, t*100./tmax); t = trecs[t_rhs] - t; printf(" --> %8s:%9.3f (%6.2f%%)\n", "rest-rhs", t, t*100./tmax); } else if (i == t_zsolve) { t = trecs[t_zsolve] - trecs[t_rdis1] - trecs[t_rdis2]; printf(" --> %8s:%9.3f (%6.2f%%)\n", "sub-zsol", t, t*100./tmax); } else if (i == t_rdis2) { t = trecs[t_rdis1] + trecs[t_rdis2]; printf(" --> %8s:%9.3f (%6.2f%%)\n", "redist", t, t*100./tmax); } } } return 0; }
omp_monte_carlo_pi.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <time.h> int in_circle(float x, float y) { return (x - 0.5f) * (x - 0.5f) + (y - 0.5f) * (y - 0.5f) < 0.5f * 0.5f; } float monte_carlo_pi(size_t N) { int i, tid, nthreads; unsigned int seed; float x, y; float start, end; size_t N_circle = 0; size_t N_total_rounds = 0; start = omp_get_wtime(); #pragma omp parallel shared(N) private(i, tid, nthreads, seed, x, y) reduction(+: N_circle, N_total_rounds) { tid = omp_get_thread_num(); nthreads = omp_get_num_threads(); seed = tid * (unsigned int) time(NULL); #pragma omp parallel for reduction(+: N_circle, N_total_rounds) for (i = 0; i < (N / nthreads + N % nthreads); ++i) { x = (float)(rand_r(&seed)) / RAND_MAX; y = (float)(rand_r(&seed)) / RAND_MAX; if (in_circle(x, y)) { N_circle++; } N_total_rounds++; // printf("tid = %d i = %d\n", tid, i); } } end = omp_get_wtime(); printf("N = %zu round of Monte-Carlo, elapsed time = %f ms\n", N, (end - start) * 1000); return ((float)(N_circle) / N) / (0.5f * 0.5f); } int main() { float pi; const size_t N = 100000000; pi = monte_carlo_pi(N); printf("Calculated PI = %f\n", pi); printf("True PI = %f\n", M_PI); printf("Diff = %f\n", fabs(pi - M_PI)); return 0; }
lock-1.c
#include <omp.h> #include <stdlib.h> int main (void) { int l = 0; omp_nest_lock_t lock; omp_init_nest_lock (&lock); if (omp_test_nest_lock (&lock) != 1) abort (); if (omp_test_nest_lock (&lock) != 2) abort (); #pragma omp parallel if (0) reduction (+:l) { /* In OpenMP 2.5 this was supposed to return 3, but in OpenMP 3.0 the parallel region has a different task and omp_*_lock_t are owned by tasks, not by threads. */ if (omp_test_nest_lock (&lock) != 0) l++; } if (l) abort (); if (omp_test_nest_lock (&lock) != 3) abort (); omp_unset_nest_lock (&lock); omp_unset_nest_lock (&lock); omp_unset_nest_lock (&lock); omp_destroy_nest_lock (&lock); return 0; }
polybench.c
// RUN: mlir-clang %s polybench_alloc_data %stdinclude | FileCheck %s // XFAIL: * /** * This version is stamped on May 10, 2016 * * Contact: * Louis-Noel Pouchet <pouchet.ohio-state.edu> * Tomofumi Yuki <tomofumi.yuki.fr> * * Web address: http://polybench.sourceforge.net */ /* polybench.c: this file is part of PolyBench/C */ #include <assert.h> #include <math.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/resource.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #ifdef _OPENMP #include <omp.h> #endif #if defined(POLYBENCH_PAPI) #undef POLYBENCH_PAPI #include "polybench.h" #define POLYBENCH_PAPI #else #include "polybench.h" #endif /* By default, collect PAPI counters on thread 0. */ #ifndef POLYBENCH_THREAD_MONITOR #define POLYBENCH_THREAD_MONITOR 0 #endif /* Total LLC cache size. By default 32+MB.. */ #ifndef POLYBENCH_CACHE_SIZE_KB #define POLYBENCH_CACHE_SIZE_KB 32770 #endif int polybench_papi_counters_threadid = POLYBENCH_THREAD_MONITOR; double polybench_program_total_flops = 0; #ifdef POLYBENCH_PAPI #include <papi.h> #define POLYBENCH_MAX_NB_PAPI_COUNTERS 96 char *_polybench_papi_eventlist[] = { #include "papi_counters.list" NULL}; int polybench_papi_eventset; int polybench_papi_eventlist[POLYBENCH_MAX_NB_PAPI_COUNTERS]; long_long polybench_papi_values[POLYBENCH_MAX_NB_PAPI_COUNTERS]; #endif /* * Allocation table, to enable inter-array padding. All data allocated * with polybench_alloc_data should be freed with polybench_free_data. * */ #define NB_INITIAL_TABLE_ENTRIES 512 struct polybench_data_ptrs { void **user_view; void **real_ptr; int nb_entries; int nb_avail_entries; }; static struct polybench_data_ptrs *_polybench_alloc_table = NULL; static size_t polybench_inter_array_padding_sz = 0; /* Timer code (gettimeofday). */ double polybench_t_start, polybench_t_end; /* Timer code (RDTSC). */ unsigned long long int polybench_c_start, polybench_c_end; static double rtclock() { #if defined(POLYBENCH_TIME) || defined(POLYBENCH_GFLOPS) struct timeval Tp; int stat; stat = gettimeofday(&Tp, NULL); if (stat != 0) printf("Error return from gettimeofday: %d", stat); return (Tp.tv_sec + Tp.tv_usec * 1.0e-6); #else return 0; #endif } #ifdef POLYBENCH_CYCLE_ACCURATE_TIMER static unsigned long long int rdtsc() { unsigned long long int ret = 0; unsigned int cycles_lo; unsigned int cycles_hi; __asm__ volatile("RDTSC" : "=a"(cycles_lo), "=d"(cycles_hi)); ret = (unsigned long long int)cycles_hi << 32 | cycles_lo; return ret; } #endif void polybench_flush_cache() { int cs = POLYBENCH_CACHE_SIZE_KB * 1024 / sizeof(double); double *flush = (double *)calloc(cs, sizeof(double)); int i; double tmp = 0.0; #ifdef _OPENMP #pragma omp parallel for reduction(+ : tmp) private(i) #endif for (i = 0; i < cs; i++) tmp += flush[i]; assert(tmp <= 10.0); free(flush); } #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER void polybench_linux_fifo_scheduler() { /* Use FIFO scheduler to limit OS interference. Program must be run as root, and this works only for Linux kernels. */ struct sched_param schedParam; schedParam.sched_priority = sched_get_priority_max(SCHED_FIFO); sched_setscheduler(0, SCHED_FIFO, &schedParam); } void polybench_linux_standard_scheduler() { /* Restore to standard scheduler policy. */ struct sched_param schedParam; schedParam.sched_priority = sched_get_priority_max(SCHED_OTHER); sched_setscheduler(0, SCHED_OTHER, &schedParam); } #endif #ifdef POLYBENCH_PAPI static void test_fail(char *file, int line, char *call, int retval) { char buf[128]; memset(buf, '\0', sizeof(buf)); if (retval != 0) fprintf(stdout, "%-40s FAILED\nLine # %d\n", file, line); else { fprintf(stdout, "%-40s SKIPPED\n", file); fprintf(stdout, "Line # %d\n", line); } if (retval == PAPI_ESYS) { sprintf(buf, "System error in %s", call); perror(buf); } else if (retval > 0) fprintf(stdout, "Error: %s\n", call); else if (retval == 0) fprintf(stdout, "Error: %s\n", call); else { char errstring[PAPI_MAX_STR_LEN]; // PAPI 5.4.3 has changed the API for PAPI_perror. #if defined(PAPI_VERSION) && ((PAPI_VERSION_MAJOR(PAPI_VERSION) == 5 && \ PAPI_VERSION_MINOR(PAPI_VERSION) >= 4) || \ PAPI_VERSION_MAJOR(PAPI_VERSION) > 5) fprintf(stdout, "Error in %s: %s\n", call, PAPI_strerror(retval)); #else PAPI_perror(retval, errstring, PAPI_MAX_STR_LEN); fprintf(stdout, "Error in %s: %s\n", call, errstring); #endif } fprintf(stdout, "\n"); if (PAPI_is_initialized()) PAPI_shutdown(); exit(1); } void polybench_papi_init() { #ifdef _OPENMP #pragma omp parallel { #pragma omp master { if (omp_get_max_threads() < polybench_papi_counters_threadid) polybench_papi_counters_threadid = omp_get_max_threads() - 1; } #pragma omp barrier if (omp_get_thread_num() == polybench_papi_counters_threadid) { #endif int retval; polybench_papi_eventset = PAPI_NULL; if ((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) test_fail(__FILE__, __LINE__, "PAPI_library_init", retval); if ((retval = PAPI_create_eventset(&polybench_papi_eventset)) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_create_eventset", retval); int k; for (k = 0; _polybench_papi_eventlist[k]; ++k) { if ((retval = PAPI_event_name_to_code( _polybench_papi_eventlist[k], &(polybench_papi_eventlist[k]))) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_event_name_to_code", retval); } polybench_papi_eventlist[k] = 0; #ifdef _OPENMP } } #pragma omp barrier #endif } void polybench_papi_close() { #ifdef _OPENMP #pragma omp parallel { if (omp_get_thread_num() == polybench_papi_counters_threadid) { #endif int retval; if ((retval = PAPI_destroy_eventset(&polybench_papi_eventset)) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_destroy_eventset", retval); if (PAPI_is_initialized()) PAPI_shutdown(); #ifdef _OPENMP } } #pragma omp barrier #endif } int polybench_papi_start_counter(int evid) { #ifndef POLYBENCH_NO_FLUSH_CACHE polybench_flush_cache(); #endif #ifdef _OPENMP #pragma omp parallel { if (omp_get_thread_num() == polybench_papi_counters_threadid) { #endif int retval = 1; char descr[PAPI_MAX_STR_LEN]; PAPI_event_info_t evinfo; PAPI_event_code_to_name(polybench_papi_eventlist[evid], descr); if (PAPI_add_event(polybench_papi_eventset, polybench_papi_eventlist[evid]) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_add_event", 1); if (PAPI_get_event_info(polybench_papi_eventlist[evid], &evinfo) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_get_event_info", retval); if ((retval = PAPI_start(polybench_papi_eventset)) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_start", retval); #ifdef _OPENMP } } #pragma omp barrier #endif return 0; } void polybench_papi_stop_counter(int evid) { #ifdef _OPENMP #pragma omp parallel { if (omp_get_thread_num() == polybench_papi_counters_threadid) { #endif int retval; long_long values[1]; values[0] = 0; if ((retval = PAPI_read(polybench_papi_eventset, &values[0])) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_read", retval); if ((retval = PAPI_stop(polybench_papi_eventset, NULL)) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_stop", retval); polybench_papi_values[evid] = values[0]; if ((retval = PAPI_remove_event(polybench_papi_eventset, polybench_papi_eventlist[evid])) != PAPI_OK) test_fail(__FILE__, __LINE__, "PAPI_remove_event", retval); #ifdef _OPENMP } } #pragma omp barrier #endif } void polybench_papi_print() { int verbose = 0; #ifdef _OPENMP #pragma omp parallel { if (omp_get_thread_num() == polybench_papi_counters_threadid) { #ifdef POLYBENCH_PAPI_VERBOSE verbose = 1; #endif if (verbose) printf("On thread %d:\n", polybench_papi_counters_threadid); #endif int evid; for (evid = 0; polybench_papi_eventlist[evid] != 0; ++evid) { if (verbose) printf("%s=", _polybench_papi_eventlist[evid]); printf("%llu ", polybench_papi_values[evid]); if (verbose) printf("\n"); } printf("\n"); #ifdef _OPENMP } } #pragma omp barrier #endif } #endif /* ! POLYBENCH_PAPI */ void polybench_prepare_instruments() { #ifndef POLYBENCH_NO_FLUSH_CACHE polybench_flush_cache(); #endif #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER polybench_linux_fifo_scheduler(); #endif } void polybench_timer_start() { polybench_prepare_instruments(); #ifndef POLYBENCH_CYCLE_ACCURATE_TIMER polybench_t_start = rtclock(); #else polybench_c_start = rdtsc(); #endif } void polybench_timer_stop() { #ifndef POLYBENCH_CYCLE_ACCURATE_TIMER polybench_t_end = rtclock(); #else polybench_c_end = rdtsc(); #endif #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER polybench_linux_standard_scheduler(); #endif } void polybench_timer_print() { #ifdef POLYBENCH_GFLOPS if (polybench_program_total_flops == 0) { printf("[PolyBench][WARNING] Program flops not defined, use " "polybench_set_program_flops(value)\n"); printf("%0.6lf\n", polybench_t_end - polybench_t_start); } else printf("%0.2lf\n", (polybench_program_total_flops / (double)(polybench_t_end - polybench_t_start)) / 1000000000); #else #ifndef POLYBENCH_CYCLE_ACCURATE_TIMER printf("%0.6f\n", polybench_t_end - polybench_t_start); #else printf("%Ld\n", polybench_c_end - polybench_c_start); #endif #endif } /* * These functions are used only if the user defines a specific * inter-array padding. It grows a global structure, * _polybench_alloc_table, which keeps track of the data allocated via * polybench_alloc_data (on which inter-array padding is applied), so * that the original, non-shifted pointer can be recovered when * calling polybench_free_data. * */ #ifdef POLYBENCH_ENABLE_INTARRAY_PAD static void grow_alloc_table() { if (_polybench_alloc_table == NULL || (_polybench_alloc_table->nb_entries % NB_INITIAL_TABLE_ENTRIES) != 0 || _polybench_alloc_table->nb_avail_entries != 0) { /* Should never happen if the API is properly used. */ fprintf(stderr, "[ERROR] Inter-array padding requires to use " "polybench_alloc_data and polybench_free_data\n"); exit(1); } size_t sz = _polybench_alloc_table->nb_entries; sz += NB_INITIAL_TABLE_ENTRIES; _polybench_alloc_table->user_view = realloc(_polybench_alloc_table->user_view, sz * sizeof(void *)); assert(_polybench_alloc_table->user_view != NULL); _polybench_alloc_table->real_ptr = realloc(_polybench_alloc_table->real_ptr, sz * sizeof(void *)); assert(_polybench_alloc_table->real_ptr != NULL); _polybench_alloc_table->nb_avail_entries = NB_INITIAL_TABLE_ENTRIES; } static void *register_padded_pointer(void *ptr, size_t orig_sz, size_t padded_sz) { if (_polybench_alloc_table == NULL) { fprintf(stderr, "[ERROR] Inter-array padding requires to use " "polybench_alloc_data and polybench_free_data\n"); exit(1); } if (_polybench_alloc_table->nb_avail_entries == 0) grow_alloc_table(); int id = _polybench_alloc_table->nb_entries++; _polybench_alloc_table->real_ptr[id] = ptr; _polybench_alloc_table->user_view[id] = ptr + (padded_sz - orig_sz); return _polybench_alloc_table->user_view[id]; } static void free_data_from_alloc_table(void *ptr) { if (_polybench_alloc_table != NULL && _polybench_alloc_table->nb_entries > 0) { int i; for (i = 0; i < _polybench_alloc_table->nb_entries; ++i) if (_polybench_alloc_table->user_view[i] == ptr || _polybench_alloc_table->real_ptr[i] == ptr) break; if (i != _polybench_alloc_table->nb_entries) { free(_polybench_alloc_table->real_ptr[i]); for (; i < _polybench_alloc_table->nb_entries - 1; ++i) { _polybench_alloc_table->user_view[i] = _polybench_alloc_table->user_view[i + 1]; _polybench_alloc_table->real_ptr[i] = _polybench_alloc_table->real_ptr[i + 1]; } _polybench_alloc_table->nb_entries--; _polybench_alloc_table->nb_avail_entries++; if (_polybench_alloc_table->nb_entries == 0) { free(_polybench_alloc_table->user_view); free(_polybench_alloc_table->real_ptr); free(_polybench_alloc_table); _polybench_alloc_table = NULL; } } } } static void check_alloc_table_state() { if (_polybench_alloc_table == NULL) { _polybench_alloc_table = (struct polybench_data_ptrs *)malloc( sizeof(struct polybench_data_ptrs)); assert(_polybench_alloc_table != NULL); _polybench_alloc_table->user_view = (void **)malloc(sizeof(void *) * NB_INITIAL_TABLE_ENTRIES); assert(_polybench_alloc_table->user_view != NULL); _polybench_alloc_table->real_ptr = (void **)malloc(sizeof(void *) * NB_INITIAL_TABLE_ENTRIES); assert(_polybench_alloc_table->real_ptr != NULL); _polybench_alloc_table->nb_entries = 0; _polybench_alloc_table->nb_avail_entries = NB_INITIAL_TABLE_ENTRIES; } } #endif // !POLYBENCH_ENABLE_INTARRAY_PAD static void *xmalloc(size_t alloc_sz) { void *ret = NULL; /* By default, post-pad the arrays. Safe behavior, but likely useless. */ polybench_inter_array_padding_sz += POLYBENCH_INTER_ARRAY_PADDING_FACTOR; size_t padded_sz = alloc_sz + polybench_inter_array_padding_sz; int err = posix_memalign(&ret, 4096, padded_sz); if (!ret || err) { fprintf(stderr, "[PolyBench] posix_memalign: cannot allocate memory"); exit(1); } /* Safeguard: this is invoked only if polybench.c has been compiled with inter-array padding support from polybench.h. If so, move the starting address of the allocation and return it to the user. The original pointer is registered in an allocation table internal to polybench.c. Data must then be freed using polybench_free_data, which will inspect the allocation table to free the original pointer.*/ #ifdef POLYBENCH_ENABLE_INTARRAY_PAD /* This moves the 'ret' pointer by (padded_sz - alloc_sz) positions, and registers it in the lookup table for future free using polybench_free_data. */ ret = register_padded_pointer(ret, alloc_sz, padded_sz); #endif return ret; } // void polybench_free_data(void* ptr) // { // #ifdef POLYBENCH_ENABLE_INTARRAY_PAD // free_data_from_alloc_table (ptr); // #else // free (ptr); // #endif // } // void* polybench_alloc_data(unsigned long long int n, int elt_size) // { // return malloc(n*elt_size); // #ifdef POLYBENCH_ENABLE_INTARRAY_PAD // check_alloc_table_state (); // #endif // /// FIXME: detect overflow! // size_t val = n; // val *= elt_size; // void* ret = xmalloc (val); // return ret; // } // CHECK: module { // CHECK-NEXT: }
cherk.c
#include "blas.h" #include "error.h" #include <stdio.h> #include "handle.h" #include "config.h" #include "cherk.fatbin.c" static inline size_t min(size_t a, size_t b) { return (a < b) ? a : b; } static inline size_t max(size_t a, size_t b) { return (a > b) ? a : b; } static inline CUresult cuMemcpyHtoD2DAsync(CUdeviceptr A, size_t lda, size_t ai, size_t aj, const void * B, size_t ldb, size_t bi, size_t bj, size_t m, size_t n, size_t elemSize, CUstream stream) { CUDA_MEMCPY2D copy = { bi * elemSize, bj, CU_MEMORYTYPE_HOST, B, 0, 0, ldb * elemSize, ai * elemSize, aj, CU_MEMORYTYPE_DEVICE, NULL, A, 0, lda * elemSize, m * elemSize, n }; return cuMemcpy2DAsync(&copy, stream); } static inline CUresult cuMemcpyDtoH2DAsync(void * A, size_t lda, size_t ai, size_t aj, CUdeviceptr B, size_t ldb, size_t bi, size_t bj, size_t m, size_t n, size_t elemSize, CUstream stream) { CUDA_MEMCPY2D copy = { bi * elemSize, bj, CU_MEMORYTYPE_DEVICE, NULL, B, 0, ldb * elemSize, ai * elemSize, aj, CU_MEMORYTYPE_HOST, A, 0, 0, lda * elemSize, m * elemSize, n }; return cuMemcpy2DAsync(&copy, stream); } static const float zero = 0.0f; static const float one = 1.0f; static const float complex czero = 0.0f + 0.0f * I; void cherk(CBlasUplo uplo, CBlasTranspose trans, size_t n, size_t k, float alpha, const float complex * restrict A, size_t lda, float beta, float complex * restrict C, size_t ldc) { const size_t nRowA = (trans == CBlasNoTrans) ? n : k; int info = 0; if (trans == CBlasTrans) info = 2; else if (lda < nRowA) info = 7; else if (ldc < n) info = 10; if (info != 0) { XERBLA(info); return; } if (n == 0 || ((alpha == zero || k == 0) && beta == one)) return; if (alpha == zero) { if (uplo == CBlasUpper) { if (beta == zero) { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = 0; i <= j; i++) C[j * ldc + i] = zero; } } else { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = 0; i < j; i++) C[j * ldc + i] *= beta; C[j * ldc + j] = beta * crealf(C[j * ldc + j]); } } } else { if (beta == zero) { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = j; i < n; i++) C[j * ldc + i] = zero; } } else { #pragma omp parallel for for (size_t j = 0; j < n; j++) { C[j * ldc + j] = beta * crealf(C[j * ldc + j]); for (size_t i = j + 1; i < n; i++) C[j * ldc + i] *= beta; } } } return; } if (trans == CBlasNoTrans) { if (uplo == CBlasUpper) { #pragma omp parallel for for (size_t j = 0; j < n; j++) { if (beta == zero) { for (size_t i = 0; i <= j; i++) C[j * ldc + i] = zero; } else if (beta != one) { for (size_t i = 0; i < j; i++) C[j * ldc + i] *= beta; C[j * ldc + j] = beta * crealf(C[j * ldc + j]); } else C[j * ldc + j] = crealf(C[j * ldc + j]); for (size_t l = 0; l < k; l++) { if (A[l * lda + j] != zero) { register float complex temp = alpha * conjf(A[l * lda + j]); for (size_t i = 0; i < j; i++) C[j * ldc + i] += temp * A[l * lda + i]; C[j * ldc + j] = crealf(C[j * ldc + j]) + crealf(temp * A[l * lda + j]); } } } } else { #pragma omp parallel for for (size_t j = 0; j < n; j++) { if (beta == zero) { for (size_t i = j; i < n; i++) C[j * ldc + i] = zero; } else if (beta != one) { C[j * ldc + j] = beta * crealf(C[j * ldc + j]); for (size_t i = j + 1; i < n; i++) C[j * ldc + i] *= beta; } else C[j * ldc + j] = crealf(C[j * ldc + j]); for (size_t l = 0; l < k; l++) { if (A[l * lda + j] != zero) { register float complex temp = alpha * conjf(A[l * lda + j]); C[j * ldc + j] = crealf(C[j * ldc + j]) + crealf(temp * A[l * lda + j]); for (size_t i = j + 1; i < n; i++) C[j * ldc + i] += temp * A[l * lda + i]; } } } } } else { if (uplo == CBlasUpper) { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = 0; i < j; i++) { register float complex temp = czero; for (size_t l = 0; l < k; l++) temp += conjf(A[i * lda + l]) * A[j * lda + l]; if (beta == zero) C[j * ldc + i] = alpha * temp; else C[j * ldc + i] = alpha * temp + beta * C[j * ldc + i]; } register float rtemp = zero; for (size_t l = 0; l < k; l++) rtemp += conjf(A[j * lda + l]) * A[j * lda + l]; if (beta == zero) C[j * ldc + j] = alpha * rtemp; else C[j * ldc + j] = alpha * rtemp + beta * crealf(C[j * ldc + j]); } } else { #pragma omp parallel for for (size_t j = 0; j < n; j++) { register float rtemp = zero; for (size_t l = 0; l < k; l++) rtemp += conjf(A[j * lda + l]) * A[j * lda + l]; if (beta == zero) C[j * ldc + j] = alpha * rtemp; else C[j * ldc + j] = alpha * rtemp + beta * crealf(C[j * ldc + j]); for (size_t i = j + 1; i < n; i++) { register float complex temp = czero; for (size_t l = 0; l < k; l++) temp += conjf(A[i * lda + l]) * A[j * lda + l]; if (beta == zero) C[j * ldc + i] = alpha * temp; else C[j * ldc + i] = alpha * temp + beta * C[j * ldc + i]; } } } } } CUresult cuCherk(CUBLAShandle handle, CBlasUplo uplo, CBlasTranspose trans, size_t n, size_t k, float alpha, CUdeviceptr A, size_t lda, float beta, CUdeviceptr C, size_t ldc, CUstream stream) { const size_t nRowA = (trans == CBlasNoTrans) ? n : k; int info = 0; if (trans == CBlasTrans) info = 2; else if (lda < nRowA) info = 7; else if (ldc < n) info = 10; if (info != 0) { XERBLA(info); return CUDA_ERROR_INVALID_VALUE; } if (n == 0 || ((alpha == zero || k == 0) && beta == one)) return CUDA_SUCCESS; CU_ERROR_CHECK(cuCtxPushCurrent(handle->context)); if (handle->cherk == NULL) CU_ERROR_CHECK(cuModuleLoadData(&handle->cherk, imageBytes)); const unsigned int mb = (trans == CBlasNoTrans) ? 64 : 32; const unsigned int nb = (trans == CBlasNoTrans) ? 8 : 16; const unsigned int kb = 8; const unsigned int bx = 8; const unsigned int by = 8; char name[89]; snprintf(name, 89, "_Z5cherkIL9CBlasUplo%dEL14CBlasTranspose%dELj%uELj%uELj%uELj%uELj%uEEvPK6float2PS2_ffiiii", uplo, trans, mb, nb, kb, bx, by); CUfunction function; CU_ERROR_CHECK(cuModuleGetFunction(&function, handle->cherk, name)); void * params[] = { &A, &C, &alpha, &beta, &lda, &ldc, &n, &k }; CU_ERROR_CHECK(cuLaunchKernel(function, (unsigned int)(n + mb - 1) / mb, (unsigned int)(n + nb - 1) / nb, 1, bx, by, 1, 0, stream, params, NULL)); CU_ERROR_CHECK(cuCtxPopCurrent(&handle->context)); return CUDA_SUCCESS; } CUresult cuMultiGPUCherk(CUmultiGPUBLAShandle handle, CBlasUplo uplo, CBlasTranspose trans, size_t n, size_t k, float alpha, const float complex * restrict A, size_t lda, float beta, float complex * restrict C, size_t ldc) { const size_t nRowA = (trans == CBlasNoTrans) ? n : k; int info = 0; if (trans == CBlasTrans) info = 2; else if (lda < nRowA) info = 7; else if (ldc < n) info = 10; if (info != 0) { XERBLA(info); return CUDA_ERROR_INVALID_VALUE; } if (n == 0 || ((alpha == zero || k == 0) && beta == one)) return CUDA_SUCCESS; if (alpha == zero) { if (uplo == CBlasUpper) { if (beta == zero) { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = 0; i <= j; i++) C[j * ldc + i] = zero; } } else { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = 0; i <= j; i++) C[j * ldc + i] *= beta; } } } else { if (beta == zero) { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = j; i < n; i++) C[j * ldc + i] = zero; } } else { #pragma omp parallel for for (size_t j = 0; j < n; j++) { for (size_t i = j; i < n; i++) C[j * ldc + i] *= beta; } } } return CUDA_SUCCESS; } const size_t nb = (trans == CBlasNoTrans) ? CGEMM_N_MB : CGEMM_C_NB; if (n < nb) { cherk(uplo, trans, n, k, alpha, A, lda, beta, C, ldc); return CUDA_SUCCESS; } if (trans == CBlasNoTrans) { if (uplo == CBlasUpper) { for (size_t j = nb; j < n; j += nb) CU_ERROR_CHECK(cuMultiGPUCgemm(handle, CBlasNoTrans, CBlasConjTrans, j, min(n - j, nb), k, alpha, A, lda, &A[j], lda, beta, &C[j * ldc], ldc)); } else { const size_t m = n - nb; for (size_t j = 0; j < m; j += nb) { const size_t jb = min(n - j, nb); CU_ERROR_CHECK(cuMultiGPUCgemm(handle, CBlasNoTrans, CBlasConjTrans, n - j - jb, jb, k, alpha, &A[j + jb], lda, &A[j], lda, beta, &C[j * ldc + j + jb], ldc)); } } for (size_t j = 0; j < n; j += nb) cherk(uplo, trans, min(n - j, nb), k, alpha, &A[j], lda, beta, &C[j * ldc + j], ldc); } else { if (uplo == CBlasUpper) { for (size_t j = nb; j < n; j += nb) CU_ERROR_CHECK(cuMultiGPUCgemm(handle, CBlasConjTrans, CBlasNoTrans, j, min(n - j, nb), k, alpha, A, lda, &A[j * lda], lda, beta, &C[j * ldc], ldc)); } else { const size_t m = n - nb; for (size_t j = 0; j < m; j += nb) { const size_t jb = min(n - j, nb); CU_ERROR_CHECK(cuMultiGPUCgemm(handle, CBlasConjTrans, CBlasNoTrans, n - j - jb, jb, k, alpha, &A[(j + jb) * lda], lda, &A[j * lda], lda, beta, &C[j * ldc + j + jb], ldc)); } } for (size_t j = 0; j < n; j += nb) cherk(uplo, trans, min(n - j, nb), k, alpha, &A[j * lda], lda, beta, &C[j * ldc + j], ldc); } return CUDA_SUCCESS; }
GB_binop__bxor_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__bxor_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__bxor_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__bxor_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__bxor_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bxor_uint64) // A*D function (colscale): GB (_AxD__bxor_uint64) // D*A function (rowscale): GB (_DxB__bxor_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__bxor_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__bxor_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bxor_uint64) // C=scalar+B GB (_bind1st__bxor_uint64) // C=scalar+B' GB (_bind1st_tran__bxor_uint64) // C=A+scalar GB (_bind2nd__bxor_uint64) // C=A'+scalar GB (_bind2nd_tran__bxor_uint64) // C type: uint64_t // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = (aij) ^ (bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,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) \ uint64_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) \ 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) ^ (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_BXOR || GxB_NO_UINT64 || GxB_NO_BXOR_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__bxor_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__bxor_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 { #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__bxor_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__bxor_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__bxor_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__bxor_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__bxor_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__bxor_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__bxor_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__bxor_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 //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bxor_uint64) ( 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 ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = (x) ^ (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bxor_uint64) ( 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) ^ (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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) ^ (aij) ; \ } GrB_Info GB (_bind1st_tran__bxor_uint64) ( 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 } //------------------------------------------------------------------------------ // 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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) ^ (y) ; \ } GrB_Info GB (_bind2nd_tran__bxor_uint64) ( 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
Util.h
// // Created by Bangtian Liu on 6/28/19. // #ifndef PROJECT_UTIL_H #define PROJECT_UTIL_H #include <string> #include <iostream> #include <fstream> #include <sstream> #include <random> #include <mkl.h> #include <cstring> //#include "../sympiler/nUtil.h" using namespace std; typedef enum{ KS_GAUSSIAN, KS_POLYNOMIAL, KS_LAPLACE, KS_GAUSSIAN_VAR_BANDWIDTH, KS_TANH, KS_QUARTIC, KS_MULTIQUADRATIC, KS_EPANECHNIKOV, KS_LOG, KS_EXPONENTIAL, KS_NEWTON }Ktype; int preprocesbin(std::string name) { ifstream file(name.data(), std::ios::in|std::ios::binary|std::ios::ate); auto size = file.tellg(); return (int)size/sizeof(double); } int preprocesoffset(std::string name) { ifstream file(name.data(), std::ios::in|std::ios::binary|std::ios::ate); auto size = file.tellg(); return (int)size/sizeof(int); } int preprocesLoffset(std::string name) { ifstream file(name.data(), std::ios::in|std::ios::binary|std::ios::ate); auto size = file.tellg(); return (int)size/sizeof(uint64_t); } void bin2read(std::string name, double *mat, int len) { ifstream in(name.data(), ios::in | ios::binary|std::ios::ate); in.seekg( 0, std::ios::beg ); in.read( (char*)mat, len*sizeof(double)); in.close(); } void bin2read(std::string name, int *mat, int len) { ifstream in(name.data(), ios::in | ios::binary|std::ios::ate); in.seekg( 0, std::ios::beg ); in.read( (char*)mat, len*sizeof(int)); in.close(); } int preprocesstxt(std::string name) { ifstream in(name.data()); string line; int len=0; while(getline(in, line)){ ++len; } return len; } void txt2read(std::string name, int *offset) { int index=0; ifstream in(name.data()); string line; while(getline(in,line)){ istringstream liness(line); liness >> offset[index]; ++index; } } void pairtxt2read(std::string name, int *nodex, int *nodey) { int index = 0; ifstream in(name.data()); string line; int i, j; while(getline(in,line)){ istringstream liness(line); liness >> i >> j; // printf("pair (%d, %d)\n",i,j); nodex[index]=i; nodey[index]=j; ++index; } in.close(); } int processlevelsets(std::string name, int &len) { ifstream in(name.data()); string line; int level, idx; int depth=0; while(getline(in, line)) { istringstream liness(line); liness >> level >> idx ; depth = std::max(depth,level); ++len; } return depth; } void readlevelset(std::string name, int *levelset, int *idx, int len, int n) { ifstream in(name.data()); string line; int l, x; int colCnt=0, nnz=0; levelset[0]=0; for(int i=1; nnz<len;) { in >> l; in >> x; if(l==i){ idx[nnz] = x; colCnt++; nnz++; } else { levelset[i]=levelset[i-1] + colCnt; i++; colCnt=1; idx[nnz] = x; nnz ++; } } levelset[n] = levelset[n-1] + colCnt; } void randu(int nrow, int ncol, double * array, double a, double b) { std::default_random_engine generator; std::uniform_real_distribution<double> distribution( a, b ); //#pragma omp parallel for for (int i = 0; i < ncol ; ++i) { for (int j = 0; j < nrow; ++j) { array[i*nrow + j ] = distribution(generator); //array[i*nrow + j ] = 1.0; // array[j*ncol + i] =array[i*ncol + j]; } } } void Fsubmatrix(std::vector<int> &amap, std::vector<int> &bmap, double *submatrix, Ktype ktype, double *X, int d, double h ) { switch (ktype) { case KS_GAUSSIAN: { #pragma omp parallel for for (int j = 0; j < bmap.size(); ++j) { for (int i = 0; i < amap.size(); ++i) { auto Kij = 0.0; #pragma omp simd reduction(+:Kij) for (int k = 0; k < d; ++k) { auto col = bmap[j]; auto row = amap[i]; auto tar = X[col * d + k]; auto src = X[row * d + k]; Kij += (tar - src) * (tar - src); } Kij = exp(-Kij / (2 * h * h)); // Kij = 1.0; submatrix[j * amap.size() + i] = Kij; } } break; } case KS_LOG: { for (int j = 0; j < bmap.size(); j++) { for (int i = 0; i < amap.size(); i++) { auto Kij = 0.0; for (int k = 0; k < d; ++k) { auto col = bmap[j]; auto row = amap[i]; auto tar = X[col * d + k]; auto src = X[row * d + k]; Kij += (tar - src) * (tar - src); } submatrix[j * amap.size() + i] = -0.5 * log(Kij); if (amap[i] == bmap[j])submatrix[j * amap.size() + i] = 1.0; } } break; } case KS_EXPONENTIAL: { for (int j = 0; j < bmap.size(); j++) { for (int i = 0; i < amap.size(); i++) { auto Kij = 0.0; for (int k = 0; k < d; ++k) { auto col = bmap[j]; auto row = amap[i]; auto tar = X[col * d + k]; auto src = X[row * d + k]; Kij += (tar - src) * (tar - src); } submatrix[j * amap.size() + i] = exp(-sqrt(Kij)); // if(i==j)submatrix[j*amap.size()+i]=1.0; } } break; } case KS_NEWTON: { for (int j = 0; j < bmap.size(); j++) { for (int i = 0; i < amap.size(); i++) { auto Kij = 0.0; for (int k = 0; k < d; ++k) { auto col = bmap[j]; auto row = amap[i]; auto tar = X[col * d + k]; auto src = X[row * d + k]; Kij += (tar - src) * (tar - src); } if(Kij==0)Kij=1; submatrix[j * amap.size() + i] = 1/sqrt(Kij); } } break; } default: { printf("invalid kernel type\n"); exit(1); break; } } } double computeError(int *lids, int len, int nrhs, int n, double *X, int d, double *W, double *U) { // len=100; int ntest=10; // printf("len=%d\n", len); auto amap = std::vector<int>(len); auto bmap = std::vector<int>(n); for(int i=0;i<len;i++) { amap[i] = lids[i]; // printf("idx=%d\n",amap[i]); } for(int i=0;i<n;i++) { bmap[i] = i; } auto Kab = (double *)mkl_malloc(sizeof(double)*len*n,64); double *result = (double *)mkl_malloc(sizeof(double)*len*nrhs,64); memset(result, 0, sizeof(double)*len*nrhs); Ktype ktype = KS_GAUSSIAN; Fsubmatrix(amap,bmap,Kab,ktype,X,d,5); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, len,nrhs,n,1.0f, Kab,len, W, n, 0.0, result,len ); double error = 0.0f; double nrm2 = 0.0f; double averror = 0.0f; for(int i=0; i<ntest; ++i) { error = 0.0f; nrm2 = 0.0f; for(int j=0; j<nrhs; ++j) { // printf("i=%d res=%f app=%f\n",i, result[j*len+i], U[j*len+i]); error += (result[j*len+i]-U[j*len+i])*(result[j*len+i]-U[j*len+i]); nrm2 += (result[j*len+i]*result[j*len+i]); } error = std::sqrt(error); nrm2 = std::sqrt(nrm2); averror += error/nrm2; } return averror/ntest; } std::string sadd(string &str) { std::string path = "../sympiler/"; path.append(str); return path; } void PrintMatrix(double *mat, int nrow, int ncol, string name) { std::cout<<"Matirx: " << name << "\n"; for(int i=0;i<nrow;i++) { for(int j=0;j<ncol;j++) { printf("%f\t",mat[j*nrow+i]); } printf("\n"); } } #endif //PROJECT_UTIL_H
preprocess.c
#include<stdlib.h> #include "graph.h" #include "mainFunctions.h" #include "print.h" //#include "powerperformacetracking.h" //#include "communities.h" #include "graphprop.h" #include "nodeIntMap.h" #include <string.h> #define DEBUG_ON int adj = 0; // 1 for reverse adjlist or 0 in adjlist. bool skewed = false; node_t* comm = NULL; typedef struct graphmap { node_t comm; node_t newPos; node_t revPos; } graphmap; typedef struct ClusterDetails { int id; int numNodes; int numEdges; int external; int commDistance; // node_t* nodeList; } ClusterDetails; inline void CopyClusterDetails(ClusterDetails* cd,int src, int dest) { cd[dest].id = cd[src].id; cd[dest].numNodes = cd[src].numNodes; cd[dest].numEdges = cd[src].numEdges; cd[dest].external = cd[src].external; cd[dest].commDistance = cd[src].commDistance; } graph* createPreprocessedGraph(graph *G, graphmap * gm) { /* Create the copy */ graph* newG = createGraph(); bool hasEdgeWeight= false; newG->numNodes = G->numNodes; newG->numEdges = G->numEdges; newG->begin = (edge_t*) malloc (sizeof(edge_t) * (newG->numNodes+1)); #ifdef DEBUG_ON assert(newG->begin != NULL); #endif newG->node_idx = (node_t*) malloc(sizeof(node_t) * newG->numEdges); edge_t edgepos = 0; newG->begin[0] = 0; for(int i=0;i< newG->numNodes; i++) { assert(gm[i].revPos != NIL_NODE); node_t origPos = gm[i].revPos; // reserse the edge list size newG->begin[i+1] = newG->begin[i] + (G->begin[origPos+1] - G->begin[origPos]); edge_t st = newG->begin[i]; edge_t ed = newG->begin[i]; // add edges for(edge_t e = G->begin[origPos]; e < G->begin[origPos+1]; e++) { node_t end = G->node_idx[e]; assert(gm[end].newPos != NIL_NODE); // get from map the new node id node_t newEnd = gm[end].newPos; edge_t sorte = st; // find right position for(; sorte < ed ; sorte++) { if(newEnd < newG->node_idx[sorte]) break; } // shift edges for(edge_t sf = ed-1; sf >= sorte; sf --) { newG->node_idx[sf+1] = newG->node_idx[sf]; } // add to right position newG->node_idx[sorte] = newEnd; ed++; } assert(ed == newG->begin[i+1]); } return newG; } /* TODO there can be atmost 1 node with no incomming edges in the community. (The universal source node of the community). If we can somehow find that node (if present, possibly it will the community ID TODO VERIFY AND OPTIMIZE THIS), the we can get away with creating the stacklist and commlist and directly use the G and comm to create the consolidated list. commlist = nodes in community stacklist = stack visited = visited list commid community id */ void * topologicalSort(graph * G, node_t* commlist , node_t* stacklist, int* visited, node_t* comm, node_t* commpos, int commSize, node_t commId) { int sortedSize = 0; stacklist[sortedSize] = commlist[0]; visited[0] = 1; sortedSize++; int curIndex = 0; node_t source; // printf("The start of stack \n"); while(sortedSize < commSize) { if(curIndex == sortedSize) { for(int i =1; i< commSize; i++ ) { if(visited[commpos[commlist[i]]] == 0) { stacklist[sortedSize] = commlist[i]; visited[commpos[commlist[i]]] = 1; sortedSize++; break; } } } assert(curIndex< sortedSize); source = stacklist[curIndex]; curIndex++; for(edge_t e = G->begin[source]; e < G->begin[source+1]; e++) { node_t d = G->node_idx[e]; if(comm[d] == commId && visited[commpos[d]] == 0) { stacklist[sortedSize] = d; visited[commpos[d]] = 1; sortedSize++; } } } // printf("The end of stack \n"); assert(sortedSize == commSize); } void dumpmapping(graph *G, graphmap* gm,const char * filename) { FILE *fp = fopen(filename, "w"); for(node_t i = 0; i < G->numNodes; i++) { fprintf(fp, "%d\t%d\n", i, gm[i].newPos); } } void initCommunities(graph *G) { comm = (node_t*) malloc (G->numNodes * sizeof(node_t)); assert(comm != NULL); } double* coeff; #define cohval(index,arr) arr[index] void merge_serial(node_t* index, double* vals, node_t start, node_t mid, node_t end) { node_t t1 = start; node_t t2 = mid; node_t tmp; node_t temp; node_t w = mid-1; node_t tempqueue[mid - start]; // should we use malloc ? node_t tpf = 0; node_t tpb = 0; while(t1 < mid && t2< end) { if(tpf == tpb) { // empty queue if(cohval(index[t1], vals) < cohval(index[t2], vals)) { tempqueue[tpf] = index[t1]; tpf++; index[t1] = index[t2]; t2++; } } else{ if(cohval(tempqueue[tpb], vals) < cohval(index[t2], vals)) { tempqueue[tpf] = index[t1]; tpf++; index[t1] = index[t2]; t2++; } else { tempqueue[tpf] = index[t1]; tpf++; index[t1] = tempqueue[tpb]; tpb++; } } t1++; } if(t1 < mid) { // on highly rare occations // copy rest of the first half to the temp array while(t1 < mid) { tempqueue[tpf] = index[t1]; tpf++; } // now copy back withou comparison t1 array already sorted. while(tpf > tpb ) { index[t1] = tempqueue[tpb]; t1++; tpb++; } } else { while(tpf > tpb ) { if(t2 < end && cohval(tempqueue[tpb], vals) < cohval(index[t2], vals)) { index[t1] = index[t2]; t2++; } else { index[t1] = tempqueue[tpb]; tpb++; } t1++; } } // TODO add assert? assert(tpf == tpb); if(t2 < end) { assert(t1 == (t2-1)); } else { //assert(t2 == end); assert(t1 == end); } // } void merge_parallel(node_t* index1, double* vals, node_t start, node_t mid, node_t end) { // TODO } void sort_selection(node_t* index, double* vals, node_t start, node_t end) { node_t sindex; for(node_t i = start; i< end-1; i++) { sindex = i; double coh = cohval(index[i], vals); for(node_t j = start+1; j<end; j++) { double coj = cohval(index[j], vals); if(coj > coh) { sindex = j; coh = coj; } } node_t temp = index[i]; index[i] = index[sindex]; index[sindex] = temp; } } void sort_serial(node_t* index, double* vals, node_t start, node_t end) { if((end-start) < 1024) { sort_selection(index, vals, start, end); } else { node_t midpoint = (start+end)/2; sort_serial(index, vals, start, midpoint); sort_serial(index, vals, midpoint, end); merge_serial(index, vals, start, midpoint, end); } } void sort_parallel(node_t* index, double* vals, node_t start, node_t end) { if(end - start < 8192) { sort_serial(index, vals, start, end); } else { /* #pragma omp parallel */ /* { */ #pragma omp task sort_parallel(index, vals, start , (start+end)/2); #pragma omp task sort_parallel(index, vals, (start+end)/2 , end); #pragma omp taskwait merge_serial(index, vals, start, (start+end)/2, end); /* } */ } } void sort(node_t* index, double* vals, node_t start, node_t end) { if((end - start) < 8192) { sort_serial(index, vals,start,end); } else { #pragma omp parallel { sort_parallel(index, vals, start, end); } } } /* int comp (const void * elem1, const void * elem2) { */ /* double f = coeff[*((int*)elem1)]; */ /* double s = coeff[*((int*)elem2)]; */ /* if (f > s) return -1; */ /* if (f < s) return 1; */ /* return 0; */ /* } */ graph* preprocess(graph* G, const char* mapfile) { bool finished = false ; finished = true ; double mean = ((double)G->numEdges)/ G->numNodes; double upperlimit = 1.5 * mean; double lowerlimit = mean * 0.5; // int outliers = 0; bool hasEdgeWeight = false; if(G->weights!= NULL) hasEdgeWeight = true; struct timeval start, end; if(adj == 1) { /* reverse edge parallelism */ createReverseEdges(G); edge_t* r_begin = G->r_begin; node_t* r_node_idx = G->r_node_idx; free(G->begin); free(G->node_idx); G->begin = r_begin; G->node_idx = r_node_idx; } gettimeofday(&start, NULL); initCommunities(G); #pragma omp parallel { #pragma omp for for (node_t x = 0; x < G->numNodes; x ++) comm[x] = x ; } int maxItrs = 100; int itrs = 0; do { finished = true ; #pragma omp parallel { nodeIntMap *map; map = NULL; map = initNodeIntMap(map, 32, 0); node_t x0; #pragma omp for schedule(dynamic, PAR_CHUNKSIZE) for (x0 = 0; x0 < G->numNodes; x0 ++) { /* We classify only nodes with more than one edge. The non classified nodes will be pused to last. */ //if((G->begin[x0+1] - G->begin[x0]) > 1) { map = reinitNodeIntMap(map, G->begin[x0+1] - G->begin[x0], 0); for (edge_t y_idx = G->begin[x0];y_idx < G->begin[x0+1] ; y_idx ++) { node_t y = G->node_idx [y_idx]; node_t source; source = comm[y]; changeValue(map, source, 1); } node_t maxVal = mapMaxValueKey(map); if ( comm[x0] != maxVal && maxVal != NIL_NODE) { #pragma omp atomic write comm[x0] = maxVal; finished = false ; } //} } closeNodeIntMap(map); } itrs++; } while ( !finished && maxItrs > itrs); gettimeofday(&end, NULL); printf("Community detection The required time is %f \n",((end.tv_sec - start.tv_sec)*1000 + ((double)(end.tv_usec - start.tv_usec))/1000)); gettimeofday(&start, NULL); ClusterDetails* cd = (ClusterDetails*) malloc (G->numNodes * sizeof(ClusterDetails)); graphmap* gm = (graphmap*) malloc (G->numNodes * sizeof(graphmap)); #pragma omp parallel for for(node_t i=0; i<G->numNodes; i++ ) { gm[i].newPos = NIL_NODE; gm[i].revPos = NIL_NODE; cd[i].numNodes = 0; cd[i].numEdges = 0; cd[i].external = 0; cd[i].id = i; //cd[i].nodeList = NULL; } /* Position of the node in the community */ node_t *commpos = (node_t*) malloc (G->numNodes * sizeof(node_t)); #ifdef DEBUG_ON printf("Start the data collection process \n"); /** * IMPORTANT: There is a high probability that in the input graph * the adject nodes are in the same cluster. * As a result, we first compare the previous nodes's * cluster ID. **/ #endif for(node_t i=0; i< G->numNodes; i++) { node_t comid = comm[i]; commpos[i] = cd[comid].numNodes; cd[comid].numNodes++; for(edge_t e = G->begin[i]; e < G->begin[i+1]; e++) { node_t end = G->node_idx[e]; if(comm[end] == comid) cd[comid].numEdges++; else cd[comid].external++; } } /* number of communities */ node_t noofComm = 0; for(node_t i=0; i< G->numNodes; i++) { if(cd[i].numNodes > 0) { if(noofComm < i) { CopyClusterDetails(cd, i, noofComm); } #ifdef DEBUG_ON assert(cd[i].numNodes == cd[noofComm].numNodes); // printf("The node id %d numNodes %d i val is %d and i numNodes is %d \n", noofComm, cd[noofComm].numNodes, i , cd[i].numNodes); assert(cd[i].numNodes > 0); // exit(0); #endif noofComm++; } } #ifdef DEBUG_ON printf("The number of clusters is %d \n ", noofComm); /* for(node_t debclusters = 0; debclusters < noofComm; debclusters++) { */ /* printf("The cluster id is %d and number of nodes in cluster is %d \n", cd[debclusters].id, cd[debclusters].numNodes); */ /* } */ #endif gettimeofday(&end, NULL); printf("data collection The required time is %f \n",((end.tv_sec - start.tv_sec)*1000 + ((double)(end.tv_usec - start.tv_usec))/1000)); /* The community with highest diffrenece between internal nodes and external nodes per node will be psuhed to start. */ gettimeofday(&start, NULL); /*community positions*/ int* commDetPointers = (int*) malloc (noofComm * sizeof(int)); coeff = (double*) malloc (noofComm * sizeof(double)); #pragma omp parallel for for(node_t i=0; i < noofComm; i++) { #ifdef DEBUG_ON // printf("The node id %d numNodes %d \n",i , cd[i].numNodes); assert(cd[i].numNodes > 0); #endif commDetPointers[i] = i; coeff[i] = ((double)cd[i].numEdges)/cd[i].numNodes; } sort_serial(commDetPointers, coeff, 0, noofComm); free(coeff); gettimeofday(&end, NULL); printf("sorting The required time is %f \n",((end.tv_sec - start.tv_sec)*1000 + ((double)(end.tv_usec - start.tv_usec))/1000)); /* Decide on destinations */ gettimeofday(&start, NULL); node_t commEnd = 0; node_t commStart = 0; /* These are the start and end indexes of graph Map */ for(node_t c =0; c<noofComm; c++) { node_t cid = commDetPointers[c]; cd[cid].commDistance = commStart; assert(cd[cid].numNodes > 0); commStart += cd[cid].numNodes; } assert(commStart == G->numNodes); /** Collect the nodes of a cluster together **/ node_t* clusterednodes = (node_t*) malloc (G->numNodes * sizeof(node_t)); node_t* clusterPositions = (node_t*) malloc (G->numNodes * sizeof(node_t)); #pragma omp parallel for for(node_t c=0; c< noofComm;c++) { clusterPositions[cd[c].id] = c; } #ifdef DEBUG_ON #pragma omp parallel for for(node_t i =0;i< G->numNodes;i++) { clusterednodes[i] = NIL_NODE; } for(node_t c; c< noofComm; c++) { assert(clusterPositions[cd[c].id] == c); } #endif for(node_t i =0;i< G->numNodes;i++) { node_t nodeCluster = comm[i]; node_t clusterPos = clusterPositions[nodeCluster]; node_t nodePos = cd[clusterPos].commDistance + commpos[i]; #ifdef DEBUG_ON // printf("The node id %d community id %d (%d), community start is %d nodePos = %d clusterednode %d \n",i,comm[i], cd[clusterPos].id, cd[clusterPos].commDistance, nodePos, clusterednodes[nodePos]); assert(cd[clusterPos].id == comm[i]); assert(clusterednodes[nodePos] == NIL_NODE); #endif clusterednodes[nodePos] = i; } free(clusterPositions); #pragma omp parallel { int* visitedlist = (int*) malloc (cd[0].numNodes * sizeof(int)); node_t * commlist = (node_t*) malloc (cd[0].numNodes * sizeof(node_t)); node_t* stacklist = (node_t*) malloc (cd[0].numNodes * sizeof(node_t)); node_t commMax = cd[0].numNodes; #pragma omp for for(node_t c = 0; c< noofComm; c++) { node_t cid = commDetPointers[c]; node_t myCommunitySize = cd[cid].numNodes; node_t commId = cd[cid].id; node_t myStart = cd[cid].commDistance; if(myCommunitySize > commMax) { commlist = (node_t*) realloc(commlist, myCommunitySize * sizeof(node_t)); stacklist = (node_t*) realloc(stacklist, myCommunitySize * sizeof(node_t)); visitedlist = (int*) realloc(visitedlist , myCommunitySize * sizeof(int)); commMax = myCommunitySize; } for(node_t i = 0; i< myCommunitySize; i++) { commlist[i] = clusterednodes[i+ myStart]; #ifdef DEBUG_ON assert(comm[commlist[i]] == commId); #endif } /*************************** TODO *************************************/ if(myCommunitySize > 3) { memset(visitedlist, 0,myCommunitySize * sizeof(int)); // BFS topologicalSort(G, commlist, stacklist, visitedlist, comm, commpos, myCommunitySize, commId); /* TODO Do a BFS after reversing the list. */ /* We might not require this exchange after the TODO */ node_t* temp = commlist; commlist = stacklist; stacklist = temp; } /* The order is set in commlist */ for(node_t i =0;i < myCommunitySize; i++){ assert(gm[myStart + i].revPos == NIL_NODE); assert(gm[commlist[i]].newPos == NIL_NODE); gm[myStart + i].revPos = commlist[i]; gm[commlist[i]].newPos = myStart + i; } } free(stacklist); free(commlist); free(visitedlist); } free(comm); free(commpos); free(cd); free(commDetPointers); free(clusterednodes); gettimeofday(&end, NULL); printf("Internal sorting the required time is %f \n",((end.tv_sec - start.tv_sec)*1000 + ((double)(end.tv_usec - start.tv_usec))/1000)); gettimeofday(&start, NULL); graph* newG = createPreprocessedGraph(G, gm); gettimeofday(&end, NULL); printf("Copy back the required time is %f \n",((end.tv_sec - start.tv_sec)*1000 + ((double)(end.tv_usec - start.tv_usec))/1000)); if(adj == 1) { /* Get the reverse edges */ createReverseEdges(newG); edge_t* r_begin = newG->r_begin; node_t* r_node_idx = newG->r_node_idx; free(newG->begin); free(newG->node_idx); newG->begin = r_begin; newG->node_idx = r_node_idx; } dumpmapping(G, gm, mapfile); /*now update edgeWeights in newG*/ if(G->weights != NULL) { int w = 0; bool found = false; edge_t pos; newG->weights = (int*) malloc(sizeof(int) * newG->numEdges); node_t x0; for (x0 = 0; x0 < G->numNodes; x0 ++) { for (edge_t y = G->begin[x0];y < G->begin[x0+1] ; y ++) { w = G->weights[y]; node_t d = G->node_idx[y]; node_t newS = gm[x0].newPos; node_t newD = gm[d].newPos; /* assert edge is added */ found = false; pos = NIL_EDGE; for(edge_t newY = newG->begin[newS]; newY < newG->begin[newS+1]; newY++) { if(newG->node_idx[newY] == newD) { found = true; pos = newY; break; } } assert(pos != NIL_EDGE); newG->weights[pos] = w; } } } free(gm); return newG; } double avgincident; double scaledT; double clusterCoeff; double aed; node_t dim; double sparsityMeasure; void writeSchema(const char *filename) { FILE *fp = fopen(filename, "w"); fprintf(fp, "Avg Adjecency = %f \n", avgincident); fprintf(fp, "Avg ClusterCoeff = %f \n",clusterCoeff); fprintf(fp, "Avg Edge Distance = %f \n", aed); fprintf(fp, "Sparsity = %0.7f \n",sparsityMeasure); fprintf(fp,"The Scaled percentange Triangles = %f\n\n", scaledT); fclose(fp); } /*** * Common entry point for all algorithms, **/ int runalgo(int argc,char** argv) { graph* G = readGraph(argv[1], argv[2]); adj = atoi(argv[6]); if(argc < 7) { const char* argList[6] = {" <inputfile> " , "graphformat.txt","<outputfile>", "<outputpropfile>", "<outputmapfilename>", "<adjecencyflag>[0/1] [no revrse/reverse]"}; printError(INCORRECT_ARG_LIST, 6, argList); return -1; } graph* newG = preprocess(G, argv[5]); avgincident = ((double) G->numEdges )/ G->numNodes; writeBackGraph(newG, argv[3]); clusterCoeff = avgClusterCoeff(G); aed = avgEdgeDistance(G); dim = diameter(G); sparsityMeasure = sparsity(G); double T = triangle_counting(G); avgClusterCoeff(newG); avgEdgeDistance(newG); diameter(newG); sparsity(newG); triangle_counting(newG); scaledT = ((double) T )/ G->numNodes; sccIndex(newG); writeSchema(argv[4]); return 0; } inline void kernel(graph *G) { }
GB_unop__identity_int8_int16.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_int8_int16) // op(A') function: GB (_unop_tran__identity_int8_int16) // C type: int8_t // A type: int16_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int8_t z = (int8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = (int8_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_INT8 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int8_int16) ( int8_t *Cx, // Cx and Ax may be aliased const int16_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 ; // 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 (int16_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int16_t aij = Ax [p] ; int8_t z = (int8_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 ; int16_t aij = Ax [p] ; int8_t z = (int8_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_int8_int16) ( 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
montecarlo.h
#ifndef MONTECARLO_H #define MONTECARLO_H #include <random> #include <iostream> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <string> #include "RngStream.h" double fun(double x) //f(x) = x; { return x; } double URDMonteCarloIntegration (double a, double b, int n) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<double> dis(0.0, 1.0); if(a > b) { return URDMonteCarloIntegration(b, a, n); } double sum = 0.0; #pragma omp parallel for reduction(+:sum) for (int i = 1; i <= n; i++) { double r = dis(gen); sum = sum + fun(a+((b-a)*r)); } sum = ((b-a)/n)*sum; return sum; } double RNGMonteCarloIntegration (double a, double b, int n) { if(a > b) { return RNGMonteCarloIntegration(b, a, n); } double sum = 0.0; #pragma omp parallel { auto s = std::to_string(omp_get_thread_num()); //std::cout<<omp_get_thread_num()<<std::endl; const char* x = s.c_str(); RngStream gen; gen = RngStream_CreateStream(x); #pragma omp for reduction(+:sum) for (int i = 1; i <= n; i++) { double r = RngStream_RandU01(gen); sum = sum + fun(a+((b-a)*r)); } } sum = ((b-a)/n)*sum; return sum; } #endif
general_basis_bitops.h
#ifndef _GENERAL_BASIS_BITOPS_H #define _GENERAL_BASIS_BITOPS_H #include <iostream> #include "general_basis_core.h" #include "numpy/ndarraytypes.h" #include "misc.h" #include "openmp.h" namespace basis_general { template<class I> struct bitwise_and_op : std::binary_function<I,I,I> { I inline operator()(I a, I b){return a & b;} }; template<class I> struct bitwise_or_op : std::binary_function<I,I,I> { I inline operator()(I a, I b){return a | b;} }; template<class I> struct bitwise_xor_op : std::binary_function<I,I,I> { I inline operator()(I a, I b){return a ^ b;} }; template<class I, class J> struct bitwise_left_shift_op : std::binary_function<I,J,I> { I inline operator()(I a, J b){return a << b;} }; template<class I, class J> struct bitwise_right_shift_op : std::binary_function<I,J,I> { I inline operator()(I a, J b){return a >> b;} }; template<class I, class binary_operator> void bitwise_op(const I x1[], const I x2[], bool *where, I *out, const npy_intp Ns, binary_operator op ) { if(where){ #pragma omp parallel { const npy_intp chunk = std::max(Ns/(100*omp_get_num_threads()),(npy_intp)1); // bitops should have dynamic workload b/c of where-if statement #pragma omp parallel for schedule(dynamic,chunk) for(npy_intp i=0;i<Ns;i++){ if(where[i]){ out[i]=op(x1[i],x2[i]); } } } } else{ #pragma omp parallel { const npy_intp chunk = std::max(Ns/(100*omp_get_num_threads()),(npy_intp)1); // bitops should have constant workload #pragma omp parallel for schedule(static,chunk) for(npy_intp i=0;i<Ns;i++){ out[i]=op(x1[i],x2[i]); } } } } template<class I, class J, class binary_operator> void bitwise_shift_op(const I x1[], const J x2[], bool *where, I *out, const npy_intp Ns, binary_operator op ) { if(where){ #pragma omp parallel { const npy_intp chunk = std::max(Ns/(100*omp_get_num_threads()),(npy_intp)1); // bitops should have dynamic workload b/c of where-if statement #pragma omp parallel for schedule(dynamic,chunk) for(npy_intp i=0;i<Ns;i++){ if(where[i]){ out[i]=op(x1[i],x2[i]); } } } } else{ #pragma omp parallel { const npy_intp chunk = std::max(Ns/(100*omp_get_num_threads()),(npy_intp)1); // bitops should have constant workload #pragma omp parallel for schedule(static,chunk) for(npy_intp i=0;i<Ns;i++){ out[i]=op(x1[i],x2[i]); } } } } template<class I> void bitwise_not_op_core(const I x1[], bool *where, I *out, const npy_intp Ns ) { if(where){ #pragma omp parallel { const npy_intp chunk = std::max(Ns/(100*omp_get_num_threads()),(npy_intp)1); // bitops should have dynamic workload b/c of where-if statement #pragma omp parallel for schedule(dynamic,chunk) for(npy_intp i=0;i<Ns;i++){ if(where[i]){ out[i]= ~x1[i]; } } } } else{ #pragma omp parallel { const npy_intp chunk = std::max(Ns/(100*omp_get_num_threads()),(npy_intp)1); // bitops should have constant workload #pragma omp parallel for schedule(static,chunk) for(npy_intp i=0;i<Ns;i++){ out[i]= ~x1[i]; } } } } } #endif
resample_utils.h
/* Copyright (c) MONAI Consortium 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 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // We need to define AT_PARALLEL_OPENMP (even if -fopenmp is // not used) so that at::parallel_for is defined somewhere. // This must be done before <ATen/Parallel.h> is included. // // Note that if AT_PARALLEL_OPENMP = 1 but compilation does not use // -fopenmp, omp pragmas will be ignored. In that case, the code will // be effectively sequential, and we don't have to worry about // operations being atomic. #if !(AT_PARALLEL_OPENMP) #if !(AT_PARALLEL_NATIVE) #if !(AT_PARALLEL_NATIVE_TBB) #error No parallel backend specified #endif #endif #endif // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // These are defines that help writing generic code for both GPU and CPU #ifdef __CUDACC__ #include <ATen/cuda/CUDAApplyUtils.cuh> #include <THC/THCAtomics.cuh> #define MONAI_INLINE __forceinline__ #define MONAI_DEVICE __device__ #define MONAI_HOST __host__ #define MONAI_ATOMIC_ADD monai::gpuAtomicAdd #define MONAI_NAMESPACE_DEVICE namespace cuda namespace monai { // atomicAdd API changed between pytorch 1.4 and 1.5. template <typename scalar_t, typename offset_t> static __forceinline__ __device__ void gpuAtomicAdd(scalar_t* ptr, offset_t offset, scalar_t value) { #if MONAI_TORCH_VERSION >= 10500 ::gpuAtomicAdd(ptr + offset, value); #else ::atomicAdd(ptr + offset, value); #endif } } // namespace monai #else #define MONAI_INLINE inline #define MONAI_DEVICE #define MONAI_HOST #define MONAI_ATOMIC_ADD monai::cpuAtomicAdd #define MONAI_NAMESPACE_DEVICE namespace cpu namespace monai { template <typename scalar_t, typename offset_t> static inline void cpuAtomicAdd(scalar_t* ptr, offset_t offset, scalar_t value) { #if AT_PARALLEL_OPENMP #if _OPENMP #pragma omp atomic #endif #endif ptr[offset] += value; } } // namespace monai #endif // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include <ATen/ATen.h> namespace monai { enum class BoundType : int64_t { Replicate, // Replicate last inbound value = clip coordinates DCT1, // Symmetric w.r.t. center of the last inbound voxel DCT2, // Symmetric w.r.t. edge of the last inbound voxel (=Neuman) DST1, // Asymmetric w.r.t. center of the last inbound voxel DST2, // Asymmetric w.r.t. edge of the last inbound voxel (=Dirichlet) DFT, // Circular / Wrap around the FOV Sliding, // For deformation-fields only: mixture of DCT2 and DST2 Zero, // Zero outside of the FOV NoCheck // /!\ Checks disabled: assume coordinates are inbound }; using BoundVectorRef = c10::ArrayRef<BoundType>; enum class InterpolationType : int64_t { Nearest, Linear, Quadratic, Cubic, FourthOrder, FifthOrder, SixthOrder, SeventhOrder }; using InterpolationVectorRef = c10::ArrayRef<InterpolationType>; static MONAI_INLINE MONAI_HOST std::ostream& operator<<(std::ostream& os, const BoundType& bound) { switch (bound) { case BoundType::Replicate: return os << "Replicate"; case BoundType::DCT1: return os << "DCT1"; case BoundType::DCT2: return os << "DCT2"; case BoundType::DST1: return os << "DST1"; case BoundType::DST2: return os << "DST2"; case BoundType::DFT: return os << "DFT"; case BoundType::Zero: return os << "Zero"; case BoundType::Sliding: return os << "Sliding"; case BoundType::NoCheck: return os << "NoCheck"; } return os << "Unknown bound"; } static MONAI_INLINE MONAI_HOST std::ostream& operator<<(std::ostream& os, const InterpolationType& itp) { switch (itp) { case InterpolationType::Nearest: return os << "Nearest"; case InterpolationType::Linear: return os << "Linear"; case InterpolationType::Quadratic: return os << "Quadratic"; case InterpolationType::Cubic: return os << "Cubic"; case InterpolationType::FourthOrder: return os << "FourthOrder"; case InterpolationType::FifthOrder: return os << "FifthOrder"; case InterpolationType::SixthOrder: return os << "SixthOrder"; case InterpolationType::SeventhOrder: return os << "SeventhOrder"; } return os << "Unknown interpolation order"; } } // namespace monai
yolov2_forward_network_quantized.c
#include "additionally.h" // some definitions from: im2col.h, blas.h, list.h, utils.h, activations.h, tree.h, layer.h, network.h // softmax_layer.h, reorg_layer.h, route_layer.h, region_layer.h, maxpool_layer.h, convolutional_layer.h #define GEMMCONV //#define SSE41 //#undef AVX #define W_MAX_VAL (256/2 - 1) // 7-bit (1-bit sign) #define I_MAX_VAL (256/2 - 1) // 7-bit (1-bit sign) #define R_MAX_VAL (256*256/2 - 1) // 31-bit (1-bit sign) #define R_MULT (32) // 4 - 32 /* // from: box.h typedef struct { float x, y, w, h; } box; */ int max_abs(int src, int max_val) { if (abs(src) > abs(max_val)) src = (src > 0) ? max_val : -max_val; return src; } short int max_abs_short(short int src, short int max_val) { if (abs(src) > abs(max_val)) src = (src > 0) ? max_val : -max_val; return src; } int * get_distribution(float *arr_ptr, int arr_size, int number_of_ranges, float start_range) { //const int number_of_ranges = 32; //const float start_range = 1.F / 65536; int *count = calloc(number_of_ranges, sizeof(int)); float min_val = 10000, max_val = 0; int i, j; for (i = 0; i < arr_size; ++i) { float w = arr_ptr[i]; float cur_range = start_range; for (j = 0; j < number_of_ranges; ++j) { if (fabs(cur_range) <= w && w < fabs(cur_range * 2)) count[j]++;// , printf("found \n"); cur_range *= 2; //printf("%f, ", w); } } return count; } float get_multiplier(float *arr_ptr, int arr_size, int bits_length) { const int number_of_ranges = 32; const float start_range = 1.F / 65536; int i, j; int *count = get_distribution(arr_ptr, arr_size, number_of_ranges, start_range); int max_count_range = 0; int index_max_count = 0; for (j = 0; j < number_of_ranges; ++j) { int counter = 0; for (i = j; i < (j + bits_length) && i < number_of_ranges; ++i) { counter += count[i]; //counter += log2(count[i]); } if (max_count_range < counter) { max_count_range = counter; index_max_count = j; } } //index_max_count = index_max_count + 2; // optimal shift multipler float multiplier = 1 / (start_range * powf(2., (float)index_max_count)); //printf(" max_count_range = %d, index_max_count = %d, multiplier = %g \n", // max_count_range, index_max_count, multiplier); free(count); return multiplier; } #ifdef OPENCV #include <opencv2/core/fast_math.hpp> #include "opencv2/highgui/highgui_c.h" #include "opencv2/core/core_c.h" #include "opencv2/core/version.hpp" #define CV_RGB(r, g, b) cvScalar( (b), (g), (r), 0 ) void draw_distribution(float *arr_ptr, int arr_size, char *name) { int img_w = 1200, img_h = 800; const int number_of_ranges = 32; const float start_range = 1.F / 65536; //int *count = calloc(number_of_ranges, sizeof(int)); //float min_val = 100, max_val = 0; int i, j; int *count = get_distribution(arr_ptr, arr_size, number_of_ranges, start_range); float multiplier = get_multiplier(arr_ptr, arr_size, 8); int max_count_range = 0; for (j = 0; j < number_of_ranges; ++j) { count[j] = log2(count[j]); if (max_count_range < count[j]) max_count_range = count[j]; } cvNamedWindow("Distribution", CV_WINDOW_NORMAL); cvResizeWindow("Distribution", img_w, img_h); IplImage *img = cvCreateImage(cvSize(img_w, img_h), IPL_DEPTH_8U, 3); if (max_count_range > 0) { for (j = 0; j < number_of_ranges; ++j) { //printf("count[j] = %d, max_count_range = %d, img_w = %d, img_h = %d, j = %d, number_of_ranges = %d \n", // count[j], max_count_range, img_w, img_h, j, number_of_ranges); CvPoint pt1, pt2; pt1.x = j*img_w / number_of_ranges; pt2.x = (j + 1)*img_w / number_of_ranges; pt1.y = img_h; pt2.y = img_h - img_h*count[j] / max_count_range; //printf("pt1.x = %d, pt1.y = %d, pt2.x = %d, pt2.y = %d \n", pt1.x, pt1.y, pt2.x, pt2.y); //if(pt2.y < pt1.y) cvRectangle(img, pt1, pt2, CV_RGB(128, 64, 32), CV_FILLED, 8, 0); cvRectangle(img, pt1, pt2, CV_RGB(32, 32, 32), 1, 8, 0); } } int index_multiplier = log2(1 / (multiplier*start_range)); int x_coord_multiplier = index_multiplier*img_w / number_of_ranges; cvLine(img, cvPoint(x_coord_multiplier, 0), cvPoint(x_coord_multiplier, img_h), CV_RGB(255, 32, 32), 1, 8, 0); char buff[256]; //sprintf(buff, "[%g - %g]", min_val, max_val); sprintf(buff, "optimal multiplier = %g", multiplier); //printf("[%g - %g]", min_val, max_val); CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 1, 1, 0, 2, 8); cvPutText(img, buff, cvPoint(100, 50), &font, CV_RGB(32, 64, 128)); if (name) cvPutText(img, name, cvPoint(0, 20), &font, CV_RGB(32, 64, 128)); float cur_range = start_range; cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.5, 0.5, 0, 1, 8); for (j = 0; j < number_of_ranges; ++j) { CvPoint pt_text = cvPoint(j*img_w / number_of_ranges, img_h - 50); int lg = log2(cur_range); sprintf(buff, "%d", lg); cvPutText(img, buff, pt_text, &font, CV_RGB(32, 64, 128)); cur_range *= 2; } cvPutText(img, "X and Y are log2", cvPoint(img_w / 2 - 100, img_h - 10), &font, CV_RGB(32, 64, 128)); cvShowImage("Distribution", img); cvWaitKey(0); free(count); } #endif // OPENCV // im2col.c int8_t im2col_get_pixel_int8(int8_t *im, int height, int width, int channels, int row, int col, int channel, int pad) { row -= pad; col -= pad; if (row < 0 || col < 0 || row >= height || col >= width) return 0; return im[col + width*(row + height*channel)]; } // im2col.c //From Berkeley Vision's Caffe! //https://github.com/BVLC/caffe/blob/master/LICENSE void im2col_cpu_int8(int8_t* data_im, int channels, int height, int width, int ksize, int stride, int pad, int8_t* data_col) { int c, h, w; int height_col = (height + 2 * pad - ksize) / stride + 1; int width_col = (width + 2 * pad - ksize) / stride + 1; int channels_col = channels * ksize * ksize; for (c = 0; c < channels_col; ++c) { int w_offset = c % ksize; int h_offset = (c / ksize) % ksize; int c_im = c / ksize / ksize; for (h = 0; h < height_col; ++h) { for (w = 0; w < width_col; ++w) { int im_row = h_offset + h * stride; int im_col = w_offset + w * stride; int col_index = (c * height_col + h) * width_col + w; data_col[col_index] = im2col_get_pixel_int8(data_im, height, width, channels, im_row, im_col, c_im, pad); } } } } // Use to enable AVX or SSE41 //#define AVX // 1.35 sec (0.8 FPS) 2.3x - GCC -mavx -mavx2 -mfma -ffp-contract=fast //#define SSE41 // 1.55 sec (0.7 FPS) 2x // default 3.10 sec (0.3 FPS) #if defined(AVX) || defined(SSE41) #ifdef _WIN64 #include <intrin.h> #else #include <x86intrin.h> #endif #include <ammintrin.h> #include <immintrin.h> #include <smmintrin.h> #include <emmintrin.h> // https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=broad&expand=561 #endif // AVX or SSE41 #if defined(AVX) __m256i _mm256_div_epi16(const __m256i va, const int b) { __m256i vb = _mm256_set1_epi16(32768 / b); return _mm256_mulhrs_epi16(va, vb); } #define INTERMEDIATE_MULT 15 // 8 or 15 #define FINAL_MULT (R_MULT / INTERMEDIATE_MULT) // 0.89 sec void gemm_nn_int8_int16_conv16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { __m256i res; __m256i a, b, d; __m128i tmp128; __m256i div256 = _mm256_set1_epi16(INTERMEDIATE_MULT); int16_t *c_tmp = calloc(N, sizeof(int16_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; a = _mm256_set1_epi16(A_PART); for (j = 0; j < N - 32; j += 32) { int index = k*ldb + j; d = _mm256_loadu_si256((__m256i*)&B[index]); tmp128 = _mm256_extractf128_si256(d, 0);// get low 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 b = _mm256_mullo_epi16(a, b); // B = A * B b = _mm256_div_epi16(b, INTERMEDIATE_MULT); // B = (A * B) / INTERMEDIATE_MULL res = _mm256_loadu_si256(&c_tmp[j]); // load temp C res = _mm256_add_epi16(b, res); // (A*B) + C _mm256_storeu_si256(&c_tmp[j], res); // store temp C tmp128 = _mm256_extractf128_si256(d, 1);// get high 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 (for low 8 bytes) b = _mm256_mullo_epi16(a, b); // B = A * B b = _mm256_div_epi16(b, INTERMEDIATE_MULT); // B = (A * B) / INTERMEDIATE_MULL res = _mm256_loadu_si256(&c_tmp[j + 16]); // Load next temp C res = _mm256_add_epi16(b, res); // (A*B) + C _mm256_storeu_si256(&c_tmp[j + 16], res); // store temp C //c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (INTERMEDIATE_MULL), (256 * 128 - 1)); } int prev_end = (N % 32 == 0) ? (N - 32) : (N / 32) * 32; for (j = prev_end; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j] / (INTERMEDIATE_MULT); } } for (j = 0; j < N; ++j) { C[i*ldc + j] += (c_tmp[j] / FINAL_MULT); c_tmp[j] = 0; } } free(c_tmp); } // 1.15 sec void gemm_nn_int8_int16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { __m256i multyplied_i32, res; __m256i a, b, d; __m128i tmp128; int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; a = _mm256_set1_epi16(A_PART); for (j = 0; j < N - 32; j += 32) { int index = k*ldb + j; d = _mm256_loadu_si256((__m256i*)&B[index]); tmp128 = _mm256_extractf128_si256(d, 0);// get low 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 b = _mm256_mullo_epi16(a, b); // B = A * B tmp128 = _mm256_extractf128_si256(b, 0); // get low 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j]); // load temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j], res); // store temp C tmp128 = _mm256_extractf128_si256(b, 1); // get high 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j + 8]); // Load next temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j + 8], res); // store temp C tmp128 = _mm256_extractf128_si256(d, 1);// get high 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 (for low 8 bytes) b = _mm256_mullo_epi16(a, b); // B = A * B tmp128 = _mm256_extractf128_si256(b, 0); // get low 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j + 16]); // Load next temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j + 16], res); // store temp C tmp128 = _mm256_extractf128_si256(b, 1); // get high 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j + 24]); // Load next temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j + 24], res); // store temp C //c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (32), (256 * 128 - 1)); } int prev_end = (N % 32 == 0) ? (N - 32) : (N / 32) * 32; for (j = prev_end; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } //for (j = 0; j < N; ++j) C[i*ldc + j] += c_tmp[j] / (R_MULT); } free(c_tmp); } #elif defined(SSE41) // 1.3 sec void gemm_nn_int8_int16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { __m128i multyplied_i32, res; __m128i a, b, d; //c = _mm_set1_epi16(32); int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; a = _mm_set1_epi16(A_PART); for (j = 0; j < N - 16; j += 16) { int index = k*ldb + j; d = _mm_loadu_si128((__m128i*)&B[index]); b = _mm_cvtepi8_epi16(d); // int8 -> int16 b = _mm_mullo_epi16(a, b); // B = A * B multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j]); // load temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j], res); // store temp C b = _mm_srli_si128(b, 8); // Shift Right -> 8 bytes multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j + 4]); // Load next temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j + 4], res); // store temp C d = _mm_srli_si128(d, 8); // Shift Right -> 8 bytes b = _mm_cvtepi8_epi16(d); // int8 -> int16 (for low 8 bytes) b = _mm_mullo_epi16(a, b); // B = A * B multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j + 8]); // Load next temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j + 8], res); // store temp C b = _mm_srli_si128(b, 8); // Shift Right -> 8 bytes multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j + 12]); // Load next temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j + 12], res); // store temp C //c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (32), (256 * 128 - 1)); } int prev_end = (N % 16 == 0) ? (N - 16) : (N / 16) * 16; for (j = prev_end; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } //for (j = 0; j < N; ++j) C[i*ldc + j] += c_tmp[j] / (R_MULT); } free(c_tmp); } void gemm_nn_int8_int16_conv16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { printf(" gemm_nn_int8_int16_conv16() isn't implemented for SSE4.1 \n"); } #else // 2.9 sec void gemm_nn_int8_int16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; //#pragma simd parallel for for (j = 0; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (R_MULT), (256 * 128 - 1)); } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } } free(c_tmp); } void gemm_nn_int8_int32(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int32_t *C, int ldc) { int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; //#pragma simd parallel for for (j = 0; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (R_MULT), (256 * 128 - 1)); } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } } free(c_tmp); } void gemm_nn_int8_int16_conv16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { printf(" gemm_nn_int8_int16_conv16() isn't implemented \n"); } #endif // SSE41 or AVX void forward_convolutional_layer_q(layer l, network_state state) { int out_h = (l.h + 2 * l.pad - l.size) / l.stride + 1; // output_height=input_height for stride=1 and pad=1 int out_w = (l.w + 2 * l.pad - l.size) / l.stride + 1; // output_width=input_width for stride=1 and pad=1 int i, f, j; int const out_size = out_h*out_w; size_t const weights_size = l.size*l.size*l.c*l.n; // fill zero (ALPHA) //for (i = 0; i < l.outputs; ++i) l.output[i] = 0; // l.n - number of filters on this layer // l.c - channels of input-array // l.h - height of input-array // l.w - width of input-array // l.size - width and height of filters (the same size for all filters) //draw_distribution(l.weights, weights_size, "weights"); //draw_distribution(state.input, l.inputs, "input"); //typedef int32_t conv_t; // l.output typedef int16_t conv_t; // l.output conv_t *output_q = calloc(l.outputs, sizeof(conv_t)); state.input_int8 = (int *)calloc(l.inputs, sizeof(int)); int z; for (z = 0; z < l.inputs; ++z) { //int16_t src = lround(state.input[k] * net.layers[0].input_quant_multipler); int16_t src = state.input[z] * l.input_quant_multipler; state.input_int8[z] = max_abs(src, I_MAX_VAL); } //////////////////////////////////// // cudnnConvolutionBiasActivationForward() // y = act ( alpha1 * conv(x) + alpha2 * z + bias ) // int8 = activation( float * conv(int8) + float * int8 + float ) // int8 = activation( conv(input_int8) + bias_float ) // X_INT8x4 or X_INT8 // https://docs.nvidia.com/deeplearning/sdk/cudnn-developer-guide/index.html#cudnnConvolutionBiasActivationForward /////////////////////////////////// // 1. Convolution !!! int fil; // cuDNN: y = conv(x) int m = l.n; int k = l.size*l.size*l.c; int n = out_h*out_w; int8_t *a = l.weights_int8; int8_t *b = (int8_t *)state.workspace; conv_t *c = output_q; // int16_t // convolution as GEMM (as part of BLAS) //for (i = 0; i < l.batch; ++i) { im2col_cpu_int8(state.input_int8, l.c, l.h, l.w, l.size, l.stride, l.pad, b); // here //gemm_nn_int8_int16(m, n, k, 1, a, k, b, n, c, n); // single-thread gemm int t; // multi-thread gemm #pragma omp parallel for for (t = 0; t < m; ++t) { gemm_nn_int8_int16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int16_conv16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int32(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); // conv_t should be int32_t } //} free(state.input_int8); float ALPHA1 = R_MULT / (l.input_quant_multipler * l.weights_quant_multipler); // cuDNN: y = alpha1 * conv(x) for (i = 0; i < l.outputs; ++i) { l.output[i] = output_q[i] * ALPHA1; // cuDNN: alpha1 } //for (fil = 0; fil < l.n; ++fil) { // for (j = 0; j < out_size; ++j) { // l.output[fil*out_size + j] = l.output[fil*out_size + j] * ALPHA1; // } //} // cuDNN: y = alpha1 * conv(x) + bias for (fil = 0; fil < l.n; ++fil) { for (j = 0; j < out_size; ++j) { l.output[fil*out_size + j] += l.biases[fil]; } } //draw_distribution(l.output, l.outputs, "output"); // cuDNN: y = act ( alpha1 * conv(x) + bias ) // bias is always FLOAT if (l.activation == LEAKY) { for (i = 0; i < l.n*out_size; ++i) { l.output[i] = (l.output[i]>0) ? l.output[i] : l.output[i] / 10; //leaky_activate(l.output[i]); } } free(output_q); } // 4 layers in 1: convolution, batch-normalization, BIAS and activation void forward_convolutional_layer_q_old(layer l, network_state state, int return_float) { int out_h = (l.h + 2 * l.pad - l.size) / l.stride + 1; // output_height=input_height for stride=1 and pad=1 int out_w = (l.w + 2 * l.pad - l.size) / l.stride + 1; // output_width=input_width for stride=1 and pad=1 int i, f, j; int const out_size = out_h*out_w; size_t const weights_size = l.size*l.size*l.c*l.n; // fill zero (ALPHA) //for (i = 0; i < l.outputs; ++i) l.output[i] = 0; // l.n - number of filters on this layer // l.c - channels of input-array // l.h - height of input-array // l.w - width of input-array // l.size - width and height of filters (the same size for all filters) //draw_distribution(l.weights, weights_size, NULL); //draw_distribution(state.input, l.inputs, NULL); typedef int16_t conv_t; // l.output conv_t *output_q = calloc(l.outputs, sizeof(conv_t)); //////////////////////////////////// // cudnnConvolutionBiasActivationForward() // y = act ( alpha1 * conv(x) + alpha2 * z + bias ) // int8 = activation( float * conv(int8) + float * int8 + float ) // int8 = activation( conv(input_int8) + bias_float ) // X_INT8x4 or X_INT8 // https://docs.nvidia.com/deeplearning/sdk/cudnn-developer-guide/index.html#cudnnConvolutionBiasActivationForward /////////////////////////////////// // 1. Convolution !!! #ifndef GEMMCONV int fil; // filter index #pragma omp parallel for // "omp parallel for" - automatic parallelization of loop by using OpenMP for (fil = 0; fil < l.n; ++fil) { int chan, y, x, f_y, f_x; // channel index for (chan = 0; chan < l.c; ++chan) // input - y for (y = 0; y < l.h; ++y) // input - x for (x = 0; x < l.w; ++x) { int const output_index = fil*l.w*l.h + y*l.w + x; int const weights_pre_index = fil*l.c*l.size*l.size + chan*l.size*l.size; int const input_pre_index = chan*l.w*l.h; //float sum = 0; //int16_t sum = 0; int32_t sum = 0; //conv_t sum = 0; // filter - y for (f_y = 0; f_y < l.size; ++f_y) { int input_y = y + f_y - l.pad; // filter - x for (f_x = 0; f_x < l.size; ++f_x) { int input_x = x + f_x - l.pad; if (input_y < 0 || input_x < 0 || input_y >= l.h || input_x >= l.w) continue; int input_index = input_pre_index + input_y*l.w + input_x; int weights_index = weights_pre_index + f_y*l.size + f_x; //sum += state.input[input_index] * l.weights[weights_index]; // int16 += int8 * int8; sum += (int32_t)state.input_int8[input_index] * (int32_t)l.weights_int8[weights_index]; } } // l.output[filters][width][height] += // state.input[channels][width][height] * // l.weights[filters][channels][filter_width][filter_height]; //output_q[output_index] += max_abs(sum, R_MAX_VAL); output_q[output_index] += max_abs(sum / R_MULT, R_MAX_VAL); //output_q[output_index] += sum / R_MULT; //if (fabs(output_q[output_index]) > 65535) printf(" fabs(output_q[output_index]) > 65535 \n"); } } #else int fil; // cuDNN: y = conv(x) int m = l.n; int k = l.size*l.size*l.c; int n = out_h*out_w; int8_t *a = l.weights_int8; int8_t *b = (int8_t *)state.workspace; conv_t *c = output_q; // int16_t // convolution as GEMM (as part of BLAS) //for (i = 0; i < l.batch; ++i) { im2col_cpu_int8(state.input_int8, l.c, l.h, l.w, l.size, l.stride, l.pad, b); // here //gemm_nn_int8_int16(m, n, k, 1, a, k, b, n, c, n); // single-thread gemm int t; // multi-thread gemm #pragma omp parallel for for (t = 0; t < m; ++t) { gemm_nn_int8_int16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int16_conv16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int32(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); conv_t should be int32_t } //} #endif // cuDNN: y = alpha1 * conv(x) //for (i = 0; i < l.outputs; ++i) { // output_q[i] = output_q[i] * l.output_multipler; // cuDNN: alpha1 //} for (fil = 0; fil < l.n; ++fil) { for (j = 0; j < out_size; ++j) { output_q[fil*out_size + j] = output_q[fil*out_size + j] * l.output_multipler; } } // cuDNN: y = alpha1 * conv(x) + bias for (fil = 0; fil < l.n; ++fil) { for (j = 0; j < out_size; ++j) { output_q[fil*out_size + j] += l.biases_quant[fil]; } } //for (i = 0; i < l.inputs; ++i) state.input[i] = state.input_int8[i]; //char buff[1024]; //sprintf(buff, "inputs - filters %d", l.n); //draw_distribution(state.input, l.inputs, buff); //for (i = 0; i < l.outputs; ++i) l.output[i] = (float)output_q[i]; //draw_distribution(l.output, l.outputs, "output"); // cuDNN: y = act ( alpha1 * conv(x) + bias ) // bias is always FLOAT if (l.activation == LEAKY) { for (i = 0; i < l.n*out_size; ++i) { output_q[i] = (output_q[i]>0) ? output_q[i] : output_q[i] / 10; //leaky_activate(l.output[i]); } } // cuDNN: y = act ( alpha1 * conv(x) + alpha2 * z + bias ), where: alpha2=0, z=NULL if (return_float) { // y - FLOAT, x,w - X_INT8 / X_INT8x4 for (i = 0; i < l.outputs; ++i) { l.output[i] = (float)output_q[i] / 16.F; // /8 // float32 // 15.769 } } else { // y - X_INT8 / X_INT8x4, x,w - X_INT8 / X_INT8x4 for (i = 0; i < l.outputs; ++i) { l.output_int8[i] = max_abs(output_q[i], I_MAX_VAL); // int8 } } free(output_q); } #define MIN_INT8 -128 // MAX pooling layer void forward_maxpool_layer_q(const layer l, network_state state) { int b, i, j, k, m, n; int w_offset = -l.pad; int h_offset = -l.pad; int h = l.out_h; int w = l.out_w; int c = l.c; // batch index for (b = 0; b < l.batch; ++b) { // channel index for (k = 0; k < c; ++k) { // y - input for (i = 0; i < h; ++i) { // x - input for (j = 0; j < w; ++j) { int out_index = j + w*(i + h*(k + c*b)); int8_t max = MIN_INT8; int max_i = -1; // pooling x-index for (n = 0; n < l.size; ++n) { // pooling y-index for (m = 0; m < l.size; ++m) { int cur_h = h_offset + i*l.stride + n; int cur_w = w_offset + j*l.stride + m; int index = cur_w + l.w*(cur_h + l.h*(k + b*l.c)); int valid = (cur_h >= 0 && cur_h < l.h && cur_w >= 0 && cur_w < l.w); int8_t val = (valid != 0) ? state.input_int8[index] : MIN_INT8; max_i = (val > max) ? index : max_i; // get max index max = (val > max) ? val : max; // get max value } } //l.output[out_index] = max; // store max value l.output_int8[out_index] = max; // store max value l.indexes[out_index] = max_i; // store max index } } } } } // Route layer - just copy 1 or more layers into the current layer void forward_route_layer_q(const layer l, network_state state) { int i, j; int offset = 0; // number of merged layers for (i = 0; i < l.n; ++i) { int index = l.input_layers[i]; // source layer index //float *input = state.net.layers[index].output; // source layer output ptr int8_t *input = state.net.layers[index].output_int8; // source layer output ptr int input_size = l.input_sizes[i]; // source layer size // batch index for (j = 0; j < l.batch; ++j) { memcpy(l.output_int8 + offset + j*l.outputs, input + j*input_size, input_size * sizeof(int8_t)); } offset += input_size; } } // Reorg layer - just change dimension sizes of the previous layer (some dimension sizes are increased by decreasing other) void forward_reorg_layer_q(const layer l, network_state state) { //float *out = l.output; //float *x = state.input; int8_t *out = l.output_int8; int8_t *x = state.input_int8; int out_w = l.out_w; int out_h = l.out_h; int out_c = l.out_c; int batch = l.batch; int stride = l.stride; int b, i, j, k; int in_c = out_c / (stride*stride); int out_w_X_stride = out_w*stride; int out_h_X_stride = out_h*stride; //printf("\n out_c = %d, out_w = %d, out_h = %d, stride = %d, forward = %d \n", out_c, out_w, out_h, stride, forward); //printf(" in_c = %d, in_w = %d, in_h = %d \n", in_c, out_w*stride, out_h*stride); // batch for (b = 0; b < batch; ++b) { // channel for (k = 0; k < out_c; ++k) { int c2 = k % in_c; int pre_out_index = out_h_X_stride*(c2 + in_c*b); int offset = k / in_c; int offset_mod_stride = offset % stride; int offset_div_stride = offset / stride; // y for (j = 0; j < out_h; ++j) { int pre_in_index = out_w*(j + out_h*(k + out_c*b)); // x for (i = 0; i < out_w; ++i) { int in_index = i + pre_in_index; int w2 = i*stride + offset_mod_stride; int h2 = j*stride + offset_div_stride; int out_index = w2 + out_w_X_stride*(h2 + pre_out_index); out[in_index] = x[out_index]; } } } } } // ---- region layer ---- static void softmax_q(float *input, int n, float temp, float *output) { int i; float sum = 0; float largest = -FLT_MAX; for (i = 0; i < n; ++i) { if (input[i] > largest) largest = input[i]; } for (i = 0; i < n; ++i) { float e = expf(input[i] / temp - largest / temp); sum += e; output[i] = e; } for (i = 0; i < n; ++i) { output[i] /= sum; } } static void softmax_tree(float *input, int batch, int inputs, float temp, tree *hierarchy, float *output) { int b; for (b = 0; b < batch; ++b) { int i; int count = 0; for (i = 0; i < hierarchy->groups; ++i) { int group_size = hierarchy->group_size[i]; softmax_q(input + b*inputs + count, group_size, temp, output + b*inputs + count); count += group_size; } } } // --- // Region layer - just change places of array items, then do logistic_activate and softmax void forward_region_layer_q(const layer l, network_state state) { int i, b; int size = l.coords + l.classes + 1; // 4 Coords(x,y,w,h) + Classes + 1 Probability-t0 //printf("\n l.coords = %d \n", l.coords); memcpy(l.output, state.input, l.outputs*l.batch * sizeof(float)); //flatten(l.output, l.w*l.h, size*l.n, l.batch, 1); // convert many channels to the one channel (depth=1) // (each grid cell will have a number of float-variables equal = to the initial number of channels) { float *x = l.output; int layer_size = l.w*l.h; // W x H - size of layer int layers = size*l.n; // number of channels (where l.n = number of anchors) int batch = l.batch; float *swap = calloc(layer_size*layers*batch, sizeof(float)); int i, c, b; // batch index for (b = 0; b < batch; ++b) { // channel index for (c = 0; c < layers; ++c) { // layer grid index for (i = 0; i < layer_size; ++i) { int i1 = b*layers*layer_size + c*layer_size + i; int i2 = b*layers*layer_size + i*layers + c; swap[i2] = x[i1]; } } } memcpy(x, swap, layer_size*layers*batch * sizeof(float)); free(swap); } // logistic activation only for: t0 (where is t0 = Probability * IoU(box, object)) for (b = 0; b < l.batch; ++b) { // for each item (x, y, anchor-index) for (i = 0; i < l.h*l.w*l.n; ++i) { int index = size*i + b*l.outputs; float x = l.output[index + 4]; l.output[index + 4] = 1.0F / (1.0F + expf(-x)); // logistic_activate_q(l.output[index + 4]); } } if (l.softmax_tree) { // Yolo 9000 for (b = 0; b < l.batch; ++b) { for (i = 0; i < l.h*l.w*l.n; ++i) { int index = size*i + b*l.outputs; softmax_tree(l.output + index + 5, 1, 0, 1, l.softmax_tree, l.output + index + 5); } } } else if (l.softmax) { // Yolo v2 // softmax activation only for Classes probability for (b = 0; b < l.batch; ++b) { // for each item (x, y, anchor-index) //#pragma omp parallel for for (i = 0; i < l.h*l.w*l.n; ++i) { int index = size*i + b*l.outputs; softmax_q(l.output + index + 5, l.classes, 1, l.output + index + 5); } } } } void yolov2_forward_network_q(network net, network_state state) { state.workspace = net.workspace; int i, k; for (i = 0; i < net.n; ++i) { state.index = i; layer l = net.layers[i]; if (l.type == CONVOLUTIONAL) { if (i >= 1 && l.activation != LINEAR) forward_convolutional_layer_q(l, state); else forward_convolutional_layer_cpu(l, state); printf("\n %d - CONVOLUTIONAL \t\t l.size = %d \n", i, l.size); } else if (l.type == MAXPOOL) { forward_maxpool_layer_cpu(l, state); //printf("\n MAXPOOL \t\t l.size = %d \n", l.size); } else if (l.type == ROUTE) { forward_route_layer_cpu(l, state); //printf("\n ROUTE \t\t\t l.n = %d \n", l.n); } else if (l.type == REORG) { forward_reorg_layer_cpu(l, state); //printf("\n REORG \n"); } else if (l.type == UPSAMPLE) { forward_upsample_layer_cpu(l, state); //printf("\n UPSAMPLE \n"); } else if (l.type == SHORTCUT) { forward_shortcut_layer_cpu(l, state); //printf("\n SHORTCUT \n"); } else if (l.type == YOLO) { forward_yolo_layer_cpu(l, state); //printf("\n YOLO \n"); } else if (l.type == REGION) { forward_region_layer_cpu(l, state); //printf("\n REGION \n"); } else { printf("\n layer: %d \n", l.type); } state.input = l.output; //state.input_int8 = l.output_int8; /* if (i == 0) { //draw_distribution(state.input, l.outputs, NULL); int k; for (k = 0; k < l.out_w*l.out_h*l.out_c; ++k) { int16_t src = state.input[k] * 3.88677;// *net.layers[2].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); //printf(" %d, ", src); } } */ } } void yolov2_forward_network_q_old(network net, network_state state) { state.workspace = net.workspace; int i, k; for (i = 0; i < net.n; ++i) { state.index = i; layer l = net.layers[i]; if (l.type == CONVOLUTIONAL) { int return_float = (net.layers[i+1].activation == LINEAR); // if next layer has LINEAR activation if (i >= 1 && l.activation != LINEAR) forward_convolutional_layer_q_old(l, state, return_float); else forward_convolutional_layer_cpu(l, state); printf("\n %d - CONVOLUTIONAL \t\t l.size = %d \n", i, l.size); } else if (l.type == MAXPOOL) { forward_maxpool_layer_q(l, state); //printf("\n MAXPOOL \t\t l.size = %d \n", l.size); } else if (l.type == ROUTE) { forward_route_layer_q(l, state); //printf("\n ROUTE \t\t\t l.n = %d \n", l.n); } else if (l.type == REORG) { forward_reorg_layer_q(l, state); //printf("\n REORG \n"); } /* else if (l.type == UPSAMPLE) { forward_upsample_layer_cpu(l, state); //printf("\n UPSAMPLE \n"); } else if (l.type == SHORTCUT) { forward_shortcut_layer_cpu(l, state); //printf("\n SHORTCUT \n"); } else if (l.type == YOLO) { forward_yolo_layer_cpu(l, state); //printf("\n YOLO \n"); } */ else if (l.type == REGION) { forward_region_layer_q(l, state); //printf("\n REGION \n"); } else { printf("\n layer: %d \n", l.type); } state.input = l.output; state.input_int8 = l.output_int8; if (i == 0) { //draw_distribution(state.input, l.outputs, NULL); int k; for (k = 0; k < l.out_w*l.out_h*l.out_c; ++k) { int16_t src = state.input[k] * 3.88677;// *net.layers[2].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); //printf(" %d, ", src); } } } } // detect on CPU float *network_predict_quantized(network net, float *input) { network_state state; state.net = net; state.index = 0; state.input = input; //state.input_int8 = calloc(net.w*net.h*net.c, sizeof(int8_t)); state.truth = 0; state.train = 0; state.delta = 0; /*/ int k; for (k = 0; k < net.w*net.h*net.c; ++k) { //int16_t src = lround(state.input[k] * net.layers[0].input_quant_multipler); int16_t src = state.input[k] * net.layers[0].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); } */ yolov2_forward_network_q(net, state); // network on CPU //float *out = get_network_output(net); int i; for (i = net.n - 1; i > 0; --i) if (net.layers[i].type != COST) break; //free(state.input_int8); return net.layers[i].output; } // detect on CPU float *network_predict_quantized_old(network net, float *input) { network_state state; state.net = net; state.index = 0; state.input = input; state.input_int8 = calloc(net.w*net.h*net.c, sizeof(int8_t)); state.truth = 0; state.train = 0; state.delta = 0; int k; for (k = 0; k < net.w*net.h*net.c; ++k) { //int16_t src = lround(state.input[k] * net.layers[0].input_quant_multipler); int16_t src = state.input[k] * net.layers[0].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); } yolov2_forward_network_q_old(net, state); // network on CPU //float *out = get_network_output(net); int i; for (i = net.n - 1; i > 0; --i) if (net.layers[i].type != COST) break; free(state.input_int8); return net.layers[i].output; } // -------------------- // x - last conv-layer output // biases - anchors from cfg-file // n - number of anchors from cfg-file box get_region_box_q(float *x, float *biases, int n, int index, int i, int j, int w, int h) { box b; b.x = (i + logistic_activate(x[index + 0])) / w; // (col + 1./(1. + exp(-x))) / width_last_layer b.y = (j + logistic_activate(x[index + 1])) / h; // (row + 1./(1. + exp(-x))) / height_last_layer b.w = expf(x[index + 2]) * biases[2 * n] / w; // exp(x) * anchor_w / width_last_layer b.h = expf(x[index + 3]) * biases[2 * n + 1] / h; // exp(x) * anchor_h / height_last_layer return b; } // get prediction boxes void get_region_boxes_q(layer l, int w, int h, float thresh, float **probs, box *boxes, int only_objectness, int *map) { int i, j, n; float *predictions = l.output; // grid index for (i = 0; i < l.w*l.h; ++i) { int row = i / l.w; int col = i % l.w; // anchor index for (n = 0; n < l.n; ++n) { int index = i*l.n + n; // index for each grid-cell & anchor int p_index = index * (l.classes + 5) + 4; float scale = predictions[p_index]; // scale = t0 = Probability * IoU(box, object) if (l.classfix == -1 && scale < .5) scale = 0; // if(t0 < 0.5) t0 = 0; int box_index = index * (l.classes + 5); boxes[index] = get_region_box_q(predictions, l.biases, n, box_index, col, row, l.w, l.h); boxes[index].x *= w; boxes[index].y *= h; boxes[index].w *= w; boxes[index].h *= h; int class_index = index * (l.classes + 5) + 5; // Yolo 9000 or Yolo v2 if (l.softmax_tree) { // Yolo 9000 hierarchy_predictions(predictions + class_index, l.classes, l.softmax_tree, 0); int found = 0; if (map) { for (j = 0; j < 200; ++j) { float prob = scale*predictions[class_index + map[j]]; probs[index][j] = (prob > thresh) ? prob : 0; } } else { for (j = l.classes - 1; j >= 0; --j) { if (!found && predictions[class_index + j] > .5) { found = 1; } else { predictions[class_index + j] = 0; } float prob = predictions[class_index + j]; probs[index][j] = (scale > thresh) ? prob : 0; } } } else { // Yolo v2 for (j = 0; j < l.classes; ++j) { float prob = scale*predictions[class_index + j]; // prob = IoU(box, object) = t0 * class-probability probs[index][j] = (prob > thresh) ? prob : 0; // if (IoU < threshold) IoU = 0; } } if (only_objectness) { probs[index][0] = scale; } } } } float entropy_calibration(float *src_arr, const size_t size, const float bin_width, const int max_bin) { //const float bin_width = 1.0 / 4096;// 1.0F / 64.0F; //const int max_bin = 2048*2;// 2048; const int max_global_val = max_bin * bin_width; // 1024 // 32 float *m_array = (float*)calloc(max_bin, sizeof(float)); float *H_histogram = (float*)calloc(max_bin, sizeof(float)); float *P_array = (float*)calloc(max_bin, sizeof(float)); float *Q_array = (float*)calloc(max_bin, sizeof(float)); float *quant_Q_array = (float*)calloc(128, sizeof(float)); // 128 for INT8 uint64_t *quant_Q_array_count = (uint64_t*)calloc(128, sizeof(uint64_t)); // 128 for INT8 int i, j; { //uint64_t outliers = 0; const int last_bin = max_bin - 1; for (j = 0; j <= last_bin; ++j) P_array[j] = 0; for (j = 0; j < size; ++j) { int bin_num = lround(fabs(src_arr[j]) / bin_width); int bin_num_saturated = (bin_num >= last_bin) ? last_bin : bin_num; H_histogram[bin_num_saturated]++; //if (bin_num > last_bin) outliers++; //else H_histogram[bin_num]++; } } for (i = 128; i < max_bin; ++i) { // [1/64; 1024] // [1/64; 32] //if (i > max_bin) printf(" i > max_bin = %d, ", i); //printf(" %d \r", i); // calculate bin histogram uint64_t outliers = 0; const int last_bin = i - 1; for (j = 0; j <= last_bin; ++j) P_array[j] = 0; /*for (j = 0; j < size; ++j) { int bin_num = lround(fabs(src_arr[j]) / bin_width); //int bin_num_saturated = (bin_num >= last_bin) ? last_bin : bin_num; if (bin_num > last_bin) outliers++; else P_array[bin_num]++; }*/ for (j = 0; j < max_bin; ++j) { if (j <= last_bin) P_array[j] = H_histogram[j]; else outliers += H_histogram[j]; } // quantinization P-i-bins to Q-128-bins const float quant_expand_width = i / 128.0F; for (j = 0; j < 128; ++j) quant_Q_array[j] = 0, quant_Q_array_count[j] = 0; for (j = 0; j < i; ++j) { int quant_bin = lround(j / quant_expand_width); if (quant_bin > 127) quant_bin = 127; // printf(" quant_bin > 127 = %d \n", quant_bin); quant_Q_array[quant_bin] += P_array[j]; if (P_array[j] != 0) quant_Q_array_count[quant_bin]++; } // expand 128-bins to i-bins for (j = 0; j < i; ++j) Q_array[j] = 0; for (j = 0; j < i; ++j) { int quant_bin = lround(j / quant_expand_width); if (quant_bin > 127) quant_bin = 127;// printf(" quant_bin > 127 = %d \n", quant_bin); //Q_array[j] = llround(quant_Q_array[quant_bin] / quant_expand_width); if (P_array[j] != 0) // preserve empty bins from original P Q_array[j] = quant_Q_array[quant_bin] / quant_Q_array_count[quant_bin]; //printf(" quant_bin = %d, Q[j] = %f = q_Q %f / q_w %f, P = %f \n", quant_bin, Q_array[j], quant_Q_array[quant_bin], quant_expand_width, P_array[j]); } P_array[last_bin] += outliers; // saturation // P /= SUM(P); Q /= SUM(Q); float sum_P = 0, sum_Q = 0, quant_sum_Q = 0; for (j = 0; j < 128; ++j) quant_sum_Q += quant_Q_array[j]; for (j = 0; j < i; ++j) { sum_P += P_array[j]; sum_Q += Q_array[j]; //printf(" P_array = %f, Q_array = %f \n", P_array[j], Q_array[j]); } for (j = 0; j < i; ++j) { P_array[j] /= sum_P; Q_array[j] /= sum_Q; } // KL_divergence(P, Q); for (j = 0; j < i; ++j) { m_array[i] += P_array[j] * (log((P_array[j] + FLT_MIN) / (Q_array[j] + FLT_MIN))); //printf(" p = %f, q = %f, p/q = %f, log(p/q) = %f, m = %f \n", P_array[j], Q_array[j], P_array[j] / Q_array[j], log((P_array[j] + FLT_MIN) / (Q_array[j] + FLT_MIN)), m_array[i]); } //printf("\n i = %d, size = %zu, sum_P = %f, sum_Q = %f, q_sum_Q = %f, q_e_width = %f, m = %f \n", i, size, sum_P, sum_Q, quant_sum_Q, quant_expand_width, m_array[i]); //getchar(); } float m_index = 128, min_m = FLT_MAX; for (i = 128; i < max_bin; ++i) { if (m_array[i] < min_m) { min_m = m_array[i]; m_index = i; } } float threshold = (m_index + 0.5) * bin_width; float multiplier = 127 / threshold; printf(" mult = %g, threshold = %g, min_m = %g, m_index = %g \n", multiplier, threshold, min_m, m_index); free(H_histogram); free(P_array); free(Q_array); free(quant_Q_array); free(quant_Q_array_count); free(m_array); //getchar(); return multiplier; } // Quantinization and get multiplers for convolutional weights for quantinization void quantinization_and_get_multipliers(network net) { // ----------- entropy_calibration(,, 1.0 / 16, 4096); - FULL ---------------------- //float input_mult[] = { 256, 4,32,64,32,32,32,32,32,64,64,64,64,64,128,64,128,128,64,128,64,128,128 }; // divided 4 - full works int counter = 0; //const int input_mult_size = sizeof(input_mult) / sizeof(float); int j; for (j = 0; j < net.n; ++j) { layer *l = &net.layers[j]; if (l->type == CONVOLUTIONAL) { size_t const weights_size = l->size*l->size*l->c*l->n; size_t const filter_size = l->size*l->size*l->c; int i, k, fil; // get optimal multipliers - for Weights //float *weights_multiplier = (float *)calloc(l->n, sizeof(float)); //l->output_multipler = (float *)calloc(l->n, sizeof(float)); //float weights_multiplier_single = entropy_calibration(l->weights, weights_size, 1.0 / (2048), (2048)); //float weights_multiplier_single = entropy_calibration(l->weights, weights_size, 1.0 / 4096, 4096) / 2; //if (j == 0) weights_multiplier_single = entropy_calibration(l->weights, weights_size, 1.0 / 2, 2048); float old_weight_mult = get_multiplier(l->weights, weights_size, 8) / 4; // good [2 - 8], best 4 float weights_multiplier_single = old_weight_mult; //float old_weight_mult = get_multiplier(l->weights, weights_size, 7) / 4; printf(" old_weight_mult = %f, weights_multiplier_single = %f \n\n", old_weight_mult, weights_multiplier_single); //weights_multiplier_single = old_weight_mult; l->weights_quant_multipler = weights_multiplier_single; for (fil = 0; fil < l->n; ++fil) { for (i = 0; i < filter_size; ++i) { float w = l->weights[fil*filter_size + i] * l->weights_quant_multipler;// [fil]; l->weights_int8[fil*filter_size + i] = max_abs(w, W_MAX_VAL); //l->weights_int8[fil*filter_size + i] = max_abs(lround(w), W_MAX_VAL); } } if (counter >= net.input_calibration_size) { printf("\n Warning: input_calibration= in the cfg-file has less values %d than convolutional layers %d \n", net.input_calibration_size, counter); } //l->input_quant_multipler = 40;//(counter < net.input_calibration_size) ? net.input_calibration[counter] : 16; // best 40 l->input_quant_multipler = (counter < net.input_calibration_size) ? net.input_calibration[counter] : 40; ++counter; //float current_input_mult = 40;//(counter < net.input_calibration_size) ? net.input_calibration[counter] : 16; float current_input_mult = (counter < net.input_calibration_size) ? net.input_calibration[counter] : 40; for (fil = 0; fil < l->n; ++fil) { if (counter == 1) l->output_multipler = current_input_mult / (l->weights_quant_multipler * l->input_quant_multipler / R_MULT); if (counter == 2) l->output_multipler = current_input_mult / (l->weights_quant_multipler * l->input_quant_multipler / R_MULT); else if (counter >= 2) l->output_multipler = current_input_mult / (l->weights_quant_multipler * l->input_quant_multipler / R_MULT); } // quantinization Biases for (fil = 0; fil < l->n; ++fil) { // calculate optimal multipliers - for Biases float biases_multipler = (l->output_multipler * l->weights_quant_multipler * l->input_quant_multipler / R_MULT); l->biases_quant[fil] = l->biases[fil] * biases_multipler; } printf(" Multiplers: weights %g, input %g, output %g \n", l->weights_quant_multipler, l->input_quant_multipler, l->output_multipler); } else { printf(" Skip layer: %d \n", l->type); } } #ifdef GPU // init weights and cuDNN for quantized IINT8x4 init_gpu_int8x4(net); #endif //GPU }
net_sha1_fmt_plug.c
/* Cracker for "Keyed SHA1" network authentication hashes. * * This software is Copyright (c) 2013, Dhiru Kholia <dhiru [at] openwall.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. * * Added linkage to dynamic (type dynamic_40) for any salt 230 bytes or less, * by Jim Fougeron. Any salts > 239 bytes will still be handled by this full * format. dynamic is limited to 256 bytes, which 'should' get us 240 bytes * of salt. I think we might be able to get 239 bytes (due to a few issues). * 240 byte salts fail. So, for peace of mind, I am limiting to 230 byte salts * within dynamic. */ #if AC_BUILT #include "autoconfig.h" #endif #ifndef DYNAMIC_DISABLED #if FMT_EXTERNS_H extern struct fmt_main fmt_netsha1; #elif FMT_REGISTERS_H john_register_one(&fmt_netsha1); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 2048 // XXX #endif #endif #include "formats.h" #include "dynamic.h" #include "sha.h" #include "misc.h" #include "common.h" #include "params.h" #include "options.h" #include "memdbg.h" #define FORMAT_LABEL "net-sha1" #define FORMAT_NAME "\"Keyed SHA1\" BFD" #define FORMAT_TAG "$netsha1$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #define ALGORITHM_NAME "SHA1 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 20 // get this right ;) #define BINARY_SIZE 20 #define BINARY_ALIGN sizeof(ARCH_WORD_32) #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN MEM_ALIGN_WORD #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define MAX_SALT_LEN 1024 static struct fmt_tests tests[] = { /* Real hashes from Cisco routers ;) */ {"$netsha1$20440a340000000100000000000f4240000f424000000000051c010000000001$709d3307304d790f58bf0a3cefd783b438408996", "password12345"}, {"$netsha1$20440a340000000100000000000f4240000f424000000000051c010000000002$94bce4d9084199508669b39f044064082a093de3", "password12345"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static void get_ptr(); static void init(struct fmt_main *self); static void done(void); #define MAGIC 0xfe5aa5ef static struct custom_salt { ARCH_WORD_32 magic; int length; unsigned char salt[MAX_SALT_LEN]; // fixed size, but should be OK } *cur_salt; static int dyna_salt_seen=0; static char Conv_Buf[300]; // max salt length we will pass to dyna is 230. 300 is MORE than enough. static struct fmt_main *pDynamicFmt, *pNetSha1_Dyna; /* this function converts a 'native' net-sha1 signature string into a $dynamic_40$ syntax string */ static char *Convert(char *Buf, char *ciphertext) { char *cp, *cp2; if (text_in_dynamic_format_already(pDynamicFmt, ciphertext)) return ciphertext; cp = strchr(&ciphertext[2], '$'); if (!cp) return "*"; cp2 = strchr(&cp[1], '$'); if (!cp2) return "*"; snprintf(Buf, sizeof(Conv_Buf), "$dynamic_40$%s$HEX%*.*s", &cp2[1], (int)(cp2-cp), (int)(cp2-cp), cp); return Buf; } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q = NULL; int len; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += TAG_LENGTH; q = strrchr(ciphertext, '$'); if (!q) return 0; q = q + 1; if ((q - p - 1) > MAX_SALT_LEN * 2) return 0; len = strspn(q, HEXCHARS_lc); if (len != BINARY_SIZE * 2 || len != strlen(q)) { get_ptr(); return pDynamicFmt->methods.valid(ciphertext, pDynamicFmt); } if (strspn(p, HEXCHARS_lc) != q - p - 1) return 0; return 1; } static void *get_salt(char *ciphertext) { static char *pBuf=NULL; struct custom_salt *cs; char *orig_ct = ciphertext; int i, len; if (!pBuf) pBuf = (char *)mem_alloc_tiny(sizeof(struct custom_salt), MEM_ALIGN_WORD); cs = (struct custom_salt*) pBuf; memset(cs, 0, sizeof(*cs)); if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) ciphertext += TAG_LENGTH; len = (strrchr(ciphertext, '$') - ciphertext) / 2; for (i = 0; i < len; i++) cs->salt[i] = (atoi16[ARCH_INDEX(ciphertext[2 * i])] << 4) | atoi16[ARCH_INDEX(ciphertext[2 * i + 1])]; if (len < 230) { // return our memset buffer (putting the dyna salt pointer into it). // This keeps the 'pre-cleaned salt() warning from hitting this format) //return pDynamicFmt->methods.salt(Convert(Conv_Buf, orig_ct)); memcpy((char*)cs, pDynamicFmt->methods.salt(Convert(Conv_Buf, orig_ct)), pDynamicFmt->params.salt_size); dyna_salt_seen=1; return cs; } cs->magic = MAGIC; cs->length = len; return cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; if (text_in_dynamic_format_already(pDynamicFmt, ciphertext)) { unsigned char *cp = pDynamicFmt->methods.binary(ciphertext); memset(out, 0, sizeof(buf.c)); memcpy(out, cp, pDynamicFmt->params.binary_size); // binary size is 16 return out; } 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) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[0](index); return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[1](index); return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[2](index); return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[3](index); return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[4](index); return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[5](index); return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[6](index); return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; get_ptr(); if (cur_salt->magic != MAGIC) { pDynamicFmt->methods.set_salt(salt); } } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; if (cur_salt->magic != MAGIC) { return pDynamicFmt->methods.crypt_all(pcount, salt); } #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, cur_salt->salt, cur_salt->length); SHA1_Update(&ctx, saved_key[index], PLAINTEXT_LENGTH); SHA1_Final((unsigned char*)crypt_out[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index = 0; if (cur_salt->magic != MAGIC) { return pDynamicFmt->methods.cmp_all(binary, count); } for (; index < count; index++) if (((ARCH_WORD_32*)binary)[0] == crypt_out[index][0]) return 1; return 0; } static int cmp_one(void *binary, int index) { if (cur_salt->magic != MAGIC) { return pDynamicFmt->methods.cmp_one(binary, index); } return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void netsha1_set_key(char *key, int index) { if (dyna_salt_seen) pDynamicFmt->methods.set_key(key, index); /* strncpy will pad with zeros, which is needed */ strncpy(saved_key[index], key, sizeof(saved_key[0])); } static char *get_key(int index) { return saved_key[index]; } static char *prepare(char *fields[10], struct fmt_main *self) { static char buf[sizeof(cur_salt->salt)*2+TAG_LENGTH+1]; char *hash = fields[1]; if (strncmp(hash, FORMAT_TAG, TAG_LENGTH) && valid(hash, self)) { get_ptr(); if (text_in_dynamic_format_already(pDynamicFmt, hash)) return hash; sprintf(buf, "%s%s", FORMAT_TAG, hash); return buf; } return hash; } struct fmt_main fmt_netsha1 = { { 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, { NULL }, tests }, { init, done, fmt_default_reset, prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, netsha1_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 } }; static void get_ptr() { if (!pDynamicFmt) { char *Buf; pNetSha1_Dyna = mem_alloc_tiny(sizeof(fmt_netsha1), 16); memcpy(pNetSha1_Dyna, &fmt_netsha1, sizeof(fmt_netsha1)); pDynamicFmt = dynamic_THIN_FORMAT_LINK(pNetSha1_Dyna, Convert(Conv_Buf, tests[1].ciphertext), "net-sha1", 0); fmt_netsha1.params.min_keys_per_crypt = pDynamicFmt->params.min_keys_per_crypt; fmt_netsha1.params.max_keys_per_crypt = pDynamicFmt->params.max_keys_per_crypt; Buf = mem_alloc_tiny(strlen(fmt_netsha1.params.algorithm_name) + 4 + strlen("dynamic_40") + 1, 1); sprintf(Buf, "%s or %s", fmt_netsha1.params.algorithm_name, "dynamic_40"); fmt_netsha1.params.algorithm_name = Buf; //pDynamicFmt->methods.init(pDynamicFmt); } } static void init(struct fmt_main *self) { // We have to allocate our dyna_40 object first, because we get 'modified' min/max counts from there. get_ptr(); if (self->private.initialized == 0) { pDynamicFmt = dynamic_THIN_FORMAT_LINK(pNetSha1_Dyna, Convert(Conv_Buf, tests[1].ciphertext), "net-sha1", 1); self->private.initialized = 1; } 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(crypt_out); MEM_FREE(saved_key); pDynamicFmt->methods.done(); } #endif /* plugin stanza */ #endif /* DYNAMIC_DISABLED */
DRB004-antidep2-var-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Two nested loops with loop-carried anti-dependence on the outer level. This is a variable-length array version in C99. Data race pair: a[i][j]@70:7 vs. a[i+1][j]@70:18 */ #include <stdlib.h> int main(int argc,char *argv[]) { int i, j; int len = 20; if (argc>1) len = atoi(argv[1]); double a[len][len]; #pragma omp parallel for for (i=0; i< len; i++) #pragma omp parallel for for (j=0; j<len; j++) a[i][j] = 0.5; for (i = 0; i < len - 1; i += 1) { #pragma omp parallel for for (j = 0; j < len ; j += 1) { a[i][j] += a[i + 1][j]; } } for (i=0; i< len; i++) for (j=0; j<len; j++) printf("%lf\n",a[i][j]); return 0; }
fluid_defsfont.c
/* FluidSynth - A Software Synthesizer * * Copyright (C) 2003 Peter Hanappe and others. * * SoundFont file loading code borrowed from Smurf SoundFont Editor * Copyright (C) 1999-2001 Josh Green * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA */ #include "fluid_defsfont.h" #include "fluid_sfont.h" #include "fluid_sys.h" #include "fluid_synth.h" #include "fluid_samplecache.h" #include "fluid_chan.h" /* EMU8k/10k hardware applies this factor to initial attenuation generator values set at preset and * instrument level in a soundfont. We apply this factor when loading the generator values to stay * compatible as most existing soundfonts expect exactly this (strange, non-standard) behaviour. */ #define EMU_ATTENUATION_FACTOR (0.4f) /* Dynamic sample loading functions */ static int pin_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset); static int unpin_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset); static int load_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset); static int unload_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset); static void unload_sample(fluid_sample_t *sample); static int dynamic_samples_preset_notify(fluid_preset_t *preset, int reason, int chan); static int dynamic_samples_sample_notify(fluid_sample_t *sample, int reason); static int fluid_preset_zone_create_voice_zones(fluid_preset_zone_t *preset_zone); static fluid_inst_t *find_inst_by_idx(fluid_defsfont_t *defsfont, int idx); /*************************************************************** * * SFONT LOADER */ /** * Creates a default soundfont2 loader that can be used with fluid_synth_add_sfloader(). * By default every synth instance has an initial default soundfont loader instance. * Calling this function is usually only necessary to load a soundfont from memory, by providing custom callback functions via fluid_sfloader_set_callbacks(). * * @param settings A settings instance obtained by new_fluid_settings() * @return A default soundfont2 loader struct */ fluid_sfloader_t *new_fluid_defsfloader(fluid_settings_t *settings) { fluid_sfloader_t *loader; fluid_return_val_if_fail(settings != NULL, NULL); loader = new_fluid_sfloader(fluid_defsfloader_load, delete_fluid_sfloader); if(loader == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return NULL; } fluid_sfloader_set_data(loader, settings); return loader; } fluid_sfont_t *fluid_defsfloader_load(fluid_sfloader_t *loader, const char *filename) { fluid_defsfont_t *defsfont; fluid_sfont_t *sfont; defsfont = new_fluid_defsfont(fluid_sfloader_get_data(loader)); if(defsfont == NULL) { return NULL; } sfont = new_fluid_sfont(fluid_defsfont_sfont_get_name, fluid_defsfont_sfont_get_preset, fluid_defsfont_sfont_iteration_start, fluid_defsfont_sfont_iteration_next, fluid_defsfont_sfont_delete); if(sfont == NULL) { delete_fluid_defsfont(defsfont); return NULL; } fluid_sfont_set_data(sfont, defsfont); defsfont->sfont = sfont; if(fluid_defsfont_load(defsfont, &loader->file_callbacks, filename) == FLUID_FAILED) { fluid_defsfont_sfont_delete(sfont); return NULL; } return sfont; } /*************************************************************** * * PUBLIC INTERFACE */ int fluid_defsfont_sfont_delete(fluid_sfont_t *sfont) { if(delete_fluid_defsfont(fluid_sfont_get_data(sfont)) != FLUID_OK) { return -1; } delete_fluid_sfont(sfont); return 0; } const char *fluid_defsfont_sfont_get_name(fluid_sfont_t *sfont) { return fluid_defsfont_get_name(fluid_sfont_get_data(sfont)); } fluid_preset_t * fluid_defsfont_sfont_get_preset(fluid_sfont_t *sfont, int bank, int prenum) { return fluid_defsfont_get_preset(fluid_sfont_get_data(sfont), bank, prenum); } void fluid_defsfont_sfont_iteration_start(fluid_sfont_t *sfont) { fluid_defsfont_iteration_start(fluid_sfont_get_data(sfont)); } fluid_preset_t *fluid_defsfont_sfont_iteration_next(fluid_sfont_t *sfont) { return fluid_defsfont_iteration_next(fluid_sfont_get_data(sfont)); } void fluid_defpreset_preset_delete(fluid_preset_t *preset) { fluid_defsfont_t *defsfont; fluid_defpreset_t *defpreset; defsfont = fluid_sfont_get_data(preset->sfont); defpreset = fluid_preset_get_data(preset); if(defsfont) { defsfont->preset = fluid_list_remove(defsfont->preset, defpreset); } delete_fluid_defpreset(defpreset); delete_fluid_preset(preset); } const char *fluid_defpreset_preset_get_name(fluid_preset_t *preset) { return fluid_defpreset_get_name(fluid_preset_get_data(preset)); } int fluid_defpreset_preset_get_banknum(fluid_preset_t *preset) { return fluid_defpreset_get_banknum(fluid_preset_get_data(preset)); } int fluid_defpreset_preset_get_num(fluid_preset_t *preset) { return fluid_defpreset_get_num(fluid_preset_get_data(preset)); } int fluid_defpreset_preset_noteon(fluid_preset_t *preset, fluid_synth_t *synth, int chan, int key, int vel) { return fluid_defpreset_noteon(fluid_preset_get_data(preset), synth, chan, key, vel); } /*************************************************************** * * SFONT */ /* * new_fluid_defsfont */ fluid_defsfont_t *new_fluid_defsfont(fluid_settings_t *settings) { fluid_defsfont_t *defsfont; defsfont = FLUID_NEW(fluid_defsfont_t); if(defsfont == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return NULL; } FLUID_MEMSET(defsfont, 0, sizeof(*defsfont)); fluid_settings_getint(settings, "synth.lock-memory", &defsfont->mlock); fluid_settings_getint(settings, "synth.dynamic-sample-loading", &defsfont->dynamic_samples); return defsfont; } /* * delete_fluid_defsfont */ int delete_fluid_defsfont(fluid_defsfont_t *defsfont) { fluid_list_t *list; fluid_preset_t *preset; fluid_sample_t *sample; fluid_return_val_if_fail(defsfont != NULL, FLUID_OK); /* If we use dynamic sample loading, make sure we unpin any * pinned presets before removing this soundfont */ if(defsfont->dynamic_samples) { for(list = defsfont->preset; list; list = fluid_list_next(list)) { preset = (fluid_preset_t *)fluid_list_get(list); unpin_preset_samples(defsfont, preset); } } /* Check that no samples are currently used */ for(list = defsfont->sample; list; list = fluid_list_next(list)) { sample = (fluid_sample_t *) fluid_list_get(list); if(sample->refcount != 0) { return FLUID_FAILED; } } if(defsfont->filename != NULL) { FLUID_FREE(defsfont->filename); } for(list = defsfont->sample; list; list = fluid_list_next(list)) { sample = (fluid_sample_t *) fluid_list_get(list); /* If the sample data pointer is different to the sampledata chunk of * the soundfont, then the sample has been loaded individually (SF3) * and needs to be unloaded explicitly. This is safe even if using * dynamic sample loading, as the sample_unload mechanism sets * sample->data to NULL after unload. */ if ((sample->data != NULL) && (sample->data != defsfont->sampledata)) { fluid_samplecache_unload(sample->data); } delete_fluid_sample(sample); } if(defsfont->sample) { delete_fluid_list(defsfont->sample); } if(defsfont->sampledata != NULL) { fluid_samplecache_unload(defsfont->sampledata); } for(list = defsfont->preset; list; list = fluid_list_next(list)) { preset = (fluid_preset_t *)fluid_list_get(list); fluid_defpreset_preset_delete(preset); } delete_fluid_list(defsfont->preset); for(list = defsfont->inst; list; list = fluid_list_next(list)) { delete_fluid_inst(fluid_list_get(list)); } delete_fluid_list(defsfont->inst); FLUID_FREE(defsfont); return FLUID_OK; } /* * fluid_defsfont_get_name */ const char *fluid_defsfont_get_name(fluid_defsfont_t *defsfont) { return defsfont->filename; } /* Load sample data for a single sample from the Soundfont file. * Returns FLUID_OK on error, otherwise FLUID_FAILED */ int fluid_defsfont_load_sampledata(fluid_defsfont_t *defsfont, SFData *sfdata, fluid_sample_t *sample) { int num_samples; unsigned int source_end = sample->source_end; /* For uncompressed samples we want to include the 46 zero sample word area following each sample * in the Soundfont. Otherwise samples with loopend > end, which we have decided not to correct, would * be corrected after all in fluid_sample_sanitize_loop */ if(!(sample->sampletype & FLUID_SAMPLETYPE_OGG_VORBIS)) { source_end += 46; /* Length of zero sample word after each sample, according to SF specs */ /* Safeguard against Soundfonts that are not quite valid and don't include 46 sample words after the * last sample */ if(source_end >= (defsfont->samplesize / sizeof(short))) { source_end = defsfont->samplesize / sizeof(short); } } num_samples = fluid_samplecache_load( sfdata, sample->source_start, source_end, sample->sampletype, defsfont->mlock, &sample->data, &sample->data24); if(num_samples < 0) { return FLUID_FAILED; } if(num_samples == 0) { sample->start = sample->end = 0; sample->loopstart = sample->loopend = 0; return FLUID_OK; } /* Ogg Vorbis samples already have loop pointers relative to the individual decompressed sample, * but SF2 samples are relative to sample chunk start, so they need to be adjusted */ if(!(sample->sampletype & FLUID_SAMPLETYPE_OGG_VORBIS)) { sample->loopstart = sample->source_loopstart - sample->source_start; sample->loopend = sample->source_loopend - sample->source_start; } /* As we've just loaded an individual sample into it's own buffer, we need to adjust the start * and end pointers */ sample->start = 0; sample->end = num_samples - 1; return FLUID_OK; } /* Loads the sample data for all samples from the Soundfont file. For SF2 files, it loads the data in * one large block. For SF3 files, each compressed sample gets loaded individually. * Returns FLUID_OK on success, otherwise FLUID_FAILED */ int fluid_defsfont_load_all_sampledata(fluid_defsfont_t *defsfont, SFData *sfdata) { fluid_list_t *list; fluid_sample_t *sample; int sf3_file = (sfdata->version.major == 3); int sample_parsing_result = FLUID_OK; /* For SF2 files, we load the sample data in one large block */ if(!sf3_file) { int read_samples; int num_samples = sfdata->samplesize / sizeof(short); read_samples = fluid_samplecache_load(sfdata, 0, num_samples - 1, 0, defsfont->mlock, &defsfont->sampledata, &defsfont->sample24data); if(read_samples != num_samples) { FLUID_LOG(FLUID_ERR, "Attempted to read %d words of sample data, but got %d instead", num_samples, read_samples); return FLUID_FAILED; } } #pragma omp parallel #pragma omp single for(list = defsfont->sample; list; list = fluid_list_next(list)) { sample = fluid_list_get(list); if(sf3_file) { /* SF3 samples get loaded individually, as most (or all) of them are in Ogg Vorbis format * anyway */ #pragma omp task firstprivate(sample,sfdata,defsfont) shared(sample_parsing_result) default(none) { if(fluid_defsfont_load_sampledata(defsfont, sfdata, sample) == FLUID_FAILED) { #pragma omp critical { FLUID_LOG(FLUID_ERR, "Failed to load sample '%s'", sample->name); sample_parsing_result = FLUID_FAILED; } } else { fluid_sample_sanitize_loop(sample, (sample->end + 1) * sizeof(short)); fluid_voice_optimize_sample(sample); } } } else { #pragma omp task firstprivate(sample, defsfont) default(none) { /* Data pointers of SF2 samples point to large sample data block loaded above */ sample->data = defsfont->sampledata; sample->data24 = defsfont->sample24data; fluid_sample_sanitize_loop(sample, defsfont->samplesize); fluid_voice_optimize_sample(sample); } } } return sample_parsing_result; } /* * fluid_defsfont_load */ int fluid_defsfont_load(fluid_defsfont_t *defsfont, const fluid_file_callbacks_t *fcbs, const char *file) { SFData *sfdata; fluid_list_t *p; SFPreset *sfpreset; SFSample *sfsample; fluid_sample_t *sample; fluid_defpreset_t *defpreset = NULL; defsfont->filename = FLUID_STRDUP(file); if(defsfont->filename == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return FLUID_FAILED; } defsfont->fcbs = fcbs; /* The actual loading is done in the sfont and sffile files */ sfdata = fluid_sffile_open(file, fcbs); if(sfdata == NULL) { /* error message already printed */ return FLUID_FAILED; } if(fluid_sffile_parse_presets(sfdata) == FLUID_FAILED) { FLUID_LOG(FLUID_ERR, "Couldn't parse presets from soundfont file"); goto err_exit; } /* Keep track of the position and size of the sample data because it's loaded separately (and might be unoaded/reloaded in future) */ defsfont->samplepos = sfdata->samplepos; defsfont->samplesize = sfdata->samplesize; defsfont->sample24pos = sfdata->sample24pos; defsfont->sample24size = sfdata->sample24size; /* Create all samples from sample headers */ p = sfdata->sample; while(p != NULL) { sfsample = (SFSample *)fluid_list_get(p); sample = new_fluid_sample(); if(sample == NULL) { goto err_exit; } if(fluid_sample_import_sfont(sample, sfsample, defsfont) == FLUID_OK) { fluid_defsfont_add_sample(defsfont, sample); } else { delete_fluid_sample(sample); sample = NULL; } /* Store reference to FluidSynth sample in SFSample for later IZone fixups */ sfsample->fluid_sample = sample; p = fluid_list_next(p); } /* If dynamic sample loading is disabled, load all samples in the Soundfont */ if(!defsfont->dynamic_samples) { if(fluid_defsfont_load_all_sampledata(defsfont, sfdata) == FLUID_FAILED) { FLUID_LOG(FLUID_ERR, "Unable to load all sample data"); goto err_exit; } } /* Load all the presets */ p = sfdata->preset; while(p != NULL) { sfpreset = (SFPreset *)fluid_list_get(p); defpreset = new_fluid_defpreset(); if(defpreset == NULL) { goto err_exit; } if(fluid_defpreset_import_sfont(defpreset, sfpreset, defsfont, sfdata) != FLUID_OK) { goto err_exit; } if(fluid_defsfont_add_preset(defsfont, defpreset) == FLUID_FAILED) { goto err_exit; } p = fluid_list_next(p); } fluid_sffile_close(sfdata); return FLUID_OK; err_exit: fluid_sffile_close(sfdata); delete_fluid_defpreset(defpreset); return FLUID_FAILED; } /* fluid_defsfont_add_sample * * Add a sample to the SoundFont */ int fluid_defsfont_add_sample(fluid_defsfont_t *defsfont, fluid_sample_t *sample) { defsfont->sample = fluid_list_prepend(defsfont->sample, sample); return FLUID_OK; } /* fluid_defsfont_add_preset * * Add a preset to the SoundFont */ int fluid_defsfont_add_preset(fluid_defsfont_t *defsfont, fluid_defpreset_t *defpreset) { fluid_preset_t *preset; preset = new_fluid_preset(defsfont->sfont, fluid_defpreset_preset_get_name, fluid_defpreset_preset_get_banknum, fluid_defpreset_preset_get_num, fluid_defpreset_preset_noteon, fluid_defpreset_preset_delete); if(preset == NULL) { return FLUID_FAILED; } if(defsfont->dynamic_samples) { preset->notify = dynamic_samples_preset_notify; } fluid_preset_set_data(preset, defpreset); defsfont->preset = fluid_list_append(defsfont->preset, preset); return FLUID_OK; } /* * fluid_defsfont_get_preset */ fluid_preset_t *fluid_defsfont_get_preset(fluid_defsfont_t *defsfont, int bank, int num) { fluid_preset_t *preset; fluid_list_t *list; for(list = defsfont->preset; list != NULL; list = fluid_list_next(list)) { preset = (fluid_preset_t *)fluid_list_get(list); if((fluid_preset_get_banknum(preset) == bank) && (fluid_preset_get_num(preset) == num)) { return preset; } } return NULL; } /* * fluid_defsfont_iteration_start */ void fluid_defsfont_iteration_start(fluid_defsfont_t *defsfont) { defsfont->preset_iter_cur = defsfont->preset; } /* * fluid_defsfont_iteration_next */ fluid_preset_t *fluid_defsfont_iteration_next(fluid_defsfont_t *defsfont) { fluid_preset_t *preset = (fluid_preset_t *)fluid_list_get(defsfont->preset_iter_cur); defsfont->preset_iter_cur = fluid_list_next(defsfont->preset_iter_cur); return preset; } /*************************************************************** * * PRESET */ /* * new_fluid_defpreset */ fluid_defpreset_t * new_fluid_defpreset(void) { fluid_defpreset_t *defpreset = FLUID_NEW(fluid_defpreset_t); if(defpreset == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return NULL; } defpreset->next = NULL; defpreset->name[0] = 0; defpreset->bank = 0; defpreset->num = 0; defpreset->global_zone = NULL; defpreset->zone = NULL; defpreset->pinned = FALSE; return defpreset; } /* * delete_fluid_defpreset */ void delete_fluid_defpreset(fluid_defpreset_t *defpreset) { fluid_preset_zone_t *zone; fluid_return_if_fail(defpreset != NULL); delete_fluid_preset_zone(defpreset->global_zone); defpreset->global_zone = NULL; zone = defpreset->zone; while(zone != NULL) { defpreset->zone = zone->next; delete_fluid_preset_zone(zone); zone = defpreset->zone; } FLUID_FREE(defpreset); } int fluid_defpreset_get_banknum(fluid_defpreset_t *defpreset) { return defpreset->bank; } int fluid_defpreset_get_num(fluid_defpreset_t *defpreset) { return defpreset->num; } const char * fluid_defpreset_get_name(fluid_defpreset_t *defpreset) { return defpreset->name; } /* * fluid_defpreset_next */ fluid_defpreset_t * fluid_defpreset_next(fluid_defpreset_t *defpreset) { return defpreset->next; } /* * Adds global and local modulators list to the voice. This is done in 2 steps: * - Step 1: Local modulators replace identic global modulators. * - Step 2: global + local modulators are added to the voice using mode. * * Instrument zone list (local/global) must be added using FLUID_VOICE_OVERWRITE. * Preset zone list (local/global) must be added using FLUID_VOICE_ADD. * * @param voice voice instance. * @param global_mod global list of modulators. * @param local_mod local list of modulators. * @param mode Determines how to handle an existing identical modulator. * #FLUID_VOICE_ADD to add (offset) the modulator amounts, * #FLUID_VOICE_OVERWRITE to replace the modulator, */ static void fluid_defpreset_noteon_add_mod_to_voice(fluid_voice_t *voice, fluid_mod_t *global_mod, fluid_mod_t *local_mod, int mode) { fluid_mod_t *mod; /* list for 'sorting' global/local modulators */ fluid_mod_t *mod_list[FLUID_NUM_MOD]; int mod_list_count, i; /* identity_limit_count is the modulator upper limit number to handle with * existing identical modulators. * When identity_limit_count is below the actual number of modulators, this * will restrict identity check to this upper limit, * This is useful when we know by advance that there is no duplicate with * modulators at index above this limit. This avoid wasting cpu cycles at * noteon. */ int identity_limit_count; /* Step 1: Local modulators replace identic global modulators. */ /* local (instrument zone/preset zone), modulators: Put them all into a list. */ mod_list_count = 0; while(local_mod) { /* As modulators number in local_mod list was limited to FLUID_NUM_MOD at soundfont loading time (fluid_limit_mod_list()), here we don't need to check if mod_list is full. */ mod_list[mod_list_count++] = local_mod; local_mod = local_mod->next; } /* global (instrument zone/preset zone), modulators. * Replace modulators with the same definition in the global list: * (Instrument zone: SF 2.01 page 69, 'bullet' 8) * (Preset zone: SF 2.01 page 69, second-last bullet). * * mod_list contains local modulators. Now we know that there * is no global modulator identic to another global modulator (this has * been checked at soundfont loading time). So global modulators * are only checked against local modulators number. */ /* Restrict identity check to the number of local modulators */ identity_limit_count = mod_list_count; while(global_mod) { /* 'Identical' global modulators are ignored. * SF2.01 section 9.5.1 * page 69, 'bullet' 3 defines 'identical'. */ for(i = 0; i < identity_limit_count; i++) { if(fluid_mod_test_identity(global_mod, mod_list[i])) { break; } } /* Finally add the new modulator to the list. */ if(i >= identity_limit_count) { /* Although local_mod and global_mod lists was limited to FLUID_NUM_MOD at soundfont loading time, it is possible that local + global modulators exceeds FLUID_NUM_MOD. So, checks if mod_list_count reaches the limit. */ if(mod_list_count >= FLUID_NUM_MOD) { /* mod_list is full, we silently forget this modulator and next global modulators. When mod_list will be added to the voice, a warning will be displayed if the voice list is full. (see fluid_voice_add_mod_local()). */ break; } mod_list[mod_list_count++] = global_mod; } global_mod = global_mod->next; } /* Step 2: global + local modulators are added to the voice using mode. */ /* * mod_list contains local and global modulators, we know that: * - there is no global modulator identic to another global modulator, * - there is no local modulator identic to another local modulator, * So these local/global modulators are only checked against * actual number of voice modulators. */ /* Restrict identity check to the actual number of voice modulators */ /* Actual number of voice modulators : defaults + [instruments] */ identity_limit_count = voice->mod_count; for(i = 0; i < mod_list_count; i++) { mod = mod_list[i]; /* in mode FLUID_VOICE_OVERWRITE disabled instruments modulators CANNOT be skipped. */ /* in mode FLUID_VOICE_ADD disabled preset modulators can be skipped. */ if((mode == FLUID_VOICE_OVERWRITE) || (mod->amount != 0)) { /* Instrument modulators -supersede- existing (default) modulators. SF 2.01 page 69, 'bullet' 6 */ /* Preset modulators -add- to existing instrument modulators. SF2.01 page 70 first bullet on page */ fluid_voice_add_mod_local(voice, mod, mode, identity_limit_count); } } } /* * fluid_defpreset_noteon */ int fluid_defpreset_noteon(fluid_defpreset_t *defpreset, fluid_synth_t *synth, int chan, int key, int vel) { fluid_preset_zone_t *preset_zone, *global_preset_zone; fluid_inst_t *inst; fluid_inst_zone_t *inst_zone, *global_inst_zone; fluid_voice_zone_t *voice_zone; fluid_list_t *list; fluid_voice_t *voice; int tuned_key; int i; /* For detuned channels it might be better to use another key for Soundfont sample selection * giving better approximations for the pitch than the original key. * Example: play key 60 on 6370 Hz => use tuned key 64 for sample selection * * This feature is only enabled for melodic channels. * For drum channels we always select Soundfont samples by key numbers. */ if(synth->channel[chan]->channel_type == CHANNEL_TYPE_MELODIC) { tuned_key = (int)(fluid_channel_get_key_pitch(synth->channel[chan], key) / 100.0f + 0.5f); } else { tuned_key = key; } global_preset_zone = fluid_defpreset_get_global_zone(defpreset); /* run thru all the zones of this preset */ preset_zone = fluid_defpreset_get_zone(defpreset); while(preset_zone != NULL) { /* check if the note falls into the key and velocity range of this preset */ if(fluid_zone_inside_range(&preset_zone->range, tuned_key, vel)) { inst = fluid_preset_zone_get_inst(preset_zone); global_inst_zone = fluid_inst_get_global_zone(inst); /* run thru all the zones of this instrument that could start a voice */ for(list = preset_zone->voice_zone; list != NULL; list = fluid_list_next(list)) { voice_zone = fluid_list_get(list); /* check if the instrument zone is ignored and the note falls into the key and velocity range of this instrument zone. An instrument zone must be ignored when its voice is already running played by a legato passage (see fluid_synth_noteon_monopoly_legato()) */ if(fluid_zone_inside_range(&voice_zone->range, tuned_key, vel)) { inst_zone = voice_zone->inst_zone; /* this is a good zone. allocate a new synthesis process and initialize it */ voice = fluid_synth_alloc_voice_LOCAL(synth, inst_zone->sample, chan, key, vel, &voice_zone->range); if(voice == NULL) { return FLUID_FAILED; } /* Instrument level, generators */ for(i = 0; i < GEN_LAST; i++) { /* SF 2.01 section 9.4 'bullet' 4: * * A generator in a local instrument zone supersedes a * global instrument zone generator. Both cases supersede * the default generator -> voice_gen_set */ if(inst_zone->gen[i].flags) { fluid_voice_gen_set(voice, i, inst_zone->gen[i].val); } else if((global_inst_zone != NULL) && (global_inst_zone->gen[i].flags)) { fluid_voice_gen_set(voice, i, global_inst_zone->gen[i].val); } else { /* The generator has not been defined in this instrument. * Do nothing, leave it at the default. */ } } /* for all generators */ /* Adds instrument zone modulators (global and local) to the voice.*/ fluid_defpreset_noteon_add_mod_to_voice(voice, /* global instrument modulators */ global_inst_zone ? global_inst_zone->mod : NULL, inst_zone->mod, /* local instrument modulators */ FLUID_VOICE_OVERWRITE); /* mode */ /* Preset level, generators */ for(i = 0; i < GEN_LAST; i++) { /* SF 2.01 section 8.5 page 58: If some generators are encountered at preset level, they should be ignored. However this check is not necessary when the soundfont loader has ignored invalid preset generators. Actually load_pgen()has ignored these invalid preset generators: GEN_STARTADDROFS, GEN_ENDADDROFS, GEN_STARTLOOPADDROFS, GEN_ENDLOOPADDROFS, GEN_STARTADDRCOARSEOFS,GEN_ENDADDRCOARSEOFS, GEN_STARTLOOPADDRCOARSEOFS, GEN_KEYNUM, GEN_VELOCITY, GEN_ENDLOOPADDRCOARSEOFS, GEN_SAMPLEMODE, GEN_EXCLUSIVECLASS,GEN_OVERRIDEROOTKEY */ /* SF 2.01 section 9.4 'bullet' 9: A generator in a * local preset zone supersedes a global preset zone * generator. The effect is -added- to the destination * summing node -> voice_gen_incr */ if(preset_zone->gen[i].flags) { fluid_voice_gen_incr(voice, i, preset_zone->gen[i].val); } else if((global_preset_zone != NULL) && global_preset_zone->gen[i].flags) { fluid_voice_gen_incr(voice, i, global_preset_zone->gen[i].val); } else { /* The generator has not been defined in this preset * Do nothing, leave it unchanged. */ } } /* for all generators */ /* Adds preset zone modulators (global and local) to the voice.*/ fluid_defpreset_noteon_add_mod_to_voice(voice, /* global preset modulators */ global_preset_zone ? global_preset_zone->mod : NULL, preset_zone->mod, /* local preset modulators */ FLUID_VOICE_ADD); /* mode */ /* add the synthesis process to the synthesis loop. */ fluid_synth_start_voice(synth, voice); /* Store the ID of the first voice that was created by this noteon event. * Exclusive class may only terminate older voices. * That avoids killing voices, which have just been created. * (a noteon event can create several voice processes with the same exclusive * class - for example when using stereo samples) */ } } } preset_zone = fluid_preset_zone_next(preset_zone); } return FLUID_OK; } /* * fluid_defpreset_set_global_zone */ int fluid_defpreset_set_global_zone(fluid_defpreset_t *defpreset, fluid_preset_zone_t *zone) { defpreset->global_zone = zone; return FLUID_OK; } /* * fluid_defpreset_import_sfont */ int fluid_defpreset_import_sfont(fluid_defpreset_t *defpreset, SFPreset *sfpreset, fluid_defsfont_t *defsfont, SFData *sfdata) { fluid_list_t *p; SFZone *sfzone; fluid_preset_zone_t *zone; int count; char zone_name[256]; if(FLUID_STRLEN(sfpreset->name) > 0) { FLUID_STRCPY(defpreset->name, sfpreset->name); } else { FLUID_SNPRINTF(defpreset->name, sizeof(defpreset->name), "Bank%d,Pre%d", sfpreset->bank, sfpreset->prenum); } defpreset->bank = sfpreset->bank; defpreset->num = sfpreset->prenum; p = sfpreset->zone; count = 0; while(p != NULL) { sfzone = (SFZone *)fluid_list_get(p); FLUID_SNPRINTF(zone_name, sizeof(zone_name), "pz:%s/%d", defpreset->name, count); zone = new_fluid_preset_zone(zone_name); if(zone == NULL) { return FLUID_FAILED; } if(fluid_preset_zone_import_sfont(zone, sfzone, defsfont, sfdata) != FLUID_OK) { delete_fluid_preset_zone(zone); return FLUID_FAILED; } if((count == 0) && (fluid_preset_zone_get_inst(zone) == NULL)) { fluid_defpreset_set_global_zone(defpreset, zone); } else if(fluid_defpreset_add_zone(defpreset, zone) != FLUID_OK) { return FLUID_FAILED; } p = fluid_list_next(p); count++; } return FLUID_OK; } /* * fluid_defpreset_add_zone */ int fluid_defpreset_add_zone(fluid_defpreset_t *defpreset, fluid_preset_zone_t *zone) { if(defpreset->zone == NULL) { zone->next = NULL; defpreset->zone = zone; } else { zone->next = defpreset->zone; defpreset->zone = zone; } return FLUID_OK; } /* * fluid_defpreset_get_zone */ fluid_preset_zone_t * fluid_defpreset_get_zone(fluid_defpreset_t *defpreset) { return defpreset->zone; } /* * fluid_defpreset_get_global_zone */ fluid_preset_zone_t * fluid_defpreset_get_global_zone(fluid_defpreset_t *defpreset) { return defpreset->global_zone; } /*************************************************************** * * PRESET_ZONE */ /* * fluid_preset_zone_next */ fluid_preset_zone_t * fluid_preset_zone_next(fluid_preset_zone_t *zone) { return zone->next; } /* * new_fluid_preset_zone */ fluid_preset_zone_t * new_fluid_preset_zone(char *name) { fluid_preset_zone_t *zone = NULL; zone = FLUID_NEW(fluid_preset_zone_t); if(zone == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return NULL; } zone->next = NULL; zone->voice_zone = NULL; zone->name = FLUID_STRDUP(name); if(zone->name == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); FLUID_FREE(zone); return NULL; } zone->inst = NULL; zone->range.keylo = 0; zone->range.keyhi = 128; zone->range.vello = 0; zone->range.velhi = 128; zone->range.ignore = FALSE; /* Flag all generators as unused (default, they will be set when they are found * in the sound font). * This also sets the generator values to default, but that is of no concern here.*/ fluid_gen_init(&zone->gen[0], NULL); zone->mod = NULL; /* list of modulators */ return zone; } /* * delete list of modulators. */ void delete_fluid_list_mod(fluid_mod_t *mod) { fluid_mod_t *tmp; while(mod) /* delete the modulators */ { tmp = mod; mod = mod->next; delete_fluid_mod(tmp); } } /* * delete_fluid_preset_zone */ void delete_fluid_preset_zone(fluid_preset_zone_t *zone) { fluid_list_t *list; fluid_return_if_fail(zone != NULL); delete_fluid_list_mod(zone->mod); for(list = zone->voice_zone; list != NULL; list = fluid_list_next(list)) { FLUID_FREE(fluid_list_get(list)); } delete_fluid_list(zone->voice_zone); FLUID_FREE(zone->name); FLUID_FREE(zone); } static int fluid_preset_zone_create_voice_zones(fluid_preset_zone_t *preset_zone) { fluid_inst_zone_t *inst_zone; fluid_sample_t *sample; fluid_voice_zone_t *voice_zone; fluid_zone_range_t *irange; fluid_zone_range_t *prange = &preset_zone->range; fluid_return_val_if_fail(preset_zone->inst != NULL, FLUID_FAILED); inst_zone = fluid_inst_get_zone(preset_zone->inst); while(inst_zone != NULL) { /* We only create voice ranges for zones that could actually start a voice, * i.e. that have a sample and don't point to ROM */ sample = fluid_inst_zone_get_sample(inst_zone); if((sample == NULL) || fluid_sample_in_rom(sample)) { inst_zone = fluid_inst_zone_next(inst_zone); continue; } voice_zone = FLUID_NEW(fluid_voice_zone_t); if(voice_zone == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return FLUID_FAILED; } voice_zone->inst_zone = inst_zone; irange = &inst_zone->range; voice_zone->range.keylo = (prange->keylo > irange->keylo) ? prange->keylo : irange->keylo; voice_zone->range.keyhi = (prange->keyhi < irange->keyhi) ? prange->keyhi : irange->keyhi; voice_zone->range.vello = (prange->vello > irange->vello) ? prange->vello : irange->vello; voice_zone->range.velhi = (prange->velhi < irange->velhi) ? prange->velhi : irange->velhi; voice_zone->range.ignore = FALSE; preset_zone->voice_zone = fluid_list_append(preset_zone->voice_zone, voice_zone); inst_zone = fluid_inst_zone_next(inst_zone); } return FLUID_OK; } /** * Checks if modulator mod is identic to another modulator in the list * (specs SF 2.0X 7.4, 7.8). * @param mod, modulator list. * @param name, if not NULL, pointer on a string displayed as warning. * @return TRUE if mod is identic to another modulator, FALSE otherwise. */ static int fluid_zone_is_mod_identic(fluid_mod_t *mod, char *name) { fluid_mod_t *next = mod->next; while(next) { /* is mod identic to next ? */ if(fluid_mod_test_identity(mod, next)) { if(name) { FLUID_LOG(FLUID_WARN, "Ignoring identic modulator %s", name); } return TRUE; } next = next->next; } return FALSE; } /** * Limits the number of modulators in a modulator list. * This is appropriate to internal synthesizer modulators tables * which have a fixed size (FLUID_NUM_MOD). * * @param zone_name, zone name * @param list_mod, address of pointer on modulator list. */ static void fluid_limit_mod_list(char *zone_name, fluid_mod_t **list_mod) { int mod_idx = 0; /* modulator index */ fluid_mod_t *prev_mod = NULL; /* previous modulator in list_mod */ fluid_mod_t *mod = *list_mod; /* first modulator in list_mod */ while(mod) { if((mod_idx + 1) > FLUID_NUM_MOD) { /* truncation of list_mod */ if(mod_idx) { prev_mod->next = NULL; } else { *list_mod = NULL; } delete_fluid_list_mod(mod); FLUID_LOG(FLUID_WARN, "%s, modulators count limited to %d", zone_name, FLUID_NUM_MOD); break; } mod_idx++; prev_mod = mod; mod = mod->next; } } /** * Checks and remove invalid modulators from a zone modulators list. * - checks valid modulator sources (specs SF 2.01 7.4, 7.8, 8.2.1). * - checks identic modulators in the list (specs SF 2.01 7.4, 7.8). * @param zone_name, zone name. * @param list_mod, address of pointer on modulators list. */ static void fluid_zone_check_mod(char *zone_name, fluid_mod_t **list_mod) { fluid_mod_t *prev_mod = NULL; /* previous modulator in list_mod */ fluid_mod_t *mod = *list_mod; /* first modulator in list_mod */ int mod_idx = 0; /* modulator index */ while(mod) { char zone_mod_name[256]; fluid_mod_t *next = mod->next; /* prepare modulator name: zonename/#modulator */ FLUID_SNPRINTF(zone_mod_name, sizeof(zone_mod_name), "%s/mod%d", zone_name, mod_idx); /* has mod invalid sources ? */ if(!fluid_mod_check_sources(mod, zone_mod_name) /* or is mod identic to any following modulator ? */ || fluid_zone_is_mod_identic(mod, zone_mod_name)) { /* the modulator is useless so we remove it */ if(prev_mod) { prev_mod->next = next; } else { *list_mod = next; } delete_fluid_mod(mod); /* freeing */ } else { prev_mod = mod; } mod = next; mod_idx++; } /* limits the size of modulators list */ fluid_limit_mod_list(zone_name, list_mod); } /* * fluid_zone_gen_import_sfont * Imports generators from sfzone to gen and range. * @param gen, pointer on destination generators table. * @param range, pointer on destination range generators. * @param sfzone, pointer on soundfont zone generators. */ static void fluid_zone_gen_import_sfont(fluid_gen_t *gen, fluid_zone_range_t *range, SFZone *sfzone) { fluid_list_t *r; SFGen *sfgen; for(r = sfzone->gen; r != NULL;) { sfgen = (SFGen *)fluid_list_get(r); switch(sfgen->id) { case GEN_KEYRANGE: range->keylo = sfgen->amount.range.lo; range->keyhi = sfgen->amount.range.hi; break; case GEN_VELRANGE: range->vello = sfgen->amount.range.lo; range->velhi = sfgen->amount.range.hi; break; case GEN_ATTENUATION: /* EMU8k/10k hardware applies a scale factor to initial attenuation generator values set at * preset and instrument level */ gen[sfgen->id].val = (fluid_real_t) sfgen->amount.sword * EMU_ATTENUATION_FACTOR; gen[sfgen->id].flags = GEN_SET; break; case GEN_INSTRUMENT: case GEN_SAMPLEID: gen[sfgen->id].val = (fluid_real_t) sfgen->amount.uword; gen[sfgen->id].flags = GEN_SET; break; default: gen[sfgen->id].val = (fluid_real_t) sfgen->amount.sword; gen[sfgen->id].flags = GEN_SET; break; } r = fluid_list_next(r); } } /* * fluid_zone_mod_source_import_sfont * Imports source information from sf_source to src and flags. * @param src, pointer on destination modulator source. * @param flags, pointer on destination modulator flags. * @param sf_source, soundfont modulator source. * @return return TRUE if success, FALSE if source type is unknown. */ static int fluid_zone_mod_source_import_sfont(unsigned char *src, unsigned char *flags, unsigned short sf_source) { int type; unsigned char flags_dest; /* destination flags */ /* sources */ *src = sf_source & 127; /* index of source, seven-bit value, SF2.01 section 8.2, page 50 */ /* Bit 7: CC flag SF 2.01 section 8.2.1 page 50*/ flags_dest = 0; if(sf_source & (1 << 7)) { flags_dest |= FLUID_MOD_CC; } else { flags_dest |= FLUID_MOD_GC; } /* Bit 8: D flag SF 2.01 section 8.2.2 page 51*/ if(sf_source & (1 << 8)) { flags_dest |= FLUID_MOD_NEGATIVE; } else { flags_dest |= FLUID_MOD_POSITIVE; } /* Bit 9: P flag SF 2.01 section 8.2.3 page 51*/ if(sf_source & (1 << 9)) { flags_dest |= FLUID_MOD_BIPOLAR; } else { flags_dest |= FLUID_MOD_UNIPOLAR; } /* modulator source types: SF2.01 section 8.2.1 page 52 */ type = sf_source >> 10; type &= 63; /* type is a 6-bit value */ if(type == 0) { flags_dest |= FLUID_MOD_LINEAR; } else if(type == 1) { flags_dest |= FLUID_MOD_CONCAVE; } else if(type == 2) { flags_dest |= FLUID_MOD_CONVEX; } else if(type == 3) { flags_dest |= FLUID_MOD_SWITCH; } else { *flags = flags_dest; /* This shouldn't happen - unknown type! */ return FALSE; } *flags = flags_dest; return TRUE; } /* * fluid_zone_mod_import_sfont * Imports modulators from sfzone to modulators list mod. * @param zone_name, zone name. * @param mod, address of pointer on modulators list to return. * @param sfzone, pointer on soundfont zone. * @return FLUID_OK if success, FLUID_FAILED otherwise. */ static int fluid_zone_mod_import_sfont(char *zone_name, fluid_mod_t **mod, SFZone *sfzone) { fluid_list_t *r; int count; /* Import the modulators (only SF2.1 and higher) */ for(count = 0, r = sfzone->mod; r != NULL; count++) { SFMod *mod_src = (SFMod *)fluid_list_get(r); fluid_mod_t *mod_dest = new_fluid_mod(); if(mod_dest == NULL) { return FLUID_FAILED; } mod_dest->next = NULL; /* pointer to next modulator, this is the end of the list now.*/ /* *** Amount *** */ mod_dest->amount = mod_src->amount; /* *** Source *** */ if(!fluid_zone_mod_source_import_sfont(&mod_dest->src1, &mod_dest->flags1, mod_src->src)) { /* This shouldn't happen - unknown type! * Deactivate the modulator by setting the amount to 0. */ mod_dest->amount = 0; } /* Note: When primary source input (src1) is set to General Controller 'No Controller', output will be forced to 0.0 at synthesis time (see fluid_mod_get_value()). That means that the minimum value of the modulator will be always 0.0. We need to force amount value to 0 to ensure a correct evaluation of the minimum value later (see fluid_voice_get_lower_boundary_for_attenuation()). */ if(((mod_dest->flags1 & FLUID_MOD_CC) == FLUID_MOD_GC) && (mod_dest->src1 == FLUID_MOD_NONE)) { mod_dest->amount = 0; } /* *** Dest *** */ mod_dest->dest = mod_src->dest; /* index of controlled generator */ /* *** Amount source *** */ if(!fluid_zone_mod_source_import_sfont(&mod_dest->src2, &mod_dest->flags2, mod_src->amtsrc)) { /* This shouldn't happen - unknown type! * Deactivate the modulator by setting the amount to 0. */ mod_dest->amount = 0; } /* Note: When secondary source input (src2) is set to General Controller 'No Controller', output will be forced to +1.0 at synthesis time (see fluid_mod_get_value()). That means that this source will behave unipolar only. We need to force the unipolar flag to ensure to ensure a correct evaluation of the minimum value later (see fluid_voice_get_lower_boundary_for_attenuation()). */ if(((mod_dest->flags2 & FLUID_MOD_CC) == FLUID_MOD_GC) && (mod_dest->src2 == FLUID_MOD_NONE)) { mod_dest->flags2 &= ~FLUID_MOD_BIPOLAR; } /* *** Transform *** */ /* SF2.01 only uses the 'linear' transform (0). * Deactivate the modulator by setting the amount to 0 in any other case. */ if(mod_src->trans != 0) { mod_dest->amount = 0; } /* Store the new modulator in the zone The order of modulators * will make a difference, at least in an instrument context: The * second modulator overwrites the first one, if they only differ * in amount. */ if(count == 0) { *mod = mod_dest; } else { fluid_mod_t *last_mod = *mod; /* Find the end of the list */ while(last_mod->next != NULL) { last_mod = last_mod->next; } last_mod->next = mod_dest; } r = fluid_list_next(r); } /* foreach modulator */ /* checks and removes invalid modulators in modulators list*/ fluid_zone_check_mod(zone_name, mod); return FLUID_OK; } /* * fluid_preset_zone_import_sfont */ int fluid_preset_zone_import_sfont(fluid_preset_zone_t *zone, SFZone *sfzone, fluid_defsfont_t *defsfont, SFData *sfdata) { /* import the generators */ fluid_zone_gen_import_sfont(zone->gen, &zone->range, sfzone); if(zone->gen[GEN_INSTRUMENT].flags == GEN_SET) { int inst_idx = (int) zone->gen[GEN_INSTRUMENT].val; zone->inst = find_inst_by_idx(defsfont, inst_idx); if(zone->inst == NULL) { zone->inst = fluid_inst_import_sfont(inst_idx, defsfont, sfdata); } if(zone->inst == NULL) { FLUID_LOG(FLUID_ERR, "Preset zone %s: Invalid instrument reference", zone->name); return FLUID_FAILED; } if(fluid_preset_zone_create_voice_zones(zone) == FLUID_FAILED) { return FLUID_FAILED; } /* We don't need this generator anymore */ zone->gen[GEN_INSTRUMENT].flags = GEN_UNUSED; } /* Import the modulators (only SF2.1 and higher) */ return fluid_zone_mod_import_sfont(zone->name, &zone->mod, sfzone); } /* * fluid_preset_zone_get_inst */ fluid_inst_t * fluid_preset_zone_get_inst(fluid_preset_zone_t *zone) { return zone->inst; } /*************************************************************** * * INST */ /* * new_fluid_inst */ fluid_inst_t * new_fluid_inst() { fluid_inst_t *inst = FLUID_NEW(fluid_inst_t); if(inst == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return NULL; } inst->name[0] = 0; inst->global_zone = NULL; inst->zone = NULL; return inst; } /* * delete_fluid_inst */ void delete_fluid_inst(fluid_inst_t *inst) { fluid_inst_zone_t *zone; fluid_return_if_fail(inst != NULL); delete_fluid_inst_zone(inst->global_zone); inst->global_zone = NULL; zone = inst->zone; while(zone != NULL) { inst->zone = zone->next; delete_fluid_inst_zone(zone); zone = inst->zone; } FLUID_FREE(inst); } /* * fluid_inst_set_global_zone */ int fluid_inst_set_global_zone(fluid_inst_t *inst, fluid_inst_zone_t *zone) { inst->global_zone = zone; return FLUID_OK; } /* * fluid_inst_import_sfont */ fluid_inst_t * fluid_inst_import_sfont(int inst_idx, fluid_defsfont_t *defsfont, SFData *sfdata) { fluid_list_t *p; fluid_list_t *inst_list; fluid_inst_t *inst; SFZone *sfzone; SFInst *sfinst; fluid_inst_zone_t *inst_zone; char zone_name[256]; int count; for (inst_list = sfdata->inst; inst_list; inst_list = fluid_list_next(inst_list)) { sfinst = fluid_list_get(inst_list); if (sfinst->idx == inst_idx) { break; } } if (inst_list == NULL) { return NULL; } inst = (fluid_inst_t *) new_fluid_inst(); if(inst == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return NULL; } inst->source_idx = sfinst->idx; p = sfinst->zone; if(FLUID_STRLEN(sfinst->name) > 0) { FLUID_STRCPY(inst->name, sfinst->name); } else { FLUID_STRCPY(inst->name, "<untitled>"); } count = 0; while(p != NULL) { sfzone = (SFZone *)fluid_list_get(p); /* instrument zone name */ FLUID_SNPRINTF(zone_name, sizeof(zone_name), "iz:%s/%d", inst->name, count); inst_zone = new_fluid_inst_zone(zone_name); if(inst_zone == NULL) { return NULL; } if(fluid_inst_zone_import_sfont(inst_zone, sfzone, defsfont, sfdata) != FLUID_OK) { delete_fluid_inst_zone(inst_zone); return NULL; } if((count == 0) && (fluid_inst_zone_get_sample(inst_zone) == NULL)) { fluid_inst_set_global_zone(inst, inst_zone); } else if(fluid_inst_add_zone(inst, inst_zone) != FLUID_OK) { return NULL; } p = fluid_list_next(p); count++; } defsfont->inst = fluid_list_append(defsfont->inst, inst); return inst; } /* * fluid_inst_add_zone */ int fluid_inst_add_zone(fluid_inst_t *inst, fluid_inst_zone_t *zone) { if(inst->zone == NULL) { zone->next = NULL; inst->zone = zone; } else { zone->next = inst->zone; inst->zone = zone; } return FLUID_OK; } /* * fluid_inst_get_zone */ fluid_inst_zone_t * fluid_inst_get_zone(fluid_inst_t *inst) { return inst->zone; } /* * fluid_inst_get_global_zone */ fluid_inst_zone_t * fluid_inst_get_global_zone(fluid_inst_t *inst) { return inst->global_zone; } /*************************************************************** * * INST_ZONE */ /* * new_fluid_inst_zone */ fluid_inst_zone_t * new_fluid_inst_zone(char *name) { fluid_inst_zone_t *zone = NULL; zone = FLUID_NEW(fluid_inst_zone_t); if(zone == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); return NULL; } zone->next = NULL; zone->name = FLUID_STRDUP(name); if(zone->name == NULL) { FLUID_LOG(FLUID_ERR, "Out of memory"); FLUID_FREE(zone); return NULL; } zone->sample = NULL; zone->range.keylo = 0; zone->range.keyhi = 128; zone->range.vello = 0; zone->range.velhi = 128; zone->range.ignore = FALSE; /* Flag the generators as unused. * This also sets the generator values to default, but they will be overwritten anyway, if used.*/ fluid_gen_init(&zone->gen[0], NULL); zone->mod = NULL; /* list of modulators */ return zone; } /* * delete_fluid_inst_zone */ void delete_fluid_inst_zone(fluid_inst_zone_t *zone) { fluid_return_if_fail(zone != NULL); delete_fluid_list_mod(zone->mod); FLUID_FREE(zone->name); FLUID_FREE(zone); } /* * fluid_inst_zone_next */ fluid_inst_zone_t * fluid_inst_zone_next(fluid_inst_zone_t *zone) { return zone->next; } /* * fluid_inst_zone_import_sfont */ int fluid_inst_zone_import_sfont(fluid_inst_zone_t *inst_zone, SFZone *sfzone, fluid_defsfont_t *defsfont, SFData *sfdata) { /* import the generators */ fluid_zone_gen_import_sfont(inst_zone->gen, &inst_zone->range, sfzone); /* FIXME */ /* if (zone->gen[GEN_EXCLUSIVECLASS].flags == GEN_SET) { */ /* FLUID_LOG(FLUID_DBG, "ExclusiveClass=%d\n", (int) zone->gen[GEN_EXCLUSIVECLASS].val); */ /* } */ if (inst_zone->gen[GEN_SAMPLEID].flags == GEN_SET) { fluid_list_t *list; SFSample *sfsample; int sample_idx = (int) inst_zone->gen[GEN_SAMPLEID].val; /* find the SFSample by index */ for(list = sfdata->sample; list; list = fluid_list_next(list)) { sfsample = fluid_list_get(list); if (sfsample->idx == sample_idx) { break; } } if (list == NULL) { FLUID_LOG(FLUID_ERR, "Instrument zone '%s': Invalid sample reference", inst_zone->name); return FLUID_FAILED; } inst_zone->sample = sfsample->fluid_sample; /* we don't need this generator anymore, mark it as unused */ inst_zone->gen[GEN_SAMPLEID].flags = GEN_UNUSED; } /* Import the modulators (only SF2.1 and higher) */ return fluid_zone_mod_import_sfont(inst_zone->name, &inst_zone->mod, sfzone); } /* * fluid_inst_zone_get_sample */ fluid_sample_t * fluid_inst_zone_get_sample(fluid_inst_zone_t *zone) { return zone->sample; } int fluid_zone_inside_range(fluid_zone_range_t *range, int key, int vel) { /* ignoreInstrumentZone is set in mono legato playing */ int ignore_zone = range->ignore; /* Reset the 'ignore' request */ range->ignore = FALSE; return !ignore_zone && ((range->keylo <= key) && (range->keyhi >= key) && (range->vello <= vel) && (range->velhi >= vel)); } /*************************************************************** * * SAMPLE */ /* * fluid_sample_in_rom */ int fluid_sample_in_rom(fluid_sample_t *sample) { return (sample->sampletype & FLUID_SAMPLETYPE_ROM); } /* * fluid_sample_import_sfont */ int fluid_sample_import_sfont(fluid_sample_t *sample, SFSample *sfsample, fluid_defsfont_t *defsfont) { FLUID_STRCPY(sample->name, sfsample->name); sample->source_start = sfsample->start; sample->source_end = (sfsample->end > 0) ? sfsample->end - 1 : 0; /* marks last sample, contrary to SF spec. */ sample->source_loopstart = sfsample->loopstart; sample->source_loopend = sfsample->loopend; sample->start = sample->source_start; sample->end = sample->source_end; sample->loopstart = sample->source_loopstart; sample->loopend = sample->source_loopend; sample->samplerate = sfsample->samplerate; sample->origpitch = sfsample->origpitch; sample->pitchadj = sfsample->pitchadj; sample->sampletype = sfsample->sampletype; if(defsfont->dynamic_samples) { sample->notify = dynamic_samples_sample_notify; } if(fluid_sample_validate(sample, defsfont->samplesize) == FLUID_FAILED) { return FLUID_FAILED; } return FLUID_OK; } /* Called if a sample is no longer used by a voice. Used by dynamic sample loading * to unload a sample that is not used by any loaded presets anymore but couldn't * be unloaded straight away because it was still in use by a voice. */ static int dynamic_samples_sample_notify(fluid_sample_t *sample, int reason) { if(reason == FLUID_SAMPLE_DONE && sample->preset_count == 0) { unload_sample(sample); } return FLUID_OK; } /* Called if a preset has been selected for or unselected from a channel. Used by * dynamic sample loading to load and unload samples on demand. */ static int dynamic_samples_preset_notify(fluid_preset_t *preset, int reason, int chan) { fluid_defsfont_t *defsfont; if(reason == FLUID_PRESET_SELECTED) { FLUID_LOG(FLUID_DBG, "Selected preset '%s' on channel %d", fluid_preset_get_name(preset), chan); defsfont = fluid_sfont_get_data(preset->sfont); return load_preset_samples(defsfont, preset); } if(reason == FLUID_PRESET_UNSELECTED) { FLUID_LOG(FLUID_DBG, "Deselected preset '%s' from channel %d", fluid_preset_get_name(preset), chan); defsfont = fluid_sfont_get_data(preset->sfont); return unload_preset_samples(defsfont, preset); } if(reason == FLUID_PRESET_PIN) { defsfont = fluid_sfont_get_data(preset->sfont); return pin_preset_samples(defsfont, preset); } if(reason == FLUID_PRESET_UNPIN) { defsfont = fluid_sfont_get_data(preset->sfont); return unpin_preset_samples(defsfont, preset); } return FLUID_OK; } static int pin_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset) { fluid_defpreset_t *defpreset; defpreset = fluid_preset_get_data(preset); if (defpreset->pinned) { return FLUID_OK; } FLUID_LOG(FLUID_DBG, "Pinning preset '%s'", fluid_preset_get_name(preset)); if(load_preset_samples(defsfont, preset) == FLUID_FAILED) { return FLUID_FAILED; } defpreset->pinned = TRUE; return FLUID_OK; } static int unpin_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset) { fluid_defpreset_t *defpreset; defpreset = fluid_preset_get_data(preset); if (!defpreset->pinned) { return FLUID_OK; } FLUID_LOG(FLUID_DBG, "Unpinning preset '%s'", fluid_preset_get_name(preset)); if(unload_preset_samples(defsfont, preset) == FLUID_FAILED) { return FLUID_FAILED; } defpreset->pinned = FALSE; return FLUID_OK; } /* Walk through all samples used by the passed in preset and make sure that the * sample data is loaded for each sample. Used by dynamic sample loading. */ static int load_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset) { fluid_defpreset_t *defpreset; fluid_preset_zone_t *preset_zone; fluid_inst_t *inst; fluid_inst_zone_t *inst_zone; fluid_sample_t *sample; SFData *sffile = NULL; defpreset = fluid_preset_get_data(preset); preset_zone = fluid_defpreset_get_zone(defpreset); while(preset_zone != NULL) { inst = fluid_preset_zone_get_inst(preset_zone); inst_zone = fluid_inst_get_zone(inst); while(inst_zone != NULL) { sample = fluid_inst_zone_get_sample(inst_zone); if((sample != NULL) && (sample->start != sample->end)) { sample->preset_count++; /* If this is the first time this sample has been selected, * load the sampledata */ if(sample->preset_count == 1) { /* Make sure we have an open Soundfont file. Do this here * to avoid having to open the file if no loading is necessary * for a preset */ if(sffile == NULL) { sffile = fluid_sffile_open(defsfont->filename, defsfont->fcbs); if(sffile == NULL) { FLUID_LOG(FLUID_ERR, "Unable to open Soundfont file"); return FLUID_FAILED; } } if(fluid_defsfont_load_sampledata(defsfont, sffile, sample) == FLUID_OK) { fluid_sample_sanitize_loop(sample, (sample->end + 1) * sizeof(short)); fluid_voice_optimize_sample(sample); } else { FLUID_LOG(FLUID_ERR, "Unable to load sample '%s', disabling", sample->name); sample->start = sample->end = 0; } } } inst_zone = fluid_inst_zone_next(inst_zone); } preset_zone = fluid_preset_zone_next(preset_zone); } if(sffile != NULL) { fluid_sffile_close(sffile); } return FLUID_OK; } /* Walk through all samples used by the passed in preset and unload the sample data * of each sample that is not used by any selected preset anymore. Used by dynamic * sample loading. */ static int unload_preset_samples(fluid_defsfont_t *defsfont, fluid_preset_t *preset) { fluid_defpreset_t *defpreset; fluid_preset_zone_t *preset_zone; fluid_inst_t *inst; fluid_inst_zone_t *inst_zone; fluid_sample_t *sample; defpreset = fluid_preset_get_data(preset); preset_zone = fluid_defpreset_get_zone(defpreset); while(preset_zone != NULL) { inst = fluid_preset_zone_get_inst(preset_zone); inst_zone = fluid_inst_get_zone(inst); while(inst_zone != NULL) { sample = fluid_inst_zone_get_sample(inst_zone); if((sample != NULL) && (sample->preset_count > 0)) { sample->preset_count--; /* If the sample is not used by any preset or used by a * sounding voice, unload it from the sample cache. If it's * still in use by a voice, dynamic_samples_sample_notify will * take care of unloading the sample as soon as the voice is * finished with it (but only on the next API call). */ if(sample->preset_count == 0 && sample->refcount == 0) { unload_sample(sample); } } inst_zone = fluid_inst_zone_next(inst_zone); } preset_zone = fluid_preset_zone_next(preset_zone); } return FLUID_OK; } /* Unload an unused sample from the samplecache */ static void unload_sample(fluid_sample_t *sample) { fluid_return_if_fail(sample != NULL); fluid_return_if_fail(sample->data != NULL); fluid_return_if_fail(sample->preset_count == 0); fluid_return_if_fail(sample->refcount == 0); FLUID_LOG(FLUID_DBG, "Unloading sample '%s'", sample->name); if(fluid_samplecache_unload(sample->data) == FLUID_FAILED) { FLUID_LOG(FLUID_ERR, "Unable to unload sample '%s'", sample->name); } else { sample->data = NULL; sample->data24 = NULL; } } static fluid_inst_t *find_inst_by_idx(fluid_defsfont_t *defsfont, int idx) { fluid_list_t *list; fluid_inst_t *inst; for(list = defsfont->inst; list != NULL; list = fluid_list_next(list)) { inst = fluid_list_get(list); if(inst->source_idx == idx) { return inst; } } return NULL; }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/OpenMPClause.h" #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> CilkHintHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static ParsedType getTypeAnnotation(const Token &Tok) { return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, ParsedType T) { Tok.setAnnotationValue(T.getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; explicit LexedMethod(Parser* P, Decl *MD) : Self(P), D(MD), TemplateScope(false) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), TemplateScope(false), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// otherwise, it is a tag declaration. bool TemplateScope : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); static void LateTemplateParserCleanupCallback(void *P); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator(); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseCilkSpawnStatement(); StmtResult ParseCilkSyncStatement(); StmtResult ParseSpawnStatement(); StmtResult ParseSyncStatement(); StmtResult ParseForallStatement(SourceLocation *TrailingElseLoc); StmtResult ParseCilkForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, Decl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Based only on the given token kind, determine whether we know that /// we're at the start of an expression or a type-specifier-seq (which may /// be an expression, in C++). /// /// This routine does not attempt to resolve any of the trick cases, e.g., /// those involving lookup of identifiers. /// /// \returns \c TPR_true if this token starts an expression, \c TPR_false if /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot /// tell. TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parses OpenMP context selectors and calls \p Callback for each /// successfully parsed context selector. bool parseOpenMPContextSelectors(SourceLocation Loc, SmallVectorImpl<Sema::OMPCtxSelectorData> &Data); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *TailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers> MapTypeModifiers; SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers> MapTypeModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation DepLinMapLastLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); NamedDecl * ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; }; } // end namespace clang #endif
filter.c
/* * Copyright (c) 2019, NVIDIA CORPORATION. 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. */ #include <stdio.h> #include <openacc.h> #include <omp.h> #define MAX(X,Y) ((X>Y) ? X:Y) #define MIN(X,Y) ((X<Y) ? X:Y) void blur5_openmp(unsigned char *imgData, unsigned char *out, long w, long h, long ch) { long step = w*ch; 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. double scale = 1.0 / 35.0; int ndevices = acc_get_num_devices(acc_device_default); long rows_per_device = (h+(ndevices-1))/ndevices; #pragma omp parallel for num_threads(ndevices) for(int device = 0; device < ndevices; device++) { long lower = device*rows_per_device; long upper = MIN(lower + rows_per_device, h); long copyLower = MAX(lower-(filtersize/2), 0); long copyUpper = MIN(upper+(filtersize/2), h); int tid = omp_get_thread_num(); acc_set_device_num(tid, acc_device_default); #pragma acc parallel loop \ copyin(imgData[copyLower*step:(copyUpper-copyLower)*step], filter) \ copyout(out[lower*step:(upper-lower)*step]) for(y = lower; y < upper; y++) { #pragma acc loop for(x = 0; x < w; x++) { double blue = 0.0, green = 0.0, red = 0.0; #pragma acc loop seq for(int fy = 0; fy < filtersize; fy++) { long iy = y - (filtersize/2) + fy; #pragma acc loop seq 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] * (double)imgData[iy * step + ix * ch]; green += filter[fy][fx] * (double)imgData[iy * step + ix * ch + 1]; red += filter[fy][fx] * (double)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); } } } // end omp parallel for }
dmd.h
#ifndef METHODS_DMD_H #define METHODS_DMD_H namespace method { // use your method name to create a subspace for your // implementation of details namespace dmd { namespace details { template<typename Potential> arma::mat effective_force(const Potential & potential, const arma::mat & points, const arma::vec & masses, const double beta) { arma::mat result = arma::mat(points.n_rows / 2, points.n_cols); #pragma omp parallel for for (arma::uword i = 0; i < points.n_cols; i++) { const arma::vec point = points.col(i); const arma::vec position = points.col(i).rows(0, points.n_rows / 2 - 1); for (arma::uword j = 0; j < points.n_rows / 2; j++) { const auto p_j = j + points.n_rows / 2; math::Polynomial<double> correction_term = math::Polynomial<double>(points.n_rows,std::pow(beta / masses(j), 2)); correction_term.exponents(p_j, 0) = 2; result(j, i) = -potential.derivative(j).at(position) + potential.derivative(j).derivative(j).derivative(j).at( position) * (correction_term - beta / masses(j)).at( point) / 24.0; } } return result; } } using State = cwa::State; template<typename Potential> struct Operator { private: PropagationType type = Classic; public: Potential potential; double beta; Operator(const State & state, const Potential & potential, const double beta = 1.0) : potential(potential), beta(beta){} inline PropagationType propagation_type() const { return Classic; } State operator()(const State & state) const { arma::mat p_submatrix = state.points.rows(state.dim(), 2 * state.dim() - 1); p_submatrix.each_col() /= state.masses; const arma::mat change_list = arma::join_cols(p_submatrix, details::effective_force(this->potential, state.points, state.masses, this->beta)); return State(change_list, state.weights, state.masses); } }; } } #endif //METHODS_DMD_H
linalg.c
/* Copyright 2015. The Regents of the University of California. * Copyright 2016-2019. 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-2019 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2013 Dara Bahri <dbahri123@gmail.com> * * * Simple linear algebra functions. */ #include <complex.h> #include <math.h> #include <assert.h> #if 1 // #define MAT_USE_LAPACK #define DOUBLE_ACC #endif #include "misc/misc.h" #ifdef MAT_USE_LAPACK #include "num/blas.h" #include "num/lapack.h" #endif #include "num/rand.h" #include "linalg.h" #ifdef DOUBLE_ACC typedef complex double cfl_acu_t; typedef double fl_acu_t; #else typedef complex float cfl_acu_t; typedef float fl_acu_t; #endif void mat_identity(int A, int B, complex float x[A][B]) { for (int i = 0; i < A; i++) for (int j = 0; j < B; j++) x[i][j] = (i == j) ? 1. : 0.; } void mat_zero(int A, int B, complex float m[A][B]) { for (int a = 0; a < A; a++) for (int b = 0; b < B; b++) m[a][b] = 0.; } void mat_gaussian(int A, int B, complex float x[A][B]) { for (int i = 0; i < A; i++) for (int j = 0; j < B; j++) x[i][j] = gaussian_rand(); } // add constant to vector void vec_sadd(long D, complex float alpha, complex float dst[D], const complex float src[D]) { // #pragma omp parallel for for (long i = 0; i < D; i++) dst[i] = alpha + src[i]; } complex float vec_mean(long D, const complex float src[D]) { cfl_acu_t val = 0; for (long i = 0; i < D; i++) val += src[i]; return val / D; } void (mat_add)(int A, int B, complex float x[A][B], const complex float y[A][B], const complex float z[A][B]) { for (int i = 0; i < A; i++) for (int j = 0; j < B; j++) x[i][j] = y[i][j] + z[i][j]; } void (mat_muladd)(int A, int B, int C, complex float x[MVLA(A)][C], const complex float y[MVLA(A)][B], const complex float z[MVLA(B)][C]) { #ifdef MAT_USE_LAPACK complex float tmp[A][C]; mat_mul(A, B, C, tmp, y, z); mat_add(A, C, x, x, tmp); #else for (int i = 0; i < A; i++) { for (int j = 0; j < C; j++) { cfl_acu_t tmp = 0.; for (int k = 0; k < B; k++) tmp += y[i][k] * z[k][j]; x[i][j] += tmp; } } #endif } void (mat_mul)(int A, int B, int C, complex float x[A][C], const complex float y[A][B], const complex float z[B][C]) { #ifdef MAT_USE_LAPACK blas_matrix_multiply(C, A, B, x, z, y); #else for (int i = 0; i < A; i++) { for (int j = 0; j < C; j++) { cfl_acu_t tmp = 0.; for (int k = 0; k < B; k++) tmp += y[i][k] * z[k][j]; x[i][j] = tmp; } } #endif } bool (mat_inverse)(unsigned int N, complex float out[N][N], const complex float in[N][N]) { #ifdef MAT_USE_LAPACK // return blas_matrix_inverse(N, out, in); UNUSED(in); UNUSED(out); assert(0); #else // ATTENTION: slow and inaccurate complex float tmp[2 * N][N]; mat_transpose(N, N, tmp, in); mat_identity(N, N, tmp + N); complex float tmp2[N][2 * N]; mat_transpose(2 * N, N, tmp2, tmp); for (unsigned int i = 0; i < N; i++) { complex float diag = tmp2[i][i]; if (0. == diag) return false; for (unsigned int j = 0; j < 2 * N; j++) tmp2[i][j] /= diag; for (unsigned int j = 0; j < N; j++) { if (i != j) vec_saxpy(2 * N, tmp2[j], -tmp2[j][i], tmp2[i]); } } mat_transpose(N, 2 * N, tmp, tmp2); mat_transpose(N, N, out, tmp + N); return true; #endif } void mat_pinv(unsigned int A, unsigned int B, complex float out[B][A], const complex float in[A][B]) { if (A == B) { mat_inverse(A, out, in); return; } assert(B < A); complex float adj[B][A]; mat_adjoint(A, B, adj, in); complex float prod[B][B]; mat_mul(B, A, B, prod, adj, in); complex float inv[B][B]; mat_inverse(B, inv, prod); mat_mul(B, B, A, out, inv, adj); } void (mat_kron)(unsigned int A, unsigned int B, unsigned int C, unsigned int D, complex float out[A * C][B * D], const complex float in1[A][B], const complex float in2[C][D]) { for (unsigned int a = 0; a < A; a++) for (unsigned int b = 0; b < B; b++) for (unsigned int c = 0; c < C; c++) for (unsigned int d = 0; d < D; d++) out[a + c * A][b + d * B] = in1[a][b] * in2[c][d]; } void (mat_vecmul)(unsigned int A, unsigned int B, complex float out[A], const complex float mat[A][B], const complex float in[B]) { for (unsigned int a = 0; a < A; a++) { cfl_acu_t tmp = 0.; for (unsigned int b = 0; b < B; b++) tmp += mat[a][b] * in[b]; out[a] = tmp; } } void (mat_vec)(unsigned int A, unsigned int B, complex float out[A * B], const complex float in[A][B]) { for (unsigned int a = 0; a < A; a++) for (unsigned int b = 0; b < B; b++) out[a * B + b] = in[a][b]; } void (vec_mat)(unsigned int A, unsigned int B, complex float out[A][B], const complex float in[A * B]) { for (unsigned int a = 0; a < A; a++) for (unsigned int b = 0; b < B; b++) out[a][b] = in[a * B + b]; } complex float vec_dot(int N, const complex float x[N], const complex float y[N]) { cfl_acu_t scalar = 0.; // use double here to avoid errors // one could also look into the Kahan summation algorithm for (int k = 0; k < N; k++) scalar += x[k] * conjf(y[k]); return scalar; } // FIXME: this is not axpy void vec_axpy(long N, complex float x[N], complex float alpha, const complex float y[N]) { // #pragma omp parallel for for (long k = 0; k < N; k++) x[k] = alpha * y[k]; } void vec_saxpy(int N, complex float x[N], complex float alpha, const complex float y[N]) { for (int k = 0; k < N; k++) x[k] += alpha * y[k]; } void (gram_matrix)(int N, complex float cov[N][N], int L, const complex float data[N][L]) { #pragma omp parallel for for (int i = 0; i < N; i++) { for (int j = 0; j <= i; j++) { complex float val = vec_dot(L, data[i], data[j]); cov[j][i] = val; cov[i][j] = conj(val); } } } void (pack_tri_matrix)(int N, complex float cov[N * (N + 1) / 2], const complex float m[N][N]) { int l = 0; for (int i = 0; i < N; i++) for (int j = 0; j <= i; j++) cov[l++] = m[i][j]; } void (unpack_tri_matrix)(int N, complex float m[N][N], const complex float cov[N * (N + 1) / 2]) { int l = 0; for (int i = 0; i < N; i++) for (int j = 0; j <= i; j++) m[i][j] = cov[l++]; } void (gram_matrix2)(int N, complex float cov[N * (N + 1) / 2], int L, const complex float data[N][L]) { #if 0 int l = 0; for (int i = 0; i < N; i++) { for (int j = 0; j <= i; j++) { complex float val = vec_dot(L, data[i], data[j]); cov[l++] = conj(val); } } #else complex float c[N][N]; gram_matrix(N, c, L, data); pack_tri_matrix(N, cov, c); #endif } void gram_schmidt(int M, int N, float vals[M], complex float vecs[M][N]) { if (M > 1) gram_schmidt(M - 1, N, vals + 1, vecs + 1); for (int j = 1; j < M; j++) { complex float scalar = vec_dot(N, vecs[0], vecs[j]); vec_saxpy(N, vecs[0], -scalar, vecs[j]); } vals[0] = sqrtf(crealf(vec_dot(N, vecs[0], vecs[0]))); for (int k = 0; k < N; k++) vecs[0][k] /= vals[0]; } void (mat_transpose)(int A, int B, complex float dst[B][A], const complex float src[A][B]) { for (int i = 0; i < B; i++) for (int j = 0; j < A; j++) dst[i][j] = src[j][i]; // swap } void (mat_adjoint)(int A, int B, complex float dst[B][A], const complex float src[A][B]) { for (int i = 0; i < B; i++) for (int j = 0; j < A; j++) dst[i][j] = conjf(src[j][i]); // swap } void (mat_copy)(int A, int B, complex float dst[A][B], const complex float src[A][B]) { for (int i = 0; i < A; i++) for (int j = 0; j < B; j++) dst[i][j] = src[i][j]; } void (mat_conj)(int A, int B, complex float dst[A][B], const complex float src[A][B]) { for (int i = 0; i < A; i++) for (int j = 0; j < B; j++) dst[i][j] = conj(src[i][j]); } void (orthiter_noinit)(int M, int N, int iter, float val[M], complex float out[M][N], const complex float matrix[N][N]) { complex float tmp[M][N]; for (int n = 0; n < iter; n++) { mat_copy(M, N, tmp, out); mat_mul(M, N, N, out, tmp, matrix); gram_schmidt(M, N, val, out); } } void (orthiter)(int M, int N, int iter, float val[M], complex float out[M][N], const complex float matrix[N][N]) { mat_identity(M, N, out); orthiter_noinit(M, N, iter, val, out, matrix); } void cholesky_double(int N, complex double A[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < i; j++) { cfl_acu_t sum = A[i][j]; for (int k = 0; k < j; k++) sum -= A[i][k] * conj(A[j][k]); A[i][j] = sum / A[j][j]; } fl_acu_t sum = creal(A[i][i]); for (int k = 0; k < i; k++) sum -= creal(A[i][k] * conj(A[i][k])); assert(sum > 0.); A[i][i] = sqrt(sum); } for (int i = 0; i < N; i++) for (int j = 0; j < i; j++) A[j][i] = conj(A[i][j]); } // Tadeusz Banachiewicz void cholesky(int N, complex float A[N][N]) { #ifdef MAT_USE_LAPACK lapack_cholesky(N, A); for (int i = 0; i < N; i++) for (int j = 0; j < i; j++) A[j][i] = conjf(A[i][j]); #else #if 0 complex double B[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // B[i][j] = A[i][j]; cholesky_double(N, B); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // A[i][j] = B[i][j]; #else for (int i = 0; i < N; i++) { for (int j = 0; j < i; j++) { cfl_acu_t sum = A[i][j]; for (int k = 0; k < j; k++) sum -= A[i][k] * conjf(A[j][k]); A[i][j] = sum / A[j][j]; } fl_acu_t sum = creal(A[i][i]); for (int k = 0; k < i; k++) sum -= crealf(A[i][k] * conjf(A[i][k])); assert(sum > 0.); A[i][i] = sqrt(sum); } for (int i = 0; i < N; i++) for (int j = 0; j < i; j++) A[j][i] = conjf(A[i][j]); #endif #endif } #if 0 static void backsubst_lower_double(int N, complex double x[N], complex double L[N][N], complex double b[N]) { for (int i = 0; i < N; i++) { complex double sum = b[i]; for (int j = 0; j < i; j++) sum -= x[j] * L[i][j]; x[i] = sum / L[i][i]; } } static void backsubst_upper_double(int N, complex double x[N], complex double L[N][N], complex double b[N]) { for (int i = N - 1; i >= 0; i--) { complex double sum = b[i]; for (int j = i + 1; j < N; j++) sum -= x[j] * L[i][j]; x[i] = sum / L[i][i]; } } void mat_adjoint_double(int A, int B, complex double dst[B][A], complex double src[A][B]) { for (int i = 0; i < B; i++) for (int j = 0; j < A; j++) dst[i][j] = conj(src[j][i]); // swap } void cholesky_solve_double(int N, complex double x[N], complex double L[N][N], complex double b[N]) { complex double y[N]; complex double T[N][N]; mat_adjoint_double(N, N, T, L); backsubst_lower_double(N, y, L, b); backsubst_upper_double(N, x, T, y); } #endif static void backsubst_lower(int N, complex float x[N], const complex float L[N][N], const complex float b[N]) { for (int i = 0; i < N; i++) { cfl_acu_t sum = b[i]; for (int j = 0; j < i; j++) sum -= x[j] * L[j][i]; x[i] = sum / L[i][i]; } } static void backsubst_upper(int N, complex float x[N], const complex float L[N][N], const complex float b[N]) { for (int i = N - 1; i >= 0; i--) { cfl_acu_t sum = b[i]; for (int j = i + 1; j < N; j++) sum -= x[j] * L[j][i]; x[i] = sum / L[i][i]; } } void (cholesky_solve)(int N, complex float x[N], const complex float L[N][N], const complex float b[N]) { complex float y[N]; backsubst_lower(N, y, L, b); backsubst_upper(N, x, L, y); } void thomas_algorithm(int N, complex float f[N], const complex float A[N][3], const complex float d[N]) { complex float c[N]; complex float e[N]; c[0] = A[0][2] / A[0][1]; e[0] = d[0] / A[0][1]; for (int i = 1; i < N; i++) { c[i] = A[i][2] / (A[i][1] - c[i - 1] * A[i][0]); e[i] = (d[i] - A[i][0] * e[i - 1]) / (A[i][1] - A[i][0] * c[i - 1]); } // backsubstitution f[N - 1] = e[N - 1]; for (int i = N - 2; 0 <= i; i--) f[i] = e[i] - c[i] * f[i + 1]; }
output.c
#define _MODULE_OUTPUT #include <omp.h> #include "gmapper.h" #include "output.h" #include "../common/output.h" #include "mapping.h" #include "../common/sw-full-common.h" /* read_start and read_end are 1 based */ static cigar_t * make_cigar(int read_start, int read_end , int read_length, char* qralign,char* dbalign) { cigar_t * cigar = (cigar_t*)xmalloc(sizeof(cigar_t)); cigar->size=2; assert(cigar->size>=2); //for start and end without loop cigar->ops=(char*)xmalloc(sizeof(char)*cigar->size); cigar->lengths=(uint32_t*)xmalloc(sizeof(uint32_t)*cigar->size); int used=0; if (read_start>1) { assert(cigar->size-used>0); cigar->ops[used]='S'; cigar->lengths[used]=read_start-1; used++; } int i=0; int qralign_length=strlen(qralign); while (i<qralign_length) { int length; char op; if (qralign[i]=='-') { for (length=0; qralign[i+length]=='-' && i+length<qralign_length; length++); op='D'; } else if (dbalign[i]=='-') { for (length=0; dbalign[i+length]=='-' && i+length<qralign_length; length++); op='I'; } else { for (length=0; dbalign[i+length]!='-' && qralign[i+length]!='-' && i+length<qralign_length; length++); op='M'; } while ((used+1)>=cigar->size) { //make it bigger, want to make sure have enough for one more after loop! assert(cigar->size!=0); cigar->size*=2; cigar->ops=(char*)xrealloc(cigar->ops,sizeof(char)*cigar->size); cigar->lengths=(uint32_t*)xrealloc(cigar->lengths,sizeof(uint32_t)*cigar->size); } cigar->ops[used]=op; cigar->lengths[used]=length; i+=length; used++; } if (read_end!=read_length) { assert(used<cigar->size); //by loop invariant and initial size >=2 cigar->ops[used]='S'; cigar->lengths[used]=read_length-read_end; used++; } cigar->ops=(char*)xrealloc(cigar->ops,sizeof(char)*used); cigar->lengths=(uint32_t*)xrealloc(cigar->lengths,sizeof(uint32_t)*used); cigar->size=used; return cigar; } static void reverse_cigar(cigar_t * cigar) { char ops[cigar->size]; uint32_t lengths[cigar->size]; memcpy(ops,cigar->ops,sizeof(char)*cigar->size); memcpy(lengths,cigar->lengths,sizeof(uint32_t)*cigar->size); int i; for (i=0; i<cigar->size; i++) { cigar->ops[i]=ops[cigar->size-i-1]; cigar->lengths[i]=lengths[cigar->size-i-1]; } return; } static char * reverse_alignment_edit_string(char * editstr) { int n = strlen(editstr); char * res = (char *)malloc((n + 1) * sizeof(char)); int i = 0; while (i < n) { if (isdigit(editstr[n - 1 - i])) { int j = i + 1; while (j < n && isdigit(editstr[n - 1 - j])) j++; j--; memcpy(&res[i], &editstr[n - 1 - j], (j - i + 1) * sizeof(char)); i = j + 1; } else if (editstr[n - 1 - i] == '-' || editstr[n - 1 - i] == 'x') { res[i] = editstr[n - 1 - i]; i++; } else if (editstr[n - 1 - i] == ')') { res[i] = '('; i++; } else if (editstr[n - 1 - i] == '(') { res[i] = ')'; i++; } else if (editstr[n - 1 - i] == 'A') { res[i] = 'T'; i++; } else if (editstr[n - 1 - i] == 'C') { res[i] = 'G'; i++; } else if (editstr[n - 1 - i] == 'G') { res[i] = 'C'; i++; } else if (editstr[n - 1 - i] == 'T') { res[i] = 'A'; i++; } else assert(0); } res[n] = 0; return res; } static char * make_cigar_string(cigar_t * cigar) { int string_length=cigar->size; //1 char for each op int i; for (i=0; i<cigar->size; i++) { int j=0,length; for (length=cigar->lengths[i]; length>0; j++) length/=10; string_length+=j; } string_length++; // for null term char * ret = (char*)xmalloc(sizeof(char)*(string_length)); int used=0; for (i=0; i<cigar->size; i++) { //printf("%d%c\n",cigar->lengths[i],cigar->ops[i]); used+=sprintf(ret+used,"%d%c",cigar->lengths[i],cigar->ops[i]); } //printf("%d vs %d, %d\n",used,string_length,cigar->size); assert(used+1==string_length); ret[used]='\0'; return ret; } static void free_cigar(cigar_t * cigar) { if (cigar->size>0) { assert(cigar->ops!=NULL); assert(cigar->lengths!=NULL); free(cigar->ops); free(cigar->lengths); } free(cigar); } //TODO move this to utils static void reverse(char* s, char* t) // USING TWO ARRAYS FOR THIS IS BAD CODE!!! { int l=strlen(s); int i; for (i=0; i<l; i++) { switch (s[i]) { case 'A': t[l-i-1]='T'; break; case 'a': t[l-i-1]='t'; break; case 'T': t[l-i-1]='A'; break; case 't': t[l-i-1]='a'; break; case 'C': t[l-i-1]='G'; break; case 'c': t[l-i-1]='g'; break; case 'G': t[l-i-1]='C'; break; case 'g': t[l-i-1]='c'; break; case '-': t[l-i-1]='-'; break; case 'N': t[l-i-1]='N'; break; case 'n': t[l-i-1]='n'; break; case '.': t[l-i-1]='.'; break; case 'R': t[l-i-1]='Y'; break; case 'r': t[l-i-1]='y'; break; case 'Y': t[l-i-1]='R'; break; case 'y': t[l-i-1]='r'; break; case 'S': t[l-i-1]='S'; break; case 's': t[l-i-1]='s'; break; case 'W': t[l-i-1]='W'; break; case 'w': t[l-i-1]='w'; break; case 'K': t[l-i-1]='M'; break; case 'k': t[l-i-1]='m'; break; case 'M': t[l-i-1]='K'; break; case 'm': t[l-i-1]='k'; break; case 'B': t[l-i-1]='V'; break; case 'b': t[l-i-1]='v'; break; case 'V': t[l-i-1]='B'; break; case 'v': t[l-i-1]='b'; break; case 'D': t[l-i-1]='H'; break; case 'd': t[l-i-1]='h'; break; case 'H': t[l-i-1]='D'; break; case 'h': t[l-i-1]='d'; break; default: fprintf(stderr,"There has been a error in getting reverse complement of %s\n",s); exit(1); } } t[l]='\0'; //printf("%s vs %s\n", s , t); strcpy(s,t); } /* * Print given hit. * */ void hit_output(struct read_entry * re, struct read_hit * rh, struct read_hit * rh_mp, bool first_in_pair, int* hits, int satisfying_alignments, bool improper_mapping) /* * This function sets the strings output1 and output2 to be the output for the current read and if in sam mode its matepair * It is capable of outputting regular shrimp output, pretty print output, and sam output * * re is the read_entry for the current read * rh is the read_hit for the current read * rh_mp is the read_hit for the current reads mate pair * * paired is true if this read is paired * first is true if this is the first read in the pair * */ { assert(re != NULL); //assert((rh != NULL && rh->sfrp != NULL) || (rh_mp != NULL && rh_mp->sfrp != NULL)); int thread_id = omp_get_thread_num(); char ** output_buffer = &thread_output_buffer_filled[thread_id]; char * output_buffer_end = thread_output_buffer[thread_id] + thread_output_buffer_sizes[thread_id] - 1 + 1; while ( (size_t)(output_buffer_end - *output_buffer) < thread_output_buffer_safety) { //fprintf(stderr,"%d incrementing buffer, free space %llu\n",thread_id,output_buffer_end - *output_buffer ); size_t new_size = thread_output_buffer_sizes[thread_id]+thread_output_buffer_increment; size_t filled = thread_output_buffer_filled[thread_id]-thread_output_buffer[thread_id]; //fprintf(stderr, "there are %llu bytes used\n",filled); //thread_output_buffer[thread_id]=(char*)realloc(thread_output_buffer[thread_id],new_size); thread_output_buffer[thread_id] = (char *) my_realloc(thread_output_buffer[thread_id], new_size, thread_output_buffer_sizes[thread_id], &mem_thread_buffer, "realloc thread_output_buffer"); /* if (thread_output_buffer[thread_id]==NULL) { fprintf(stderr,"Hit output : realloc failed!\n"); exit(1); } */ thread_output_buffer_sizes[thread_id]=new_size; thread_output_buffer_filled[thread_id]=thread_output_buffer[thread_id]+filled; output_buffer = thread_output_buffer_filled+thread_id; output_buffer_end = thread_output_buffer[thread_id] + thread_output_buffer_sizes[thread_id] - 1 + 1; } if (!Eflag) // old shrimp output format { char * tmp_output; if (rh != NULL) { int score=rh->sfrp->score; rh->sfrp->score=rh->score_full; tmp_output = output_normal(re->name, contig_names[rh->cn], rh->sfrp, genome_len[rh->cn], shrimp_mode == MODE_COLOUR_SPACE, re->read[rh->st], re->read_len, re->initbp[rh->st], rh->gen_st, Rflag); *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "%s\n", tmp_output); free(tmp_output); if (Pflag) { //pretty print output tmp_output = output_pretty(re->name, contig_names[rh->cn], rh->sfrp, genome_contigs[rh->cn], genome_len[rh->cn], (shrimp_mode == MODE_COLOUR_SPACE), re->read[rh->st], re->read_len, re->initbp[rh->st], rh->gen_st); *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "%s\n", tmp_output); free(tmp_output); } rh->sfrp->score=score; } else { // this is an unmapped read (part of a pair) *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, ">%s\n", re->name); } } else // SAM output { //TODO change this size? //int buffer_size=MAX(longest_read_len,1000)*8; //*output1 = (char *)xmalloc(sizeof(char *)*buffer_size); //qname char * read_name = re->name; char qname[strlen(read_name)+1]; strcpy(qname,read_name); //flag int flag; //rname char const * rname = "*"; //pos int pos=0; //mapq int mapq = (rh != NULL ? rh->sfrp->mqv : 0); //cigar char * cigar=(char *)"*"; cigar_t * cigar_binary=NULL; //mrnm const char * mrnm = "*"; //mate reference name //mpos int mpos=0; //isize int isize=0; //seq assert(shrimp_mode==MODE_COLOUR_SPACE || (signed int)strlen(re->seq)==re->read_len); assert(shrimp_mode==MODE_LETTER_SPACE || (signed int)strlen(re->seq)==re->read_len+1); char seq[re->read_len+1]; if (shrimp_mode == MODE_LETTER_SPACE) { int i; for (i=0; i<re->read_len; i++) { char c = re->seq[i]; switch(c) { case 'R': case 'Y': case 'S': case 'W': case 'K': case 'M': case 'B': case 'D': case 'H': case 'V': seq[i]='N'; break; default: if (c>='a') { c-=32; } seq[i]=c; break; } } assert(i==re->read_len); seq[re->read_len]='\0'; } else { seq[0]='*'; seq[1]='\0'; } //qual int read_length = re->read_len; char qual[read_length+10]; strcpy(qual,"*"); //initialize flags bool paired_read = re->paired; struct read_entry * re_mp = re->mate_pair; assert(!paired_read || re_mp!=NULL); bool paired_alignment = paired_read && (rh!=NULL && rh_mp!=NULL && !improper_mapping); //paired mapping, not paired read! //bool proper_pair = (paired_read && !query_unmapped && !mate_unmapped); //bool query_unmapped = (re->n_hits[0] + re->n_hits[1])>0 ? false : true; bool query_unmapped = (rh==NULL); bool mate_unmapped=false; bool reverse_strand = false; bool reverse_strand_mp = false; int genome_end_mp=0; int genome_start_mp=0; if (paired_read) { int min_read_name_length=MIN(strlen(read_name),strlen(re_mp->name)); int i; for (i=0; i<min_read_name_length; i++) { if (read_name[i]==re_mp->name[i]) { qname[i]=read_name[i]; } else { break; } } if (i>0 && (qname[i-1]==':' || qname[i-1]=='/')) { i--; } qname[i]='\0'; //mate_unmapped=(re_mp->n_hits[0]+re_mp->n_hits[1])>0 ? false : true; mate_unmapped= (rh_mp==NULL); if (!mate_unmapped) { //char * read_name_mp = re->name; //char * rname_mp = contig_names[rh_mp->cn]; int read_start_mp = rh_mp->sfrp->read_start+1; //1based //int read_length_mp = re_mp->read_len; int read_end_mp = read_start_mp + rh_mp->sfrp->rmapped -1; //1base int genome_length_mp = genome_len[rh_mp->cn]; reverse_strand_mp = (rh_mp->gen_st ==1); if (!reverse_strand_mp) { genome_start_mp = rh_mp->sfrp->genome_start+1; // 0 based -> 1 based } else { int genome_right_most_coordinate = genome_length_mp - rh_mp->sfrp->genome_start; //rh->sfrp->deletions is deletions in the reference // This is when the read has extra characters that dont match into ref genome_start_mp = genome_right_most_coordinate - (read_end_mp - read_start_mp - rh_mp->sfrp->deletions + rh_mp->sfrp->insertions); } genome_end_mp=genome_start_mp+rh_mp->sfrp->gmapped-1; mpos=genome_start_mp; mrnm = contig_names[rh_mp->cn]; } } bool second_in_pair = (paired_read && !first_in_pair); bool primary_alignment = false; bool platform_quality_fail = false; bool pcr_duplicate = false; #ifndef NDEBUG int stored_alignments = MIN(num_outputs,satisfying_alignments); //IH #endif //if the read has no mapping or if not in half_paired mode and the mate has no mapping if (query_unmapped || (!half_paired && paired_read && mate_unmapped)) { mapq=0; if (Qflag && shrimp_mode == MODE_LETTER_SPACE ){ strcpy(qual,re->qual); } flag = ( paired_read ? 0x0001 : 0) | ( paired_alignment ? 0x0002 : 0) | ( query_unmapped ? 0x0004 : 0) | ( mate_unmapped ? 0x0008 : 0) | ( reverse_strand ? 0x0010 : 0) | ( reverse_strand_mp ? 0x0020 : 0) | ( first_in_pair ? 0x0040 : 0) | ( second_in_pair ? 0x0080 : 0) | ( primary_alignment ? 0x0100 : 0) | ( platform_quality_fail ? 0x0200 : 0) | ( pcr_duplicate ? 0x0400 : 0); //char *extra = *output1 + sprintf(*output1,"%s\t%i\t%s\t%u\t%i\t%s\t%s\t%u\t%i\t%s\t%s", // qname,flag,rname,pos,mapq,cigar,mrnm,mpos, // isize,seq,qual); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer, "%s\t%i\t%s\t%u\t%i\t%s\t%s\t%u\t%i\t%s\t%s", qname,flag,rname,pos,mapq,cigar,mrnm,mpos, isize,seq,qual); if (shrimp_mode == MODE_COLOUR_SPACE) { if (Qflag) { //extra = extra + sprintf(extra,"\tCQ:Z:%s",re->qual); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer,"\tCQ:Z:%s",re->qual); } else { //extra = extra + sprintf(extra,"\tCQ:Z:%s",qual); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer,"\tCQ:Z:%s",qual); } //extra = extra + sprintf(extra, "\tCS:Z:%s",re->seq); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer, "\tCS:Z:%s",re->seq); } if (sam_r2) { if (shrimp_mode == MODE_COLOUR_SPACE) { //extra = extra + sprintf(extra, "\tX2:Z:%s",re_mp->seq); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer, "\tX2:Z:%s",re_mp->seq); } else { //extra = extra + sprintf(extra, "\tR2:Z:%s",re_mp->seq); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer, "\tR2:Z:%s",re_mp->seq); } } if (sam_read_group_name!=NULL ){ //extra+=sprintf(extra,"\tRG:Z:%s",sam_read_group_name); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer,"\tRG:Z:%s",sam_read_group_name); } *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer,"\n"); assert(satisfying_alignments==0); assert(stored_alignments==0); //assert(hits[0]==0); //assert(hits[1]==0); //assert(hits[2]==0); //assert(hits[3]==0); //extra = extra + sprintf(extra,"\tH0:i:%d\tH1:i:%d\tH2:i:%d\tNH:i:%d\tIH:i:%d",hits[0],hits[1],hits[2],found_alignments,stored_alignments); return; } assert(rh!=NULL); assert( !paired_read || (!query_unmapped && !mate_unmapped) || half_paired); //start filling in the fields rname = contig_names[rh->cn]; reverse_strand = (rh->gen_st == 1); int read_start = rh->sfrp->read_start+1; //1based int read_end = read_start + rh->sfrp->rmapped -1; //1base int genome_length = genome_len[rh->cn]; cigar_binary = make_cigar(read_start,read_end,read_length,rh->sfrp->qralign,rh->sfrp->dbalign); int qralign_length=strlen(rh->sfrp->qralign); int i,j=0; int seq_length=0; if (shrimp_mode == MODE_LETTER_SPACE ) { j=read_start-1; seq_length=re->read_len; } else if (shrimp_mode == MODE_COLOUR_SPACE ) { seq_length=read_end-read_start+1; } assert(seq_length<=re->read_len); for(i=0;i<qralign_length;i++) { char c=rh->sfrp->qralign[i]; if (c!='-') { if (c>='a') { c-=32; } if (c!='A' && c!='a' && c!='G' && c!='g' && c!='C' && c!='c' && c!='T' && c!='t' && c!='N' && c!='n') { //see if we can figure out what its suppose to be c='N'; if (rh->sfrp->dbalign[i]!='-') { char r = rh->sfrp->dbalign[i]; if (r>='a') { r-=32; } switch (r) { case 'A': if (c=='R' || c=='W' || c=='M' || c=='D' || c=='H' || c=='V' ) c='A'; break; case 'C': if (c=='Y' || c=='S' || c=='M' || c=='B' || c=='H' || c=='V') c='C'; break; case 'G': if (c=='R' || c=='S' || c=='K' || c=='B' || c=='D' || c=='V') c='G'; break; case 'T': if (c=='Y' || c=='W' || c=='K' || c=='B' || c=='D' || c=='H') c='T'; break; default: fprintf(stderr,"There has been an error in printing an alignment, %c\n",r); break; } } } seq[j++]=c; } } if (shrimp_mode == MODE_LETTER_SPACE ) { assert(j+(re->read_len-read_end)==seq_length); seq[j+(re->read_len-read_end)]='\0'; } else if (shrimp_mode == MODE_COLOUR_SPACE) { assert(j==seq_length); seq[seq_length]='\0'; } //if its letter space need to reverse the qual string if its backwards if (shrimp_mode == MODE_LETTER_SPACE) { //seq=re->seq; if (Qflag) { if (!reverse_strand) { strcpy(qual,re->qual); } else { int qual_len = strlen(re->qual); //not same as read_len, for color space reads... apperently..... assert((qual_len+1)<(re->read_len+10)); int i; for (i=0; i<qual_len; i++) { qual[(qual_len-1)-i]=re->qual[i]; } qual[qual_len]='\0'; } if (qual_delta!=33) { int qual_len = strlen(re->qual); //not same as read_len, for color space reads... apperently..... int i; for (i=0; i<qual_len; i++) { qual[i]=qual[i]-qual_delta+33; } } } //else in colour space dont print a qual string //but get the seq differently and change 'S' to 'H' in cigar } else if (shrimp_mode == MODE_COLOUR_SPACE) { //also change 'S' in cigar to 'H' //clip the qual values for (i=0; i<cigar_binary->size; i++) { if (cigar_binary->ops[i]=='S') { cigar_binary->ops[i]='H'; } } if (Qflag) { if (Bflag) { int read_length=(read_end-read_start+1); for (i=0; i<read_length; i++) { qual[i]=re->qual[i+read_start-1]; } qual[i]='\0'; for (i=0; i<read_length-1; i++) { //this is different from bfast //qralign is already clipped! i.e. doesn't have clipped stuff and is //read orientation (not always on positive reference strand!) int first_position_mismatch = rh->sfrp->qralign[i] > 96; int second_position_mismatch = rh->sfrp->qralign[i+1] > 96; int base_qual=0; if (first_position_mismatch && second_position_mismatch ) { base_qual+=0; } else if (first_position_mismatch) { base_qual+=qual[i+1]-qual[i]; } else if (second_position_mismatch) { base_qual+=qual[i]-qual[i+1]+33; } else { base_qual+=qual[i]+qual[i+1]+10-33; } base_qual=MIN('`',MAX(base_qual,'"')); qual[i]=base_qual; } if (reverse_strand) { for (i = 0; i < rh->sfrp->rmapped/2; i++) { char temp = qual[i]; qual[i]=qual[rh->sfrp->rmapped-i-1]; qual[rh->sfrp->rmapped-i-1]=temp; } } } else if (compute_mapping_qualities) { strcpy(qual, rh->sfrp->qual); if (reverse_strand) { for (i = 0; i < rh->sfrp->rmapped/2; i++) { char temp = qual[i]; qual[i]=qual[rh->sfrp->rmapped-i-1]; qual[rh->sfrp->rmapped-i-1]=temp; } } } } } //get the pos int genome_start; if (!reverse_strand) { genome_start = rh->sfrp->genome_start+1; // 0 based -> 1 based } else { int genome_right_most_coordinate = genome_length - rh->sfrp->genome_start; //rh->sfrp->deletions is deletions in the reference // This is when the read has extra characters that dont match into ref genome_start = genome_right_most_coordinate - (read_end - read_start - rh->sfrp->deletions + rh->sfrp->insertions); char * tmp = (char*)xmalloc(sizeof(char)*(strlen(seq)+1)); reverse(seq,tmp); free(tmp); reverse_cigar(cigar_binary); } int genome_end=genome_start+rh->sfrp->gmapped-1; pos=genome_start; //make the cigar string cigar = make_cigar_string(cigar_binary); //do some stats using matepair if (paired_read && !mate_unmapped) { assert(rh_mp!=NULL && re_mp!=NULL); if (strcmp(rname, mrnm) == 0) { mrnm = "="; //printf("%d %d %c, %d %d %c\n",genome_start, genome_end,reverse_strand ? '-' : '+' , genome_start_mp, genome_end_mp, reverse_strand_mp ? '-' : '+'); int fivep = 0; int fivep_mp = 0; if (reverse_strand) fivep = genome_end; else fivep = genome_start - 1; if (reverse_strand_mp) fivep_mp = genome_end_mp; else fivep_mp = genome_start_mp-1; isize = (fivep_mp - fivep); } else { // map to different chromosomes isize = 0; } } flag = ( paired_read ? 0x0001 : 0) | ( paired_alignment ? 0x0002 : 0) | ( query_unmapped ? 0x0004 : 0) | ( mate_unmapped ? 0x0008 : 0) | ( reverse_strand ? 0x0010 : 0) | ( reverse_strand_mp ? 0x0020 : 0) | ( first_in_pair ? 0x0040 : 0) | ( second_in_pair ? 0x0080 : 0) | ( primary_alignment ? 0x0100 : 0) | ( platform_quality_fail ? 0x0200 : 0) | ( pcr_duplicate ? 0x0400 : 0); //char *extra = *output1 + sprintf(*output1,"%s\t%i\t%s\t%u\t%i\t%s\t%s\t%u\t%i\t%s\t%s", // qname,flag,rname,pos,mapq,cigar,mrnm,mpos, // isize,seq,qual); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer,"%s\t%i\t%s\t%u\t%i\t%s\t%s\t%u\t%i\t%s\t%s", qname,flag,rname,pos,mapq,cigar,mrnm,mpos, isize,seq,qual); //extra = extra + sprintf(extra,"\tAS:i:%d\tH0:i:%d\tH1:i:%d\tH2:i:%d\tNM:i:%d\tNH:i:%d\tIH:i:%d",rh->sfrp->score,hits[0],hits[1],hits[2],rh->sfrp->mismatches+rh->sfrp->deletions+rh->sfrp->insertions,found_alignments,stored_alignments); //MERGESAM DEPENDS ON SCORE BEING FIRST! *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tAS:i:%d", rh->score_full); if (compute_mapping_qualities && !all_contigs) { if (pair_mode == PAIR_NONE) { *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tZ0:i:%d\tZ1:i:%d", double_to_neglog(rh->sfrp->z0), double_to_neglog(rh->sfrp->z1)); } else // paired mode { if (rh != NULL && rh_mp != NULL && !improper_mapping) { *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tZ2:i:%d\tZ3:i:%d\tZ4:i:%d\tZ6:i:%d", double_to_neglog(rh->sfrp->z2), double_to_neglog(rh->sfrp->z3), double_to_neglog(rh->sfrp->pr_top_random_at_location), double_to_neglog(rh->sfrp->insert_size_denom)); } else { *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tZ0:i:%d\tZ1:i:%d\tZ4:i:%d\tZ5:i:%d", double_to_neglog(rh->sfrp->z0), double_to_neglog(rh->sfrp->z1), double_to_neglog(rh->sfrp->pr_top_random_at_location), double_to_neglog(rh->sfrp->pr_missed_mp)); } } } //*output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tH0:i:%d\tH1:i:%d\tH2:i:%d", // hits[0],hits[1],hits[2]); *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tNM:i:%d", rh->sfrp->mismatches+rh->sfrp->deletions+rh->sfrp->insertions); //*output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tNH:i:%d\tIH:i:%d", // satisfying_alignments, stored_alignments); if (shrimp_mode == COLOUR_SPACE){ //TODO //int first_bp = re->initbp[0]; //printf("%s vs %s\n",readtostr(re->read[0],re->read_len,true,first_bp),re->seq); //assert(strcmp(readtostr(re->read[0],re->read_len,true,first_bp),re->seq)==0); if (Qflag) { //extra = extra + sprintf(extra,"\tCQ:Z:%s",re->qual); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer,"\tCQ:Z:%s",re->qual); } //extra = extra + sprintf(extra, "\tCS:Z:%s\tCM:i:%d\tXX:Z:%s",re->seq,rh->sfrp->crossovers,rh->sfrp->qralign); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer, "\tCS:Z:%s\tCM:i:%d\tXX:Z:%s",re->seq,rh->sfrp->crossovers,rh->sfrp->qralign); } if (sam_r2) { if (shrimp_mode == MODE_COLOUR_SPACE) { //extra = extra + sprintf(extra, "\tX2:Z:%s",re_mp->seq); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer, "\tX2:Z:%s",re_mp->seq); } else { //extra = extra + sprintf(extra, "\tR2:Z:%s",re_mp->seq); *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer, "\tR2:Z:%s",re_mp->seq); } } if (sam_read_group_name!=NULL) { //extra+=sprintf(extra,"\tRG:Z:%s",sam_read_group_name); *output_buffer+=snprintf(*output_buffer,output_buffer_end-*output_buffer,"\tRG:Z:%s",sam_read_group_name); } if (extra_sam_fields) { char * editstr = alignment_edit_string(rh->sfrp->dbalign, rh->sfrp->qralign); if (reverse_strand) { char * tmp = reverse_alignment_edit_string(editstr); free(editstr); editstr = tmp; } *output_buffer += snprintf(*output_buffer, output_buffer_end - *output_buffer, "\tZM:i:%d\tZR:i:%d\tZV:i:%d\tZH:i:%d\tZE:Z:%s", rh->matches, rh->score_window_gen, rh->score_vector, rh->sfrp->score, editstr); free(editstr); } if (cigar_binary!=NULL) { free_cigar(cigar_binary); free(cigar); } *output_buffer += snprintf(*output_buffer,output_buffer_end-*output_buffer,"\n"); //to calculate the insert size we need to find the five' end of the reads /* inp.score); if(re_mp != NULL){ free(name); } free(read); free(cigar); format_free(fsp);*/ } } static void compute_unpaired_mqv(read_entry * re, read_hit * * hits, int n_hits) { int i; double z1 = 0.0; for (i = 0; i < n_hits; i++) { z1 += hits[i]->sfrp->posterior; } for (i = 0; i < n_hits; i++) { hits[i]->sfrp->z0 = hits[i]->sfrp->posterior; hits[i]->sfrp->z1 = z1; hits[i]->sfrp->mqv = qv_from_pr_corr(hits[i]->sfrp->posterior / z1); if (hits[i]->sfrp->mqv < 4) hits[i]->sfrp->mqv = 0; } } static inline double get_pr_insert_size(double insert_size) { double res; res = normal_cdf(insert_size + 10, insert_size_mean, insert_size_stddev) - normal_cdf(insert_size - 10, insert_size_mean, insert_size_stddev); //int bucket = (insert_size - min_insert_size) / insert_histogram_bucket_size; //if (bucket < 0) bucket = 0; //if (bucket > 99) bucket = 99; //res = (double)insert_histogram[bucket] / (double)insert_histogram_load; if (res < 1e-200) res = 1e-200; //fprintf(stderr,"INVOKED WITH %e, %e %e, res %e\n",insert_size,insert_size_mean, insert_size_stddev,res); return res; } static void compute_paired_mqv(pair_entry * pe) { int i, j, nip; double z1[2]; double z3; double insert_size_denom; double pr_top_random[3] = { 1.0, 1.0, 1.0 }; double pr_missed_mp[2]; double class_select_denom; // first, compute z1s for unpaired hits, which give unpaired posteriors for (nip = 0; nip < 2; nip++) { z1[nip] = 0; for (i = 0; i < pe->re[nip]->n_final_unpaired_hits; i++) z1[nip] += pe->re[nip]->final_unpaired_hits[i].sfrp->posterior; // and write them back for (i = 0; i < pe->re[nip]->n_final_unpaired_hits; i++) { pe->re[nip]->final_unpaired_hits[i].sfrp->z0 = pe->re[nip]->final_unpaired_hits[i].sfrp->posterior; pe->re[nip]->final_unpaired_hits[i].sfrp->z1 = z1[nip]; } } // renormalize insert sizes into a distribution insert_size_denom = 0.0; for (i = 0; i < pe->n_final_paired_hits; i++) { double pr_ins = get_pr_insert_size(pe->final_paired_hits[i].insert_size); insert_size_denom += pr_ins; } // write denom to all sfr structs of paired mappings for (nip = 0; nip < 2; nip++) { for (i = 0; i < pe->final_paired_hit_pool_size[nip]; i++) { pe->final_paired_hit_pool[nip][i].sfrp->insert_size_denom = insert_size_denom; } } // compute paired posteriors z3 = 0.0; for (nip = 0; nip < 2; nip++) { for (i = 0; i < pe->final_paired_hit_pool_size[nip]; i++) { read_hit * rhp = &pe->final_paired_hit_pool[nip][i]; double tmp = 0.0; for (j = 0; j < rhp->n_paired_hit_idx; j++) { read_hit_pair * rhpp = &pe->final_paired_hits[rhp->paired_hit_idx[j]]; read_hit * rh_mpP = &pe->final_paired_hit_pool[1 - nip][rhpp->rh_idx[1 - nip]]; double pr_ins = get_pr_insert_size(rhpp->insert_size); tmp += pr_ins * rh_mpP->sfrp->posterior; } tmp *= rhp->sfrp->posterior; if (tmp < 1e-200) tmp = 1e-200; rhp->sfrp->z2 = tmp; if (nip == 0) z3 += tmp; } } for (nip = 0; nip < 2; nip++) { for (i = 0; i < pe->final_paired_hit_pool_size[nip]; i++) { pe->final_paired_hit_pool[nip][i].sfrp->z3 = z3; } } // compute the probability that the top mapping in each class is random // for unpaired, use the one with max posterior for (nip = 0; nip < 2; nip++) { // find the mapping with max score int max_idx = 0; if (pe->re[nip]->n_final_unpaired_hits == 0) continue; for (i = 1; i < pe->re[nip]->n_final_unpaired_hits; i++) if (pe->re[nip]->final_unpaired_hits[i].sfrp->z0 > pe->re[nip]->final_unpaired_hits[max_idx].sfrp->z0) max_idx = i; // find pr a mapping of that score arises by chance pr_top_random[nip] = pr_random_mapping_given_score(pe->re[nip], pe->re[nip]->final_unpaired_hits[max_idx].sfrp->posterior_score); // write the coefficient back for (i = 0; i < pe->re[nip]->n_final_unpaired_hits; i++) pe->re[nip]->final_unpaired_hits[i].sfrp->pr_top_random_at_location = pr_top_random[nip]; pr_top_random[nip] *= (double)total_genome_size; if (pr_top_random[nip] > 1) pr_top_random[nip] = 1.0; } // for paired, both mappings must be random for (i = 0; i < pe->n_final_paired_hits; i++) { double tmp = pr_random_mapping_given_score(pe->re[0], pe->final_paired_hit_pool[0][pe->final_paired_hits[i].rh_idx[0]].sfrp->posterior_score); tmp *= pr_random_mapping_given_score(pe->re[1], pe->final_paired_hit_pool[1][pe->final_paired_hits[i].rh_idx[1]].sfrp->posterior_score); tmp *= 1000; if (tmp < pr_top_random[2]) pr_top_random[2] = tmp; } // write it back for (i = 0; i < pe->n_final_paired_hits; i++) { pe->final_paired_hit_pool[0][pe->final_paired_hits[i].rh_idx[0]].sfrp->pr_top_random_at_location = pr_top_random[2]; pe->final_paired_hit_pool[1][pe->final_paired_hits[i].rh_idx[1]].sfrp->pr_top_random_at_location = pr_top_random[2]; } pr_top_random[2] *= (double)total_genome_size; if (pr_top_random[2] > 1) pr_top_random[2] = 1.0; // finally, for unpaired mappings, compute the prob the algo missed the mate mapping for (nip = 0; nip < 2; nip++) { pr_missed_mp[nip] = get_pr_missed(pe->re[1-nip]); // write it to sfrp for (i = 0; i < pe->re[nip]->n_final_unpaired_hits; i++) pe->re[nip]->final_unpaired_hits[i].sfrp->pr_missed_mp = pr_missed_mp[nip]; } // compute denominator selecting between classes of mappings class_select_denom = 0.0; if (pe->re[0]->n_final_unpaired_hits > 0) class_select_denom += pr_top_random[1] * pr_top_random[2] * pr_missed_mp[0]; if (pe->re[1]->n_final_unpaired_hits > 0) class_select_denom += pr_top_random[0] * pr_top_random[2] * pr_missed_mp[1]; if (pe->n_final_paired_hits > 0) class_select_denom += pr_top_random[0] * pr_top_random[1]; // DONE! ready to compute mqvs // unpaired: for (nip = 0; nip < 2; nip++) { for (i = 0; i < pe->re[nip]->n_final_unpaired_hits; i++) { read_hit * rhp = &pe->re[nip]->final_unpaired_hits[i]; double p_corr = (pr_top_random[1-nip] * pr_top_random[2] * pr_missed_mp[nip] / class_select_denom) * (rhp->sfrp->z0 / rhp->sfrp->z1); rhp->sfrp->mqv = qv_from_pr_corr(p_corr); if (rhp->sfrp->mqv < 4) rhp->sfrp->mqv = 0; } } // paired: for (i = 0; i < pe->n_final_paired_hits; i++) { for (nip = 0; nip < 2; nip++) { read_hit * rhp = &pe->final_paired_hit_pool[nip][pe->final_paired_hits[i].rh_idx[nip]]; double p_corr = (pr_top_random[0] * pr_top_random[1] / class_select_denom) * (rhp->sfrp->z2 / (/*insert_size_denom * */rhp->sfrp->z3)); rhp->sfrp->mqv = qv_from_pr_corr(p_corr); if (rhp->sfrp->mqv < 4) rhp->sfrp->mqv = 0; } } } static void add_sam_hit_counts(struct read_hit * h, int * sam_hit_counts) { int edit_distance = h->sfrp->mismatches + h->sfrp->insertions + h->sfrp->deletions; if (0 <= edit_distance && edit_distance < 3) { sam_hit_counts[edit_distance]++; } } void read_output(struct read_entry * re, struct read_hit * * hits_pass2, int n_hits_pass2) { int i; int sam_hit_counts[3] = {0, 0, 0}; int first, last; if (n_hits_pass2 == 0) return; if (Eflag) { for (i = 0; i < n_hits_pass2; i++) { add_sam_hit_counts(hits_pass2[i], sam_hit_counts); } } // Compute mapping qualities only if in unpaired mode. // Note: this procedure might be called in paired mode by setting save_outputs to false; no mqv in that case first = 0; last = n_hits_pass2; if (pair_mode == PAIR_NONE && compute_mapping_qualities) { compute_unpaired_mqv(re, hits_pass2, n_hits_pass2); if (single_best_mapping) { int max_idx = 0; for (i = 1; i < n_hits_pass2; i++) if (hits_pass2[i]->sfrp->mqv > hits_pass2[max_idx]->sfrp->mqv) max_idx = i; first = max_idx; last = max_idx + 1; } } bool good_unpair = false; for (i = first; i < last; i++) { struct read_hit * rh = hits_pass2[i]; if (pair_mode == PAIR_NONE) { hit_output(re, rh, NULL, false, sam_hit_counts, n_hits_pass2, false); if (rh->sfrp->mqv >= 10) good_unpair = true; } else { if (re->first_in_pair) { hit_output(re, rh, NULL, true, sam_hit_counts, n_hits_pass2, false); hit_output(re->mate_pair, NULL, rh, false, NULL, 0, false); } else { hit_output(re->mate_pair, NULL, rh, true, NULL, 0, false); hit_output(re, rh, NULL, false, sam_hit_counts, n_hits_pass2, false); } } } if (pair_mode == PAIR_NONE && good_unpair) { #pragma omp atomic total_reads_matched_conf++; } } void readpair_output_no_mqv(pair_entry * pe, struct read_hit_pair * hits_pass2, int n_hits_pass2) { int i; int sam_hit_counts[2][3] = { {0, 0, 0}, {0, 0, 0} }; if (Eflag) { for (i = 0; i < n_hits_pass2; i++) { add_sam_hit_counts(hits_pass2[i].rh[0], sam_hit_counts[0]); add_sam_hit_counts(hits_pass2[i].rh[1], sam_hit_counts[1]); } } for (i = 0; i < n_hits_pass2; i++) { struct read_hit * rh1 = hits_pass2[i].rh[0]; struct read_hit * rh2 = hits_pass2[i].rh[1]; uint bucket; hit_output(pe->re[0], rh1, rh2, true, sam_hit_counts[0], n_hits_pass2, false); hit_output(pe->re[1], rh2, rh1, false, sam_hit_counts[1], n_hits_pass2, false); if (Xflag) { if (hits_pass2[i].insert_size < min_insert_size) bucket = 0; else if (hits_pass2[i].insert_size > max_insert_size) bucket = 99; else bucket = (uint)((hits_pass2[i].insert_size - min_insert_size) / insert_histogram_bucket_size); if (bucket >= 100) bucket = 99; #pragma omp atomic insert_histogram[bucket]++; } } } // Find paired mapping containing given mapping of one read // and max mqv mapping of the other int get_idx_mp_max_mqv(pair_entry * pe, int nip, int idx) { assert(pe != NULL && idx < pe->final_paired_hit_pool_size[nip]); assert(pe->final_paired_hit_pool[nip][idx].n_paired_hit_idx > 0); int best_other_mqv = -1; int i, idx_pair = -1; // init not needed read_hit * rhp = &pe->final_paired_hit_pool[nip][idx]; for (i = 0; i < rhp->n_paired_hit_idx; i++) { read_hit * rh_mpP = &pe->final_paired_hit_pool[1 - nip][pe->final_paired_hits[rhp->paired_hit_idx[i]].rh_idx[1 - nip]]; if (rh_mpP->sfrp->mqv > best_other_mqv) { best_other_mqv = rh_mpP->sfrp->mqv; idx_pair = rhp->paired_hit_idx[i]; } } return idx_pair; } void readpair_output(pair_entry * pe) { int i, nip; int sam_hit_counts[2][3] = { {0, 0, 0}, {0, 0, 0} }; int first[3], last[3]; if (Eflag) { for (nip = 0; nip < 2; nip++) { for (i = 0; i < pe->re[nip]->n_final_unpaired_hits; i++) add_sam_hit_counts(&pe->re[nip]->final_unpaired_hits[i], sam_hit_counts[nip]); for (i = 0; i < pe->final_paired_hit_pool_size[nip]; i++) add_sam_hit_counts(&pe->final_paired_hit_pool[nip][i], sam_hit_counts[nip]); } } first[0] = 0; last[0] = pe->re[0]->n_final_unpaired_hits; first[1] = 0; last[1] = pe->re[1]->n_final_unpaired_hits; first[2] = 0; last[2] = pe->n_final_paired_hits; if (compute_mapping_qualities) { compute_paired_mqv(pe); if (single_best_mapping && (pe->n_final_paired_hits > 0 || pe->re[0]->n_final_unpaired_hits > 0 || pe->re[1]->n_final_unpaired_hits > 0)) { // find out the max mqv for either read int max_is_paired[2]; int max_idx_unpaired[2] = { -1, -1 }; int max_idx_paired[2] = { -1, -1 }; int max_idx[2]; int max_mqv_unpaired[2] = { -1, -1 }; int max_mqv_paired[2] = { -1, -1 }; int max_mqv[2]; int best_nip, idx_pair; for (nip = 0; nip < 2; nip++) { for (i = 0; i < pe->re[nip]->n_final_unpaired_hits; i++) if (pe->re[nip]->final_unpaired_hits[i].sfrp->mqv > max_mqv_unpaired[nip]) { max_mqv_unpaired[nip] = pe->re[nip]->final_unpaired_hits[i].sfrp->mqv; max_idx_unpaired[nip] = i; } for (i = 0; i < pe->final_paired_hit_pool_size[nip]; i++) if (pe->final_paired_hit_pool[nip][i].sfrp->mqv > max_mqv_paired[nip]) { max_mqv_paired[nip] = pe->final_paired_hit_pool[nip][i].sfrp->mqv; max_idx_paired[nip] = i; } } if (!all_contigs) { // output top mapping in each class // for unpaired, take max for (nip = 0; nip < 2; nip++) if (max_idx_unpaired[nip] >= 0) { first[nip] = max_idx_unpaired[nip]; last[nip] = max_idx_unpaired[nip] + 1; } // for paired, take the max mqv, then the mate with the max mqv if (max_mqv_paired[0] > max_mqv_paired[1]) best_nip = 0; else best_nip = 1; if (max_mqv_paired[best_nip] >= 0) { idx_pair = get_idx_mp_max_mqv(pe, best_nip, max_idx_paired[best_nip]); first[2] = idx_pair; last[2] = idx_pair + 1; } } else // all-contigs { // output top mapping over all classes for (nip = 0; nip < 2; nip++) { if (max_mqv_unpaired[nip] > max_mqv_paired[nip]) { max_mqv[nip] = max_mqv_unpaired[nip]; max_is_paired[nip] = 0; max_idx[nip] = max_idx_unpaired[nip]; } else { max_mqv[nip] = max_mqv_paired[nip]; max_is_paired[nip] = 1; max_idx[nip] = max_idx_paired[nip]; } } if (max_mqv[0] >= max_mqv[1]) // will output best hit for read0 best_nip = 0; else best_nip = 1; if (max_is_paired[best_nip] == 1) { // output a pair containing max // choose max mq for the other read idx_pair = get_idx_mp_max_mqv(pe, best_nip, max_idx[best_nip]); /* // update the histogram of insert sizes int bucket = (pe->final_paired_hits[idx_pair].insert_size - min_insert_size) / insert_histogram_bucket_size; if (bucket < 0) bucket = 0; if (bucket > 99) bucket = 99; #pragma omp atomic insert_histogram[bucket]++; #pragma omp atomic insert_histogram_load++; */ last[0] = 0; last[1] = 0; first[2] = idx_pair; last[2] = idx_pair + 1; } else { // max mqv is in an unpaired hit // see if it can be paired with best one from read1 int idx_best_other = -1; double max_other_z0 = 0.0; for (i = 0; i < pe->re[1 - best_nip]->n_final_unpaired_hits; i++) { if (pe->re[1 - best_nip]->final_unpaired_hits[i].sfrp->z0 > max_other_z0) { max_other_z0 = pe->re[1 - best_nip]->final_unpaired_hits[i].sfrp->z0; idx_best_other = i; } } int best_other_mqv = -1; if (idx_best_other >= 0) //best_other_mqv = qv_from_pr_corr(exp((-max_other_z0 + pe->re[1 - best_nip]->final_unpaired_hits[idx_best_other].sfrp->z1) / 1000)); best_other_mqv = qv_from_pr_corr(max_other_z0 / pe->re[1 - best_nip]->final_unpaired_hits[idx_best_other].sfrp->z1); if (!improper_mappings || max_mqv_unpaired[best_nip] < 10 || best_other_mqv < 10) { // output unpaired hit last[2] = 0; last[1-best_nip] = 0; first[best_nip] = max_idx[best_nip]; last[best_nip] = max_idx[best_nip] + 1; } else { // unpaired qv >= 10: // pair up hits, possibly across chromosomes // for this, create a new read_hit_pair entry read_hit_pair * rhpp; pe->final_paired_hits = (read_hit_pair *) my_realloc(pe->final_paired_hits, (pe->n_final_paired_hits + 1) * sizeof(pe->final_paired_hits[0]), pe->n_final_paired_hits * sizeof(pe->final_paired_hits[0]), &mem_mapping, "final_paired_hits [%s,%s]", pe->re[0]->name, pe->re[1]->name); pe->n_final_paired_hits++; rhpp = &pe->final_paired_hits[pe->n_final_paired_hits - 1]; rhpp->rh[best_nip] = &pe->re[best_nip]->final_unpaired_hits[max_idx[best_nip]]; rhpp->rh[1 - best_nip] = &pe->re[1 - best_nip]->final_unpaired_hits[idx_best_other]; rhpp->score_max = rhpp->rh[0]->score_max + rhpp->rh[1]->score_max; rhpp->insert_size = get_insert_size(rhpp->rh[best_nip], rhpp->rh[1 - best_nip]); rhpp->improper_mapping = true; last[0] = 0; last[1] = 0; first[2] = pe->n_final_paired_hits - 1; last[2] = pe->n_final_paired_hits; } } } } } // time to output stuff bool good_pair = false; bool good_unpair = false; for (i = first[2]; i < last[2]; i++) { read_hit * rh1 = pe->final_paired_hits[i].rh[0]; read_hit * rh2 = pe->final_paired_hits[i].rh[1]; if (rh1 == NULL) rh1 = &pe->final_paired_hit_pool[0][pe->final_paired_hits[i].rh_idx[0]]; if (rh2 == NULL) rh2 = &pe->final_paired_hit_pool[1][pe->final_paired_hits[i].rh_idx[1]]; hit_output(pe->re[0], rh1, rh2, true, sam_hit_counts[0], pe->n_final_paired_hits, pe->final_paired_hits[i].improper_mapping); hit_output(pe->re[1], rh2, rh1, false, sam_hit_counts[1], pe->n_final_paired_hits, pe->final_paired_hits[i].improper_mapping); if (!pe->final_paired_hits[i].improper_mapping && (rh1->sfrp->mqv >= 10 || rh2->sfrp->mqv >= 10)) { good_pair = true; } else if (pe->final_paired_hits[i].improper_mapping && (rh1->sfrp->mqv >= 10 || rh2->sfrp->mqv >= 10)) { good_unpair = true; } if (Xflag && !pe->final_paired_hits[i].improper_mapping) { // update the histogram of insert sizes int bucket = (pe->final_paired_hits[i].insert_size - min_insert_size) / insert_histogram_bucket_size; if (bucket < 0) bucket = 0; if (bucket > 99) bucket = 99; #pragma omp atomic insert_histogram[bucket]++; #pragma omp atomic insert_histogram_load++; } } for (nip = 0; nip < 2; nip++) for (i = first[nip]; i < last[nip]; i++) { read_entry * rep = pe->re[nip]; read_hit * rhp = &rep->final_unpaired_hits[i]; if (rep->first_in_pair) { hit_output(rep, rhp, NULL, true, sam_hit_counts[0], rep->n_final_unpaired_hits, false); hit_output(rep->mate_pair, NULL, rhp, false, NULL, 0, false); } else { hit_output(rep->mate_pair, NULL, rhp, true, NULL, 0, false); hit_output(rep, rhp, NULL, false, sam_hit_counts[1], rep->n_final_unpaired_hits, false); } if (rhp->sfrp->mqv >= 10) { good_unpair = true; } } if (good_pair) { #pragma omp atomic total_pairs_matched_conf++; } else if (good_unpair) { #pragma omp atomic total_reads_matched_conf++; } }
nodal_residualbased_elimination_builder_and_solver.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi, Alessandro Franci // // #if !defined(KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER) #define KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER /* System includes */ #include <set> #ifdef _OPENMP #include <omp.h> #endif /* External includes */ // #define USE_GOOGLE_HASH #ifdef USE_GOOGLE_HASH #include "sparsehash/dense_hash_set" //included in external libraries #else #include <unordered_set> #endif /* Project includes */ #include "utilities/timer.h" #include "includes/define.h" #include "includes/key_hash.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" #include "pfem_fluid_dynamics_application_variables.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class NodalResidualBasedEliminationBuilderAndSolver * @ingroup KratosCore * @brief Current class provides an implementation for standard builder and solving operations. * @details The RHS is constituted by the unbalanced loads (residual) * Degrees of freedom are reordered putting the restrained degrees of freedom at * the end of the system ordered in reverse order with respect to the DofSet. * Imposition of the dirichlet conditions is naturally dealt with as the residual already contains * this information. * Calculation of the reactions involves a cost very similiar to the calculation of the total residual * @author Riccardo Rossi */ template <class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class NodalResidualBasedEliminationBuilderAndSolver : public BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(NodalResidualBasedEliminationBuilderAndSolver); typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef Node<3> NodeType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; typedef Vector VectorType; typedef GlobalPointersVector<Node<3>> NodeWeakPtrVectorType; ///@} ///@name Life Cycle ///@{ /** Constructor. */ NodalResidualBasedEliminationBuilderAndSolver( typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>(pNewLinearSystemSolver) { // KRATOS_INFO("NodalResidualBasedEliminationBuilderAndSolver") << "Using the standard builder and solver " << std::endl; } /** Destructor. */ ~NodalResidualBasedEliminationBuilderAndSolver() override { } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ void SetMaterialPropertiesToFluid( ModelPart::NodeIterator itNode, double &density, double &deviatoricCoeff, double &volumetricCoeff, double timeInterval, double nodalVolume) { density = itNode->FastGetSolutionStepValue(DENSITY); deviatoricCoeff = itNode->FastGetSolutionStepValue(DYNAMIC_VISCOSITY); double yieldShear = itNode->FastGetSolutionStepValue(YIELD_SHEAR); if (yieldShear > 0) { double adaptiveExponent = itNode->FastGetSolutionStepValue(ADAPTIVE_EXPONENT); double equivalentStrainRate = itNode->FastGetSolutionStepValue(NODAL_EQUIVALENT_STRAIN_RATE); double exponent = -adaptiveExponent * equivalentStrainRate; if (equivalentStrainRate != 0) { deviatoricCoeff += (yieldShear / equivalentStrainRate) * (1 - exp(exponent)); } if (equivalentStrainRate < 0.00001 && yieldShear != 0 && adaptiveExponent != 0) { // for gamma_dot very small the limit of the Papanastasiou viscosity is mu=m*tau_yield deviatoricCoeff = adaptiveExponent * yieldShear; } } volumetricCoeff = timeInterval * itNode->FastGetSolutionStepValue(BULK_MODULUS); if (volumetricCoeff > 0) { volumetricCoeff = timeInterval * itNode->FastGetSolutionStepValue(BULK_MODULUS); double bulkReduction = density * nodalVolume / (timeInterval * volumetricCoeff); volumetricCoeff *= bulkReduction; } } void BuildFluidNodally( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; /* std::cout<<"Building LHS and RHS of Momentum Equation Nodally"<<std::endl; */ //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different terms Element::EquationIdVectorType EquationId; ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; const double FourThirds = 4.0 / 3.0; const double nTwoThirds = -2.0 / 3.0; double theta = 0.5; array_1d<double, 3> Acc(3, 0.0); // array_1d<double,6> Sigma(6,0.0); double pressure = 0; double dNdXi = 0; double dNdYi = 0; double dNdZi = 0; double dNdXj = 0; double dNdYj = 0; double dNdZj = 0; unsigned int firstRow = 0; unsigned int firstCol = 0; double density = 0; double deviatoricCoeff = 0; double volumetricCoeff = 0; /* #pragma omp parallel */ // { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); Vector nodalSFDneighboursId = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER); // const unsigned int neighSize = neighb_nodes.size()+1; const unsigned int neighSize = nodalSFDneighboursId.size(); const double nodalVolume = itNode->FastGetSolutionStepValue(NODAL_VOLUME); if (neighSize > 1 && nodalVolume > 0) { const unsigned int localSize = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS).size(); if (LHS_Contribution.size1() != localSize) LHS_Contribution.resize(localSize, localSize, false); //false says not to preserve existing storage!! if (RHS_Contribution.size() != localSize) RHS_Contribution.resize(localSize, false); //false says not to preserve existing storage!! if (EquationId.size() != localSize) EquationId.resize(localSize, false); LHS_Contribution = ZeroMatrix(localSize, localSize); RHS_Contribution = ZeroVector(localSize); this->SetMaterialPropertiesToFluid(itNode, density, deviatoricCoeff, volumetricCoeff, timeInterval, nodalVolume); firstRow = 0; firstCol = 0; if (dimension == 2) { //////////////////////////// LHS TERMS ////////////////////////////// LHS_Contribution(0, 0) += nodalVolume * density * 2.0 / timeInterval; LHS_Contribution(1, 1) += nodalVolume * density * 2.0 / timeInterval; //////////////////////////// RHS TERMS ////////////////////////////// //-------- DYNAMIC FORCES TERM -------// Acc = 2.0 * (itNode->FastGetSolutionStepValue(VELOCITY, 0) - itNode->FastGetSolutionStepValue(VELOCITY, 1)) / timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION, 0); RHS_Contribution[0] += -nodalVolume * density * Acc[0]; RHS_Contribution[1] += -nodalVolume * density * Acc[1]; //-------- EXTERNAL FORCES TERM -------// array_1d<double, 3> &VolumeAcceleration = itNode->FastGetSolutionStepValue(VOLUME_ACCELERATION); // double posX= itNode->X(); // double posY= itNode->Y(); // double coeffX =(12.0-24.0*posY)*pow(posX,4); // coeffX += (-24.0+48.0*posY)*pow(posX,3); // coeffX += (-48.0*posY+72.0*pow(posY,2)-48.0*pow(posY,3)+12.0)*pow(posX,2); // coeffX += (-2.0+24.0*posY-72.0*pow(posY,2)+48.0*pow(posY,3))*posX; // coeffX += 1.0-4.0*posY+12.0*pow(posY,2)-8.0*pow(posY,3); // double coeffY =(8.0-48.0*posY+48.0*pow(posY,2))*pow(posX,3); // coeffY += (-12.0+72.0*posY-72.0*pow(posY,2))*pow(posX,2); // coeffY += (4.0-24.0*posY+48.0*pow(posY,2)-48.0*pow(posY,3)+24.0*pow(posY,4))*posX; // coeffY += -12.0*pow(posY,2)+24.0*pow(posY,3)-12.0*pow(posY,4); // RHS_Contribution[0]+=nodalVolume*density*VolumeAcceleration[0]*coeffX; // RHS_Contribution[1]+=nodalVolume*density*VolumeAcceleration[1]*coeffY; RHS_Contribution[0] += nodalVolume * density * VolumeAcceleration[0]; RHS_Contribution[1] += nodalVolume * density * VolumeAcceleration[1]; //-------- INTERNAL FORCES TERM -------// array_1d<double, 3> Sigma(3, 0.0); Sigma = itNode->FastGetSolutionStepValue(NODAL_CAUCHY_STRESS); pressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) * theta + itNode->FastGetSolutionStepValue(PRESSURE, 1) * (1 - theta); Sigma[0] = itNode->FastGetSolutionStepValue(NODAL_DEVIATORIC_CAUCHY_STRESS)[0] + pressure; Sigma[1] = itNode->FastGetSolutionStepValue(NODAL_DEVIATORIC_CAUCHY_STRESS)[1] + pressure; const unsigned int xDofPos = itNode->GetDofPosition(VELOCITY_X); EquationId[0] = itNode->GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[1] = itNode->GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); for (unsigned int i = 0; i < neighSize; i++) { dNdXi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 1]; RHS_Contribution[firstCol] += -nodalVolume * (dNdXi * Sigma[0] + dNdYi * Sigma[2]); RHS_Contribution[firstCol + 1] += -nodalVolume * (dNdYi * Sigma[1] + dNdXi * Sigma[2]); for (unsigned int j = 0; j < neighSize; j++) { dNdXj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow]; dNdYj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow + 1]; LHS_Contribution(firstRow, firstCol) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdXi + dNdYj * dNdYi * deviatoricCoeff) * theta; LHS_Contribution(firstRow, firstCol + 1) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdYi + dNdYj * dNdXi * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 1, firstCol) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdXi + dNdXj * dNdYi * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 1, firstCol + 1) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdYi + dNdXj * dNdXi * deviatoricCoeff) * theta; firstRow += 2; } firstRow = 0; firstCol += 2; if (i < neighb_nodes.size()) { EquationId[firstCol] = neighb_nodes[i].GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[firstCol + 1] = neighb_nodes[i].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); } } /* std::cout << "LHS_Contribution = " << LHS_Contribution << std::endl; */ } else if (dimension == 3) { //////////////////////////// LHS TERMS ////////////////////////////// LHS_Contribution(0, 0) += nodalVolume * density * 2.0 / timeInterval; LHS_Contribution(1, 1) += nodalVolume * density * 2.0 / timeInterval; LHS_Contribution(2, 2) += nodalVolume * density * 2.0 / timeInterval; //////////////////////////// RHS TERMS ////////////////////////////// //-------- DYNAMIC FORCES TERM -------// Acc = 2.0 * (itNode->FastGetSolutionStepValue(VELOCITY, 0) - itNode->FastGetSolutionStepValue(VELOCITY, 1)) / timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION, 0); RHS_Contribution[0] += -nodalVolume * density * Acc[0]; RHS_Contribution[1] += -nodalVolume * density * Acc[1]; RHS_Contribution[2] += -nodalVolume * density * Acc[2]; //-------- EXTERNAL FORCES TERM -------// array_1d<double, 3> &VolumeAcceleration = itNode->FastGetSolutionStepValue(VOLUME_ACCELERATION); RHS_Contribution[0] += nodalVolume * density * VolumeAcceleration[0]; RHS_Contribution[1] += nodalVolume * density * VolumeAcceleration[1]; RHS_Contribution[2] += nodalVolume * density * VolumeAcceleration[2]; //-------- INTERNAL FORCES TERM -------// array_1d<double, 6> Sigma(6, 0.0); Sigma = itNode->FastGetSolutionStepValue(NODAL_CAUCHY_STRESS); pressure = itNode->FastGetSolutionStepValue(PRESSURE, 0) * theta + itNode->FastGetSolutionStepValue(PRESSURE, 1) * (1 - theta); Sigma[0] = itNode->FastGetSolutionStepValue(NODAL_DEVIATORIC_CAUCHY_STRESS)[0] + pressure; Sigma[1] = itNode->FastGetSolutionStepValue(NODAL_DEVIATORIC_CAUCHY_STRESS)[1] + pressure; Sigma[2] = itNode->FastGetSolutionStepValue(NODAL_DEVIATORIC_CAUCHY_STRESS)[2] + pressure; const unsigned int xDofPos = itNode->GetDofPosition(VELOCITY_X); EquationId[0] = itNode->GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[1] = itNode->GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); EquationId[2] = itNode->GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); for (unsigned int i = 0; i < neighSize; i++) { dNdXi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 1]; dNdZi = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol + 2]; RHS_Contribution[firstCol] += -nodalVolume * (dNdXi * Sigma[0] + dNdYi * Sigma[3] + dNdZi * Sigma[4]); RHS_Contribution[firstCol + 1] += -nodalVolume * (dNdYi * Sigma[1] + dNdXi * Sigma[3] + dNdZi * Sigma[5]); RHS_Contribution[firstCol + 2] += -nodalVolume * (dNdZi * Sigma[2] + dNdXi * Sigma[4] + dNdYi * Sigma[5]); for (unsigned int j = 0; j < neighSize; j++) { dNdXj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow]; dNdYj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow + 1]; dNdZj = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow + 2]; LHS_Contribution(firstRow, firstCol) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdXi + (dNdYj * dNdYi + dNdZj * dNdZi) * deviatoricCoeff) * theta; LHS_Contribution(firstRow, firstCol + 1) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdYi + dNdYj * dNdXi * deviatoricCoeff) * theta; LHS_Contribution(firstRow, firstCol + 2) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdZi + dNdZj * dNdXi * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 1, firstCol) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdXi + dNdXj * dNdYi * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 1, firstCol + 1) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdYi + (dNdXj * dNdXi + dNdZj * dNdZi) * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 1, firstCol + 2) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdZi + dNdZj * dNdYi * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 2, firstCol) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdZj * dNdXi + dNdXj * dNdZi * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 2, firstCol + 1) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdZj * dNdYi + dNdYj * dNdZi * deviatoricCoeff) * theta; LHS_Contribution(firstRow + 2, firstCol + 2) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdZj * dNdZi + (dNdXj * dNdXi + dNdYj * dNdYi) * deviatoricCoeff) * theta; firstRow += 3; } firstRow = 0; firstCol += 3; if (i < neighb_nodes.size()) { EquationId[firstCol] = neighb_nodes[i].GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[firstCol + 1] = neighb_nodes[i].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); EquationId[firstCol + 2] = neighb_nodes[i].GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); } } } #ifdef _OPENMP Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif } } // } KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void SystemSolve( TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else TSparseSpace::SetToZero(Dx); // Prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** *@brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector * @param rModelPart The model part of the problem to solve */ void SystemSolveWithPhysics( TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b, ModelPart &rModelPart) { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //provide physical data as needed if (BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded()) BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, rModelPart); //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else { TSparseSpace::SetToZero(Dx); KRATOS_WARNING_IF("NodalResidualBasedEliminationBuilderAndSolver", rModelPart.GetCommunicator().MyPID() == 0) << "ATTENTION! setting the RHS to zero!" << std::endl; } // Prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building and solving phase at the same time. * @details It is ideally the fastest and safer function to use when it is possible to solve * just after building * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { KRATOS_TRY Timer::Start("Build"); // boost::timer m_build_time; BuildFluidNodally(pScheme, rModelPart, A, b); // std::cout << "MOMENTUM EQ: build_time : " << m_build_time.elapsed() << std::endl; Timer::Stop("Build"); // ApplyPointLoads(pScheme,rModelPart,b); // Does nothing...dirichlet conditions are naturally dealt with in defining the residual ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; const double start_solve = OpenMPUtils::GetCurrentTime(); Timer::Start("Solve"); /* boost::timer m_solve_time; */ SystemSolveWithPhysics(A, Dx, b, rModelPart); /* std::cout << "MOMENTUM EQ: solve_time : " << m_solve_time.elapsed() << std::endl; */ Timer::Stop("Solve"); const double stop_solve = OpenMPUtils::GetCurrentTime(); KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "System solve time: " << stop_solve - start_solve << std::endl; KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; KRATOS_CATCH("") } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element * and condition its Dofs. * @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the * way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart) override { KRATOS_TRY; KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << "Setting up the dofs" << std::endl; //Gets the array of elements from the modeler ElementsArrayType &pElements = rModelPart.Elements(); const int nelements = static_cast<int>(pElements.size()); Element::DofsVectorType ElementalDofList; ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); unsigned int nthreads = OpenMPUtils::GetNumThreads(); // typedef boost::fast_pool_allocator< NodeType::DofType::Pointer > allocator_type; // typedef std::unordered_set < NodeType::DofType::Pointer, // DofPointerHasher, // DofPointerComparor, // allocator_type > set_type; #ifdef USE_GOOGLE_HASH typedef google::dense_hash_set<NodeType::DofType::Pointer, DofPointerHasher> set_type; #else typedef std::unordered_set<NodeType::DofType::Pointer, DofPointerHasher> set_type; #endif // std::vector<set_type> dofs_aux_list(nthreads); // std::vector<allocator_type> allocators(nthreads); for (int i = 0; i < static_cast<int>(nthreads); i++) { #ifdef USE_GOOGLE_HASH dofs_aux_list[i].set_empty_key(NodeType::DofType::Pointer()); #else // dofs_aux_list[i] = set_type( allocators[i]); dofs_aux_list[i].reserve(nelements); #endif } // #pragma omp parallel for firstprivate(nelements, ElementalDofList) for (int i = 0; i < static_cast<int>(nelements); i++) { typename ElementsArrayType::iterator it = pElements.begin() + i; const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // gets list of Dof involved on every element pScheme->GetElementalDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } ConditionsArrayType &pConditions = rModelPart.Conditions(); const int nconditions = static_cast<int>(pConditions.size()); #pragma omp parallel for firstprivate(nconditions, ElementalDofList) for (int i = 0; i < nconditions; i++) { typename ConditionsArrayType::iterator it = pConditions.begin() + i; const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // gets list of Dof involved on every element pScheme->GetConditionDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } //here we do a reduction in a tree so to have everything on thread 0 unsigned int old_max = nthreads; unsigned int new_max = ceil(0.5 * static_cast<double>(old_max)); while (new_max >= 1 && new_max != old_max) { // //just for debugging // std::cout << "old_max" << old_max << " new_max:" << new_max << std::endl; // for (int i = 0; i < new_max; i++) // { // if (i + new_max < old_max) // { // std::cout << i << " - " << i + new_max << std::endl; // } // } // std::cout << "********************" << std::endl; #pragma omp parallel for for (int i = 0; i < static_cast<int>(new_max); i++) { if (i + new_max < old_max) { dofs_aux_list[i].insert(dofs_aux_list[i + new_max].begin(), dofs_aux_list[i + new_max].end()); dofs_aux_list[i + new_max].clear(); } } old_max = new_max; new_max = ceil(0.5 * static_cast<double>(old_max)); } DofsArrayType Doftemp; BaseType::mDofSet = DofsArrayType(); Doftemp.reserve(dofs_aux_list[0].size()); for (auto it = dofs_aux_list[0].begin(); it != dofs_aux_list[0].end(); it++) { Doftemp.push_back((*it)); } Doftemp.Sort(); BaseType::mDofSet = Doftemp; // Throws an execption if there are no Degrees of freedom involved in the analysis KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl; BaseType::mDofSetIsInitialized = true; KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0) << "Finished setting up the dofs" << std::endl; #ifdef _OPENMP if (mlock_array.size() != 0) { for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_destroy_lock(&mlock_array[i]); } mlock_array.resize(BaseType::mDofSet.size()); for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_init_lock(&mlock_array[i]); #endif // If reactions are to be calculated, we check if all the dofs have reactions defined // This is tobe done only in debug mode #ifdef KRATOS_DEBUG if (BaseType::GetCalculateReactionsFlag()) { for (auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) { KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " << std::endl << "Node : " << dof_iterator->Id() << std::endl << "Dof : " << (*dof_iterator) << std::endl << "Not possible to calculate reactions." << std::endl; } } #endif KRATOS_CATCH(""); } /** * @brief Organises the dofset in order to speed up the building phase * @param rModelPart The model part of the problem to solve */ void SetUpSystem( ModelPart &rModelPart) override { // Set equation id for degrees of freedom // the free degrees of freedom are positioned at the beginning of the system, // while the fixed one are at the end (in opposite order). // // that means that if the EquationId is greater than "mEquationSystemSize" // the pointed degree of freedom is restrained // int free_id = 0; int fix_id = BaseType::mDofSet.size(); for (typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) if (dof_iterator->IsFixed()) dof_iterator->SetEquationId(--fix_id); else dof_iterator->SetEquationId(free_id++); BaseType::mEquationSystemSize = fix_id; } //************************************************************************** //************************************************************************** void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType &pA, TSystemVectorPointerType &pDx, TSystemVectorPointerType &pb, ModelPart &rModelPart) override { KRATOS_TRY // boost::timer m_contruct_matrix; if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } if (BaseType::mpReactionsVector == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewReactionsVector = TSystemVectorPointerType(new TSystemVectorType(0)); BaseType::mpReactionsVector.swap(pNewReactionsVector); } TSystemMatrixType &A = *pA; TSystemVectorType &Dx = *pDx; TSystemVectorType &b = *pb; //resizing the system vectors and matrix if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart); } else { if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize) { KRATOS_WATCH("it should not come here!!!!!!!! ... this is SLOW"); KRATOS_ERROR << "The equation system size has changed during the simulation. This is not permited." << std::endl; A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true); ConstructMatrixStructure(pScheme, A, rModelPart); } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); if (b.size() != BaseType::mEquationSystemSize) b.resize(BaseType::mEquationSystemSize, false); //if needed resize the vector for the calculation of reactions if (BaseType::mCalculateReactionsFlag == true) { unsigned int ReactionsVectorSize = BaseType::mDofSet.size(); if (BaseType::mpReactionsVector->size() != ReactionsVectorSize) BaseType::mpReactionsVector->resize(ReactionsVectorSize, false); } // std::cout << "MOMENTUM EQ: contruct_matrix : " << m_contruct_matrix.elapsed() << std::endl; KRATOS_CATCH("") } //************************************************************************** //************************************************************************** /** * @brief Applies the dirichlet conditions. This operation may be very heavy or completely * unexpensive depending on the implementation choosen and on how the System Matrix is built. * @details For explanation of how it works for a particular implementation the user * should refer to the particular Builder And Solver choosen * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &Dx, TSystemVectorType &b) override { } /** * @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { this->mDofSet = DofsArrayType(); if (this->mpReactionsVector != NULL) TSparseSpace::Clear((this->mpReactionsVector)); // this->mReactionsVector = TSystemVectorType(); this->mpLinearSystemSolver->Clear(); KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 1) << "Clear Function called" << std::endl; } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model part of the problem to solve * @return 0 all ok */ int Check(ModelPart &rModelPart) override { KRATOS_TRY return 0; KRATOS_CATCH(""); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ void Assemble( TSystemMatrixType &A, TSystemVectorType &b, const LocalSystemMatrixType &LHS_Contribution, const LocalSystemVectorType &RHS_Contribution, const Element::EquationIdVectorType &EquationId #ifdef _OPENMP , std::vector<omp_lock_t> &lock_array #endif ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { #ifdef _OPENMP omp_set_lock(&lock_array[i_global]); #endif b[i_global] += RHS_Contribution(i_local); for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) { A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } #ifdef _OPENMP omp_unset_lock(&lock_array[i_global]); #endif } //note that assembly on fixed rows is not performed here } } //************************************************************************** virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType &A, ModelPart &rModelPart) { //filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); // Getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); const std::size_t equation_size = BaseType::mEquationSystemSize; #ifdef USE_GOOGLE_HASH std::vector<google::dense_hash_set<std::size_t>> indices(equation_size); const std::size_t empty_key = 2 * equation_size + 10; #else std::vector<std::unordered_set<std::size_t>> indices(equation_size); #endif #pragma omp parallel for firstprivate(equation_size) for (int iii = 0; iii < static_cast<int>(equation_size); iii++) { #ifdef USE_GOOGLE_HASH indices[iii].set_empty_key(empty_key); #else indices[iii].reserve(40); #endif } Element::EquationIdVectorType EquationId; ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { const unsigned int localSize = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS).size(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); Vector nodalSFDneighboursId = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER); if (EquationId.size() != localSize) EquationId.resize(localSize, false); unsigned int firstCol = 0; const unsigned int xDofPos = itNode->GetDofPosition(VELOCITY_X); EquationId[0] = itNode->GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[1] = itNode->GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); if (dimension == 3) EquationId[2] = itNode->GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); for (unsigned int i = 0; i < neighb_nodes.size(); i++) { firstCol += dimension; EquationId[firstCol] = neighb_nodes[i].GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[firstCol + 1] = neighb_nodes[i].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); if (dimension == 3) { EquationId[firstCol + 2] = neighb_nodes[i].GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); } } for (std::size_t i = 0; i < EquationId.size(); i++) { if (EquationId[i] < BaseType::mEquationSystemSize) { #ifdef _OPENMP omp_set_lock(&mlock_array[EquationId[i]]); #endif auto &row_indices = indices[EquationId[i]]; for (auto it = EquationId.begin(); it != EquationId.end(); it++) { if (*it < BaseType::mEquationSystemSize) row_indices.insert(*it); } #ifdef _OPENMP omp_unset_lock(&mlock_array[EquationId[i]]); #endif } } } Element::EquationIdVectorType ids(3, 0); #pragma omp parallel for firstprivate(nconditions, ids) for (int iii = 0; iii < nconditions; iii++) { typename ConditionsArrayType::iterator i_condition = cond_begin + iii; pScheme->Condition_EquationId(*(i_condition.base()), ids, CurrentProcessInfo); for (std::size_t i = 0; i < ids.size(); i++) { if (ids[i] < BaseType::mEquationSystemSize) { #ifdef _OPENMP omp_set_lock(&mlock_array[ids[i]]); #endif auto &row_indices = indices[ids[i]]; for (auto it = ids.begin(); it != ids.end(); it++) { if (*it < BaseType::mEquationSystemSize) row_indices.insert(*it); } #ifdef _OPENMP omp_unset_lock(&mlock_array[ids[i]]); #endif } } } //count the row sizes unsigned int nnz = 0; for (unsigned int i = 0; i < indices.size(); i++) nnz += indices[i].size(); A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz); double *Avalues = A.value_data().begin(); std::size_t *Arow_indices = A.index1_data().begin(); std::size_t *Acol_indices = A.index2_data().begin(); //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Arow_indices[0] = 0; for (int i = 0; i < static_cast<int>(A.size1()); i++) Arow_indices[i + 1] = Arow_indices[i] + indices[i].size(); #pragma omp parallel for for (int i = 0; i < static_cast<int>(A.size1()); i++) { const unsigned int row_begin = Arow_indices[i]; const unsigned int row_end = Arow_indices[i + 1]; unsigned int k = row_begin; for (auto it = indices[i].begin(); it != indices[i].end(); it++) { Acol_indices[k] = *it; Avalues[k] = 0.0; k++; } std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); } A.set_filled(indices.size() + 1, nnz); Timer::Stop("MatrixStructure"); } void AssembleLHS( TSystemMatrixType &A, LocalSystemMatrixType &LHS_Contribution, Element::EquationIdVectorType &EquationId) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ #ifdef _OPENMP std::vector<omp_lock_t> mlock_array; #endif ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ inline void AddUnique(std::vector<std::size_t> &v, const std::size_t &candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while (i != endit && (*i) != candidate) { i++; } if (i == endit) { v.push_back(candidate); } } void AssembleRHS( TSystemVectorType &b, const LocalSystemVectorType &RHS_Contribution, const Element::EquationIdVectorType &EquationId) { unsigned int local_size = RHS_Contribution.size(); if (BaseType::mCalculateReactionsFlag == false) { for (unsigned int i_local = 0; i_local < local_size; i_local++) { const unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //free dof { // ASSEMBLING THE SYSTEM VECTOR double &b_value = b[i_global]; const double &rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } } else { TSystemVectorType &ReactionsVector = *BaseType::mpReactionsVector; for (unsigned int i_local = 0; i_local < local_size; i_local++) { const unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //free dof { // ASSEMBLING THE SYSTEM VECTOR double &b_value = b[i_global]; const double &rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } else //fixed dof { double &b_value = ReactionsVector[i_global - BaseType::mEquationSystemSize]; const double &rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } } } //************************************************************************** void AssembleLHS_CompleteOnFreeRows( TSystemMatrixType &A, LocalSystemMatrixType &LHS_Contribution, Element::EquationIdVectorType &EquationId) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { int j_global = EquationId[j_local]; A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class NodalResidualBasedEliminationBuilderAndSolver */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER defined */
GB_unaryop__lnot_int64_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_int64_uint32 // op(A') function: GB_tran__lnot_int64_uint32 // C type: int64_t // A type: uint32_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ int64_t z = (int64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT64 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int64_uint32 ( int64_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_int64_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
NeighborhoodGraph.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _SPTAG_COMMON_NG_H_ #define _SPTAG_COMMON_NG_H_ #include "../VectorIndex.h" #include "CommonUtils.h" #include "Dataset.h" #include "FineGrainedLock.h" #include "QueryResultSet.h" namespace SPTAG { namespace COMMON { class NeighborhoodGraph { public: NeighborhoodGraph(): m_iTPTNumber(32), m_iTPTLeafSize(2000), m_iSamples(1000), m_numTopDimensionTPTSplit(5), m_iNeighborhoodSize(32), m_iNeighborhoodScale(2), m_iCEFScale(2), m_iRefineIter(2), m_iCEF(1000), m_iAddCEF(500), m_iMaxCheckForRefineGraph(10000) { m_pNeighborhoodGraph.SetName("Graph"); } ~NeighborhoodGraph() {} virtual void InsertNeighbors(VectorIndex* index, const SizeType node, SizeType insertNode, float insertDist) = 0; virtual void RebuildNeighbors(VectorIndex* index, const SizeType node, SizeType* nodes, const BasicResult* queryResults, const int numResults) = 0; virtual float GraphAccuracyEstimation(VectorIndex* index, const SizeType samples, const std::unordered_map<SizeType, SizeType>* idmap = nullptr) = 0; template <typename T> void BuildGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap = nullptr) { std::cout << "build RNG graph!" << std::endl; m_iGraphSize = index->GetNumSamples(); m_iNeighborhoodSize = m_iNeighborhoodSize * m_iNeighborhoodScale; m_pNeighborhoodGraph.Initialize(m_iGraphSize, m_iNeighborhoodSize); if (m_iGraphSize < 1000) { RefineGraph<T>(index, idmap); std::cout << "Build RNG Graph end!" << std::endl; return; } { COMMON::Dataset<float> NeighborhoodDists(m_iGraphSize, m_iNeighborhoodSize); std::vector<std::vector<SizeType>> TptreeDataIndices(m_iTPTNumber, std::vector<SizeType>(m_iGraphSize)); std::vector<std::vector<std::pair<SizeType, SizeType>>> TptreeLeafNodes(m_iTPTNumber, std::vector<std::pair<SizeType, SizeType>>()); for (SizeType i = 0; i < m_iGraphSize; i++) for (DimensionType j = 0; j < m_iNeighborhoodSize; j++) (NeighborhoodDists)[i][j] = MaxDist; std::cout << "Parallel TpTree Partition begin " << std::endl; #pragma omp parallel for schedule(dynamic) for (int i = 0; i < m_iTPTNumber; i++) { Sleep(i * 100); std::srand(clock()); for (SizeType j = 0; j < m_iGraphSize; j++) TptreeDataIndices[i][j] = j; std::random_shuffle(TptreeDataIndices[i].begin(), TptreeDataIndices[i].end()); PartitionByTptree<T>(index, TptreeDataIndices[i], 0, m_iGraphSize - 1, TptreeLeafNodes[i]); std::cout << "Finish Getting Leaves for Tree " << i << std::endl; } std::cout << "Parallel TpTree Partition done" << std::endl; for (int i = 0; i < m_iTPTNumber; i++) { #pragma omp parallel for schedule(dynamic) for (SizeType j = 0; j < (SizeType)TptreeLeafNodes[i].size(); j++) { SizeType start_index = TptreeLeafNodes[i][j].first; SizeType end_index = TptreeLeafNodes[i][j].second; if (omp_get_thread_num() == 0) std::cout << "\rProcessing Tree " << i << ' ' << j * 100 / TptreeLeafNodes[i].size() << '%'; for (SizeType x = start_index; x < end_index; x++) { for (SizeType y = x + 1; y <= end_index; y++) { SizeType p1 = TptreeDataIndices[i][x]; SizeType p2 = TptreeDataIndices[i][y]; float dist = index->ComputeDistance(index->GetSample(p1), index->GetSample(p2)); if (idmap != nullptr) { p1 = (idmap->find(p1) == idmap->end()) ? p1 : idmap->at(p1); p2 = (idmap->find(p2) == idmap->end()) ? p2 : idmap->at(p2); } COMMON::Utils::AddNeighbor(p2, dist, (m_pNeighborhoodGraph)[p1], (NeighborhoodDists)[p1], m_iNeighborhoodSize); COMMON::Utils::AddNeighbor(p1, dist, (m_pNeighborhoodGraph)[p2], (NeighborhoodDists)[p2], m_iNeighborhoodSize); } } } TptreeDataIndices[i].clear(); TptreeLeafNodes[i].clear(); std::cout << std::endl; } TptreeDataIndices.clear(); TptreeLeafNodes.clear(); } RefineGraph<T>(index, idmap); } template <typename T> void RefineGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap = nullptr) { for (int iter = 0; iter < m_iRefineIter - 1; iter++) { #pragma omp parallel for schedule(dynamic) for (SizeType i = 0; i < m_iGraphSize; i++) { RefineNode<T>(index, i, false, false, m_iCEF * m_iCEFScale); if (i % 1000 == 0) std::cout << "\rRefine " << iter << " " << static_cast<int>(i * 1.0 / m_iGraphSize * 100) << "%"; } std::cout << "Refine RNG, graph acc:" << GraphAccuracyEstimation(index, 100, idmap) << std::endl; } m_iNeighborhoodSize /= m_iNeighborhoodScale; #pragma omp parallel for schedule(dynamic) for (SizeType i = 0; i < m_iGraphSize; i++) { RefineNode<T>(index, i, false, false, m_iCEF); if (i % 1000 == 0) std::cout << "\rRefine " << (m_iRefineIter - 1) << " " << static_cast<int>(i * 1.0 / m_iGraphSize * 100) << "%"; } std::cout << "Refine RNG, graph acc:" << GraphAccuracyEstimation(index, 100, idmap) << std::endl; if (idmap != nullptr) { for (auto iter = idmap->begin(); iter != idmap->end(); iter++) if (iter->first < 0) { m_pNeighborhoodGraph[-1 - iter->first][m_iNeighborhoodSize - 1] = -2 - iter->second; } } } template <typename T> ErrorCode RefineGraph(VectorIndex* index, std::vector<SizeType>& indices, std::vector<SizeType>& reverseIndices, std::ostream* output, NeighborhoodGraph* newGraph, const std::unordered_map<SizeType, SizeType>* idmap = nullptr) { SizeType R = (SizeType)indices.size(); if (newGraph != nullptr) { newGraph->m_pNeighborhoodGraph.Initialize(R, m_iNeighborhoodSize); newGraph->m_iGraphSize = R; newGraph->m_iNeighborhoodSize = m_iNeighborhoodSize; } #pragma omp parallel for schedule(dynamic) for (SizeType i = 0; i < R; i++) { RefineNode<T>(index, indices[i], false, false, m_iCEF); if (i % 1000 == 0) std::cout << "\rRefine " << static_cast<int>(i * 1.0 / R * 100) << "%"; SizeType *nodes, *outnodes; nodes = outnodes = m_pNeighborhoodGraph[indices[i]]; if (newGraph != nullptr) outnodes = newGraph->m_pNeighborhoodGraph[i]; std::unordered_map<SizeType, SizeType>::const_iterator iter; for (DimensionType j = 0; j < m_iNeighborhoodSize; j++) { if (nodes[j] >= 0 && nodes[j] < reverseIndices.size()) outnodes[j] = reverseIndices[nodes[j]]; if (idmap != nullptr && (iter = idmap->find(outnodes[j])) != idmap->end()) outnodes[j] = iter->second; } if (idmap != nullptr && (iter = idmap->find(-1 - i)) != idmap->end()) outnodes[m_iNeighborhoodSize - 1] = -2 - iter->second; } if (output != nullptr) { output->write((char*)&R, sizeof(SizeType)); output->write((char*)&m_iNeighborhoodSize, sizeof(DimensionType)); for (SizeType i = 0; i < R; i++) { output->write((char*)m_pNeighborhoodGraph[indices[i]], sizeof(SizeType) * m_iNeighborhoodSize); } std::cout << "Save Refine " << m_pNeighborhoodGraph.Name() << " (" << R << ", " << m_iNeighborhoodSize << ") Finish!" << std::endl; } return ErrorCode::Success; } template <typename T> void RefineNode(VectorIndex* index, const SizeType node, bool updateNeighbors, bool searchDeleted, int CEF) { COMMON::QueryResultSet<T> query((const T*)index->GetSample(node), CEF + 1); index->RefineSearchIndex(query, searchDeleted); RebuildNeighbors(index, node, m_pNeighborhoodGraph[node], query.GetResults(), CEF + 1); if (updateNeighbors) { // update neighbors for (int j = 0; j <= CEF; j++) { BasicResult* item = query.GetResult(j); if (item->VID < 0) break; if (item->VID == node) continue; InsertNeighbors(index, item->VID, node, item->Dist); } } } template <typename T> void PartitionByTptree(VectorIndex* index, std::vector<SizeType>& indices, const SizeType first, const SizeType last, std::vector<std::pair<SizeType, SizeType>> & leaves) { if (last - first <= m_iTPTLeafSize) { leaves.emplace_back(first, last); } else { std::vector<float> Mean(index->GetFeatureDim(), 0); int iIteration = 100; SizeType end = min(first + m_iSamples, last); SizeType count = end - first + 1; // calculate the mean of each dimension for (SizeType j = first; j <= end; j++) { const T* v = (const T*)index->GetSample(indices[j]); for (DimensionType k = 0; k < index->GetFeatureDim(); k++) { Mean[k] += v[k]; } } for (DimensionType k = 0; k < index->GetFeatureDim(); k++) { Mean[k] /= count; } std::vector<BasicResult> Variance; Variance.reserve(index->GetFeatureDim()); for (DimensionType j = 0; j < index->GetFeatureDim(); j++) { Variance.emplace_back(j, 0.0f); } // calculate the variance of each dimension for (SizeType j = first; j <= end; j++) { const T* v = (const T*)index->GetSample(indices[j]); for (DimensionType k = 0; k < index->GetFeatureDim(); k++) { float dist = v[k] - Mean[k]; Variance[k].Dist += dist*dist; } } std::sort(Variance.begin(), Variance.end(), COMMON::Compare); std::vector<SizeType> indexs(m_numTopDimensionTPTSplit); std::vector<float> weight(m_numTopDimensionTPTSplit), bestweight(m_numTopDimensionTPTSplit); float bestvariance = Variance[index->GetFeatureDim() - 1].Dist; for (int i = 0; i < m_numTopDimensionTPTSplit; i++) { indexs[i] = Variance[index->GetFeatureDim() - 1 - i].VID; bestweight[i] = 0; } bestweight[0] = 1; float bestmean = Mean[indexs[0]]; std::vector<float> Val(count); for (int i = 0; i < iIteration; i++) { float sumweight = 0; for (int j = 0; j < m_numTopDimensionTPTSplit; j++) { weight[j] = float(rand() % 10000) / 5000.0f - 1.0f; sumweight += weight[j] * weight[j]; } sumweight = sqrt(sumweight); for (int j = 0; j < m_numTopDimensionTPTSplit; j++) { weight[j] /= sumweight; } float mean = 0; for (SizeType j = 0; j < count; j++) { Val[j] = 0; const T* v = (const T*)index->GetSample(indices[first + j]); for (int k = 0; k < m_numTopDimensionTPTSplit; k++) { Val[j] += weight[k] * v[indexs[k]]; } mean += Val[j]; } mean /= count; float var = 0; for (SizeType j = 0; j < count; j++) { float dist = Val[j] - mean; var += dist * dist; } if (var > bestvariance) { bestvariance = var; bestmean = mean; for (int j = 0; j < m_numTopDimensionTPTSplit; j++) { bestweight[j] = weight[j]; } } } SizeType i = first; SizeType j = last; // decide which child one point belongs while (i <= j) { float val = 0; const T* v = (const T*)index->GetSample(indices[i]); for (int k = 0; k < m_numTopDimensionTPTSplit; k++) { val += bestweight[k] * v[indexs[k]]; } if (val < bestmean) { i++; } else { std::swap(indices[i], indices[j]); j--; } } // if all the points in the node are equal,equally split the node into 2 if ((i == first) || (i == last + 1)) { i = (first + last + 1) / 2; } Mean.clear(); Variance.clear(); Val.clear(); indexs.clear(); weight.clear(); bestweight.clear(); PartitionByTptree<T>(index, indices, first, i - 1, leaves); PartitionByTptree<T>(index, indices, i, last, leaves); } } inline std::uint64_t BufferSize() const { return m_pNeighborhoodGraph.BufferSize(); } bool LoadGraph(std::string sGraphFilename) { if (!m_pNeighborhoodGraph.Load(sGraphFilename)) return false; m_iGraphSize = m_pNeighborhoodGraph.R(); m_iNeighborhoodSize = m_pNeighborhoodGraph.C(); return true; } bool LoadGraph(char* pGraphMemFile) { m_pNeighborhoodGraph.Load(pGraphMemFile); m_iGraphSize = m_pNeighborhoodGraph.R(); m_iNeighborhoodSize = m_pNeighborhoodGraph.C(); return true; } bool SaveGraph(std::string sGraphFilename) const { std::cout << "Save " << m_pNeighborhoodGraph.Name() << " To " << sGraphFilename << std::endl; std::ofstream output(sGraphFilename, std::ios::binary); if (!output.is_open()) return false; SaveGraph(output); output.close(); return true; } bool SaveGraph(std::ostream& output) const { output.write((char*)&m_iGraphSize, sizeof(SizeType)); output.write((char*)&m_iNeighborhoodSize, sizeof(DimensionType)); for (SizeType i = 0; i < m_iGraphSize; i++) output.write((char*)m_pNeighborhoodGraph[i], sizeof(SizeType) * m_iNeighborhoodSize); std::cout << "Save " << m_pNeighborhoodGraph.Name() << " (" << m_iGraphSize << ", " << m_iNeighborhoodSize << ") Finish!" << std::endl; return true; } inline ErrorCode AddBatch(SizeType num) { ErrorCode ret = m_pNeighborhoodGraph.AddBatch(num); if (ret != ErrorCode::Success) return ret; m_iGraphSize += num; return ErrorCode::Success; } inline SizeType* operator[](SizeType index) { return m_pNeighborhoodGraph[index]; } inline const SizeType* operator[](SizeType index) const { return m_pNeighborhoodGraph[index]; } void Update(SizeType row, DimensionType col, SizeType val) { std::lock_guard<std::mutex> lock(m_dataUpdateLock[row]); m_pNeighborhoodGraph[row][col] = val; } inline void SetR(SizeType rows) { m_pNeighborhoodGraph.SetR(rows); m_iGraphSize = rows; } inline SizeType R() const { return m_iGraphSize; } static std::shared_ptr<NeighborhoodGraph> CreateInstance(std::string type); protected: // Graph structure SizeType m_iGraphSize; COMMON::Dataset<SizeType> m_pNeighborhoodGraph; FineGrainedLock m_dataUpdateLock; public: int m_iTPTNumber, m_iTPTLeafSize, m_iSamples, m_numTopDimensionTPTSplit; DimensionType m_iNeighborhoodSize; int m_iNeighborhoodScale, m_iCEFScale, m_iRefineIter, m_iCEF, m_iAddCEF, m_iMaxCheckForRefineGraph; }; } } #endif
fill_int2c.c
/* Copyright 2014-2018 The PySCF Developers. 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. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <complex.h> #include "config.h" #include "cint.h" #include "np_helper/np_helper.h" #define PLAIN 0 #define HERMITIAN 1 #define ANTIHERMI 2 #define SYMMETRIC 3 int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env); /* * mat(naoi,naoj,comp) in F-order */ void GTOint2c(int (*intor)(), double *mat, int comp, int hermi, int *shls_slice, int *ao_loc, CINTOpt *opt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const int cache_size = GTOmax_cache_size(intor, shls_slice, 2, atm, natm, bas, nbas, env); #pragma omp parallel { int dims[] = {naoi, naoj}; int ish, jsh, ij, i0, j0; int shls[2]; double *cache = malloc(sizeof(double) * cache_size); #pragma omp for schedule(dynamic, 4) for (ij = 0; ij < nish*njsh; ij++) { ish = ij / njsh; jsh = ij % njsh; if (hermi != PLAIN && ish > jsh) { // fill up only upper triangle of F-array continue; } ish += ish0; jsh += jsh0; shls[0] = ish; shls[1] = jsh; i0 = ao_loc[ish] - ao_loc[ish0]; j0 = ao_loc[jsh] - ao_loc[jsh0]; (*intor)(mat+j0*naoi+i0, dims, shls, atm, natm, bas, nbas, env, opt, cache); } free(cache); } if (hermi != PLAIN) { // lower triangle of F-array int ic; for (ic = 0; ic < comp; ic++) { NPdsymm_triu(naoi, mat+ic*naoi*naoi, hermi); } } } void GTOint2c_spinor(int (*intor)(), double complex *mat, int comp, int hermi, int *shls_slice, int *ao_loc, CINTOpt *opt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const int cache_size = GTOmax_cache_size(intor, shls_slice, 2, atm, natm, bas, nbas, env); #pragma omp parallel { int dims[] = {naoi, naoj}; int ish, jsh, ij, i0, j0; int shls[2]; double *cache = malloc(sizeof(double) * cache_size); #pragma omp for schedule(dynamic, 4) for (ij = 0; ij < nish*njsh; ij++) { ish = ij / njsh; jsh = ij % njsh; if (hermi != PLAIN && ish > jsh) { continue; } ish += ish0; jsh += jsh0; shls[0] = ish; shls[1] = jsh; i0 = ao_loc[ish] - ao_loc[ish0]; j0 = ao_loc[jsh] - ao_loc[jsh0]; (*intor)(mat+j0*naoi+i0, dims, shls, atm, natm, bas, nbas, env, opt, cache); } free(cache); } if (hermi != PLAIN) { int ic; for (ic = 0; ic < comp; ic++) { NPzhermi_triu(naoi, mat+ic*naoi*naoi, hermi); } } }
xm.c
/* * Copyright (c) 2014-2018 Ilya Kaliman * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef XM_USE_MPI #include <mpi.h> #endif #include "xm.h" #include "util.h" void xm_set(xm_tensor_t *a, xm_scalar_t x) { xm_dim_t *blklist; xm_scalar_type_t scalartype; size_t i, maxblksize, nblklist; void *buf; int mpirank = 0, mpisize = 1; #ifdef XM_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpirank); MPI_Comm_size(MPI_COMM_WORLD, &mpisize); #endif if ((buf = malloc(xm_tensor_get_largest_block_bytes(a))) == NULL) fatal("out of memory"); maxblksize = xm_tensor_get_largest_block_size(a); scalartype = xm_tensor_get_scalar_type(a); xm_scalar_set(buf, x, maxblksize, scalartype); xm_tensor_get_canonical_block_list(a, &blklist, &nblklist); #ifdef _OPENMP #pragma omp parallel private(i) #endif { #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (i = 0; i < nblklist; i++) { if ((int)i % mpisize == mpirank) xm_tensor_write_block(a, blklist[i], buf); } } free(buf); free(blklist); #ifdef XM_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif } void xm_copy(xm_tensor_t *a, xm_scalar_t s, const xm_tensor_t *b, const char *idxa, const char *idxb) { const xm_block_space_t *bsa, *bsb; xm_dim_t cidxa, cidxb, zero, *blklist; xm_scalar_type_t scalartypea, scalartypeb; size_t i, maxblkbytesa, maxblkbytesb, nblklist; int mpirank = 0, mpisize = 1; if (xm_tensor_get_allocator(a) != xm_tensor_get_allocator(b)) fatal("tensors must use same allocator"); #ifdef XM_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpirank); MPI_Comm_size(MPI_COMM_WORLD, &mpisize); #endif bsa = xm_tensor_get_block_space(a); bsb = xm_tensor_get_block_space(b); if (strlen(idxa) != xm_block_space_get_ndims(bsa)) fatal("idxa does not match tensor dimensions"); if (strlen(idxb) != xm_block_space_get_ndims(bsb)) fatal("idxb does not match tensor dimensions"); xm_make_masks(idxa, idxb, &cidxa, &cidxb); if (cidxa.n != xm_block_space_get_ndims(bsa) || cidxb.n != xm_block_space_get_ndims(bsb)) fatal("index spaces do not match"); for (i = 0; i < cidxa.n; i++) if (!xm_block_space_eq1(bsa, cidxa.i[i], bsb, cidxb.i[i])) fatal("inconsistent block-spaces"); scalartypea = xm_tensor_get_scalar_type(a); scalartypeb = xm_tensor_get_scalar_type(b); zero = xm_dim_zero(0); maxblkbytesa = xm_tensor_get_largest_block_bytes(a); maxblkbytesb = xm_tensor_get_largest_block_bytes(b); xm_tensor_get_canonical_block_list(a, &blklist, &nblklist); #ifdef _OPENMP #pragma omp parallel private(i) #endif { xm_dim_t ia, ib; void *buf1a, *buf2a, *buf1b, *buf2b; size_t blksize; xm_block_type_t blocktype; if ((buf1a = malloc(maxblkbytesa)) == NULL) fatal("out of memory"); if ((buf2a = malloc(maxblkbytesa)) == NULL) fatal("out of memory"); if ((buf1b = malloc(maxblkbytesb)) == NULL) fatal("out of memory"); if ((buf2b = malloc(maxblkbytesb)) == NULL) fatal("out of memory"); ib = xm_dim_zero(cidxb.n); #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (i = 0; i < nblklist; i++) { if ((int)i % mpisize == mpirank) { ia = blklist[i]; xm_dim_set_mask(&ib, &cidxb, &ia, &cidxa); blksize = xm_tensor_get_block_size(b, ib); blocktype = xm_tensor_get_block_type(b, ib); if (s == 0 || blocktype == XM_BLOCK_TYPE_ZERO) { memset(buf2a, 0, maxblkbytesa); } else { xm_scalar_t scalar = xm_scalar_mul(s, xm_tensor_get_block_scalar(b, ib), scalartypeb); xm_tensor_read_block(b, ib, buf2b); xm_tensor_unfold_block(b, ib, cidxb, zero, buf2b, buf1b, blksize); xm_scalar_scale(buf1b, scalar, blksize, scalartypeb); xm_scalar_convert(buf1a, buf1b, blksize, scalartypea, scalartypeb); xm_tensor_fold_block(a, ia, cidxa, zero, buf1a, buf2a, blksize); } xm_tensor_write_block(a, ia, buf2a); } } free(buf1a); free(buf2a); free(buf1b); free(buf2b); } free(blklist); #ifdef XM_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif } void xm_add(xm_scalar_t alpha, xm_tensor_t *a, xm_scalar_t beta, const xm_tensor_t *b, const char *idxa, const char *idxb) { const xm_block_space_t *bsa, *bsb; xm_dim_t cidxa, cidxb, zero, *blklist; xm_scalar_type_t scalartype; size_t i, maxblkbytes, nblklist; int mpirank = 0, mpisize = 1; if (xm_tensor_get_allocator(a) != xm_tensor_get_allocator(b)) fatal("tensors must use same allocator"); if (xm_tensor_get_scalar_type(a) != xm_tensor_get_scalar_type(b)) fatal("tensors must have same scalar type"); #ifdef XM_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpirank); MPI_Comm_size(MPI_COMM_WORLD, &mpisize); #endif bsa = xm_tensor_get_block_space(a); bsb = xm_tensor_get_block_space(b); if (strlen(idxa) != xm_block_space_get_ndims(bsa)) fatal("idxa does not match tensor dimensions"); if (strlen(idxb) != xm_block_space_get_ndims(bsb)) fatal("idxb does not match tensor dimensions"); xm_make_masks(idxa, idxb, &cidxa, &cidxb); if (cidxa.n != xm_block_space_get_ndims(bsa) || cidxb.n != xm_block_space_get_ndims(bsb)) fatal("index spaces do not match"); for (i = 0; i < cidxa.n; i++) if (!xm_block_space_eq1(bsa, cidxa.i[i], bsb, cidxb.i[i])) fatal("inconsistent block-spaces"); scalartype = xm_tensor_get_scalar_type(a); zero = xm_dim_zero(0); maxblkbytes = xm_tensor_get_largest_block_bytes(a); xm_tensor_get_canonical_block_list(a, &blklist, &nblklist); #ifdef _OPENMP #pragma omp parallel private(i) #endif { xm_dim_t ia, ib; void *buf1, *buf2; size_t blksize; xm_block_type_t blocktype; if ((buf1 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); if ((buf2 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); ib = xm_dim_zero(cidxb.n); #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (i = 0; i < nblklist; i++) { if ((int)i % mpisize == mpirank) { ia = blklist[i]; xm_dim_set_mask(&ib, &cidxb, &ia, &cidxa); blksize = xm_tensor_get_block_size(b, ib); blocktype = xm_tensor_get_block_type(b, ib); if (beta == 0 || blocktype == XM_BLOCK_TYPE_ZERO) { memset(buf2, 0, maxblkbytes); } else { xm_scalar_t scalar = xm_scalar_mul(beta, xm_tensor_get_block_scalar(b, ib), scalartype); xm_tensor_read_block(b, ib, buf2); xm_tensor_unfold_block(b, ib, cidxb, zero, buf2, buf1, blksize); xm_scalar_scale(buf1, scalar, blksize, scalartype); xm_tensor_fold_block(a, ia, cidxa, zero, buf1, buf2, blksize); } if (alpha == 0) xm_tensor_write_block(a, ia, buf2); else { xm_tensor_read_block(a, ia, buf1); xm_scalar_axpy(buf1, alpha, buf2, 1, blksize, scalartype); xm_tensor_write_block(a, ia, buf1); } } } free(buf1); free(buf2); } free(blklist); #ifdef XM_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif } void xm_mul(xm_tensor_t *a, const xm_tensor_t *b, const char *idxa, const char *idxb) { const xm_block_space_t *bsa, *bsb; xm_dim_t cidxa, cidxb, zero, *blklist; xm_scalar_type_t scalartype; size_t i, maxblkbytes, nblklist; int mpirank = 0, mpisize = 1; if (xm_tensor_get_allocator(a) != xm_tensor_get_allocator(b)) fatal("tensors must use same allocator"); if (xm_tensor_get_scalar_type(a) != xm_tensor_get_scalar_type(b)) fatal("tensors must have same scalar type"); #ifdef XM_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpirank); MPI_Comm_size(MPI_COMM_WORLD, &mpisize); #endif bsa = xm_tensor_get_block_space(a); bsb = xm_tensor_get_block_space(b); if (strlen(idxa) != xm_block_space_get_ndims(bsa)) fatal("idxa does not match tensor dimensions"); if (strlen(idxb) != xm_block_space_get_ndims(bsb)) fatal("idxb does not match tensor dimensions"); xm_make_masks(idxa, idxb, &cidxa, &cidxb); if (cidxa.n != xm_block_space_get_ndims(bsa) || cidxb.n != xm_block_space_get_ndims(bsb)) fatal("index spaces do not match"); for (i = 0; i < cidxa.n; i++) if (!xm_block_space_eq1(bsa, cidxa.i[i], bsb, cidxb.i[i])) fatal("inconsistent block-spaces"); scalartype = xm_tensor_get_scalar_type(a); zero = xm_dim_zero(0); maxblkbytes = xm_tensor_get_largest_block_bytes(a); xm_tensor_get_canonical_block_list(a, &blklist, &nblklist); #ifdef _OPENMP #pragma omp parallel private(i) #endif { xm_dim_t ia, ib; void *buf1, *buf2; size_t blksize; xm_block_type_t blocktype; if ((buf1 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); if ((buf2 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); ib = xm_dim_zero(cidxb.n); #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (i = 0; i < nblklist; i++) { if ((int)i % mpisize == mpirank) { xm_scalar_t scalar; ia = blklist[i]; xm_dim_set_mask(&ib, &cidxb, &ia, &cidxa); blksize = xm_tensor_get_block_size(b, ib); blocktype = xm_tensor_get_block_type(b, ib); if (blocktype == XM_BLOCK_TYPE_ZERO) { memset(buf1, 0, maxblkbytes); } else { scalar = xm_tensor_get_block_scalar(b, ib); xm_tensor_read_block(b, ib, buf1); xm_tensor_unfold_block(b, ib, cidxb, zero, buf1, buf2, blksize); xm_tensor_read_block(a, ia, buf1); xm_scalar_vec_mul(buf1, scalar, buf2, blksize, scalartype); } xm_tensor_write_block(a, ia, buf1); } } free(buf1); free(buf2); } free(blklist); #ifdef XM_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif } void xm_div(xm_tensor_t *a, const xm_tensor_t *b, const char *idxa, const char *idxb) { const xm_block_space_t *bsa, *bsb; xm_dim_t cidxa, cidxb, zero, *blklist; xm_scalar_type_t scalartype; size_t i, maxblkbytes, nblklist; int mpirank = 0, mpisize = 1; if (xm_tensor_get_allocator(a) != xm_tensor_get_allocator(b)) fatal("tensors must use same allocator"); if (xm_tensor_get_scalar_type(a) != xm_tensor_get_scalar_type(b)) fatal("tensors must have same scalar type"); #ifdef XM_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpirank); MPI_Comm_size(MPI_COMM_WORLD, &mpisize); #endif bsa = xm_tensor_get_block_space(a); bsb = xm_tensor_get_block_space(b); if (strlen(idxa) != xm_block_space_get_ndims(bsa)) fatal("idxa does not match tensor dimensions"); if (strlen(idxb) != xm_block_space_get_ndims(bsb)) fatal("idxb does not match tensor dimensions"); xm_make_masks(idxa, idxb, &cidxa, &cidxb); if (cidxa.n != xm_block_space_get_ndims(bsa) || cidxb.n != xm_block_space_get_ndims(bsb)) fatal("index spaces do not match"); for (i = 0; i < cidxa.n; i++) if (!xm_block_space_eq1(bsa, cidxa.i[i], bsb, cidxb.i[i])) fatal("inconsistent block-spaces"); scalartype = xm_tensor_get_scalar_type(a); zero = xm_dim_zero(0); maxblkbytes = xm_tensor_get_largest_block_bytes(a); xm_tensor_get_canonical_block_list(a, &blklist, &nblklist); #ifdef _OPENMP #pragma omp parallel private(i) #endif { xm_dim_t ia, ib; void *buf1, *buf2; size_t blksize; xm_block_type_t blocktype; if ((buf1 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); if ((buf2 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); ib = xm_dim_zero(cidxb.n); #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (i = 0; i < nblklist; i++) { if ((int)i % mpisize == mpirank) { xm_scalar_t scalar; ia = blklist[i]; xm_dim_set_mask(&ib, &cidxb, &ia, &cidxa); blksize = xm_tensor_get_block_size(b, ib); blocktype = xm_tensor_get_block_type(b, ib); if (blocktype == XM_BLOCK_TYPE_ZERO) fatal("division by zero"); scalar = xm_tensor_get_block_scalar(b, ib); xm_tensor_read_block(b, ib, buf1); xm_tensor_unfold_block(b, ib, cidxb, zero, buf1, buf2, blksize); xm_tensor_read_block(a, ia, buf1); xm_scalar_vec_div(buf1, scalar, buf2, blksize, scalartype); xm_tensor_write_block(a, ia, buf1); } } free(buf1); free(buf2); } free(blklist); #ifdef XM_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif } xm_scalar_t xm_dot(const xm_tensor_t *a, const xm_tensor_t *b, const char *idxa, const char *idxb) { const xm_block_space_t *bsa, *bsb; xm_dim_t cidxa, cidxb, zero, nblocks; xm_scalar_type_t scalartype; xm_scalar_t dot = 0; size_t i, maxblkbytes, nblklist; int mpirank = 0, mpisize = 1; if (xm_tensor_get_allocator(a) != xm_tensor_get_allocator(b)) fatal("tensors must use same allocator"); if (xm_tensor_get_scalar_type(a) != xm_tensor_get_scalar_type(b)) fatal("tensors must have same scalar type"); #ifdef XM_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpirank); MPI_Comm_size(MPI_COMM_WORLD, &mpisize); #endif bsa = xm_tensor_get_block_space(a); bsb = xm_tensor_get_block_space(b); if (strlen(idxa) != xm_block_space_get_ndims(bsa)) fatal("idxa does not match tensor dimensions"); if (strlen(idxb) != xm_block_space_get_ndims(bsb)) fatal("idxb does not match tensor dimensions"); xm_make_masks(idxa, idxb, &cidxa, &cidxb); if (cidxa.n != xm_block_space_get_ndims(bsa) || cidxb.n != xm_block_space_get_ndims(bsb)) fatal("index spaces do not match"); for (i = 0; i < cidxa.n; i++) if (!xm_block_space_eq1(bsa, cidxa.i[i], bsb, cidxb.i[i])) fatal("inconsistent block-spaces"); scalartype = xm_tensor_get_scalar_type(a); zero = xm_dim_zero(0); maxblkbytes = xm_tensor_get_largest_block_bytes(a); nblocks = xm_tensor_get_nblocks(a); nblklist = xm_dim_dot(&nblocks); #ifdef _OPENMP #pragma omp parallel private(i) reduction(+:dot) #endif { xm_dim_t ia, ib; void *buf1, *buf2, *buf3; size_t blksize; xm_block_type_t blocktype; if ((buf1 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); if ((buf2 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); if ((buf3 = malloc(maxblkbytes)) == NULL) fatal("out of memory"); ib = xm_dim_zero(cidxb.n); #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (i = 0; i < nblklist; i++) { if ((int)i % mpisize == mpirank) { xm_scalar_t scalara, scalarb; ia = xm_dim_from_offset(i, &nblocks); xm_dim_set_mask(&ib, &cidxb, &ia, &cidxa); blocktype = xm_tensor_get_block_type(a, ia); if (blocktype == XM_BLOCK_TYPE_ZERO) continue; blocktype = xm_tensor_get_block_type(b, ib); if (blocktype == XM_BLOCK_TYPE_ZERO) continue; blksize = xm_tensor_get_block_size(b, ib); xm_tensor_read_block(b, ib, buf1); xm_tensor_unfold_block(b, ib, cidxb, zero, buf1, buf2, blksize); xm_tensor_read_block(a, ia, buf1); xm_tensor_unfold_block(a, ia, cidxa, zero, buf1, buf3, blksize); scalara = xm_tensor_get_block_scalar(a, ia); scalarb = xm_tensor_get_block_scalar(b, ib); scalara = xm_scalar_mul(scalara, scalarb, scalartype); scalarb = xm_scalar_dot(buf2, buf3, blksize, scalartype); scalara = xm_scalar_mul(scalara, scalarb, scalartype); dot = xm_scalar_add(dot, scalara, scalartype); } } free(buf1); free(buf2); free(buf3); } #ifdef XM_USE_MPI MPI_Allreduce(MPI_IN_PLACE, &dot, 1, MPI_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD); #endif return dot; } void xm_print_banner(void) { printf("Libxm Tensor Library\n"); printf("Copyright (c) 2014-2018 Ilya Kaliman\n"); printf("https://github.com/ilyak/libxm\n"); printf("Reference: https://dx.doi.org/10.1002/jcc.24713\n"); }
effect.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE FFFFF FFFFF EEEEE CCCC TTTTT % % E F F E C T % % EEE FFF FFF EEE C T % % E F F E C T % % EEEEE F F EEEEE CCCC T % % % % % % MagickCore Image Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/distort.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/matrix.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/morphology.h" #include "magick/morphology-private.h" #include "magick/opencl-private.h" #include "magick/paint.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/transform.h" #include "magick/threshold.h" #ifdef MAGICKCORE_CLPERFMARKER #include "CLPerfMarker.h" #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveBlurImage() adaptively blurs the image by blurring less % intensely near image edges and more intensely far from edges. We blur the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveBlurImage() selects a suitable radius for you. % % The format of the AdaptiveBlurImage method is: % % Image *AdaptiveBlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *AdaptiveBlurImageChannel(const Image *image, % const ChannelType channel,double radius,const double sigma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *blur_image; blur_image=AdaptiveBlurImageChannel(image,DefaultChannels,radius,sigma, exception); return(blur_image); } MagickExport Image *AdaptiveBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { #define AdaptiveBlurImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *blur_view, *edge_view, *image_view; double **kernel, normalize; Image *blur_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; register ssize_t i; size_t width; ssize_t j, k, u, v, y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); blur_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) <= MagickEpsilon) return(blur_image); if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } /* Edge detect the image brighness channel, level, blur, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, sizeof(*kernel))); if (kernel == (double **) NULL) { edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (double *) NULL) break; normalize=0.0; j=(ssize_t) (width-i)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(double) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(k-1)/2]+=(1.0-normalize); if (sigma < MagickEpsilon) kernel[i][(k-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively blur image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,blur_image->rows,1) #endif for (y=0; y < (ssize_t) blur_image->rows; y++) { register const IndexPacket *restrict indexes; register const PixelPacket *restrict p, *restrict r; register IndexPacket *restrict blur_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((r == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) blur_image->columns; x++) { double alpha, gamma; DoublePixelPacket pixel; register const double *restrict k; register ssize_t i, u, v; gamma=0.0; i=(ssize_t) ceil((double) width*QuantumScale* GetPixelIntensity(edge_image,r)-0.5); if (i < 0) i=0; else if (i > (ssize_t) width) i=(ssize_t) width; if ((i & 0x01) != 0) i--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-i)/2L),y- (ssize_t) ((width-i)/2L),width-i,width-i,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; k=kernel[i]; for (v=0; v < (ssize_t) (width-i); v++) { for (u=0; u < (ssize_t) (width-i); u++) { alpha=1.0; if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p)); if ((channel & RedChannel) != 0) pixel.red+=(*k)*alpha*GetPixelRed(p); if ((channel & GreenChannel) != 0) pixel.green+=(*k)*alpha*GetPixelGreen(p); if ((channel & BlueChannel) != 0) pixel.blue+=(*k)*alpha*GetPixelBlue(p); if ((channel & OpacityChannel) != 0) pixel.opacity+=(*k)*GetPixelOpacity(p); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+(width-i)*v+u); gamma+=(*k)*alpha; k++; p++; } } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index)); q++; r++; } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveBlurImageChannel) #endif proceed=SetImageProgress(image,AdaptiveBlurImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveSharpenImage() adaptively sharpens the image by sharpening more % intensely near image edges and less intensely far from edges. We sharpen the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveSharpenImage() selects a suitable radius for you. % % The format of the AdaptiveSharpenImage method is: % % Image *AdaptiveSharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *AdaptiveSharpenImageChannel(const Image *image, % const ChannelType channel,double radius,const double sigma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveSharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *sharp_image; sharp_image=AdaptiveSharpenImageChannel(image,DefaultChannels,radius,sigma, exception); return(sharp_image); } MagickExport Image *AdaptiveSharpenImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { #define AdaptiveSharpenImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *sharp_view, *edge_view, *image_view; double **kernel, normalize; Image *sharp_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; register ssize_t i; size_t width; ssize_t j, k, u, v, y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); sharp_image=CloneImage(image,0,0,MagickTrue,exception); if (sharp_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) <= MagickEpsilon) return(sharp_image); if (SetImageStorageClass(sharp_image,DirectClass) == MagickFalse) { InheritException(exception,&sharp_image->exception); sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } /* Edge detect the image brighness channel, level, sharp, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, sizeof(*kernel))); if (kernel == (double **) NULL) { edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (double *) NULL) break; normalize=0.0; j=(ssize_t) (width-i-1)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(double) (-exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(k-1)/2]=(double) ((-2.0)*normalize); if (sigma < MagickEpsilon) kernel[i][(k-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively sharpen image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); sharp_view=AcquireAuthenticCacheView(sharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,sharp_image,sharp_image->rows,1) #endif for (y=0; y < (ssize_t) sharp_image->rows; y++) { register const IndexPacket *restrict indexes; register const PixelPacket *restrict p, *restrict r; register IndexPacket *restrict sharp_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(sharp_view,0,y,sharp_image->columns,1, exception); if ((r == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } sharp_indexes=GetCacheViewAuthenticIndexQueue(sharp_view); for (x=0; x < (ssize_t) sharp_image->columns; x++) { double alpha, gamma; DoublePixelPacket pixel; register const double *restrict k; register ssize_t i, u, v; gamma=0.0; i=(ssize_t) ceil((double) width*(1.0-QuantumScale* GetPixelIntensity(edge_image,r))-0.5); if (i < 0) i=0; else if (i > (ssize_t) width) i=(ssize_t) width; if ((i & 0x01) != 0) i--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-i)/2L),y- (ssize_t) ((width-i)/2L),width-i,width-i,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); k=kernel[i]; pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; for (v=0; v < (ssize_t) (width-i); v++) { for (u=0; u < (ssize_t) (width-i); u++) { alpha=1.0; if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p)); if ((channel & RedChannel) != 0) pixel.red+=(*k)*alpha*GetPixelRed(p); if ((channel & GreenChannel) != 0) pixel.green+=(*k)*alpha*GetPixelGreen(p); if ((channel & BlueChannel) != 0) pixel.blue+=(*k)*alpha*GetPixelBlue(p); if ((channel & OpacityChannel) != 0) pixel.opacity+=(*k)*GetPixelOpacity(p); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+(width-i)*v+u); gamma+=(*k)*alpha; k++; p++; } } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(sharp_indexes+x,ClampToQuantum(gamma*pixel.index)); q++; r++; } if (SyncCacheViewAuthenticPixels(sharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveSharpenImageChannel) #endif proceed=SetImageProgress(image,AdaptiveSharpenImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sharp_image->type=image->type; sharp_view=DestroyCacheView(sharp_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) sharp_image=DestroyImage(sharp_image); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlurImage() blurs an image. We convolve the image with a Gaussian operator % of the given radius and standard deviation (sigma). For reasonable results, % the radius should be larger than sigma. Use a radius of 0 and BlurImage() % selects a suitable radius for you. % % The format of the BlurImage method is: % % Image *BlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *BlurImageChannel(const Image *image,const ChannelType channel, % const double radius,const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *blur_image; blur_image=BlurImageChannel(image,DefaultChannels,radius,sigma,exception); return(blur_image); } MagickExport Image *BlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { char geometry[MaxTextExtent]; KernelInfo *kernel_info; Image *blur_image = NULL; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); blur_image=AccelerateBlurImage(image,channel,radius,sigma,exception); if (blur_image != (Image *) NULL) return(blur_image); (void) FormatLocaleString(geometry,MaxTextExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=MorphologyApply(image,channel,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n v o l v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvolveImage() applies a custom convolution kernel to the image. % % The format of the ConvolveImage method is: % % Image *ConvolveImage(const Image *image,const size_t order, % const double *kernel,ExceptionInfo *exception) % Image *ConvolveImageChannel(const Image *image,const ChannelType channel, % const size_t order,const double *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o order: the number of columns and rows in the filter kernel. % % o kernel: An array of double representing the convolution kernel. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConvolveImage(const Image *image,const size_t order, const double *kernel,ExceptionInfo *exception) { Image *convolve_image; #ifdef MAGICKCORE_CLPERFMARKER clBeginPerfMarkerAMD(__FUNCTION__,""); #endif convolve_image=ConvolveImageChannel(image,DefaultChannels,order,kernel, exception); #ifdef MAGICKCORE_CLPERFMARKER clEndPerfMarkerAMD(); #endif return(convolve_image); } MagickExport Image *ConvolveImageChannel(const Image *image, const ChannelType channel,const size_t order,const double *kernel, ExceptionInfo *exception) { Image *convolve_image; KernelInfo *kernel_info; register ssize_t i; kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); kernel_info->width=order; kernel_info->height=order; kernel_info->x=(ssize_t) (order-1)/2; kernel_info->y=(ssize_t) (order-1)/2; kernel_info->signature=MagickSignature; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->width*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (order*order); i++) kernel_info->values[i]=kernel[i]; convolve_image=AccelerateConvolveImageChannel(image,channel,kernel_info, exception); if (convolve_image == (Image *) NULL) convolve_image=MorphologyApply(image,channel,ConvolveMorphology,1, kernel_info,UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(convolve_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s p e c k l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DespeckleImage() reduces the speckle noise in an image while perserving the % edges of the original image. A speckle removing filter uses a complementary % hulling technique (raising pixels that are darker than their surrounding % neighbors, then complementarily lowering pixels that are brighter than their % surrounding neighbors) to reduce the speckle index of that image (reference % Crimmins speckle removal). % % The format of the DespeckleImage method is: % % Image *DespeckleImage(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. % */ static void Hull(const Image *image,const ssize_t x_offset, const ssize_t y_offset,const size_t columns,const size_t rows, const int polarity,Quantum *restrict f,Quantum *restrict g) { register Quantum *p, *q, *r, *s; ssize_t y; assert(f != (Quantum *) NULL); assert(g != (Quantum *) NULL); p=f+(columns+2); q=g+(columns+2); r=p+(y_offset*(columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) rows; y++) { register ssize_t i, x; SignedQuantum v; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) p[i]; if ((SignedQuantum) r[i] >= (v+ScaleCharToQuantum(2))) v+=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) p[i]; if ((SignedQuantum) r[i] <= (v-ScaleCharToQuantum(2))) v-=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } } p=f+(columns+2); q=g+(columns+2); r=q+(y_offset*(columns+2)+x_offset); s=q-(y_offset*(columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) rows; y++) { register ssize_t i, x; SignedQuantum v; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) q[i]; if (((SignedQuantum) s[i] >= (v+ScaleCharToQuantum(2))) && ((SignedQuantum) r[i] > v)) v+=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) q[i]; if (((SignedQuantum) s[i] <= (v-ScaleCharToQuantum(2))) && ((SignedQuantum) r[i] < v)) v-=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } } } MagickExport Image *DespeckleImage(const Image *image,ExceptionInfo *exception) { #define DespeckleImageTag "Despeckle/Image" CacheView *despeckle_view, *image_view; Image *despeckle_image; MagickBooleanType status; MemoryInfo *buffer_info, *pixel_info; register ssize_t i; Quantum *restrict buffer, *restrict pixels; size_t length, number_channels; static const ssize_t X[4] = {0, 1, 1,-1}, Y[4] = {1, 0, 1, 1}; /* Allocate despeckled image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); despeckle_image=AccelerateDespeckleImage(image, exception); if (despeckle_image != (Image *) NULL) return(despeckle_image); despeckle_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (despeckle_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(despeckle_image,DirectClass) == MagickFalse) { InheritException(exception,&despeckle_image->exception); despeckle_image=DestroyImage(despeckle_image); return((Image *) NULL); } /* Allocate image buffer. */ length=(size_t) ((image->columns+2)*(image->rows+2)); pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); buffer_info=AcquireVirtualMemory(length,sizeof(*buffer)); if ((pixel_info == (MemoryInfo *) NULL) || (buffer_info == (MemoryInfo *) NULL)) { if (buffer_info != (MemoryInfo *) NULL) buffer_info=RelinquishVirtualMemory(buffer_info); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image=DestroyImage(despeckle_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(Quantum *) GetVirtualMemoryBlob(pixel_info); buffer=(Quantum *) GetVirtualMemoryBlob(buffer_info); /* Reduce speckle in the image. */ status=MagickTrue; number_channels=(size_t) (image->colorspace == CMYKColorspace ? 5 : 4); image_view=AcquireVirtualCacheView(image,exception); despeckle_view=AcquireAuthenticCacheView(despeckle_image,exception); for (i=0; i < (ssize_t) number_channels; i++) { register ssize_t k, x; ssize_t j, y; if (status == MagickFalse) continue; if ((image->matte == MagickFalse) && (i == 3)) continue; (void) ResetMagickMemory(pixels,0,length*sizeof(*pixels)); j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); j++; for (x=0; x < (ssize_t) image->columns; x++) { switch (i) { case 0: pixels[j]=GetPixelRed(p); break; case 1: pixels[j]=GetPixelGreen(p); break; case 2: pixels[j]=GetPixelBlue(p); break; case 3: pixels[j]=GetPixelOpacity(p); break; case 4: pixels[j]=GetPixelBlack(indexes+x); break; default: break; } p++; j++; } j++; } (void) ResetMagickMemory(buffer,0,length*sizeof(*buffer)); for (k=0; k < 4; k++) { Hull(image,X[k],Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,-1,pixels,buffer); Hull(image,X[k],Y[k],image->columns,image->rows,-1,pixels,buffer); } j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register IndexPacket *restrict indexes; register PixelPacket *restrict q; q=GetCacheViewAuthenticPixels(despeckle_view,0,y,despeckle_image->columns, 1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(despeckle_view); j++; for (x=0; x < (ssize_t) image->columns; x++) { switch (i) { case 0: SetPixelRed(q,pixels[j]); break; case 1: SetPixelGreen(q,pixels[j]); break; case 2: SetPixelBlue(q,pixels[j]); break; case 3: SetPixelOpacity(q,pixels[j]); break; case 4: SetPixelIndex(indexes+x,pixels[j]); break; default: break; } q++; j++; } sync=SyncCacheViewAuthenticPixels(despeckle_view,exception); if (sync == MagickFalse) { status=MagickFalse; break; } j++; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DespeckleImageTag,(MagickOffsetType) i, number_channels); if (proceed == MagickFalse) status=MagickFalse; } } despeckle_view=DestroyCacheView(despeckle_view); image_view=DestroyCacheView(image_view); buffer_info=RelinquishVirtualMemory(buffer_info); pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image->type=image->type; if (status == MagickFalse) despeckle_image=DestroyImage(despeckle_image); return(despeckle_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EdgeImage() finds edges in an image. Radius defines the radius of the % convolution filter. Use a radius of 0 and EdgeImage() selects a suitable % radius for you. % % The format of the EdgeImage method is: % % Image *EdgeImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EdgeImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *edge_image; KernelInfo *kernel_info; register ssize_t i; size_t width; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); width=GetOptimalKernelWidth1D(radius,0.5); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (kernel_info->width-1)/2; kernel_info->y=(ssize_t) (kernel_info->height-1)/2; kernel_info->signature=MagickSignature; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->height*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]=(-1.0); kernel_info->values[i/2]=(double) kernel_info->width*kernel_info->height-1.0; edge_image=AccelerateConvolveImageChannel(image,DefaultChannels,kernel_info, exception); if (edge_image == (Image *) NULL) edge_image=MorphologyApply(image,DefaultChannels,ConvolveMorphology,1, kernel_info,UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E m b o s s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EmbossImage() returns a grayscale image with a three-dimensional effect. % We convolve the image with a Gaussian operator of the given radius and % standard deviation (sigma). For reasonable results, radius should be % larger than sigma. Use a radius of 0 and Emboss() selects a suitable % radius for you. % % The format of the EmbossImage method is: % % Image *EmbossImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EmbossImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { double gamma, normalize; Image *emboss_image; KernelInfo *kernel_info; register ssize_t i; size_t width; ssize_t j, k, u, v; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); width=GetOptimalKernelWidth1D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->width*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } j=(ssize_t) (kernel_info->width-1)/2; k=j; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(double) (((u < 0) || (v < 0) ? -8.0 : 8.0)*exp(-((double) u*u+v*v)/(2.0*MagickSigma*MagickSigma))/ (2.0*MagickPI*MagickSigma*MagickSigma)); if (u != k) kernel_info->values[i]=0.0; i++; } k--; } normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; emboss_image=AccelerateConvolveImageChannel(image,DefaultChannels,kernel_info, exception); if (emboss_image == (Image *) NULL) emboss_image=MorphologyApply(image,DefaultChannels,ConvolveMorphology,1, kernel_info,UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); if (emboss_image != (Image *) NULL) (void) EqualizeImageChannel(emboss_image,(ChannelType) (AllChannels &~ SyncChannels)); return(emboss_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F i l t e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FilterImage() applies a custom convolution kernel to the image. % % The format of the FilterImage method is: % % Image *FilterImage(const Image *image,const KernelInfo *kernel, % ExceptionInfo *exception) % Image *FilterImageChannel(const Image *image,const ChannelType channel, % const KernelInfo *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o kernel: the filtering kernel. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *FilterImage(const Image *image,const KernelInfo *kernel, ExceptionInfo *exception) { Image *filter_image; filter_image=FilterImageChannel(image,DefaultChannels,kernel,exception); return(filter_image); } MagickExport Image *FilterImageChannel(const Image *image, const ChannelType channel,const KernelInfo *kernel,ExceptionInfo *exception) { #define FilterImageTag "Filter/Image" CacheView *filter_view, *image_view; Image *filter_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; MagickRealType *filter_kernel; register ssize_t i; ssize_t y; #ifdef MAGICKCORE_CLPERFMARKER clBeginPerfMarkerAMD(__FUNCTION__,""); #endif /* Initialize filter image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((kernel->width % 2) == 0) ThrowImageException(OptionError,"KernelWidthMustBeAnOddNumber"); if (image->debug != MagickFalse) { char format[MaxTextExtent], *message; register const double *k; ssize_t u, v; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " FilterImage with %.20gx%.20g kernel:",(double) kernel->width,(double) kernel->height); message=AcquireString(""); k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { *message='\0'; (void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < (ssize_t) kernel->width; u++) { (void) FormatLocaleString(format,MaxTextExtent,"%g ",*k++); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } filter_image=AccelerateConvolveImageChannel(image,channel,kernel,exception); if (filter_image != (Image *) NULL) { #ifdef MAGICKCORE_CLPERFMARKER clEndPerfMarkerAMD(); #endif return(filter_image); } filter_image=CloneImage(image,0,0,MagickTrue,exception); if (filter_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(filter_image,DirectClass) == MagickFalse) { InheritException(exception,&filter_image->exception); filter_image=DestroyImage(filter_image); return((Image *) NULL); } /* Normalize kernel. */ filter_kernel=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory( kernel->width,kernel->width*sizeof(*filter_kernel))); if (filter_kernel == (MagickRealType *) NULL) { filter_image=DestroyImage(filter_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (kernel->width*kernel->width); i++) filter_kernel[i]=(MagickRealType) kernel->values[i]; /* Filter image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); filter_view=AcquireAuthenticCacheView(filter_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,filter_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict filter_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (kernel->width-1)/2L),y- (ssize_t) ((kernel->height-1)/2L),image->columns+kernel->width, kernel->height,exception); q=GetCacheViewAuthenticPixels(filter_view,0,y,filter_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); filter_indexes=GetCacheViewAuthenticIndexQueue(filter_view); for (x=0; x < (ssize_t) image->columns; x++) { DoublePixelPacket pixel; register const MagickRealType *restrict k; register const PixelPacket *restrict kernel_pixels; register ssize_t u; ssize_t v; pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; k=filter_kernel; kernel_pixels=p; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.red+=(*k)*kernel_pixels[u].red; pixel.green+=(*k)*kernel_pixels[u].green; pixel.blue+=(*k)*kernel_pixels[u].blue; k++; } kernel_pixels+=image->columns+kernel->width; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) { k=filter_kernel; kernel_pixels=p; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.opacity+=(*k)*kernel_pixels[u].opacity; k++; } kernel_pixels+=image->columns+kernel->width; } SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { register const IndexPacket *restrict kernel_indexes; k=filter_kernel; kernel_indexes=indexes; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.index+=(*k)*GetPixelIndex(kernel_indexes+u); k++; } kernel_indexes+=image->columns+kernel->width; } SetPixelIndex(filter_indexes+x,ClampToQuantum(pixel.index)); } } else { double alpha, gamma; gamma=0.0; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { alpha=(MagickRealType) (QuantumScale*(QuantumRange- GetPixelOpacity(kernel_pixels+u))); pixel.red+=(*k)*alpha*GetPixelRed(kernel_pixels+u); pixel.green+=(*k)*alpha*GetPixelGreen(kernel_pixels+u); pixel.blue+=(*k)*alpha*GetPixelBlue(kernel_pixels+u); gamma+=(*k)*alpha; k++; } kernel_pixels+=image->columns+kernel->width; } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); if ((channel & OpacityChannel) != 0) { k=filter_kernel; kernel_pixels=p; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.opacity+=(*k)*GetPixelOpacity(kernel_pixels+u); k++; } kernel_pixels+=image->columns+kernel->width; } SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { register const IndexPacket *restrict kernel_indexes; k=filter_kernel; kernel_pixels=p; kernel_indexes=indexes; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { alpha=(MagickRealType) (QuantumScale*(QuantumRange- kernel_pixels[u].opacity)); pixel.index+=(*k)*alpha*GetPixelIndex(kernel_indexes+u); k++; } kernel_pixels+=image->columns+kernel->width; kernel_indexes+=image->columns+kernel->width; } SetPixelIndex(filter_indexes+x,ClampToQuantum(gamma*pixel.index)); } } indexes++; p++; q++; } sync=SyncCacheViewAuthenticPixels(filter_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FilterImageChannel) #endif proceed=SetImageProgress(image,FilterImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } filter_image->type=image->type; filter_view=DestroyCacheView(filter_view); image_view=DestroyCacheView(image_view); filter_kernel=(MagickRealType *) RelinquishAlignedMemory(filter_kernel); if (status == MagickFalse) filter_image=DestroyImage(filter_image); #ifdef MAGICKCORE_CLPERFMARKER clEndPerfMarkerAMD(); #endif return(filter_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a u s s i a n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GaussianBlurImage() blurs an image. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, the radius should be larger than sigma. Use a % radius of 0 and GaussianBlurImage() selects a suitable radius for you % % The format of the GaussianBlurImage method is: % % Image *GaussianBlurImage(const Image *image,onst double radius, % const double sigma,ExceptionInfo *exception) % Image *GaussianBlurImageChannel(const Image *image, % const ChannelType channel,const double radius,const double sigma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GaussianBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *blur_image; blur_image=GaussianBlurImageChannel(image,DefaultChannels,radius,sigma, exception); return(blur_image); } MagickExport Image *GaussianBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { char geometry[MaxTextExtent]; KernelInfo *kernel_info; Image *blur_image; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); (void) FormatLocaleString(geometry,MaxTextExtent,"gaussian:%.20gx%.20g", radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=AccelerateConvolveImageChannel(image,channel,kernel_info, exception); if (blur_image == (Image *) NULL) blur_image=MorphologyApply(image,channel,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o t i o n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MotionBlurImage() simulates motion blur. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, radius should be larger than sigma. Use a % radius of 0 and MotionBlurImage() selects a suitable radius for you. % Angle gives the angle of the blurring motion. % % Andrew Protano contributed this effect. % % The format of the MotionBlurImage method is: % % Image *MotionBlurImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % Image *MotionBlurImageChannel(const Image *image,const ChannelType channel, % const double radius,const double sigma,const double angle, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ static double *GetMotionBlurKernel(const size_t width,const double sigma) { double *kernel, normalize; register ssize_t i; /* Generate a 1-D convolution kernel. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); kernel=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, sizeof(*kernel))); if (kernel == (double *) NULL) return(kernel); normalize=0.0; for (i=0; i < (ssize_t) width; i++) { kernel[i]=(double) (exp((-((double) i*i)/(double) (2.0*MagickSigma* MagickSigma)))/(MagickSQ2PI*MagickSigma)); normalize+=kernel[i]; } for (i=0; i < (ssize_t) width; i++) kernel[i]/=normalize; return(kernel); } MagickExport Image *MotionBlurImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { Image *motion_blur; motion_blur=MotionBlurImageChannel(image,DefaultChannels,radius,sigma,angle, exception); return(motion_blur); } MagickExport Image *MotionBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double angle,ExceptionInfo *exception) { #define BlurImageTag "Blur/Image" CacheView *blur_view, *image_view; double *kernel; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; OffsetInfo *offset; PointInfo point; register ssize_t i; size_t width; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); width=GetOptimalKernelWidth1D(radius,sigma); kernel=GetMotionBlurKernel(width,sigma); if (kernel == (double *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); offset=(OffsetInfo *) AcquireQuantumMemory(width,sizeof(*offset)); if (offset == (OffsetInfo *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } point.x=(double) width*sin(DegreesToRadians(angle)); point.y=(double) width*cos(DegreesToRadians(angle)); for (i=0; i < (ssize_t) width; i++) { offset[i].x=(ssize_t) ceil((double) (i*point.y)/hypot(point.x,point.y)-0.5); offset[i].y=(ssize_t) ceil((double) (i*point.x)/hypot(point.x,point.y)-0.5); } /* Motion blur image. */ blur_image=AccelerateMotionBlurImage(image,channel,kernel,width,offset ,exception); if (blur_image != (Image*)NULL) { return blur_image; } blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); return((Image *) NULL); } if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { kernel=(double *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); image_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict blur_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket qixel; PixelPacket pixel; register const IndexPacket *restrict indexes; register double *restrict k; register ssize_t i; k=kernel; qixel=bias; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (i=0; i < (ssize_t) width; i++) { (void) GetOneCacheViewVirtualPixel(image_view,x+offset[i].x,y+ offset[i].y,&pixel,exception); qixel.red+=(*k)*pixel.red; qixel.green+=(*k)*pixel.green; qixel.blue+=(*k)*pixel.blue; qixel.opacity+=(*k)*pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=(*k)*(*indexes); } k++; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(qixel.index)); } else { double alpha, gamma; alpha=0.0; gamma=0.0; for (i=0; i < (ssize_t) width; i++) { (void) GetOneCacheViewVirtualPixel(image_view,x+offset[i].x,y+ offset[i].y,&pixel,exception); alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(&pixel)); qixel.red+=(*k)*alpha*pixel.red; qixel.green+=(*k)*alpha*pixel.green; qixel.blue+=(*k)*alpha*pixel.blue; qixel.opacity+=(*k)*pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=(*k)*alpha*GetPixelIndex(indexes); } gamma+=(*k)*alpha; k++; } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*qixel.index)); } q++; } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MotionBlurImageChannel) #endif proceed=SetImageProgress(image,BlurImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); image_view=DestroyCacheView(image_view); kernel=(double *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r e v i e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PreviewImage() tiles 9 thumbnails of the specified image with an image % processing operation applied with varying parameters. This may be helpful % pin-pointing an appropriate parameter for a particular image processing % operation. % % The format of the PreviewImages method is: % % Image *PreviewImages(const Image *image,const PreviewType preview, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o preview: the image processing operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PreviewImage(const Image *image,const PreviewType preview, ExceptionInfo *exception) { #define NumberTiles 9 #define PreviewImageTag "Preview/Image" #define DefaultPreviewGeometry "204x204+10+10" char factor[MaxTextExtent], label[MaxTextExtent]; double degrees, gamma, percentage, radius, sigma, threshold; Image *images, *montage_image, *preview_image, *thumbnail; ImageInfo *preview_info; MagickBooleanType proceed; MontageInfo *montage_info; QuantizeInfo quantize_info; RectangleInfo geometry; register ssize_t i, x; size_t colors; ssize_t y; /* Open output image file. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); colors=2; degrees=0.0; gamma=(-0.2f); preview_info=AcquireImageInfo(); SetGeometry(image,&geometry); (void) ParseMetaGeometry(DefaultPreviewGeometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); images=NewImageList(); percentage=12.5; GetQuantizeInfo(&quantize_info); radius=0.0; sigma=1.0; threshold=0.0; x=0; y=0; for (i=0; i < NumberTiles; i++) { thumbnail=ThumbnailImage(image,geometry.width,geometry.height,exception); if (thumbnail == (Image *) NULL) break; (void) SetImageProgressMonitor(thumbnail,(MagickProgressMonitor) NULL, (void *) NULL); (void) SetImageProperty(thumbnail,"label",DefaultTileLabel); if (i == (NumberTiles/2)) { (void) QueryColorDatabase("#dfdfdf",&thumbnail->matte_color,exception); AppendImageToList(&images,thumbnail); continue; } switch (preview) { case RotatePreview: { degrees+=45.0; preview_image=RotateImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"rotate %g",degrees); break; } case ShearPreview: { degrees+=5.0; preview_image=ShearImage(thumbnail,degrees,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"shear %gx%g", degrees,2.0*degrees); break; } case RollPreview: { x=(ssize_t) ((i+1)*thumbnail->columns)/NumberTiles; y=(ssize_t) ((i+1)*thumbnail->rows)/NumberTiles; preview_image=RollImage(thumbnail,x,y,exception); (void) FormatLocaleString(label,MaxTextExtent,"roll %+.20gx%+.20g", (double) x,(double) y); break; } case HuePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"100,100,%g", 2.0*percentage); (void) ModulateImage(preview_image,factor); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case SaturationPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"100,%g",2.0*percentage); (void) ModulateImage(preview_image,factor); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case BrightnessPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"%g",2.0*percentage); (void) ModulateImage(preview_image,factor); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case GammaPreview: default: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; gamma+=0.4f; (void) GammaImageChannel(preview_image,DefaultChannels,gamma); (void) FormatLocaleString(label,MaxTextExtent,"gamma %g",gamma); break; } case SpiffPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image != (Image *) NULL) for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickTrue); (void) FormatLocaleString(label,MaxTextExtent,"contrast (%.20g)", (double) i+1); break; } case DullPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickFalse); (void) FormatLocaleString(label,MaxTextExtent,"+contrast (%.20g)", (double) i+1); break; } case GrayscalePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; quantize_info.colorspace=GRAYColorspace; (void) QuantizeImage(&quantize_info,preview_image); (void) FormatLocaleString(label,MaxTextExtent, "-colorspace gray -colors %.20g",(double) colors); break; } case QuantizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; (void) QuantizeImage(&quantize_info,preview_image); (void) FormatLocaleString(label,MaxTextExtent,"colors %.20g",(double) colors); break; } case DespecklePreview: { for (x=0; x < (i-1); x++) { preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; thumbnail=DestroyImage(thumbnail); thumbnail=preview_image; } preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(label,MaxTextExtent,"despeckle (%.20g)", (double) i+1); break; } case ReduceNoisePreview: { preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) radius, (size_t) radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"noise %g",radius); break; } case AddNoisePreview: { switch ((int) i) { case 0: { (void) CopyMagickString(factor,"uniform",MaxTextExtent); break; } case 1: { (void) CopyMagickString(factor,"gaussian",MaxTextExtent); break; } case 2: { (void) CopyMagickString(factor,"multiplicative",MaxTextExtent); break; } case 3: { (void) CopyMagickString(factor,"impulse",MaxTextExtent); break; } case 5: { (void) CopyMagickString(factor,"laplacian",MaxTextExtent); break; } case 6: { (void) CopyMagickString(factor,"poisson",MaxTextExtent); break; } default: { (void) CopyMagickString(thumbnail->magick,"NULL",MaxTextExtent); break; } } preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) i, (size_t) i,exception); (void) FormatLocaleString(label,MaxTextExtent,"+noise %s",factor); break; } case SharpenPreview: { preview_image=SharpenImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MaxTextExtent,"sharpen %gx%g", radius,sigma); break; } case BlurPreview: { preview_image=BlurImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MaxTextExtent,"blur %gx%g",radius, sigma); break; } case ThresholdPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) BilevelImage(thumbnail, (double) (percentage*((MagickRealType) QuantumRange+1.0))/100.0); (void) FormatLocaleString(label,MaxTextExtent,"threshold %g", (double) (percentage*((MagickRealType) QuantumRange+1.0))/100.0); break; } case EdgeDetectPreview: { preview_image=EdgeImage(thumbnail,radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"edge %g",radius); break; } case SpreadPreview: { preview_image=SpreadImage(thumbnail,radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"spread %g", radius+0.5); break; } case SolarizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) SolarizeImage(preview_image,(double) QuantumRange* percentage/100.0); (void) FormatLocaleString(label,MaxTextExtent,"solarize %g", (QuantumRange*percentage)/100.0); break; } case ShadePreview: { degrees+=10.0; preview_image=ShadeImage(thumbnail,MagickTrue,degrees,degrees, exception); (void) FormatLocaleString(label,MaxTextExtent,"shade %gx%g", degrees,degrees); break; } case RaisePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; geometry.width=(size_t) (2*i+2); geometry.height=(size_t) (2*i+2); geometry.x=(i-1)/2; geometry.y=(i-1)/2; (void) RaiseImage(preview_image,&geometry,MagickTrue); (void) FormatLocaleString(label,MaxTextExtent, "raise %.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); break; } case SegmentPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; threshold+=0.4f; (void) SegmentImage(preview_image,sRGBColorspace,MagickFalse,threshold, threshold); (void) FormatLocaleString(label,MaxTextExtent,"segment %gx%g", threshold,threshold); break; } case SwirlPreview: { preview_image=SwirlImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"swirl %g",degrees); degrees+=45.0; break; } case ImplodePreview: { degrees+=0.1f; preview_image=ImplodeImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"implode %g",degrees); break; } case WavePreview: { degrees+=5.0f; preview_image=WaveImage(thumbnail,0.5*degrees,2.0*degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"wave %gx%g", 0.5*degrees,2.0*degrees); break; } case OilPaintPreview: { preview_image=OilPaintImage(thumbnail,(double) radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"paint %g",radius); break; } case CharcoalDrawingPreview: { preview_image=CharcoalImage(thumbnail,(double) radius,(double) sigma, exception); (void) FormatLocaleString(label,MaxTextExtent,"charcoal %gx%g", radius,sigma); break; } case JPEGPreview: { char filename[MaxTextExtent]; int file; MagickBooleanType status; preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; preview_info->quality=(size_t) percentage; (void) FormatLocaleString(factor,MaxTextExtent,"%.20g",(double) preview_info->quality); file=AcquireUniqueFileResource(filename); if (file != -1) file=close(file)-1; (void) FormatLocaleString(preview_image->filename,MaxTextExtent, "jpeg:%s",filename); status=WriteImage(preview_info,preview_image); if (status != MagickFalse) { Image *quality_image; (void) CopyMagickString(preview_info->filename, preview_image->filename,MaxTextExtent); quality_image=ReadImage(preview_info,exception); if (quality_image != (Image *) NULL) { preview_image=DestroyImage(preview_image); preview_image=quality_image; } } (void) RelinquishUniqueFileResource(preview_image->filename); if ((GetBlobSize(preview_image)/1024) >= 1024) (void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%gmb ", factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/ 1024.0/1024.0); else if (GetBlobSize(preview_image) >= 1024) (void) FormatLocaleString(label,MaxTextExtent, "quality %s\n%gkb ",factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/1024.0); else (void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%.20gb ", factor,(double) ((MagickOffsetType) GetBlobSize(thumbnail))); break; } } thumbnail=DestroyImage(thumbnail); percentage+=12.5; radius+=0.5; sigma+=0.25; if (preview_image == (Image *) NULL) break; (void) DeleteImageProperty(preview_image,"label"); (void) SetImageProperty(preview_image,"label",label); AppendImageToList(&images,preview_image); proceed=SetImageProgress(image,PreviewImageTag,(MagickOffsetType) i, NumberTiles); if (proceed == MagickFalse) break; } if (images == (Image *) NULL) { preview_info=DestroyImageInfo(preview_info); return((Image *) NULL); } /* Create the montage. */ montage_info=CloneMontageInfo(preview_info,(MontageInfo *) NULL); (void) CopyMagickString(montage_info->filename,image->filename,MaxTextExtent); montage_info->shadow=MagickTrue; (void) CloneString(&montage_info->tile,"3x3"); (void) CloneString(&montage_info->geometry,DefaultPreviewGeometry); (void) CloneString(&montage_info->frame,DefaultTileFrame); montage_image=MontageImages(images,montage_info,exception); montage_info=DestroyMontageInfo(montage_info); images=DestroyImageList(images); if (montage_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (montage_image->montage != (char *) NULL) { /* Free image directory. */ montage_image->montage=(char *) RelinquishMagickMemory( montage_image->montage); if (image->directory != (char *) NULL) montage_image->directory=(char *) RelinquishMagickMemory( montage_image->directory); } preview_info=DestroyImageInfo(preview_info); return(montage_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o t a t i o n a l B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotationalBlurImage() applies a rotational blur to the image. % % Andrew Protano contributed this effect. % % The format of the RotationalBlurImage method is: % % Image *RotationalBlurImage(const Image *image,const double angle, % ExceptionInfo *exception) % Image *RotationalBlurImageChannel(const Image *image, % const ChannelType channel,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o angle: the angle of the rotational blur. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *RotationalBlurImage(const Image *image,const double angle, ExceptionInfo *exception) { Image *blur_image; blur_image=RotationalBlurImageChannel(image,DefaultChannels,angle,exception); return(blur_image); } MagickExport Image *RotationalBlurImageChannel(const Image *image, const ChannelType channel,const double angle,ExceptionInfo *exception) { CacheView *blur_view, *image_view; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; MagickRealType blur_radius, *cos_theta, offset, *sin_theta, theta; PointInfo blur_center; register ssize_t i; size_t n; ssize_t y; /* Allocate blur image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); blur_image=AccelerateRadialBlurImage(image,channel,angle,exception); if (blur_image != (Image *) NULL) return(blur_image); blur_center.x=(double) (image->columns-1)/2.0; blur_center.y=(double) (image->rows-1)/2.0; blur_radius=hypot(blur_center.x,blur_center.y); n=(size_t) fabs(4.0*DegreesToRadians(angle)*sqrt((double) blur_radius)+2UL); theta=DegreesToRadians(angle)/(MagickRealType) (n-1); cos_theta=(MagickRealType *) AcquireQuantumMemory((size_t) n, sizeof(*cos_theta)); sin_theta=(MagickRealType *) AcquireQuantumMemory((size_t) n, sizeof(*sin_theta)); if ((cos_theta == (MagickRealType *) NULL) || (sin_theta == (MagickRealType *) NULL)) { ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } offset=theta*(MagickRealType) (n-1)/2.0; for (i=0; i < (ssize_t) n; i++) { cos_theta[i]=cos((double) (theta*i-offset)); sin_theta[i]=sin((double) (theta*i-offset)); } blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) { cos_theta=(MagickRealType *) RelinquishMagickMemory(cos_theta); sin_theta=(MagickRealType *) RelinquishMagickMemory(sin_theta); return((Image *) NULL); } if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { cos_theta=(MagickRealType *) RelinquishMagickMemory(cos_theta); sin_theta=(MagickRealType *) RelinquishMagickMemory(sin_theta); InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } /* Radial blur image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); image_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,blur_image->rows,1) #endif for (y=0; y < (ssize_t) blur_image->rows; y++) { register const IndexPacket *restrict indexes; register IndexPacket *restrict blur_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) blur_image->columns; x++) { MagickPixelPacket qixel; MagickRealType normalize, radius; PixelPacket pixel; PointInfo center; register ssize_t i; size_t step; center.x=(double) x-blur_center.x; center.y=(double) y-blur_center.y; radius=hypot((double) center.x,center.y); if (radius == 0) step=1; else { step=(size_t) (blur_radius/radius); if (step == 0) step=1; else if (step >= n) step=n-1; } normalize=0.0; qixel=bias; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (i=0; i < (ssize_t) n; i+=(ssize_t) step) { (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) (blur_center.x+center.x*cos_theta[i]-center.y*sin_theta[i]+0.5), (ssize_t) (blur_center.y+center.x*sin_theta[i]+center.y* cos_theta[i]+0.5),&pixel,exception); qixel.red+=pixel.red; qixel.green+=pixel.green; qixel.blue+=pixel.blue; qixel.opacity+=pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=(*indexes); } normalize+=1.0; } normalize=PerceptibleReciprocal(normalize); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(normalize*qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(normalize*qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(normalize*qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(normalize*qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(normalize*qixel.index)); } else { double alpha, gamma; alpha=1.0; gamma=0.0; for (i=0; i < (ssize_t) n; i+=(ssize_t) step) { (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) (blur_center.x+center.x*cos_theta[i]-center.y*sin_theta[i]+0.5), (ssize_t) (blur_center.y+center.x*sin_theta[i]+center.y* cos_theta[i]+0.5),&pixel,exception); alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(&pixel)); qixel.red+=alpha*pixel.red; qixel.green+=alpha*pixel.green; qixel.blue+=alpha*pixel.blue; qixel.opacity+=pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=alpha*(*indexes); } gamma+=alpha; normalize+=1.0; } gamma=PerceptibleReciprocal(gamma); normalize=PerceptibleReciprocal(normalize); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(normalize*qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*qixel.index)); } q++; } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RotationalBlurImageChannel) #endif proceed=SetImageProgress(image,BlurImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); image_view=DestroyCacheView(image_view); cos_theta=(MagickRealType *) RelinquishMagickMemory(cos_theta); sin_theta=(MagickRealType *) RelinquishMagickMemory(sin_theta); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e l e c t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SelectiveBlurImage() selectively blur pixels within a contrast threshold. % It is similar to the unsharpen mask that sharpens everything with contrast % above a certain threshold. % % The format of the SelectiveBlurImage method is: % % Image *SelectiveBlurImage(const Image *image,const double radius, % const double sigma,const double threshold,ExceptionInfo *exception) % Image *SelectiveBlurImageChannel(const Image *image, % const ChannelType channel,const double radius,const double sigma, % const double threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o threshold: only pixels within this contrast threshold are included % in the blur operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SelectiveBlurImage(const Image *image,const double radius, const double sigma,const double threshold,ExceptionInfo *exception) { Image *blur_image; blur_image=SelectiveBlurImageChannel(image,DefaultChannels,radius,sigma, threshold,exception); return(blur_image); } MagickExport Image *SelectiveBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double threshold,ExceptionInfo *exception) { #define SelectiveBlurImageTag "SelectiveBlur/Image" CacheView *blur_view, *image_view, *luminance_view; double *kernel; Image *blur_image, *luminance_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; register ssize_t i; size_t width; ssize_t center, j, u, v, y; /* Initialize blur image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); width=GetOptimalKernelWidth1D(radius,sigma); kernel=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, width*sizeof(*kernel))); if (kernel == (double *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); j=(ssize_t) (width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) kernel[i++]=(double) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); } if (image->debug != MagickFalse) { char format[MaxTextExtent], *message; register const double *k; ssize_t u, v; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " SelectiveBlurImage with %.20gx%.20g kernel:",(double) width,(double) width); message=AcquireString(""); k=kernel; for (v=0; v < (ssize_t) width; v++) { *message='\0'; (void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < (ssize_t) width; u++) { (void) FormatLocaleString(format,MaxTextExtent,"%+f ",*k++); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { kernel=(double *) RelinquishAlignedMemory(kernel); InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } luminance_image=CloneImage(image,0,0,MagickTrue,exception); if (luminance_image == (Image *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); blur_image=DestroyImage(blur_image); return((Image *) NULL); } status=TransformImageColorspace(luminance_image,GRAYColorspace); if (status == MagickFalse) { InheritException(exception,&luminance_image->exception); kernel=(double *) RelinquishAlignedMemory(kernel); blur_image=DestroyImage(blur_image); luminance_image=DestroyImage(luminance_image); return((Image *) NULL); } /* Threshold blur image. */ status=MagickTrue; progress=0; center=(ssize_t) ((image->columns+width)*((width-1)/2L)+((width-1)/2L)); GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); luminance_view=AcquireVirtualCacheView(luminance_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double gamma; MagickBooleanType sync; register const IndexPacket *restrict indexes; register const PixelPacket *restrict l, *restrict p; register IndexPacket *restrict blur_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (width-1)/2L),y-(ssize_t) ((width-1)/2L),image->columns+width,width,exception); l=GetCacheViewVirtualPixels(luminance_view,-((ssize_t) (width-1)/2L),y- (ssize_t) ((width-1)/2L),luminance_image->columns+width,width,exception); q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (l == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) image->columns; x++) { double contrast; DoublePixelPacket pixel; MagickRealType intensity; register const double *restrict k; register ssize_t u; ssize_t j, v; pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; k=kernel; intensity=GetPixelIntensity(image,p+center); gamma=0.0; j=0; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { pixel.red+=(*k)*GetPixelRed(p+u+j); pixel.green+=(*k)*GetPixelGreen(p+u+j); pixel.blue+=(*k)*GetPixelBlue(p+u+j); gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } if (gamma != 0.0) { gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); } if ((channel & OpacityChannel) != 0) { gamma=0.0; j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { pixel.opacity+=(*k)*(p+u+j)->opacity; gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } gamma=PerceptibleReciprocal(gamma); SetPixelOpacity(q,ClampToQuantum(gamma*pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { gamma=0.0; j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { pixel.index+=(*k)*GetPixelIndex(indexes+x+u+j); gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } gamma=PerceptibleReciprocal(gamma); SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index)); } } else { MagickRealType alpha; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p+u+j)); pixel.red+=(*k)*alpha*GetPixelRed(p+u+j); pixel.green+=(*k)*alpha*GetPixelGreen(p+u+j); pixel.blue+=(*k)*alpha*GetPixelBlue(p+u+j); pixel.opacity+=(*k)*GetPixelOpacity(p+u+j); gamma+=(*k)*alpha; } k++; } j+=(ssize_t) (image->columns+width); } if (gamma != 0.0) { gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); } if ((channel & OpacityChannel) != 0) { gamma=0.0; j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { pixel.opacity+=(*k)*GetPixelOpacity(p+u+j); gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } gamma=PerceptibleReciprocal(gamma); SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { gamma=0.0; j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { alpha=(MagickRealType) (QuantumScale* GetPixelAlpha(p+u+j)); pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+u+j); gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } gamma=PerceptibleReciprocal(gamma); SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index)); } } p++; l++; q++; } sync=SyncCacheViewAuthenticPixels(blur_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SelectiveBlurImageChannel) #endif proceed=SetImageProgress(image,SelectiveBlurImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); luminance_view=DestroyCacheView(luminance_view); image_view=DestroyCacheView(image_view); luminance_image=DestroyImage(luminance_image); kernel=(double *) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadeImage() shines a distant light on an image to create a % three-dimensional effect. You control the positioning of the light with % azimuth and elevation; azimuth is measured in degrees off the x axis % and elevation is measured in pixels above the Z axis. % % The format of the ShadeImage method is: % % Image *ShadeImage(const Image *image,const MagickBooleanType gray, % const double azimuth,const double elevation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o gray: A value other than zero shades the intensity of each pixel. % % o azimuth, elevation: Define the light source direction. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadeImage(const Image *image,const MagickBooleanType gray, const double azimuth,const double elevation,ExceptionInfo *exception) { #define ShadeImageTag "Shade/Image" CacheView *image_view, *shade_view; Image *linear_image, *shade_image; MagickBooleanType status; MagickOffsetType progress; PrimaryInfo light; ssize_t y; /* Initialize shaded image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); linear_image=CloneImage(image,0,0,MagickTrue,exception); shade_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (shade_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (shade_image != (Image *) NULL) shade_image=DestroyImage(shade_image); return((Image *) NULL); } if (SetImageStorageClass(shade_image,DirectClass) == MagickFalse) { InheritException(exception,&shade_image->exception); linear_image=DestroyImage(linear_image); shade_image=DestroyImage(shade_image); return((Image *) NULL); } /* Compute the light vector. */ light.x=(double) QuantumRange*cos(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.y=(double) QuantumRange*sin(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.z=(double) QuantumRange*sin(DegreesToRadians(elevation)); /* Shade image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(linear_image,exception); shade_view=AcquireAuthenticCacheView(shade_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(linear_image,shade_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { MagickRealType distance, normal_distance, shade; PrimaryInfo normal; register const PixelPacket *restrict p, *restrict s0, *restrict s1, *restrict s2; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-1,y-1,linear_image->columns+2,3, exception); q=QueueCacheViewAuthenticPixels(shade_view,0,y,shade_image->columns,1, exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } /* Shade this row of pixels. */ normal.z=2.0*(double) QuantumRange; /* constant Z of surface normal */ s0=p+1; s1=s0+image->columns+2; s2=s1+image->columns+2; for (x=0; x < (ssize_t) linear_image->columns; x++) { /* Determine the surface normal and compute shading. */ normal.x=(double) (GetPixelIntensity(linear_image,s0-1)+ GetPixelIntensity(linear_image,s1-1)+ GetPixelIntensity(linear_image,s2-1)- GetPixelIntensity(linear_image,s0+1)- GetPixelIntensity(linear_image,s1+1)- GetPixelIntensity(linear_image,s2+1)); normal.y=(double) (GetPixelIntensity(linear_image,s2-1)+ GetPixelIntensity(linear_image,s2)+ GetPixelIntensity(linear_image,s2+1)- GetPixelIntensity(linear_image,s0-1)- GetPixelIntensity(linear_image,s0)- GetPixelIntensity(linear_image,s0+1)); if ((normal.x == 0.0) && (normal.y == 0.0)) shade=light.z; else { shade=0.0; distance=normal.x*light.x+normal.y*light.y+normal.z*light.z; if (distance > MagickEpsilon) { normal_distance=normal.x*normal.x+normal.y*normal.y+normal.z* normal.z; if (normal_distance > (MagickEpsilon*MagickEpsilon)) shade=distance/sqrt((double) normal_distance); } } if (gray != MagickFalse) { SetPixelRed(q,shade); SetPixelGreen(q,shade); SetPixelBlue(q,shade); } else { SetPixelRed(q,ClampToQuantum(QuantumScale*shade*GetPixelRed(s1))); SetPixelGreen(q,ClampToQuantum(QuantumScale*shade*GetPixelGreen(s1))); SetPixelBlue(q,ClampToQuantum(QuantumScale*shade*GetPixelBlue(s1))); } q->opacity=s1->opacity; s0++; s1++; s2++; q++; } if (SyncCacheViewAuthenticPixels(shade_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ShadeImage) #endif proceed=SetImageProgress(image,ShadeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } shade_view=DestroyCacheView(shade_view); image_view=DestroyCacheView(image_view); linear_image=DestroyImage(linear_image); if (status == MagickFalse) shade_image=DestroyImage(shade_image); return(shade_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SharpenImage() sharpens the image. We convolve the image with a Gaussian % operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SharpenImage() selects a suitable radius for you. % % Using a separable kernel would be faster, but the negative weights cancel % out on the corners of the kernel producing often undesirable ringing in the % filtered result; this can be avoided by using a 2D gaussian shaped image % sharpening kernel instead. % % The format of the SharpenImage method is: % % Image *SharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *SharpenImageChannel(const Image *image,const ChannelType channel, % const double radius,const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *sharp_image; sharp_image=SharpenImageChannel(image,DefaultChannels,radius,sigma,exception); return(sharp_image); } MagickExport Image *SharpenImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { double gamma, normalize; Image *sharp_image; KernelInfo *kernel_info; register ssize_t i; size_t width; ssize_t j, u, v; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); width=GetOptimalKernelWidth2D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->signature=MagickSignature; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->height*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } normalize=0.0; j=(ssize_t) (kernel_info->width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(double) (-exp(-((double) u*u+v*v)/(2.0* MagickSigma*MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel_info->values[i]; i++; } } kernel_info->values[i/2]=(double) ((-2.0)*normalize); normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; sharp_image=MorphologyApply(image,channel,ConvolveMorphology,1,kernel_info, UndefinedCompositeOp,0.0,exception); kernel_info=DestroyKernelInfo(kernel_info); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p r e a d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpreadImage() is a special effects method that randomly displaces each % pixel in a block defined by the radius parameter. % % The format of the SpreadImage method is: % % Image *SpreadImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: Choose a random pixel in a neighborhood of this extent. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpreadImage(const Image *image,const double radius, ExceptionInfo *exception) { #define SpreadImageTag "Spread/Image" CacheView *image_view, *spread_view; Image *spread_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; RandomInfo **restrict random_info; size_t width; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize spread image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); spread_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (spread_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(spread_image,DirectClass) == MagickFalse) { InheritException(exception,&spread_image->exception); spread_image=DestroyImage(spread_image); return((Image *) NULL); } /* Spread image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(spread_image,&bias); width=GetOptimalKernelWidth1D(radius,0.5); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); spread_view=AcquireAuthenticCacheView(spread_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,spread_image,spread_image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) spread_image->rows; y++) { const int id = GetOpenMPThreadId(); MagickPixelPacket pixel; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(spread_view,0,y,spread_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(spread_view); pixel=bias; for (x=0; x < (ssize_t) spread_image->columns; x++) { (void) InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) x+width*(GetPseudoRandomValue( random_info[id])-0.5),(double) y+width*(GetPseudoRandomValue( random_info[id])-0.5),&pixel,exception); SetPixelPacket(spread_image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(spread_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SpreadImage) #endif proceed=SetImageProgress(image,SpreadImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } spread_view=DestroyCacheView(spread_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) spread_image=DestroyImage(spread_image); return(spread_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n s h a r p M a s k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnsharpMaskImage() sharpens one or more image channels. We convolve the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and UnsharpMaskImage() selects a suitable radius for you. % % The format of the UnsharpMaskImage method is: % % Image *UnsharpMaskImage(const Image *image,const double radius, % const double sigma,const double amount,const double threshold, % ExceptionInfo *exception) % Image *UnsharpMaskImageChannel(const Image *image, % const ChannelType channel,const double radius,const double sigma, % const double gain,const double threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o gain: the percentage of the difference between the original and the % blur image that is added back into the original. % % o threshold: the threshold in pixels needed to apply the diffence gain. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *UnsharpMaskImage(const Image *image,const double radius, const double sigma,const double gain,const double threshold, ExceptionInfo *exception) { Image *sharp_image; sharp_image=UnsharpMaskImageChannel(image,DefaultChannels,radius,sigma,gain, threshold,exception); return(sharp_image); } MagickExport Image *UnsharpMaskImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double gain,const double threshold,ExceptionInfo *exception) { #define SharpenImageTag "Sharpen/Image" CacheView *image_view, *unsharp_view; Image *unsharp_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; MagickRealType quantum_threshold; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); unsharp_image=AccelerateUnsharpMaskImage(image,channel,radius,sigma,gain, threshold,exception); if (unsharp_image != (Image *) NULL) return(unsharp_image); unsharp_image=BlurImageChannel(image,(ChannelType) (channel &~ SyncChannels), radius,sigma,exception); if (unsharp_image == (Image *) NULL) return((Image *) NULL); quantum_threshold=(MagickRealType) QuantumRange*threshold; /* Unsharp-mask image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); image_view=AcquireVirtualCacheView(image,exception); unsharp_view=AcquireAuthenticCacheView(unsharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,unsharp_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { DoublePixelPacket pixel; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict unsharp_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(unsharp_view,0,y,unsharp_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); unsharp_indexes=GetCacheViewAuthenticIndexQueue(unsharp_view); pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { pixel.red=GetPixelRed(p)-(MagickRealType) GetPixelRed(q); if (fabs(2.0*pixel.red) < quantum_threshold) pixel.red=(MagickRealType) GetPixelRed(p); else pixel.red=(MagickRealType) GetPixelRed(p)+(pixel.red*gain); SetPixelRed(q,ClampToQuantum(pixel.red)); } if ((channel & GreenChannel) != 0) { pixel.green=GetPixelGreen(p)-(MagickRealType) q->green; if (fabs(2.0*pixel.green) < quantum_threshold) pixel.green=(MagickRealType) GetPixelGreen(p); else pixel.green=(MagickRealType) GetPixelGreen(p)+(pixel.green*gain); SetPixelGreen(q,ClampToQuantum(pixel.green)); } if ((channel & BlueChannel) != 0) { pixel.blue=GetPixelBlue(p)-(MagickRealType) q->blue; if (fabs(2.0*pixel.blue) < quantum_threshold) pixel.blue=(MagickRealType) GetPixelBlue(p); else pixel.blue=(MagickRealType) GetPixelBlue(p)+(pixel.blue*gain); SetPixelBlue(q,ClampToQuantum(pixel.blue)); } if ((channel & OpacityChannel) != 0) { pixel.opacity=GetPixelOpacity(p)-(MagickRealType) q->opacity; if (fabs(2.0*pixel.opacity) < quantum_threshold) pixel.opacity=(MagickRealType) GetPixelOpacity(p); else pixel.opacity=GetPixelOpacity(p)+(pixel.opacity*gain); SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { pixel.index=GetPixelIndex(indexes+x)-(MagickRealType) GetPixelIndex(unsharp_indexes+x); if (fabs(2.0*pixel.index) < quantum_threshold) pixel.index=(MagickRealType) GetPixelIndex(indexes+x); else pixel.index=(MagickRealType) GetPixelIndex(indexes+x)+ (pixel.index*gain); SetPixelIndex(unsharp_indexes+x,ClampToQuantum(pixel.index)); } p++; q++; } if (SyncCacheViewAuthenticPixels(unsharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_UnsharpMaskImageChannel) #endif proceed=SetImageProgress(image,SharpenImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } unsharp_image->type=image->type; unsharp_view=DestroyCacheView(unsharp_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) unsharp_image=DestroyImage(unsharp_image); return(unsharp_image); }
mat_mul_p4a_6000.c
/* * file for mat_mul.c */ #include "./mat_mul.h" #include "./size.h" void mat_mul(int *a, int *b, int *c); void mat_mul(int *a, int *b, int *c) { int i, j, k, t; #pragma omp parallel for private(j, t, k) for(i = 0; i <= 5999; i += 1) for(j = 0; j <= 5999; j += 1) { c[i*6000+j] = 0; for(k = 0; k <= 5999; k += 1) for(t = 0; t <= 99; t += 1) c[i*6000+j] += a[i*6000+k]*b[j*6000+k]; } return; }
gdal_metric_eta.c
#include<stdio.h> #include<omp.h> #include<math.h> #include "gdal.h" #include "metric_eta.h" #include "ogr_srs_api.h" #include "proj_api.h" void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--OpenMP code----\n"); printf( "-----------------------------------------\n"); printf( "./metric_eta inNdvi inLai inLst inAlb inDem\n"); printf( "\toutMetric_eta outMetric_evapfr outMetric_dtair outMetric_theta\n"); printf( "-----------------------------------------\n"); printf( "\tdoy Ta rh u z h eto_alf kc iteration\n"); printf( "\t[-mproj/-mcolrow/-mauto]\n"); printf( "\nBelow are wet/dry pixels modes\n"); printf( "---------------------------------------------\n"); printf( "-mproj projXwet ProjYwet projXdry projYdry\t Manual wet/dry pixel mode (projected)\n"); printf( "-mcolrow Xwet Ywet Xdry Ydry\t Manual wet/dry pixel mode (NOT projected)\n"); printf( "-mauto\t Automatic seek wet/dry pixel mode (Careful!)\n\n"); return; } int main( int argc, char *argv[] ) { if( argc < 18 ) { usage(); return 1; } int mproj=0, mcolrow=0, mauto=0; double projXwet,projYwet,projXdry,projYdry; double Xwet,Ywet,Xdry,Ydry; int col_wet, col_dry; int row_wet, row_dry; char *inB1 = argv[1]; //NDVI char *inB2 = argv[2]; //LAI char *inB3 = argv[3]; //LST char *inB4 = argv[4]; //ALBEDO char *inB5 = argv[5]; //DEM char *metric_etaF = argv[6]; char *metric_evapfrF = argv[7]; char *metric_dtairF = argv[8]; char *metric_thetaF = argv[9]; int doy = atoi(argv[10]); // Day Of Year [0-366] double ta = atof(argv[11]); // Air Temperature (K) double rh = atof(argv[12]); // Relative Humidity (-) double u = atof(argv[13]); // wind speed (m/s) at z height double z = atof(argv[14]); // z height (m) of anemometer double h = atof(argv[15]); // h (m) of vegetation under anemometer double eto_alf = atof(argv[16]); // Reference ET of Alfalfa double kc = atof(argv[17]); // Reference ET associated crop coefficient int iteration = atoi(argv[18]); // Iteration number for H //MDBA Farm A // double phase_max=sin(2*3.1415927*(doy+365/3.3)/365); // double tmax =31.17+(36.9-24.1)/2*((1+1/3+1/5+1/7)*phase_max); // double esat =6.11*exp(17.27*tmax/(tmax+237.3)); // double eact =rh*esat/100; // double phase_min=sin(2*3.1415927*(doy+365/3.5)/365); // double tmin =31.17+(36.9-24.1)/2*((1+1/3+1/5+1/7)*phase_min); // ta =tmin+(tmax-tmin)*0.8; double tsw=0; printf("NDVI=%s LAI=%s LST=%s ALBEDO=%s DEM=%s Out=%s\n",inB1,inB2,inB3,inB4,inB5,metric_etaF); printf("doy=%i Ta=%f u=%f z=%f h=%f eto_alf=%f kc=%f\n",doy,ta,u,z,h,eto_alf,kc); int c; for (c = 19; c <argc; c++) { // printf("argv[%i] = %s\n",c,argv[c]); /* Manual wet / dry input, projected */ if (!strcmp(argv[c],"-mproj")) { mproj=1; mcolrow=0; mauto=0; projXwet = atof( argv[c+1] ); projYwet = atof( argv[c+2] ); projXdry = atof( argv[c+3] ); projYdry = atof( argv[c+4] ); // printf("projXYwet=(%f,%f) projXYdry=(%f,%f)\n",projXwet,projYwet,projXdry,projYdry); } /* Manual wet / dry input row / col */ if (!strcmp(argv[c],"-mcolrow")) { mproj=0; mcolrow=1; mauto=0; col_wet = atoi( argv[c+1] ); row_wet = atoi( argv[c+2] ); col_dry = atoi( argv[c+3] ); row_dry = atoi( argv[c+4] ); } /* Automatic wet / dry input row / col */ if (!strcmp(argv[c],"-mauto")) { mproj=0; mcolrow=0; mauto=1; } } if (mproj==0 && mcolrow==0 && mauto==0){ printf("Choose a wet/dry pixel mode please\n"); exit(1); } GDALAllRegister(); GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//NDVI GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//LAI GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//LST GDALDatasetH hD4 = GDALOpen(inB4,GA_ReadOnly);//ALBEDO GDALDatasetH hD5 = GDALOpen(inB5,GA_ReadOnly);//DEM if(hD1==NULL||hD2==NULL||hD3==NULL ||hD4==NULL||hD5==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); GDALDriverH hDr5 = GDALGetDatasetDriver(hD5); //Evapfr out GDALDatasetH hDOut0 = GDALCreateCopy( hDr5, metric_evapfrF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut0 = GDALGetRasterBand(hDOut0,1); //ETa out GDALDatasetH hDOut = GDALCreateCopy( hDr5, metric_etaF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); //dTair out GDALDatasetH hDOut1 = GDALCreateCopy( hDr5, metric_dtairF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut1 = GDALGetRasterBand(hDOut1,1); //theta out GDALDatasetH hDOut2 = GDALCreateCopy( hDr5, metric_thetaF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut2 = GDALGetRasterBand(hDOut2,1); // //latitude temporary skeleton GDALDatasetH hDLat = GDALCreateCopy( hDr5, "latitude",hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBLat = GDALGetRasterBand(hDLat,1); GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//NDVI GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//LAI GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//LST GDALRasterBandH hB4 = GDALGetRasterBand(hD4,1);//ALBEDO GDALRasterBandH hB5 = GDALGetRasterBand(hD5,1);//DEM int nX = GDALGetRasterBandXSize(hB1); int nY = GDALGetRasterBandYSize(hB1); int N=nX*nY; float *mat1 = (float *) malloc(sizeof(float)*N); float *mat2 = (float *) malloc(sizeof(float)*N); float *mat3 = (float *) malloc(sizeof(float)*N); float *mat4 = (float *) malloc(sizeof(float)*N); float *mat5 = (float *) malloc(sizeof(float)*N); float *matOut2 = (float *) malloc(sizeof(float)*N); float *matOut1 = (float *) malloc(sizeof(float)*N); float *matOut0 = (float *) malloc(sizeof(float)*N); float *matOut = (float *) malloc(sizeof(float)*N); //Latitude matrix float *matLat = (float *) malloc(sizeof(float)*N); //tmp scanlines float *l1 = (float *) malloc(sizeof(float)*nX); float *l2 = (float *) malloc(sizeof(float)*nX); float *l3 = (float *) malloc(sizeof(float)*nX); float *l4 = (float *) malloc(sizeof(float)*nX); float *l5 = (float *) malloc(sizeof(float)*nX); float e0, kin, lin, lout, lnet, rnet, g_0, z_0m, h0 ; float metriceta, metricevapfr, metricdtair, pmeto, metrictheta; int i, row, col, rowcol; double a[10]={0.0}, b[10]={0.0}; // a = (double *) malloc(sizeof(double)*10); // b = (double *) malloc(sizeof(double)*10); // for (i=0;i<10;i++){ // a[i]=0.0; // b[i]=0.0; // } // printf("a[0]=%f\tb[0]=%f\n",a[0],b[0]); //Calculation of effective wind speed (initilasation of a unique point based ustar) float ustar_0 = ustar0(u, z, h); //Calculation of surface roughness of momentum z_0m=0.12*h; float u200 = ustar_0*log(200/z_0m)/0.41; //Calculation of aerodynamic resistance to heat flux momentum float rah_0 = rah0(ustar_0);//initialsation of rah calculation //Seed the wet and dry pixels variables double dem_wet=0,rnet_wet,g0_wet; double dem_dry=2000,rnet_dry,g0_dry; //LOAD DATA MATRICES //NDVI GDALRasterIO(hB1,GF_Read,0,0,nX,nY,mat1,nX,nY,GDT_Float32,0,0); //LAI GDALRasterIO(hB2,GF_Read,0,0,nX,nY,mat2,nX,nY,GDT_Float32,0,0); //LST GDALRasterIO(hB3,GF_Read,0,0,nX,nY,mat3,nX,nY,GDT_Float32,0,0); //ALBEDO GDALRasterIO(hB4,GF_Read,0,0,nX,nY,mat4,nX,nY,GDT_Float32,0,0); //DEM GDALRasterIO(hB5,GF_Read,0,0,nX,nY,mat5,nX,nY,GDT_Float32,0,0); // PROCESS DRY AND WET PIXELS //PROJ4 things for reproject lat/long pix into row/col projPJ proj4; projUV in, out; char *proj; char *pszWKT; OGRSpatialReferenceH hSRS; hSRS = OSRNewSpatialReference( NULL ); double coef; int temp; double geomx[6]={0.0}; double tempk_min, tempk_max; double t0dem_min, t0dem_max; double tempk_dry, tempk_wet; double t0dem_dry, t0dem_wet; double h_dry; double dailyN, t0dem, tadem; //LATITUDE MATRIX FILLING if((GDALGetProjectionRef( hD5 )) != NULL && strlen(GDALGetProjectionRef( hD5 ))>0){ pszWKT = (char *) GDALGetProjectionRef(hD5); printf( "Projection Info\n\t%s\n", pszWKT ); OSRImportFromWkt(hSRS, &pszWKT); OSRExportToProj4(hSRS, &proj); GDALGetGeoTransform(hD5,geomx); /* Do Nothing */ printf( "Origin (ULx,ULy) = (%.6f,%.6f)\n", geomx[0], geomx[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", geomx[1], geomx[5] ); printf( "Rot0 = (%.6f,%.6f)\n", geomx[2], geomx[4] ); } else { printf("ERROR: Projection acquisition problem from SRTM\n"); exit(1); } // printf("Passed 2\n"); //if(pj_is_latlong(proj)){ for(row=0;row<nY;row++){ #pragma omp parallel for default(none) \ private(col) shared( row, geomx, nX, l1) for(col=0;col<nX;col++){ l1[col] = geomx[3]+geomx[4]*col+geomx[5]*row; } #pragma omp barrier GDALRasterIO(hBLat,GF_Write,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); } //LATITUDE MATRIX FILLING GDALRasterIO(hBLat,GF_Read,0,0,nX,nY,matLat,nX,nY,GDT_Float32,0,0); //} else { // printf("ERROR: Projection is NOT LAT/LONG\n"); // exit(1); //} //Accessing the data rowxrow if(mcolrow||mproj){ if(mcolrow){ row = row_dry; col = col_dry; } else if (mproj){ if((GDALGetProjectionRef( hD1 )) != NULL && strlen(GDALGetProjectionRef( hD1 ))>0){ pszWKT = (char *) GDALGetProjectionRef(hD1); // printf( "%s\n", pszWKT ); OSRImportFromWkt(hSRS, &pszWKT); OSRExportToProj4(hSRS, &proj); } proj4 = pj_init_plus(proj); if(pj_is_latlong(proj4)){ Xwet = projXwet; Ywet = projYwet; Xdry = projXdry; Ydry = projYdry; // printf("Xwet=%f Ywet=%f Xdry=%f Ydry=%f\n",Xwet,Ywet,Xdry,Ydry); }else{ //reproject wet pixels in.u = projXwet; in.v = projYwet; in.u *= DEG_TO_RAD; in.v *= DEG_TO_RAD; out = pj_inv(in, proj4); Xwet = out.u; Ywet = out.v; //reproject dry pixels in.u = projXdry; in.v = projYdry; in.u *= DEG_TO_RAD; in.v *= DEG_TO_RAD; out = pj_inv(in, proj4); Xdry = out.u; Ydry = out.v; } if(GDALGetGeoTransform(hD1,geomx)==CE_None){ /* Do Nothing */ // printf( "Origin (ULx,ULy) = (%.6f,%.6f)\n", geomx[0], geomx[3] ); // printf( "Pixel Size = (%.6f,%.6f)\n", geomx[1], geomx[5] ); // printf( "Rot0 = (%.6f,%.6f)\n", geomx[2], geomx[4] ); } else { printf("ERROR: Projection acquisition problem from Band1\n"); exit(1); } // printf( "Origin(ULx,ULy)= (%.6f,%.6f)\n", geomx[0], geomx[3] ); // printf( "Pixel Size= (%.6f,%.6f)\n", geomx[1], geomx[5] ); // printf( "Rot1= (%.6f,%.6f)\n", geomx[2], geomx[4] ); if(geomx[2]<=0.0001||(-geomx[4])<=0.0001){ col=(Xdry-geomx[0])/geomx[1]; row=(geomx[3]-Ydry)/(-geomx[5]); // printf("col1=%i row1=%i\n",col,row); }else { coef = geomx[5]/geomx[4]; // printf("coef_dry=%f\n",coef); col = (coef*Xdry-coef*geomx[0]-Ydry+geomx[3])/(coef*geomx[1]-geomx[2]); // printf("col=%i\n",col); row = (Xdry - (geomx[0] + geomx[1] * col))/geomx[2]; // printf("row=%i\n",row); } // projXdry = geomx[0] + geomx[1] * col_dry + geomx[2] * row_dry; // projYdry = geomx[3] + geomx[4] * col_dry + geomx[5] * row_dry; } /* Collect T0Dem_dry */ GDALRasterIO(hB3,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); tempk_dry = l1[col] * 0.02; GDALRasterIO(hB5,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); t0dem_dry = tempk_dry - 0.00625*l2[col] ; GDALRasterIO(hB1,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); GDALRasterIO(hB4,GF_Read,0,row,nX,1,l4,nX,1,GDT_Float32,0,0); GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); // Surface emissivity calculations (e0=f(ndvi,lai)) e0=e_0(l1[col]*0.0001,l2[col]*0.1); //Incoming longwave radiation (Lin). To be derived locally at CSU tsw = 0.75 + 2 * pow(10,-5)*l5[col]; lin = Lin(tsw, ta); // printf("lin=%f\n", lin); //Outgoing longwave radiation (Lout=f(e0,lst)) lout=Lout(e0,tempk_dry); //Net longwave radiation (Lnet) lnet=Lnet(lout,lin); //Solar shortwave incoming irradiance kin=Kin(doy,geomx[3]+geomx[4]*col+geomx[5]*row,tsw); //Net Radiation (Rnet = f(alb,lnet,kin) rnet_dry=Rnet(l4[col]*0.001,lnet,kin); //calculation of g_0 = f(rnet,lst,alb,ndvi) g0_dry=g0(rnet_dry,tempk_dry,l4[col]*0.001,l1[col]*0.0001); h_dry = rnet_dry - g0_dry ; row_dry=row; col_dry=col; if(mcolrow){ row = row_wet; col = col_wet; } else if (mproj){ if(geomx[2]<=0.0001||(-geomx[4])<=0.0001){ col=(Xwet-geomx[0])/geomx[1]; row=(geomx[3]-Ywet)/(-geomx[5]); // printf("col=%i row=%i\n",col,row); }else { coef = geomx[5]/geomx[4]; col = (coef*Xwet-coef*geomx[0]-Ywet+geomx[3])/(coef*geomx[1]-geomx[2]); row = (Xwet - (geomx[0] + geomx[1] * col))/geomx[2]; } // projXwet = geomx[0] + geomx[1] * col_wet + geomx[2] * row_wet; // projYwet = geomx[3] + geomx[4] * col_wet + geomx[5] * row_wet; } /* Collect T0Dem_wet */ GDALRasterIO(hB3,GF_Read,0,row,nX,1,l3,nX,1,GDT_Float32,0,0); tempk_wet = l3[col] * 0.02; GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); t0dem_wet = tempk_wet - 0.00625*l5[col] ; GDALRasterIO(hB1,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); GDALRasterIO(hB4,GF_Read,0,row,nX,1,l4,nX,1,GDT_Float32,0,0); GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); // Surface emissivity calculations (e0=f(ndvi,lai)) e0=e_0(l1[col]*0.0001,l2[col]*0.1); //Incoming longwave radiation (Lin). To be derived locally at CSU tsw = 0.75 + 2 * pow(10,-5)*l5[col]; lin = Lin(tsw, ta); // printf("lin=%f\n", lin); //Outgoing longwave radiation (Lout=f(e0,lst)) lout=Lout(e0,tempk_wet); //Net longwave radiation (Lnet) lnet=Lnet(lout,lin); //Solar shortwave incoming irradiance kin=Kin(doy,geomx[3]+geomx[4]*col+geomx[5]*row,tsw); //Net Radiation (Rnet = f(alb,lnet,kin) rnet_wet=Rnet(l4[col]*0.001,lnet,kin); //calculation of g0 = f(rnet,lst,alb,ndvi) g0_wet=g0(rnet_wet,tempk_wet,l4[col]*0.001,l1[col]*0.0001); row_wet=row; col_wet=col; } else { //--------------------------- // Dry/wet pixel AUTOMATIC seek //--------------------------- // printf("Started Heuristic\n"); tempk_min=400.0; tempk_max=0.0; t0dem_min=400.0; t0dem_max=0.0; col_dry = 0; row_dry = 0; col_wet = 0; row_wet = 0; /* Pick up wet and dry pixel values */ double h0, dem, albedo, t0dem, tempk ; double h0_min=1000.0; double h0_max=0.0; /*START Temperature minimum search */ /*This is correcting for un-Earthly temperatures*/ /*It finds when histogram is actually starting to pull up...*/ int peak1, peak2, peak3; int i_peak1, i_peak2, i_peak3; int bottom1a, bottom1b; int bottom2a, bottom2b; int bottom3a, bottom3b; int i_bottom1a, i_bottom1b; int i_bottom2a, i_bottom2b; int i_bottom3a, i_bottom3b; int histogramT[400]; for (i=0;i<400;i++){ histogramT[i]=0; } /****************************/ /* Process pixels histogram */ #pragma omp parallel for default(none) \ private(rowcol, temp)\ shared(N, mat3, mat5, histogramT) for(rowcol=0;rowcol<N;rowcol++){ temp = (int) (mat3[rowcol]*0.02-0.00625*mat5[rowcol]); if(temp>200||mat3[rowcol]!=-28768){ histogramT[temp]=histogramT[temp]+1.0; } } #pragma omp barrier // printf("Histogram of Temperature map"); // printf(" (if it has rogue values to clean)\n"); //int peak1, peak2, peak3; //int i_peak1, i_peak2, i_peak3; peak1=0; peak2=0; peak3=0; i_peak1=0; i_peak2=0; i_peak3=0; //int bottom1a, bottom1b; //int bottom2a, bottom2b; //int bottom3a, bottom3b; //int i_bottom1a, i_bottom1b; //int i_bottom2a, i_bottom2b; //int i_bottom3a, i_bottom3b; bottom1a=100000; bottom1b=100000; bottom2a=100000; bottom2b=100000; bottom3a=100000; bottom3b=100000; i_bottom1a=1000; i_bottom1b=1000; i_bottom2a=1000; i_bottom2b=1000; i_bottom3a=1000; i_bottom3b=1000; for(i=0;i<400;i++){ /* Search for highest peak of dataset (2) */ /* Highest Peak */ if(histogramT[i]>peak2){ peak2 = histogramT[i]; i_peak2=i; } } int stop=0; for(i=i_peak2;i>5;i--){ if(((histogramT[i]+histogramT[i-1]+histogramT[i-2]+histogramT[i-3]+histogramT[i-4])/5)<histogramT[i]&&stop==0){ bottom2a = histogramT[i]; i_bottom2a = i; } else if(((histogramT[i]+histogramT[i-1]+histogramT[i-2]+histogramT[i-3]+histogramT[i-4])/5)>histogramT[i]&&stop==0){ /*Search for peaks of datasets (1)*/ peak1 = histogramT[i]; i_peak1=i; stop=1; } } stop=0; for(i=i_peak2;i<395;i++){ if(((histogramT[i]+histogramT[i+1]+histogramT[i+2]+histogramT[i+3]+histogramT[i+4])/5)<histogramT[i]&&stop==0){ bottom2b = histogramT[i]; i_bottom2b = i; } else if(((histogramT[i]+histogramT[i+1]+histogramT[i+2]+histogramT[i+3]+histogramT[i+4])/5)>histogramT[i]&&stop==0){ /*Search for peaks of datasets (3)*/ peak3 = histogramT[i]; i_peak3=i; stop=1; } } /* First histogram lower bound */ for(i=250;i<i_peak1;i++){ if(histogramT[i]<bottom1a){ bottom1a = histogramT[i]; i_bottom1a = i; } } /* First histogram higher bound */ for(i=i_peak2;i>i_peak1;i--){ if(histogramT[i]<=bottom1b){ bottom1b = histogramT[i]; i_bottom1b = i; } } /* Third histogram lower bound */ for(i=i_peak2;i<i_peak3;i++){ if(histogramT[i]<bottom3a){ bottom3a = histogramT[i]; i_bottom3a = i; } } /* Third histogram higher bound */ for(i=399;i>i_peak3;i--){ if(histogramT[i]<bottom3b){ bottom3b = histogramT[i]; i_bottom3b = i; } } // printf("bottom1a: [%i]=>%i\n",i_bottom1a, bottom1a); // printf("peak1: [%i]=>%i\n",i_peak1, peak1); // printf("bottom1b: [%i]=>%i\n",i_bottom1b, bottom1b); // printf("bottom2a: [%i]=>%i\n",i_bottom2a, bottom2a); // printf("peak2: [%i]=>%i\n",i_peak2, peak2); // printf("bottom2b: [%i]=>%i\n",i_bottom2b, bottom2b); // printf("bottom3a: [%i]=>%i\n",i_bottom3a, bottom3a); // printf("peak3: [%i]=>%i\n",i_peak3, peak3); // printf("bottom3b: [%i]=>%i\n",i_bottom3b, bottom3b); rnet_dry=1000.0; dem_dry=2000.0; for(row=0;row<nY;row++){ //NDVI GDALRasterIO(hB1,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); //LAI GDALRasterIO(hB2,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); //LST GDALRasterIO(hB3,GF_Read,0,row,nX,1,l3,nX,1,GDT_Float32,0,0); //ALBEDO GDALRasterIO(hB4,GF_Read,0,row,nX,1,l4,nX,1,GDT_Float32,0,0); //DEM GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private(col, albedo, t0dem, tempk, dem, e0, lin, lout, lnet, kin, rnet, g_0, h0) \ shared(nX, row, geomx, tsw, doy, ta, t0dem_min, t0dem_max, tempk_min, tempk_max, \ tempk_wet, tempk_dry, t0dem_wet, t0dem_dry, \ g0_wet, g0_dry, rnet_wet, rnet_dry, dem_dry, \ row_wet, row_dry, col_wet, col_dry, h0_max, \ i_peak3, i_peak1, h0_min,\ l1, l2, l3, l4, l5) for(col=0;col<nX;col++){ if(l1[col]==-28768||l3[col]==-28768||l3[col]*0.02>200||l4[col]*0.001>0.001){ albedo = l4[col]*0.001; t0dem = l3[col]*0.02-0.00625*l5[col]; tempk = l3[col]*0.02; dem = l5[col]; // Surface emissivity calculations (e0=f(ndvi,lai)) e0=e_0(l1[col]*0.0001,l2[col]*0.1); // printf("e0=%f\n",e0); //Incoming longwave radiation (Lin). To be derived locally at CSU (AU) tsw = 0.75 + 2 * pow(10,-5) * l5[col]; //For Sri Lanka // tsw = 0.65 + 2 * pow(10,-5) * l5[col]; // printf("tsw=%f dem=%f\n", tsw, l5[col]); lin = Lin(tsw, ta); // printf("lin=%f\n", lin); //Outgoing longwave radiation (Lout=f(e0,lst)) lout=Lout(e0,tempk); // printf("lout=%f\n",lout); //Net longwave radiation (Lnet) lnet=Lnet(lout,lin); // printf("lnet=%f\n",lnet); //Solar shortwave incoming irradiance kin=Kin(doy,geomx[3]+geomx[4]*col+geomx[5]*row,tsw); // printf("lat=%f\n",geomx[3]+geomx[4]*col+geomx[5]*row); // printf("kin=%f\n",kin); //Net Radiation (Rnet = f(alb,lnet,kin) rnet=Rnet(l4[col]*0.001,lnet,kin); // printf("Alb=%f\n",l4[col]*0.001); // printf("rnet=%f\n",rnet); //calculation of g_0 = f(rnet,lst,alb,ndvi) g_0=g0(rnet,tempk,l4[col]*0.001,l1[col]*0.0001); // printf("g_0=%f\n",g_0); h0 = rnet - g_0; // printf("h0=%f\n",h0); if(t0dem>250&&t0dem<t0dem_min&&t0dem>274.0&&h0>0.0&&h0<h0_min&&g_0>0.0){ t0dem_min=t0dem; t0dem_wet=t0dem; tempk_min=tempk; tempk_wet=tempk; rnet_wet=rnet; g0_wet=g_0; h0_min=h0; col_wet=col; row_wet=row; } if(tempk>250&&tempk>=((double)i_peak1-5.0)&& tempk<((double)i_peak1+1.0)&&rnet>0.0&&albedo>0.1){ tempk_min=tempk; tempk_wet=tempk; t0dem_min=t0dem; t0dem_wet=t0dem; rnet_wet=rnet; g0_wet=g_0; h0_min=h0; col_wet=col; row_wet=row; } if(t0dem>t0dem_max&&rnet>0.0&&g_0>0.0&&dem<dem_dry&&rnet<rnet_dry){ t0dem_max=t0dem; t0dem_dry=t0dem; tempk_max=tempk; tempk_dry=tempk; rnet_dry=rnet; g0_dry=g_0; dem_dry=dem; col_dry=col; row_dry=row; } if(t0dem>=((double)i_peak3-0.0)&& t0dem<((double)i_peak3+7.0)&& h0>100.0&&h0>h0_max&& g_0>10.0&&rnet<rnet_dry&& albedo>0.35&&dem>0.0&&dem<dem_dry){ tempk_max=tempk; tempk_dry=tempk; t0dem_max=t0dem; t0dem_dry=t0dem; rnet_dry=rnet; g0_dry=g_0; h0_max=h0; dem_dry=dem; col_dry=col; row_dry=row; } }//END OF pafScanlineOut2 > 0.0 } #pragma omp barrier } printf("tempk_min=%f\ntempk_max=%f\n",tempk_min,tempk_max); } printf("row_wet=%d\tcol_wet=%d\n",row_wet,col_wet); printf("row_dry=%d\tcol_dry=%d\n\n",row_dry,col_dry); printf("t0dem_wet = %f\n",t0dem_wet); printf("tempk_wet=%f\n",tempk_wet); printf("g0_wet=%f\n",g0_wet); printf("rnet_wet=%f\n",rnet_wet); printf("LE_wet=%f\n\n",rnet_wet-g0_wet); printf("tempk_dry=%f\n",tempk_dry); printf("dem_dry=%f\n",dem_dry); printf("t0dem_dry=%f\n",t0dem_dry); printf("rnet_dry=%f\n",rnet_dry); printf("g0_dry=%f\n",g0_dry); // calculation of dTair (spreadsheet calculations) dTair(a,b,eto_alf,kc,dem_wet,t0dem_wet,rnet_wet,g0_wet,dem_dry,t0dem_dry,rnet_dry,g0_dry); // printf("***OUT***a[0]=%f\tb[0]=%f\n",a[0],b[0]); // PROCESS METRIC #pragma omp parallel for default(none) \ private(rowcol, e0, tsw, lin, lout, lnet, kin, \ rnet, g_0, z_0m, h0, t0dem, tadem, pmeto, dailyN, \ metricevapfr, metriceta, metricdtair, metrictheta)\ shared(N, rh, u, a, b, doy, ta, u200, rah_0, ustar_0, iteration, \ mat1, mat2, mat3, mat4, mat5, matOut2, matOut1, matOut0, matOut, matLat ) for(rowcol=0;rowcol<N;rowcol++){ if(mat1[rowcol]==-28768||mat3[rowcol]==-28768||mat4[rowcol]<=0|| mat3[rowcol]*0.02<250.0||mat3[rowcol]*0.02>360.0) { matOut[rowcol] = -28768; matOut0[rowcol] = -28768; matOut1[rowcol] = -28768; } else { // METRIC ETa (Allen, 2005) // Surface emissivity calculations (e0=f(ndvi,lai)) e0 = e_0(mat1[rowcol]*0.0001,mat2[rowcol]*0.1); //Incoming longwave radiation (Lin). To be derived locally at CSU //tsw=0.7;//Colombo? tsw = 0.75 + 2 * pow(10,-5)*mat5[rowcol]; lin = Lin(tsw, ta); //Outgoing longwave radiation (Lout=f(e0,lst)) lout = Lout(e0,mat3[rowcol]*0.02); // printf("lout=%f\n",lout); //Net longwave radiation (Lnet) lnet = Lnet(lout,lin); // printf("lnet=%f\n",lnet); //Solar shortwave incoming irradiance kin = Kin(doy,matLat[rowcol],tsw); // printf("kin=%f\n",kin); //Net Radiation (Rnet = f(alb,lnet,kin) rnet = Rnet(mat4[rowcol]*0.001,lnet,kin); // printf("rnet=%f\n",rnet); //calculation of g_0 = f(rnet,lst,alb,ndvi) g_0 = g0(rnet,mat3[rowcol]*0.02,mat4[rowcol]*0.001,mat1[rowcol]*0.0001); // printf("g_0=%f\n",g_0); //Calculation of surface roughness of momentum = f(lai) z_0m = z0m(mat2[rowcol]*0.01); // printf("z_0m=%f\n",z_0m); //Sensible Heat flux Calculations // printf("a[7]=%f,b[7]=%f,mat3*0.02=%f,rah_0=%f,z_0m=%f,ustar_0=%f,mat5=%f,u200=%f\n",a[7],b[7],mat3[rowcol]*0.02,rah_0,z_0m,ustar_0,mat5[rowcol],u200); h0 = metiter(a,b,mat3[rowcol]*0.02,rah_0,z_0m,ustar_0,mat5[rowcol],u200,iteration); // printf("h0=%f\n",h0); dailyN = daily_N(doy, matLat[rowcol]); t0dem = mat3[rowcol]*0.02-0.00625*mat5[rowcol]; tadem = t0dem-(a[iteration]*t0dem+b[iteration]); //Export dTair to raster file metricdtair = (a[iteration]*mat3[rowcol]*0.02)+b[iteration]; matOut1[rowcol] = metricdtair; //ETinst metriceta = ETinst(rnet,g_0,h0,tadem); matOut[rowcol] = metriceta; // printf("eta=%f\t",metriceta); pmeto = EToPM( mat3[rowcol]*0.02, mat5[rowcol], u, rnet*0.0864, rh, 0.6, dailyN); // printf("pmeto=%f\t",pmeto); metricevapfr = metriceta / pmeto; // printf("metricevapfr=%f\n",metricevapfr); if(metricevapfr < 0.0) matOut0[rowcol] = -28768; else matOut0[rowcol] = metricevapfr; if(metricevapfr < 0.0) metrictheta = -28768; else metrictheta = soilmoisture(metricevapfr); matOut2[rowcol] = metrictheta; } } #pragma omp barrier GDALRasterIO(hBOut2,GF_Write,0,0,nX,nY,matOut2,nX,nY,GDT_Float32,0,0); GDALRasterIO(hBOut1,GF_Write,0,0,nX,nY,matOut1,nX,nY,GDT_Float32,0,0); GDALRasterIO(hBOut0,GF_Write,0,0,nX,nY,matOut0,nX,nY,GDT_Float32,0,0); GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,matOut,nX,nY,GDT_Float32,0,0); //free memory close unused files if(mat1 != NULL) free(mat1); if(mat2 != NULL) free(mat2); if(mat3 != NULL) free(mat3); if(mat4 != NULL) free(mat4); if(mat5 != NULL) free(mat5); if(matOut2 != NULL) free(matOut2); if(matOut1 != NULL) free(matOut1); if(matOut0 != NULL) free(matOut0); if(matOut != NULL) free(matOut); if(matLat != NULL) free(matLat); GDALClose(hD1); GDALClose(hD2); GDALClose(hD3); GDALClose(hD4); GDALClose(hD5); GDALClose(hDOut2); GDALClose(hDOut1); GDALClose(hDOut0); GDALClose(hDOut); GDALClose(hDLat); return(EXIT_SUCCESS); }
sp.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB SP code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// //--------------------------------------------------------------------- // program SP //--------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #endif #include "header.h" #include "print_results.h" /* common /global/ */ int grid_points[3], nx2, ny2, nz2; logical timeron; /* common /constants/ */ double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3, dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4, dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt, ce[5][13], dxmax, dymax, dzmax, xxcon1, xxcon2, xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1, dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4, yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1, zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1, dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1, dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2, c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt, dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1, c2dtty1, c2dttz1, comz1, comz4, comz5, comz6, c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16; /* common /fields/ */ double u [KMAX][JMAXP+1][IMAXP+1][5]; double us [KMAX][JMAXP+1][IMAXP+1]; double vs [KMAX][JMAXP+1][IMAXP+1]; double ws [KMAX][JMAXP+1][IMAXP+1]; double qs [KMAX][JMAXP+1][IMAXP+1]; double rho_i [KMAX][JMAXP+1][IMAXP+1]; double speed [KMAX][JMAXP+1][IMAXP+1]; double square [KMAX][JMAXP+1][IMAXP+1]; double rhs [KMAX][JMAXP+1][IMAXP+1][5]; double forcing[KMAX][JMAXP+1][IMAXP+1][5]; /* common /work_1d/ */ double cv [PROBLEM_SIZE]; double rhon[PROBLEM_SIZE]; double rhos[PROBLEM_SIZE]; double rhoq[PROBLEM_SIZE]; double cuf [PROBLEM_SIZE]; double q [PROBLEM_SIZE]; double ue [PROBLEM_SIZE][5]; double buf[PROBLEM_SIZE][5]; #pragma omp threadprivate(cv,rhon,rhos,rhoq,cuf,q,ue,buf) /* common /work_lhs/ */ double lhs [IMAXP+1][IMAXP+1][5]; double lhsp[IMAXP+1][IMAXP+1][5]; double lhsm[IMAXP+1][IMAXP+1][5]; #pragma omp threadprivate(lhs,lhsp,lhsm) //kai int k1,k2,k3,k4,k5,k6,k7,k8,k9,k10, k11, k12, k13, k14, k15, k16; int main(int argc, char *argv[]) { /* //EC:for crash tests //kai // crucial_data(grid_points, "int", 3); // crucial_data(ce,"double", 13*5); crucial_data(u, "double", KMAX*(JMAXP+1)*(IMAXP+1)*5); crucial_data(us, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(vs, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(ws, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(qs, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(rho_i, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(speed, "double", KMAX*(JMAXP+1)*(IMAXP+1)); crucial_data(square, "double", KMAX*(JMAXP+1)*(IMAXP+1)); //crucial_data(forcing, "double", KMAX*(JMAXP+1)*(IMAXP+1)*5); crucial_data(rhs, "double", KMAX*(JMAXP+1)*(IMAXP+1)*5); crucial_data(cv, "double", PROBLEM_SIZE); crucial_data(rhon, "double", PROBLEM_SIZE); crucial_data(rhos, "double", PROBLEM_SIZE); crucial_data(rhoq, "double", PROBLEM_SIZE); //crucial_data(cuf, "double", PROBLEM_SIZE); //crucial_data(q, "double", PROBLEM_SIZE); //crucial_data(ue, "double", (PROBLEM_SIZE)*5); //crucial_data(buf, "double", (PROBLEM_SIZE)*5); crucial_data(lhs, "double", (IMAXP+1)*(IMAXP+1)*5); crucial_data(lhsp, "double", (IMAXP+1)*(IMAXP+1)*5); crucial_data(lhsm, "double", (IMAXP+1)*(IMAXP+1)*5); //int k1,k2,k3,k4,k5,k6,k7,k8,k9,k10, k11; consistent_data(&k1, "int", 1); consistent_data(&k2, "int", 1); consistent_data(&k3, "int", 1); consistent_data(&k4, "int", 1); consistent_data(&k5, "int", 1); consistent_data(&k6, "int", 1); consistent_data(&k7, "int", 1); consistent_data(&k8, "int", 1); consistent_data(&k9, "int", 1); consistent_data(&k10, "int", 1); consistent_data(&k11, "int", 1); consistent_data(&k12, "int", 1); consistent_data(&k13, "int", 1); consistent_data(&k14, "int", 1); consistent_data(&k15, "int", 1); consistent_data(&k16, "int", 1); */ int i, niter, step, n3; double mflops, t, tmax, trecs[t_last+1]; logical verified; char Class; char *t_names[t_last+1]; //--------------------------------------------------------------------- // Read input file (if it exists), else take // defaults from parameters //--------------------------------------------------------------------- FILE *fp; if ((fp = fopen("timer.flag", "r")) != NULL) { timeron = true; t_names[t_total] = "total"; t_names[t_rhsx] = "rhsx"; t_names[t_rhsy] = "rhsy"; t_names[t_rhsz] = "rhsz"; t_names[t_rhs] = "rhs"; t_names[t_xsolve] = "xsolve"; t_names[t_ysolve] = "ysolve"; t_names[t_zsolve] = "zsolve"; t_names[t_rdis1] = "redist1"; t_names[t_rdis2] = "redist2"; t_names[t_tzetar] = "tzetar"; t_names[t_ninvr] = "ninvr"; t_names[t_pinvr] = "pinvr"; t_names[t_txinvr] = "txinvr"; t_names[t_add] = "add"; fclose(fp); } else { timeron = false; } printf("\n\n NAS Parallel Benchmarks (NPB3.3-OMP-C) - SP Benchmark\n\n"); if ((fp = fopen("inputsp.data", "r")) != NULL) { int result; printf(" Reading from input file inputsp.data\n"); result = fscanf(fp, "%d", &niter); while (fgetc(fp) != '\n'); result = fscanf(fp, "%lf", &dt); while (fgetc(fp) != '\n'); result = fscanf(fp, "%d%d%d", &grid_points[0], &grid_points[1], &grid_points[2]); fclose(fp); } else { printf(" No input file inputsp.data. Using compiled defaults\n"); niter = NITER_DEFAULT; dt = DT_DEFAULT; grid_points[0] = PROBLEM_SIZE; grid_points[1] = PROBLEM_SIZE; grid_points[2] = PROBLEM_SIZE; } printf(" Size: %4dx%4dx%4d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Iterations: %4d dt: %11.7f\n", niter, dt); printf(" Number of available threads: %5d\n", omp_get_max_threads()); printf("\n"); if ((grid_points[0] > IMAX) || (grid_points[1] > JMAX) || (grid_points[2] > KMAX) ) { printf(" %d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Problem size too big for compiled array sizes\n"); return 0; } nx2 = grid_points[0] - 2; ny2 = grid_points[1] - 2; nz2 = grid_points[2] - 2; set_constants(); for (i = 1; i <= t_last; i++) { timer_clear(i); } exact_rhs(); initialize(); //--------------------------------------------------------------------- // do one time step to touch all code, and reinitialize //--------------------------------------------------------------------- adi(); initialize(); for (i = 1; i <= t_last; i++) { timer_clear(i); } timer_start(1); //kai consistent_data(&step, "int", 1); flush_whole_cache(); //start_crash(); for (step = 1; step <= niter; step++) { if ((step % 20) == 0 || step == 1) { printf(" Time step %4d\n", step); } //if(step == 5) //start_crash(); //if(step == 11) //end_crash(); // if (step != 2) { adi(); //EasyCrash: critical data objs: u, us, vs, ws, qs, rho\_i, speed, square //EasyCrash: candidates: u, us, vs, ws, qs, rho\_i, speed,square, rhs, cv, rhon, rhos, rhoq, lhs, lhsp, lhsm /*//checkpoint checkpoint(u, KMAX*(JMAXP+1)*(IMAXP+1)*5*sizeof(double)); checkpoint(us, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); checkpoint(vs, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); checkpoint(ws, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); checkpoint(qs, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); checkpoint(rho_i, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); checkpoint(speed, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); checkpoint(square, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); checkpoint(rhs, KMAX*(JMAXP+1)*(IMAXP+1)*5*sizeof(double)); checkpoint(cv, PROBLEM_SIZE*sizeof(double)); checkpoint(rhon, PROBLEM_SIZE*sizeof(double)); checkpoint(rhos, PROBLEM_SIZE*sizeof(double)); checkpoint(rhoq, PROBLEM_SIZE*sizeof(double)); checkpoint(lhs, (JMAXP+1)*(IMAXP+1)*5*sizeof(double)); checkpoint(lhsp, (JMAXP+1)*(IMAXP+1)*5*sizeof(double)); checkpoint(lhsm, (JMAXP+1)*(IMAXP+1)*5*sizeof(double)); checkpoint(&step, sizeof(step)); mfence(); // */ /* EC(u, KMAX*(JMAXP+1)*(IMAXP+1)*5*sizeof(double)); EC(us, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); EC(vs, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); EC(ws, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); EC(qs, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); EC(rho_i, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); EC(speed, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); EC(square, KMAX*(JMAXP+1)*(IMAXP+1)*sizeof(double)); EC(rhs, KMAX*(JMAXP+1)*(IMAXP+1)*5*sizeof(double)); mfence(); */ } //kai //end_crash(); timer_stop(1); tmax = timer_read(1); verify(niter, &Class, &verified); if (tmax != 0.0) { n3 = grid_points[0]*grid_points[1]*grid_points[2]; t = (grid_points[0]+grid_points[1]+grid_points[2])/3.0; mflops = (881.174 * (double)n3 - 4683.91 * (t * t) + 11484.5 * t - 19272.4) * (double)niter / (tmax*1000000.0); } else { mflops = 0.0; } print_results("SP", Class, grid_points[0], grid_points[1], grid_points[2], niter, tmax, mflops, " floating point", verified, NPBVERSION,COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, "(none)"); //--------------------------------------------------------------------- // More timers //--------------------------------------------------------------------- if (timeron) { for (i = 1; i <= t_last; i++) { trecs[i] = timer_read(i); } if (tmax == 0.0) tmax = 1.0; printf(" SECTION Time (secs)\n"); for (i = 1; i <= t_last; i++) { printf(" %-8s:%9.3f (%6.2f%%)\n", t_names[i], trecs[i], trecs[i]*100./tmax); if (i == t_rhs) { t = trecs[t_rhsx] + trecs[t_rhsy] + trecs[t_rhsz]; printf(" --> %8s:%9.3f (%6.2f%%)\n", "sub-rhs", t, t*100./tmax); t = trecs[t_rhs] - t; printf(" --> %8s:%9.3f (%6.2f%%)\n", "rest-rhs", t, t*100./tmax); } else if (i == t_zsolve) { t = trecs[t_zsolve] - trecs[t_rdis1] - trecs[t_rdis2]; printf(" --> %8s:%9.3f (%6.2f%%)\n", "sub-zsol", t, t*100./tmax); } else if (i == t_rdis2) { t = trecs[t_rdis1] + trecs[t_rdis2]; printf(" --> %8s:%9.3f (%6.2f%%)\n", "redist", t, t*100./tmax); } } } return 0; }
decorate.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD EEEEE CCCC OOO RRRR AAA TTTTT EEEEE % % D D E C O O R R A A T E % % D D EEE C O O RRRR AAAAA T EEE % % D D E C O O R R A A T E % % DDDD EEEEE CCCC OOO R R A A T EEEEE % % % % % % MagickCore Image Decoration Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/color-private.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/decorate.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/quantum.h" #include "magick/resource_.h" #include "magick/thread-private.h" #include "magick/transform.h" /* Define declarations. */ #define AccentuateModulate ScaleCharToQuantum(80) #define HighlightModulate ScaleCharToQuantum(125) #define ShadowModulate ScaleCharToQuantum(135) #define DepthModulate ScaleCharToQuantum(185) #define TroughModulate ScaleCharToQuantum(110) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B o r d e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BorderImage() surrounds the image with a border of the color defined by % the bordercolor member of the image structure. The width and height % of the border are defined by the corresponding members of the border_info % structure. % % The format of the BorderImage method is: % % Image *BorderImage(const Image *image,const RectangleInfo *border_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o border_info: Define the width and height of the border. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BorderImage(const Image *image, const RectangleInfo *border_info,ExceptionInfo *exception) { Image *border_image, *clone_image; FrameInfo frame_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(border_info != (RectangleInfo *) NULL); frame_info.width=image->columns+(border_info->width << 1); frame_info.height=image->rows+(border_info->height << 1); frame_info.x=(ssize_t) border_info->width; frame_info.y=(ssize_t) border_info->height; frame_info.inner_bevel=0; frame_info.outer_bevel=0; clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); clone_image->matte_color=image->border_color; border_image=FrameImage(clone_image,&frame_info,exception); clone_image=DestroyImage(clone_image); if (border_image != (Image *) NULL) border_image->matte_color=image->matte_color; return(border_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F r a m e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FrameImage() adds a simulated three-dimensional border around the image. % The color of the border is defined by the matte_color member of image. % Members width and height of frame_info specify the border width of the % vertical and horizontal sides of the frame. Members inner and outer % indicate the width of the inner and outer shadows of the frame. % % The format of the FrameImage method is: % % Image *FrameImage(const Image *image,const FrameInfo *frame_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o frame_info: Define the width and height of the frame and its bevels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *FrameImage(const Image *image,const FrameInfo *frame_info, ExceptionInfo *exception) { #define FrameImageTag "Frame/Image" CacheView *image_view, *frame_view; Image *frame_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket accentuate, border, highlight, matte, shadow, trough; register ssize_t x; size_t bevel_width, height, width; ssize_t y; /* Check frame geometry. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(frame_info != (FrameInfo *) NULL); if ((frame_info->outer_bevel < 0) || (frame_info->inner_bevel < 0)) ThrowImageException(OptionError,"FrameIsLessThanImageSize"); bevel_width=(size_t) (frame_info->outer_bevel+frame_info->inner_bevel); x=(ssize_t) frame_info->width-frame_info->x-bevel_width; y=(ssize_t) frame_info->height-frame_info->y-bevel_width; if ((x < (ssize_t) image->columns) || (y < (ssize_t) image->rows)) ThrowImageException(OptionError,"FrameIsLessThanImageSize"); /* Initialize framed image attributes. */ frame_image=CloneImage(image,frame_info->width,frame_info->height,MagickTrue, exception); if (frame_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(frame_image,DirectClass) == MagickFalse) { InheritException(exception,&frame_image->exception); frame_image=DestroyImage(frame_image); return((Image *) NULL); } if ((IsPixelGray(&frame_image->border_color) == MagickFalse) && (IsGrayColorspace(frame_image->colorspace) != MagickFalse)) (void) SetImageColorspace(frame_image,sRGBColorspace); if ((frame_image->border_color.opacity != OpaqueOpacity) && (frame_image->matte == MagickFalse)) (void) SetImageAlphaChannel(frame_image,OpaqueAlphaChannel); frame_image->page=image->page; if ((image->page.width != 0) && (image->page.height != 0)) { frame_image->page.width+=frame_image->columns-image->columns; frame_image->page.height+=frame_image->rows-image->rows; } /* Initialize 3D effects color. */ GetMagickPixelPacket(frame_image,&matte); matte.colorspace=sRGBColorspace; SetMagickPixelPacket(frame_image,&image->matte_color,(IndexPacket *) NULL, &matte); GetMagickPixelPacket(frame_image,&border); border.colorspace=sRGBColorspace; SetMagickPixelPacket(frame_image,&image->border_color,(IndexPacket *) NULL, &border); GetMagickPixelPacket(frame_image,&accentuate); accentuate.red=(MagickRealType) (QuantumScale*((QuantumRange- AccentuateModulate)*matte.red+(QuantumRange*AccentuateModulate))); accentuate.green=(MagickRealType) (QuantumScale*((QuantumRange- AccentuateModulate)*matte.green+(QuantumRange*AccentuateModulate))); accentuate.blue=(MagickRealType) (QuantumScale*((QuantumRange- AccentuateModulate)*matte.blue+(QuantumRange*AccentuateModulate))); accentuate.opacity=matte.opacity; GetMagickPixelPacket(frame_image,&highlight); highlight.red=(MagickRealType) (QuantumScale*((QuantumRange- HighlightModulate)*matte.red+(QuantumRange*HighlightModulate))); highlight.green=(MagickRealType) (QuantumScale*((QuantumRange- HighlightModulate)*matte.green+(QuantumRange*HighlightModulate))); highlight.blue=(MagickRealType) (QuantumScale*((QuantumRange- HighlightModulate)*matte.blue+(QuantumRange*HighlightModulate))); highlight.opacity=matte.opacity; GetMagickPixelPacket(frame_image,&shadow); shadow.red=QuantumScale*matte.red*ShadowModulate; shadow.green=QuantumScale*matte.green*ShadowModulate; shadow.blue=QuantumScale*matte.blue*ShadowModulate; shadow.opacity=matte.opacity; GetMagickPixelPacket(frame_image,&trough); trough.red=QuantumScale*matte.red*TroughModulate; trough.green=QuantumScale*matte.green*TroughModulate; trough.blue=QuantumScale*matte.blue*TroughModulate; trough.opacity=matte.opacity; if (image->colorspace == CMYKColorspace) { ConvertRGBToCMYK(&matte); ConvertRGBToCMYK(&border); ConvertRGBToCMYK(&accentuate); ConvertRGBToCMYK(&highlight); ConvertRGBToCMYK(&shadow); ConvertRGBToCMYK(&trough); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); frame_view=AcquireAuthenticCacheView(frame_image,exception); height=(size_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+ frame_info->inner_bevel); if (height != 0) { register IndexPacket *magick_restrict frame_indexes; register ssize_t x; register PixelPacket *magick_restrict q; /* Draw top of ornamental border. */ q=QueueCacheViewAuthenticPixels(frame_view,0,0,frame_image->columns, height,exception); frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view); if (q != (PixelPacket *) NULL) { /* Draw top of ornamental border. */ for (y=0; y < (ssize_t) frame_info->outer_bevel; y++) { for (x=0; x < (ssize_t) (frame_image->columns-y); x++) { if (x < y) SetPixelPacket(frame_image,&highlight,q,frame_indexes); else SetPixelPacket(frame_image,&accentuate,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) frame_image->columns; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } for (y=0; y < (ssize_t) (frame_info->y-bevel_width); y++) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_image->columns-2*frame_info->outer_bevel; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } for (y=0; y < (ssize_t) frame_info->inner_bevel; y++) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } width=image->columns+((size_t) frame_info->inner_bevel << 1)- y; for (x=0; x < (ssize_t) width; x++) { if (x < y) SetPixelPacket(frame_image,&shadow,q,frame_indexes); else SetPixelPacket(frame_image,&trough,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_info->width-frame_info->x-image->columns-bevel_width; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } (void) SyncCacheViewAuthenticPixels(frame_view,exception); } } /* Draw sides of ornamental border. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,frame_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict frame_indexes; register ssize_t x; register PixelPacket *magick_restrict q; /* Initialize scanline with matte color. */ if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(frame_view,0,frame_info->y+y, frame_image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view); for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->inner_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } /* Set frame interior pixels. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelPacket(frame_image,&border,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->inner_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_info->width-frame_info->x-image->columns-bevel_width; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } if (SyncCacheViewAuthenticPixels(frame_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,FrameImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } height=(size_t) (frame_info->inner_bevel+frame_info->height- frame_info->y-image->rows-bevel_width+frame_info->outer_bevel); if (height != 0) { register IndexPacket *magick_restrict frame_indexes; register ssize_t x; register PixelPacket *magick_restrict q; /* Draw bottom of ornamental border. */ q=QueueCacheViewAuthenticPixels(frame_view,0,(ssize_t) (frame_image->rows- height),frame_image->columns,height,exception); if (q != (PixelPacket *) NULL) { /* Draw bottom of ornamental border. */ frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view); for (y=frame_info->inner_bevel-1; y >= 0; y--) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < y; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++) { if (x >= (ssize_t) (image->columns+2*frame_info->inner_bevel-y)) SetPixelPacket(frame_image,&highlight,q,frame_indexes); else SetPixelPacket(frame_image,&accentuate,q,frame_indexes); q++; frame_indexes++; } width=frame_info->width-frame_info->x-image->columns-bevel_width; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } height=frame_info->height-frame_info->y-image->rows-bevel_width; for (y=0; y < (ssize_t) height; y++) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_image->columns-2*frame_info->outer_bevel; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } for (y=frame_info->outer_bevel-1; y >= 0; y--) { for (x=0; x < y; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) frame_image->columns; x++) { if (x >= (ssize_t) (frame_image->columns-y)) SetPixelPacket(frame_image,&shadow,q,frame_indexes); else SetPixelPacket(frame_image,&trough,q,frame_indexes); q++; frame_indexes++; } } (void) SyncCacheViewAuthenticPixels(frame_view,exception); } } frame_view=DestroyCacheView(frame_view); image_view=DestroyCacheView(image_view); x=(ssize_t) (frame_info->outer_bevel+(frame_info->x-bevel_width)+ frame_info->inner_bevel); y=(ssize_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+ frame_info->inner_bevel); if (status != MagickFalse) status=CompositeImage(frame_image,image->compose,image,x,y); if (status == MagickFalse) frame_image=DestroyImage(frame_image); return(frame_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RaiseImage() creates a simulated three-dimensional button-like effect % by lightening and darkening the edges of the image. Members width and % height of raise_info define the width of the vertical and horizontal % edge of the effect. % % The format of the RaiseImage method is: % % MagickBooleanType RaiseImage(const Image *image, % const RectangleInfo *raise_info,const MagickBooleanType raise) % % A description of each parameter follows: % % o image: the image. % % o raise_info: Define the width and height of the raise area. % % o raise: A value other than zero creates a 3-D raise effect, % otherwise it has a lowered effect. % */ MagickExport MagickBooleanType RaiseImage(Image *image, const RectangleInfo *raise_info,const MagickBooleanType raise) { #define AccentuateFactor ScaleCharToQuantum(135) #define HighlightFactor ScaleCharToQuantum(190) #define ShadowFactor ScaleCharToQuantum(190) #define RaiseImageTag "Raise/Image" #define TroughFactor ScaleCharToQuantum(135) CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; Quantum foreground, background; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(raise_info != (RectangleInfo *) NULL); exception=(&image->exception); if ((image->columns <= (raise_info->width << 1)) || (image->rows <= (raise_info->height << 1))) ThrowBinaryException(OptionError,"ImageSizeMustExceedBevelWidth", image->filename); foreground=QuantumRange; background=(Quantum) 0; if (raise == MagickFalse) { foreground=(Quantum) 0; background=QuantumRange; } if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); /* Raise image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,raise_info->height,1) #endif for (y=0; y < (ssize_t) raise_info->height; y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < y; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); q++; } for ( ; x < (ssize_t) (image->columns-y); x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*AccentuateFactor+(MagickRealType) foreground* (QuantumRange-AccentuateFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*AccentuateFactor+(MagickRealType) foreground* (QuantumRange-AccentuateFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*AccentuateFactor+(MagickRealType) foreground* (QuantumRange-AccentuateFactor)))); q++; } for ( ; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows-2*raise_info->height,1) #endif for (y=(ssize_t) raise_info->height; y < (ssize_t) (image->rows-raise_info->height); y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) raise_info->width; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); q++; } for ( ; x < (ssize_t) (image->columns-raise_info->width); x++) q++; for ( ; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows-raise_info->height,1) #endif for (y=(ssize_t) (image->rows-raise_info->height); y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) (image->rows-y); x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); q++; } for ( ; x < (ssize_t) (image->columns-(image->rows-y)); x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*TroughFactor+(MagickRealType) background* (QuantumRange-TroughFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*TroughFactor+(MagickRealType) background* (QuantumRange-TroughFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*TroughFactor+(MagickRealType) background* (QuantumRange-TroughFactor)))); q++; } for ( ; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
GB_binop__bshift_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__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_01__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_02__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_03__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_int32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bshift_int32) // C+=b function (dense accum): GB (_Cdense_accumb__bshift_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_int32) // C=scalar+B GB (_bind1st__bshift_int32) // C=scalar+B' GB (_bind1st_tran__bshift_int32) // C=A+scalar GB (_bind2nd__bshift_int32) // C=A'+scalar GB (_bind2nd_tran__bshift_int32) // C type: int32_t // A type: int32_t // B,b type: int8_t // BinaryOp: cij = GB_bitshift_int32 (aij, bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 0 // 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 \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_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_bitshift_int32 (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BSHIFT || GxB_NO_INT32 || GxB_NO_BSHIFT_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bshift_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__bshift_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__bshift_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 int8_t int8_t bwork = (*((int8_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, 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 } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bshift_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 or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__bshift_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_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__bshift_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_03__bshift_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_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__bshift_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__bshift_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)) ; int8_t *Bx = (int8_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 ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_bitshift_int32 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bshift_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 ; int8_t y = (*((int8_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_bitshift_int32 (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) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_bitshift_int32 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__bshift_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 \ int8_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_bitshift_int32 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__bshift_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 int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
statistic.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical 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/accelerate-private.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.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/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.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/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/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.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/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.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/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImage method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ typedef struct _PixelChannels { double channel[MaxPixelChannels]; } PixelChannels; static PixelChannels **DestroyPixelThreadSet(const Image *images, PixelChannels **pixels) { register ssize_t i; size_t rows; assert(pixels != (PixelChannels **) NULL); rows=MagickMax(GetImageListLength(images),(size_t) GetMagickResourceLimit(ThreadResource)); for (i=0; i < (ssize_t) rows; i++) if (pixels[i] != (PixelChannels *) NULL) pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]); pixels=(PixelChannels **) RelinquishMagickMemory(pixels); return(pixels); } static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_images, rows; number_images=GetImageListLength(images); rows=MagickMax(number_images,(size_t) GetMagickResourceLimit(ThreadResource)); pixels=(PixelChannels **) AcquireQuantumMemory(rows,sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,rows*sizeof(*pixels)); columns=MagickMax(number_images,MaxPixelChannels); for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) rows; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(images,pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const PixelChannels *color_1, *color_2; double distance; register ssize_t i; color_1=(const PixelChannels *) x; color_2=(const PixelChannels *) y; distance=0.0; for (i=0; i < MaxPixelChannels; i++) distance+=color_1->channel[i]-(double) color_2->channel[i]; return(distance < 0 ? -1 : distance > 0 ? 1 : 0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel, const MagickEvaluateOperator op,const double value) { double result; register ssize_t i; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(double) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(double) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() that returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(double) ((ssize_t) pixel & (ssize_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,GaussianNoise, value); break; } case ImpulseNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise, value); break; } case InverseLogEvaluateOperator: { result=(QuantumRange*pow((value+1.0),QuantumScale*pixel)-1.0)* PerceptibleReciprocal(value); break; } case LaplacianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(double) pixel; for (i=0; i < (ssize_t) value; i++) result*=2.0; break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+ 1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(double) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(double) (pixel+value); break; } case MedianEvaluateOperator: { result=(double) (pixel+value); break; } case MinEvaluateOperator: { result=(double) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(double) (value*pixel); break; } case OrEvaluateOperator: { result=(double) ((ssize_t) pixel | (ssize_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise, value); break; } case PowEvaluateOperator: { if (pixel < 0) result=(double) -(QuantumRange*pow((double) -(QuantumScale*pixel), (double) value)); else result=(double) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(double) pixel; for (i=0; i < (ssize_t) value; i++) result/=2.0; break; } case RootMeanSquareEvaluateOperator: { result=((double) pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(double) (pixel-value); break; } case SumEvaluateOperator: { result=(double) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(double) (((double) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise, value); break; } case XorEvaluateOperator: { result=(double) ((ssize_t) pixel ^ (ssize_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, rows; q=images; columns=images->columns; rows=images->rows; for (p=images; p != (Image *) NULL; p=p->next) { if (p->number_channels > q->number_channels) q=p; if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view, **image_view; const Image *next; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict evaluate_pixels; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t j, y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif 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=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } image_view=(CacheView **) AcquireQuantumMemory(number_images, sizeof(*image_view)); if (image_view == (CacheView **) NULL) { image=DestroyImage(image); evaluate_pixels=DestroyPixelThreadSet(images,evaluate_pixels); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return(image); } next=images; for (j=0; j < (ssize_t) number_images; j++) { image_view[j]=AcquireVirtualCacheView(next,exception); next=GetNextImageInList(next); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Image *next; const int id = GetOpenMPThreadId(); const Quantum **p; register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; register ssize_t x; ssize_t j; if (status == MagickFalse) continue; p=(const Quantum **) AcquireQuantumMemory(number_images,sizeof(*p)); if (p == (const Quantum **) NULL) { status=MagickFalse; (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", images->filename); continue; } for (j=0; j < (ssize_t) number_images; j++) { p[j]=GetCacheViewVirtualPixels(image_view[j],0,y,image->columns,1, exception); if (p[j] == (const Quantum *) NULL) break; } q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if ((j < (ssize_t) number_images) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; next=images; for (j=0; j < (ssize_t) number_images; j++) { for (i=0; i < MaxPixelChannels; i++) evaluate_pixel[j].channel[i]=0.0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait evaluate_traits = GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0)) continue; evaluate_pixel[j].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(next,channel,p[j]),op, evaluate_pixel[j].channel[i]); } p[j]+=GetPixelChannels(next); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0)) continue; q[i]=ClampToQuantum(evaluate_pixel[number_images/2].channel[i]); } q+=GetPixelChannels(image); } p=(const Quantum **) RelinquishMagickMemory(p); if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Image *next; const int id = GetOpenMPThreadId(); const Quantum **p; register ssize_t i, x; register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; p=(const Quantum **) AcquireQuantumMemory(number_images,sizeof(*p)); if (p == (const Quantum **) NULL) { status=MagickFalse; (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", images->filename); continue; } for (j=0; j < (ssize_t) number_images; j++) { p[j]=GetCacheViewVirtualPixels(image_view[j],0,y,image->columns,1, exception); if (p[j] == (const Quantum *) NULL) break; } q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if ((j < (ssize_t) number_images) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) evaluate_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait evaluate_traits = GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[x].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(next,channel,p[j]),j == 0 ? AddEvaluateOperator : op,evaluate_pixel[x].channel[i]); } p[j]+=GetPixelChannels(next); } next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { switch (op) { case MeanEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]/=(double) number_images; break; } case MultiplyEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) evaluate_pixel[x].channel[i]*=QuantumScale; } break; } case RootMeanSquareEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]=sqrt(evaluate_pixel[x].channel[i]/ number_images); break; } default: break; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0)) continue; q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]); } q+=GetPixelChannels(image); } p=(const Quantum **) RelinquishMagickMemory(p); if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } for (j=0; j < (ssize_t) number_images; j++) image_view[j]=DestroyCacheView(image_view[j]); image_view=(CacheView **) RelinquishMagickMemory(image_view); evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(images,evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif 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); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); 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++) { double result; register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; if ((traits & UpdatePixelTrait) == 0) continue; result=ApplyEvaluateOperator(random_info[id],q[i],op,value); if (op == MeanEvaluateOperator) result/=2.0; q[i]=ClampToQuantum(result); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EvaluateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImage method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { double result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+ c1*x^2+c2*x+c3). */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel+parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { double amplitude, bias, frequency, phase; /* Sinusoid: frequency, phase, amplitude, bias. */ frequency=(number_parameters >= 1) ? parameters[0] : 1.0; phase=(number_parameters >= 2) ? parameters[1] : 0.0; amplitude=(number_parameters >= 3) ? parameters[2] : 0.5; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (QuantumRange*(amplitude*sin((double) (2.0* MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias)); break; } case ArcsinFunction: { double bias, center, range, width; /* Arcsin (peged at range limits for invalid results): width, center, range, and bias. */ width=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=2.0/width*(QuantumScale*pixel-center); if ( result <= -1.0 ) result=bias-range/2.0; else if (result >= 1.0) result=bias+range/2.0; else result=(double) (range/MagickPI*asin((double) result)+bias); result*=QuantumRange; break; } case ArctanFunction: { double center, bias, range, slope; /* Arctan: slope, center, range, and bias. */ slope=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (MagickPI*slope*(QuantumScale*pixel-center)); result=(double) (QuantumRange*(range/MagickPI*atan((double) result)+bias)); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; 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); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateFunctionImage(image,function,number_parameters,parameters, exception) != MagickFalse) return(MagickTrue); #endif if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,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++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyFunction(q[i],function,number_parameters,parameters, exception); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,FunctionImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageEntropy() returns the entropy of one or more image channels. % % The format of the GetImageEntropy method is: % % MagickBooleanType GetImageEntropy(const Image *image,double *entropy, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *entropy=channel_statistics[CompositePixelChannel].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtrema() returns the extrema of one or more image channels. % % The format of the GetImageExtrema method is: % % MagickBooleanType GetImageExtrema(const Image *image,size_t *minima, % size_t *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageRange(image,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageKurtosis() returns the kurtosis and skewness of one or more image % channels. % % The format of the GetImageKurtosis method is: % % MagickBooleanType GetImageKurtosis(const Image *image,double *kurtosis, % double *skewness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *kurtosis=channel_statistics[CompositePixelChannel].kurtosis; *skewness=channel_statistics[CompositePixelChannel].skewness; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMean() returns the mean and standard deviation of one or more image % channels. % % The format of the GetImageMean method is: % % MagickBooleanType GetImageMean(const Image *image,double *mean, % double *standard_deviation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *mean=channel_statistics[CompositePixelChannel].mean; *standard_deviation= channel_statistics[CompositePixelChannel].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageMoments method is: % % ChannelMoments *GetImageMoments(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. % */ static size_t GetImageChannels(const Image *image) { register ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; channels++; } return((size_t) (channels == 0 ? 1 : channels)); } MagickExport ChannelMoments *GetImageMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 CacheView *image_view; ChannelMoments *channel_moments; double M00[MaxPixelChannels+1], M01[MaxPixelChannels+1], M02[MaxPixelChannels+1], M03[MaxPixelChannels+1], M10[MaxPixelChannels+1], M11[MaxPixelChannels+1], M12[MaxPixelChannels+1], M20[MaxPixelChannels+1], M21[MaxPixelChannels+1], M22[MaxPixelChannels+1], M30[MaxPixelChannels+1]; PointInfo centroid[MaxPixelChannels+1]; ssize_t channel, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_moments=(ChannelMoments *) AcquireQuantumMemory(MaxPixelChannels+1, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,(MaxPixelChannels+1)* sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M00[channel]+=QuantumScale*p[i]; M00[MaxPixelChannels]+=QuantumScale*p[i]; M10[channel]+=x*QuantumScale*p[i]; M10[MaxPixelChannels]+=x*QuantumScale*p[i]; M01[channel]+=y*QuantumScale*p[i]; M01[MaxPixelChannels]+=y*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute center of mass (centroid). */ centroid[channel].x=M10[channel]*PerceptibleReciprocal(M00[channel]); centroid[channel].y=M01[channel]*PerceptibleReciprocal(M00[channel]); } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M11[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M11[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M20[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M20[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M02[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M02[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M21[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M21[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M22[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M22[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M30[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M30[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M03[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M03[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } M00[MaxPixelChannels]/=GetImageChannels(image); M01[MaxPixelChannels]/=GetImageChannels(image); M02[MaxPixelChannels]/=GetImageChannels(image); M03[MaxPixelChannels]/=GetImageChannels(image); M10[MaxPixelChannels]/=GetImageChannels(image); M11[MaxPixelChannels]/=GetImageChannels(image); M12[MaxPixelChannels]/=GetImageChannels(image); M20[MaxPixelChannels]/=GetImageChannels(image); M21[MaxPixelChannels]/=GetImageChannels(image); M22[MaxPixelChannels]/=GetImageChannels(image); M30[MaxPixelChannels]/=GetImageChannels(image); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0* PerceptibleReciprocal(M00[channel]))*((M20[channel]+M02[channel])+ sqrt(4.0*M11[channel]*M11[channel]+(M20[channel]-M02[channel])* (M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0* PerceptibleReciprocal(M00[channel]))*((M20[channel]+M02[channel])- sqrt(4.0*M11[channel]*M11[channel]+(M20[channel]-M02[channel])* (M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(1.0/2.0*atan(2.0* M11[channel]*PerceptibleReciprocal(M20[channel]-M02[channel]))); if (fabs(M11[channel]) < 0.0) { if ((fabs(M20[channel]-M02[channel]) >= 0.0) && ((M20[channel]-M02[channel]) < 0.0)) channel_moments[channel].ellipse_angle+=90.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) >= 0.0) { if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } } else if ((fabs(M20[channel]-M02[channel]) >= 0.0) && ((M20[channel]-M02[channel]) < 0.0)) channel_moments[channel].ellipse_angle+=90.0; channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y* channel_moments[channel].ellipse_axis.y*PerceptibleReciprocal( channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.x))); channel_moments[channel].ellipse_intensity=M00[channel]* PerceptibleReciprocal(MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(1.0+1.0)/2.0)); M20[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(2.0+0.0)/2.0)); M02[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(0.0+2.0)/2.0)); M21[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(2.0+1.0)/2.0)); M12[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(1.0+2.0)/2.0)); M22[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(2.0+2.0)/2.0)); M30[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(3.0+0.0)/2.0)); M03[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(0.0+3.0)/2.0)); M00[channel]=1.0; } image_view=DestroyCacheView(image_view); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].invariant[0]=M20[channel]+M02[channel]; channel_moments[channel].invariant[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].invariant[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].invariant[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].invariant[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].invariant[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[7]=M11[channel]*((M30[channel]+ M12[channel])*(M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImagePerceptualHash method is: % % ChannelPerceptualHash *GetImagePerceptualHash(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. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, ExceptionInfo *exception) { ChannelPerceptualHash *perceptual_hash; char *colorspaces, *q; const char *artifact; MagickBooleanType status; register char *p; register ssize_t i; perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( MaxPixelChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); artifact=GetImageArtifact(image,"phash:colorspaces"); if (artifact != NULL) colorspaces=AcquireString(artifact); else colorspaces=AcquireString("sRGB,HCLp"); perceptual_hash[0].number_colorspaces=0; perceptual_hash[0].number_channels=0; q=colorspaces; for (i=0; (p=StringToken(",",&q)) != (char *) NULL; i++) { ChannelMoments *moments; Image *hash_image; size_t j; ssize_t channel, colorspace; if (i >= MaximumNumberOfPerceptualColorspaces) break; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,p); if (colorspace < 0) break; perceptual_hash[0].colorspace[i]=(ColorspaceType) colorspace; hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) break; hash_image->depth=8; status=TransformImageColorspace(hash_image,(ColorspaceType) colorspace, exception); if (status == MagickFalse) break; moments=GetImageMoments(hash_image,exception); perceptual_hash[0].number_colorspaces++; perceptual_hash[0].number_channels+=GetImageChannels(hash_image); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) break; for (channel=0; channel <= MaxPixelChannels; channel++) for (j=0; j < MaximumNumberOfImageMoments; j++) perceptual_hash[channel].phash[i][j]= (-MagickLog10(moments[channel].invariant[j])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); } colorspaces=DestroyString(colorspaces); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageRange() returns the range of one or more image channels. % % The format of the GetImageRange method is: % % MagickBooleanType GetImageRange(const Image *image,double *minima, % double *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima, double *maxima,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType initialize, 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; initialize=MagickTrue; *maxima=0.0; *minima=0.0; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,initialize) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double row_maxima = 0.0, row_minima = 0.0; MagickBooleanType row_initialize; register const Quantum *magick_restrict 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; } row_initialize=MagickTrue; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (row_initialize != MagickFalse) { row_minima=(double) p[i]; row_maxima=(double) p[i]; row_initialize=MagickFalse; } else { if ((double) p[i] < row_minima) row_minima=(double) p[i]; if ((double) p[i] > row_maxima) row_maxima=(double) p[i]; } } p+=GetPixelChannels(image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageRange) #endif { if (initialize != MagickFalse) { *minima=row_minima; *maxima=row_maxima; initialize=MagickFalse; } else { if (row_minima < *minima) *minima=row_minima; if (row_maxima > *maxima) *maxima=row_maxima; } } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageStatistics() returns statistics for each channel in the image. The % statistics include the channel depth, its minima, maxima, mean, standard % deviation, kurtosis and skewness. You can access the red channel mean, for % example, like this: % % channel_statistics=GetImageStatistics(image,exception); % red_mean=channel_statistics[RedPixelChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageStatistics method is: % % ChannelStatistics *GetImageStatistics(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 ChannelStatistics *GetImageStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, *histogram, standard_deviation; MagickStatusType status; QuantumAny range; register ssize_t i; size_t depth; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); channel_statistics=(ChannelStatistics *) AcquireQuantumMemory( MaxPixelChannels+1,sizeof(*channel_statistics)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (double *) NULL)) { if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,(MaxPixelChannels+1)* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[channel].depth; range=GetQuantumRange(depth); status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range), range) ? MagickTrue : MagickFalse; if (status != MagickFalse) { channel_statistics[channel].depth++; i--; continue; } } if ((double) p[i] < channel_statistics[channel].minima) channel_statistics[channel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[channel].maxima) channel_statistics[channel].maxima=(double) p[i]; channel_statistics[channel].sum+=p[i]; channel_statistics[channel].sum_squared+=(double) p[i]*p[i]; channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]* p[i]; channel_statistics[channel].area++; if ((double) p[i] < channel_statistics[CompositePixelChannel].minima) channel_statistics[CompositePixelChannel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[CompositePixelChannel].maxima) channel_statistics[CompositePixelChannel].maxima=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum((double) p[i]))+i]++; channel_statistics[CompositePixelChannel].sum+=(double) p[i]; channel_statistics[CompositePixelChannel].sum_squared+=(double) p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].area++; } p+=GetPixelChannels(image); } } for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Normalize pixel statistics. */ area=PerceptibleReciprocal(channel_statistics[i].area); channel_statistics[i].sum*=area; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=channel_statistics[i].sum; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal(channel_statistics[i].area- 1.0)*channel_statistics[i].area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double number_bins; register ssize_t j; /* Compute pixel entropy. */ PixelChannel channel = GetPixelChannelChannel(image,i); number_bins=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) if (histogram[GetPixelChannels(image)*j+i] > 0.0) number_bins++; area=PerceptibleReciprocal(channel_statistics[channel].area); for (j=0; j <= (ssize_t) MaxMap; j++) { double count; count=area*histogram[GetPixelChannels(image)*j+i]; channel_statistics[channel].entropy+=-count*MagickLog10(count)* PerceptibleReciprocal(MagickLog10(number_bins)); channel_statistics[CompositePixelChannel].entropy+=-count* MagickLog10(count)*PerceptibleReciprocal(MagickLog10(number_bins))/ GetPixelChannels(image); } } histogram=(double *) RelinquishMagickMemory(histogram); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositePixelChannel].mean=0.0; channel_statistics[CompositePixelChannel].standard_deviation=0.0; channel_statistics[CompositePixelChannel].entropy=0.0; for (i=0; i < (ssize_t) MaxPixelChannels; i++) { channel_statistics[CompositePixelChannel].mean+= channel_statistics[i].mean; channel_statistics[CompositePixelChannel].standard_deviation+= channel_statistics[i].standard_deviation; channel_statistics[CompositePixelChannel].entropy+= channel_statistics[i].entropy; } channel_statistics[CompositePixelChannel].mean/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].standard_deviation/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].entropy/=(double) GetImageChannels(image); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict polynomial_pixels; size_t number_images; ssize_t y; 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=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *polynomial_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } polynomial_pixel=polynomial_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) polynomial_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; if (j >= (ssize_t) number_terms) continue; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { MagickRealType coefficient, degree; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (polynomial_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; coefficient=(MagickRealType) terms[2*j]; degree=(MagickRealType) terms[(j << 1)+1]; polynomial_pixel[x].channel[i]+=coefficient* pow(QuantumScale*GetPixelChannel(image,channel,p),degree); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(QuantumRange*polynomial_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,PolynomialImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(images,polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ typedef struct _SkipNode { size_t next[9], count, signature; } SkipNode; typedef struct _SkipList { ssize_t level; SkipNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed; SkipList skip_list; size_t signature; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); if (pixel_list->skip_list.nodes != (SkipNode *) NULL) pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory( pixel_list->skip_list.nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->skip_list.nodes)); if (pixel_list->skip_list.nodes == (SkipNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->skip_list.nodes,0,65537UL* sizeof(*pixel_list->skip_list.nodes)); pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const size_t color) { register SkipList *p; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ p=(&pixel_list->skip_list); p->nodes[color].signature=pixel_list->signature; p->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=p->level; level >= 0; level--) { while (p->nodes[search].next[level] < color) search=p->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (p->level+2)) level=p->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > p->level) { p->level++; update[p->level]=65536UL; } /* Link the node into the skip-list. */ do { p->nodes[color].next[level]=p->nodes[update[level]].next[level]; p->nodes[update[level]].next[level]=color; } while (level-- > 0); } static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color; ssize_t count; /* Find the median value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; do { color=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, max_count, mode; ssize_t count; /* Make each pixel the 'predominant color' of the specified neighborhood. */ p=(&pixel_list->skip_list); color=65536L; mode=color; max_count=p->nodes[mode].count; count=0; do { color=p->nodes[color].next[0]; if (p->nodes[color].count > max_count) { mode=color; max_count=p->nodes[mode].count; } count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) mode); } static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, next, previous; ssize_t count; /* Finds the non peak value for each of the colors. */ p=(&pixel_list->skip_list); color=65536L; next=p->nodes[color].next[0]; count=0; do { previous=color; color=next; next=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(pixel); signature=pixel_list->skip_list.nodes[index].signature; if (signature == pixel_list->signature) { pixel_list->skip_list.nodes[index].count++; return; } AddNodePixelList(pixel_list,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register SkipNode *root; register SkipList *p; /* Reset the skip-list. */ p=(&pixel_list->skip_list); root=p->nodes+65536UL; p->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; ssize_t center, y; /* Initialize statistics image attributes. */ 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); statistic_image=CloneImage(image,0,0,MagickTrue, exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(statistic_image,DirectClass,exception); if (status == MagickFalse) { statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } pixel_list=AcquirePixelListThreadSet(MagickMax(width,1),MagickMax(height,1)); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))* (MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L); status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y- (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1), MagickMax(height,1),exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) statistic_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double area, maximum, minimum, sum, sum_squared; Quantum pixel; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image, channel); if ((traits == UndefinedPixelTrait) || (statistic_traits == UndefinedPixelTrait)) continue; if (((statistic_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(image,p) <= (QuantumRange/2))) { SetPixelChannel(statistic_image,channel,p[center+i],q); continue; } if ((statistic_traits & UpdatePixelTrait) == 0) continue; pixels=p; area=0.0; minimum=pixels[i]; maximum=pixels[i]; sum=0.0; sum_squared=0.0; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) MagickMax(height,1); v++) { for (u=0; u < (ssize_t) MagickMax(width,1); u++) { if ((type == MedianStatistic) || (type == ModeStatistic) || (type == NonpeakStatistic)) { InsertPixelList(pixels[i],pixel_list[id]); pixels+=GetPixelChannels(image); continue; } area++; if (pixels[i] < minimum) minimum=(double) pixels[i]; if (pixels[i] > maximum) maximum=(double) pixels[i]; sum+=(double) pixels[i]; sum_squared+=(double) pixels[i]*pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } switch (type) { case GradientStatistic: { pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum)); break; } case MaximumStatistic: { pixel=ClampToQuantum(maximum); break; } case MeanStatistic: default: { pixel=ClampToQuantum(sum/area); break; } case MedianStatistic: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { pixel=ClampToQuantum(minimum); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { pixel=ClampToQuantum(sqrt(sum_squared/area)); break; } case StandardDeviationStatistic: { pixel=ClampToQuantum(sqrt(sum_squared/area-(sum/area*sum/area))); break; } } SetPixelChannel(statistic_image,channel,pixel,q); } p+=GetPixelChannels(image); q+=GetPixelChannels(statistic_image); } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,StatisticImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
rhs4sgcurv_rev.c
// SW4 LICENSE // # ---------------------------------------------------------------------- // # SW4 - Seismic Waves, 4th order // # ---------------------------------------------------------------------- // # Copyright (c) 2013, Lawrence Livermore National Security, LLC. // # Produced at the Lawrence Livermore National Laboratory. // # // # Written by: // # N. Anders Petersson (petersson1@llnl.gov) // # Bjorn Sjogreen (sjogreen2@llnl.gov) // # // # LLNL-CODE-643337 // # // # All rights reserved. // # // # This file is part of SW4, Version: 1.0 // # // # Please also read LICENCE.txt, which contains "Our Notice and GNU General Public License" // # // # 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) version 2, dated June 1991. // # // # 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 terms and // # conditions of 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA #include "sw4.h" void rhs4sgcurv_rev( int ifirst, int ilast, int jfirst, int jlast, int kfirst, int klast, float_sw4* __restrict__ a_u, float_sw4* __restrict__ a_mu, float_sw4* __restrict__ a_lambda, float_sw4* __restrict__ a_met, float_sw4* __restrict__ a_jac, float_sw4* __restrict__ a_lu, int* onesided, float_sw4* __restrict__ a_acof, float_sw4* __restrict__ a_bope, float_sw4* __restrict__ a_ghcof, float_sw4* __restrict__ a_strx, float_sw4* __restrict__ a_stry ) { // subroutine CURVILINEAR4SG( ifirst, ilast, jfirst, jlast, kfirst, // * klast, u, mu, la, met, jac, lu, // * onesided, acof, bope, ghcof, strx, stry, // * op ) // Routine with supergrid stretchings strx and stry. No stretching // in z, since top is always topography, and bottom always interface // to a deeper Cartesian grid. // opcount: // Interior (k>6), 2126 arithmetic ops. // Boundary discretization (1<=k<=6 ), 6049 arithmetic ops. const float_sw4 a1 = 0; const float_sw4 i6 = 1.0/6; const float_sw4 tf = 0.75; const float_sw4 c1 = 2.0/3; const float_sw4 c2 = -1.0/12; const int ni = ilast-ifirst+1; const int nij = ni*(jlast-jfirst+1); const int nijk = nij*(klast-kfirst+1); const int base = -(ifirst+ni*jfirst+nij*kfirst); const int base3 = base-nijk; const int base4 = base-nijk; const int ifirst0 = ifirst; const int jfirst0 = jfirst; // Direct reuse of fortran code by these macro definitions: #define mu(i,j,k) a_mu[base+i+ni*(j)+nij*(k)] #define la(i,j,k) a_lambda[base+i+ni*(j)+nij*(k)] #define jac(i,j,k) a_jac[base+i+ni*(j)+nij*(k)] #define u(c,i,j,k) a_u[base3+(i)+ni*(j)+nij*(k)+nijk*(c)] #define lu(c,i,j,k) a_lu[base3+(i)+ni*(j)+nij*(k)+nijk*(c)] #define met(c,i,j,k) a_met[base4+(i)+ni*(j)+nij*(k)+nijk*(c)] #define strx(i) a_strx[i-ifirst0] #define stry(j) a_stry[j-jfirst0] #define acof(i,j,k) a_acof[(i-1)+6*(j-1)+48*(k-1)] #define bope(i,j) a_bope[i-1+6*(j-1)] #define ghcof(i) a_ghcof[i-1] #pragma omp parallel { int kstart = kfirst+2; if( onesided[4] == 1 ) { kstart = 7; // SBP Boundary closure terms #pragma omp for for( int k= 1; k <= 6 ; k++ ) for( int j=jfirst+2; j <= jlast-2 ; j++ ) #pragma simd #pragma ivdep for( int i=ifirst+2; i <= ilast-2 ; i++ ) { // 5 ops float_sw4 ijac = strx(i)*stry(j)/jac(i,j,k); float_sw4 istry = 1/(stry(j)); float_sw4 istrx = 1/(strx(i)); float_sw4 istrxy = istry*istrx; float_sw4 r1 = 0,r2 = 0,r3 = 0; // pp derivative (u) (u-eq) // 53 ops, tot=58 float_sw4 cof1=(2*mu(i-2,j,k)+la(i-2,j,k))*met(1,i-2,j,k)*met(1,i-2,j,k) *strx(i-2); float_sw4 cof2=(2*mu(i-1,j,k)+la(i-1,j,k))*met(1,i-1,j,k)*met(1,i-1,j,k) *strx(i-1); float_sw4 cof3=(2*mu(i,j,k)+la(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*strx(i); float_sw4 cof4=(2*mu(i+1,j,k)+la(i+1,j,k))*met(1,i+1,j,k)*met(1,i+1,j,k) *strx(i+1); float_sw4 cof5=(2*mu(i+2,j,k)+la(i+2,j,k))*met(1,i+2,j,k)*met(1,i+2,j,k) *strx(i+2); float_sw4 mux1 = cof2 -tf*(cof3+cof1); float_sw4 mux2 = cof1 + cof4+3*(cof3+cof2); float_sw4 mux3 = cof2 + cof5+3*(cof4+cof3); float_sw4 mux4 = cof4-tf*(cof3+cof5); r1 = r1 + i6* ( mux1*(u(1,i-2,j,k)-u(1,i,j,k)) + mux2*(u(1,i-1,j,k)-u(1,i,j,k)) + mux3*(u(1,i+1,j,k)-u(1,i,j,k)) + mux4*(u(1,i+2,j,k)-u(1,i,j,k)) )*istry; // qq derivative (u) (u-eq) // 43 ops, tot=101 cof1=(mu(i,j-2,k))*met(1,i,j-2,k)*met(1,i,j-2,k)*stry(j-2); cof2=(mu(i,j-1,k))*met(1,i,j-1,k)*met(1,i,j-1,k)*stry(j-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*stry(j); cof4=(mu(i,j+1,k))*met(1,i,j+1,k)*met(1,i,j+1,k)*stry(j+1); cof5=(mu(i,j+2,k))*met(1,i,j+2,k)*met(1,i,j+2,k)*stry(j+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 = r1 + i6* ( mux1*(u(1,i,j-2,k)-u(1,i,j,k)) + mux2*(u(1,i,j-1,k)-u(1,i,j,k)) + mux3*(u(1,i,j+1,k)-u(1,i,j,k)) + mux4*(u(1,i,j+2,k)-u(1,i,j,k)) )*istrx; // pp derivative (v) (v-eq) // 43 ops, tot=144 cof1=(mu(i-2,j,k))*met(1,i-2,j,k)*met(1,i-2,j,k)*strx(i-2); cof2=(mu(i-1,j,k))*met(1,i-1,j,k)*met(1,i-1,j,k)*strx(i-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*strx(i); cof4=(mu(i+1,j,k))*met(1,i+1,j,k)*met(1,i+1,j,k)*strx(i+1); cof5=(mu(i+2,j,k))*met(1,i+2,j,k)*met(1,i+2,j,k)*strx(i+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r2 = r2 + i6* ( mux1*(u(2,i-2,j,k)-u(2,i,j,k)) + mux2*(u(2,i-1,j,k)-u(2,i,j,k)) + mux3*(u(2,i+1,j,k)-u(2,i,j,k)) + mux4*(u(2,i+2,j,k)-u(2,i,j,k)) )*istry; // qq derivative (v) (v-eq) // 53 ops, tot=197 cof1=(2*mu(i,j-2,k)+la(i,j-2,k))*met(1,i,j-2,k)*met(1,i,j-2,k)*stry(j-2); cof2=(2*mu(i,j-1,k)+la(i,j-1,k))*met(1,i,j-1,k)*met(1,i,j-1,k)*stry(j-1); cof3=(2*mu(i,j,k)+la(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*stry(j); cof4=(2*mu(i,j+1,k)+la(i,j+1,k))*met(1,i,j+1,k)*met(1,i,j+1,k)*stry(j+1); cof5=(2*mu(i,j+2,k)+la(i,j+2,k))*met(1,i,j+2,k)*met(1,i,j+2,k)*stry(j+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r2 = r2 + i6* ( mux1*(u(2,i,j-2,k)-u(2,i,j,k)) + mux2*(u(2,i,j-1,k)-u(2,i,j,k)) + mux3*(u(2,i,j+1,k)-u(2,i,j,k)) + mux4*(u(2,i,j+2,k)-u(2,i,j,k)) )*istrx; // pp derivative (w) (w-eq) // 43 ops, tot=240 cof1=(mu(i-2,j,k))*met(1,i-2,j,k)*met(1,i-2,j,k)*strx(i-2); cof2=(mu(i-1,j,k))*met(1,i-1,j,k)*met(1,i-1,j,k)*strx(i-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*strx(i); cof4=(mu(i+1,j,k))*met(1,i+1,j,k)*met(1,i+1,j,k)*strx(i+1); cof5=(mu(i+2,j,k))*met(1,i+2,j,k)*met(1,i+2,j,k)*strx(i+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r3 = r3 + i6* ( mux1*(u(3,i-2,j,k)-u(3,i,j,k)) + mux2*(u(3,i-1,j,k)-u(3,i,j,k)) + mux3*(u(3,i+1,j,k)-u(3,i,j,k)) + mux4*(u(3,i+2,j,k)-u(3,i,j,k)) )*istry; // qq derivative (w) (w-eq) // 43 ops, tot=283 cof1=(mu(i,j-2,k))*met(1,i,j-2,k)*met(1,i,j-2,k)*stry(j-2); cof2=(mu(i,j-1,k))*met(1,i,j-1,k)*met(1,i,j-1,k)*stry(j-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*stry(j); cof4=(mu(i,j+1,k))*met(1,i,j+1,k)*met(1,i,j+1,k)*stry(j+1); cof5=(mu(i,j+2,k))*met(1,i,j+2,k)*met(1,i,j+2,k)*stry(j+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r3 = r3 + i6* ( mux1*(u(3,i,j-2,k)-u(3,i,j,k)) + mux2*(u(3,i,j-1,k)-u(3,i,j,k)) + mux3*(u(3,i,j+1,k)-u(3,i,j,k)) + mux4*(u(3,i,j+2,k)-u(3,i,j,k)) )*istrx; // All rr-derivatives at once // averaging the coefficient // 54*8*8+25*8 = 3656 ops, tot=3939 float_sw4 mucofu2, mucofuv, mucofuw, mucofvw, mucofv2, mucofw2; for( int q=1 ; q <= 8 ; q++ ) { mucofu2=0; mucofuv=0; mucofuw=0; mucofvw=0; mucofv2=0; mucofw2=0; for( int m=1 ; m <= 8 ; m++ ) { mucofu2 += acof(k,q,m)*((2*mu(i,j,m)+la(i,j,m))*(met(2,i,j,m)*strx(i))*(met(2,i,j,m)*strx(i)) + mu(i,j,m)*(met(3,i,j,m)*stry(j)*met(3,i,j,m)*stry(j)+ met(4,i,j,m)*met(4,i,j,m))); mucofv2 += acof(k,q,m)*((2*mu(i,j,m)+la(i,j,m))*(met(3,i,j,m)*stry(j))*met(3,i,j,m)*stry(j) + mu(i,j,m)*((met(2,i,j,m)*strx(i))*met(2,i,j,m)*strx(i)+ met(4,i,j,m)*met(4,i,j,m))); mucofw2 += acof(k,q,m)*((2*mu(i,j,m)+la(i,j,m))*met(4,i,j,m)*met(4,i,j,m) + mu(i,j,m)*( met(2,i,j,m)*strx(i)*met(2,i,j,m)*strx(i)+ met(3,i,j,m)*stry(j)*met(3,i,j,m)*stry(j) ) ); mucofuv += acof(k,q,m)*(mu(i,j,m)+la(i,j,m))*met(2,i,j,m)*met(3,i,j,m); mucofuw += acof(k,q,m)*(mu(i,j,m)+la(i,j,m))*met(2,i,j,m)*met(4,i,j,m); mucofvw += acof(k,q,m)*(mu(i,j,m)+la(i,j,m))*met(3,i,j,m)*met(4,i,j,m); } // Computing the second derivative, r1 += istrxy*mucofu2*u(1,i,j,q) + mucofuv*u(2,i,j,q) + istry*mucofuw*u(3,i,j,q); r2 += mucofuv*u(1,i,j,q) + istrxy*mucofv2*u(2,i,j,q) + istrx*mucofvw*u(3,i,j,q); r3 += istry*mucofuw*u(1,i,j,q) + istrx*mucofvw*u(2,i,j,q) + istrxy*mucofw2*u(3,i,j,q); } // Ghost point values, only nonzero for k=1. // 72 ops., tot=4011 mucofu2 = ghcof(k)*((2*mu(i,j,1)+la(i,j,1))* met(2,i,j,1)*strx(i)*met(2,i,j,1)*strx(i) + mu(i,j,1)*(met(3,i,j,1)*stry(j)*met(3,i,j,1)*stry(j)+ met(4,i,j,1)*met(4,i,j,1) )); mucofv2 = ghcof(k)*((2*mu(i,j,1)+la(i,j,1))* met(3,i,j,1)*stry(j)*met(3,i,j,1)*stry(j) + mu(i,j,1)*( met(2,i,j,1)*strx(i)*met(2,i,j,1)*strx(i)+ met(4,i,j,1)*met(4,i,j,1) ) ); mucofw2 = ghcof(k)*((2*mu(i,j,1)+la(i,j,1))*met(4,i,j,1)*met(4,i,j,1) + mu(i,j,1)* ( met(2,i,j,1)*strx(i)*met(2,i,j,1)*strx(i)+ met(3,i,j,1)*stry(j)*met(3,i,j,1)*stry(j) ) ); mucofuv = ghcof(k)*(mu(i,j,1)+la(i,j,1))*met(2,i,j,1)*met(3,i,j,1); mucofuw = ghcof(k)*(mu(i,j,1)+la(i,j,1))*met(2,i,j,1)*met(4,i,j,1); mucofvw = ghcof(k)*(mu(i,j,1)+la(i,j,1))*met(3,i,j,1)*met(4,i,j,1); r1 += istrxy*mucofu2*u(1,i,j,0) + mucofuv*u(2,i,j,0) + istry*mucofuw*u(3,i,j,0); r2 += mucofuv*u(1,i,j,0) + istrxy*mucofv2*u(2,i,j,0) + istrx*mucofvw*u(3,i,j,0); r3 += istry*mucofuw*u(1,i,j,0) + istrx*mucofvw*u(2,i,j,0) + istrxy*mucofw2*u(3,i,j,0); // pq-derivatives (u-eq) // 38 ops., tot=4049 r1 += c2*( mu(i,j+2,k)*met(1,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(2,i+2,j+2,k)-u(2,i-2,j+2,k)) + c1*(u(2,i+1,j+2,k)-u(2,i-1,j+2,k)) ) - mu(i,j-2,k)*met(1,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(2,i+2,j-2,k)-u(2,i-2,j-2,k))+ c1*(u(2,i+1,j-2,k)-u(2,i-1,j-2,k)) ) ) + c1*( mu(i,j+1,k)*met(1,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(2,i+2,j+1,k)-u(2,i-2,j+1,k)) + c1*(u(2,i+1,j+1,k)-u(2,i-1,j+1,k)) ) - mu(i,j-1,k)*met(1,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(2,i+2,j-1,k)-u(2,i-2,j-1,k)) + c1*(u(2,i+1,j-1,k)-u(2,i-1,j-1,k)))); // qp-derivatives (u-eq) // 38 ops. tot=4087 r1 += c2*( la(i+2,j,k)*met(1,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(2,i+2,j+2,k)-u(2,i+2,j-2,k)) + c1*(u(2,i+2,j+1,k)-u(2,i+2,j-1,k)) ) - la(i-2,j,k)*met(1,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(2,i-2,j+2,k)-u(2,i-2,j-2,k))+ c1*(u(2,i-2,j+1,k)-u(2,i-2,j-1,k)) ) ) + c1*( la(i+1,j,k)*met(1,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(2,i+1,j+2,k)-u(2,i+1,j-2,k)) + c1*(u(2,i+1,j+1,k)-u(2,i+1,j-1,k)) ) - la(i-1,j,k)*met(1,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(2,i-1,j+2,k)-u(2,i-1,j-2,k)) + c1*(u(2,i-1,j+1,k)-u(2,i-1,j-1,k)))); // pq-derivatives (v-eq) // 38 ops. , tot=4125 r2 += c2*( la(i,j+2,k)*met(1,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(1,i+2,j+2,k)-u(1,i-2,j+2,k)) + c1*(u(1,i+1,j+2,k)-u(1,i-1,j+2,k)) ) - la(i,j-2,k)*met(1,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(1,i+2,j-2,k)-u(1,i-2,j-2,k))+ c1*(u(1,i+1,j-2,k)-u(1,i-1,j-2,k)) ) ) + c1*( la(i,j+1,k)*met(1,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(1,i+2,j+1,k)-u(1,i-2,j+1,k)) + c1*(u(1,i+1,j+1,k)-u(1,i-1,j+1,k)) ) - la(i,j-1,k)*met(1,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(1,i+2,j-1,k)-u(1,i-2,j-1,k)) + c1*(u(1,i+1,j-1,k)-u(1,i-1,j-1,k)))); //* qp-derivatives (v-eq) // 38 ops., tot=4163 r2 += c2*( mu(i+2,j,k)*met(1,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(1,i+2,j+2,k)-u(1,i+2,j-2,k)) + c1*(u(1,i+2,j+1,k)-u(1,i+2,j-1,k)) ) - mu(i-2,j,k)*met(1,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(1,i-2,j+2,k)-u(1,i-2,j-2,k))+ c1*(u(1,i-2,j+1,k)-u(1,i-2,j-1,k)) ) ) + c1*( mu(i+1,j,k)*met(1,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(1,i+1,j+2,k)-u(1,i+1,j-2,k)) + c1*(u(1,i+1,j+1,k)-u(1,i+1,j-1,k)) ) - mu(i-1,j,k)*met(1,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(1,i-1,j+2,k)-u(1,i-1,j-2,k)) + c1*(u(1,i-1,j+1,k)-u(1,i-1,j-1,k)))); // rp - derivatives // 24*8 = 192 ops, tot=4355 float_sw4 dudrm2 = 0, dudrm1=0, dudrp1=0, dudrp2=0; float_sw4 dvdrm2 = 0, dvdrm1=0, dvdrp1=0, dvdrp2=0; float_sw4 dwdrm2 = 0, dwdrm1=0, dwdrp1=0, dwdrp2=0; for( int q=1 ; q <= 8 ; q++ ) { dudrm2 += bope(k,q)*u(1,i-2,j,q); dvdrm2 += bope(k,q)*u(2,i-2,j,q); dwdrm2 += bope(k,q)*u(3,i-2,j,q); dudrm1 += bope(k,q)*u(1,i-1,j,q); dvdrm1 += bope(k,q)*u(2,i-1,j,q); dwdrm1 += bope(k,q)*u(3,i-1,j,q); dudrp2 += bope(k,q)*u(1,i+2,j,q); dvdrp2 += bope(k,q)*u(2,i+2,j,q); dwdrp2 += bope(k,q)*u(3,i+2,j,q); dudrp1 += bope(k,q)*u(1,i+1,j,q); dvdrp1 += bope(k,q)*u(2,i+1,j,q); dwdrp1 += bope(k,q)*u(3,i+1,j,q); } // rp derivatives (u-eq) // 67 ops, tot=4422 r1 += ( c2*( (2*mu(i+2,j,k)+la(i+2,j,k))*met(2,i+2,j,k)*met(1,i+2,j,k)* strx(i+2)*dudrp2 + la(i+2,j,k)*met(3,i+2,j,k)*met(1,i+2,j,k)*dvdrp2*stry(j) + la(i+2,j,k)*met(4,i+2,j,k)*met(1,i+2,j,k)*dwdrp2 -((2*mu(i-2,j,k)+la(i-2,j,k))*met(2,i-2,j,k)*met(1,i-2,j,k)* strx(i-2)*dudrm2 + la(i-2,j,k)*met(3,i-2,j,k)*met(1,i-2,j,k)*dvdrm2*stry(j) + la(i-2,j,k)*met(4,i-2,j,k)*met(1,i-2,j,k)*dwdrm2 ) ) + c1*( (2*mu(i+1,j,k)+la(i+1,j,k))*met(2,i+1,j,k)*met(1,i+1,j,k)* strx(i+1)*dudrp1 + la(i+1,j,k)*met(3,i+1,j,k)*met(1,i+1,j,k)*dvdrp1*stry(j) + la(i+1,j,k)*met(4,i+1,j,k)*met(1,i+1,j,k)*dwdrp1 -((2*mu(i-1,j,k)+la(i-1,j,k))*met(2,i-1,j,k)*met(1,i-1,j,k)* strx(i-1)*dudrm1 + la(i-1,j,k)*met(3,i-1,j,k)*met(1,i-1,j,k)*dvdrm1*stry(j) + la(i-1,j,k)*met(4,i-1,j,k)*met(1,i-1,j,k)*dwdrm1 ) ) )*istry; // rp derivatives (v-eq) // 42 ops, tot=4464 r2 += c2*( mu(i+2,j,k)*met(3,i+2,j,k)*met(1,i+2,j,k)*dudrp2 + mu(i+2,j,k)*met(2,i+2,j,k)*met(1,i+2,j,k)*dvdrp2* strx(i+2)*istry - (mu(i-2,j,k)*met(3,i-2,j,k)*met(1,i-2,j,k)*dudrm2 + mu(i-2,j,k)*met(2,i-2,j,k)*met(1,i-2,j,k)*dvdrm2* strx(i-2)*istry ) ) + c1*( mu(i+1,j,k)*met(3,i+1,j,k)*met(1,i+1,j,k)*dudrp1 + mu(i+1,j,k)*met(2,i+1,j,k)*met(1,i+1,j,k)*dvdrp1* strx(i+1)*istry - (mu(i-1,j,k)*met(3,i-1,j,k)*met(1,i-1,j,k)*dudrm1 + mu(i-1,j,k)*met(2,i-1,j,k)*met(1,i-1,j,k)*dvdrm1* strx(i-1)*istry ) ); // rp derivatives (w-eq) // 38 ops, tot=4502 r3 += istry*(c2*( mu(i+2,j,k)*met(4,i+2,j,k)*met(1,i+2,j,k)*dudrp2 + mu(i+2,j,k)*met(2,i+2,j,k)*met(1,i+2,j,k)*dwdrp2*strx(i+2) - (mu(i-2,j,k)*met(4,i-2,j,k)*met(1,i-2,j,k)*dudrm2 + mu(i-2,j,k)*met(2,i-2,j,k)*met(1,i-2,j,k)*dwdrm2*strx(i-2)) ) + c1*( mu(i+1,j,k)*met(4,i+1,j,k)*met(1,i+1,j,k)*dudrp1 + mu(i+1,j,k)*met(2,i+1,j,k)*met(1,i+1,j,k)*dwdrp1*strx(i+1) - (mu(i-1,j,k)*met(4,i-1,j,k)*met(1,i-1,j,k)*dudrm1 + mu(i-1,j,k)*met(2,i-1,j,k)*met(1,i-1,j,k)*dwdrm1*strx(i-1)) ) ); // rq - derivatives // 24*8 = 192 ops , tot=4694 dudrm2 = 0; dudrm1 = 0; dudrp1 = 0; dudrp2 = 0; dvdrm2 = 0; dvdrm1 = 0; dvdrp1 = 0; dvdrp2 = 0; dwdrm2 = 0; dwdrm1 = 0; dwdrp1 = 0; dwdrp2 = 0; for( int q=1 ; q <= 8 ; q++ ) { dudrm2 += bope(k,q)*u(1,i,j-2,q); dvdrm2 += bope(k,q)*u(2,i,j-2,q); dwdrm2 += bope(k,q)*u(3,i,j-2,q); dudrm1 += bope(k,q)*u(1,i,j-1,q); dvdrm1 += bope(k,q)*u(2,i,j-1,q); dwdrm1 += bope(k,q)*u(3,i,j-1,q); dudrp2 += bope(k,q)*u(1,i,j+2,q); dvdrp2 += bope(k,q)*u(2,i,j+2,q); dwdrp2 += bope(k,q)*u(3,i,j+2,q); dudrp1 += bope(k,q)*u(1,i,j+1,q); dvdrp1 += bope(k,q)*u(2,i,j+1,q); dwdrp1 += bope(k,q)*u(3,i,j+1,q); } // rq derivatives (u-eq) // 42 ops, tot=4736 r1 += c2*( mu(i,j+2,k)*met(3,i,j+2,k)*met(1,i,j+2,k)*dudrp2* stry(j+2)*istrx + mu(i,j+2,k)*met(2,i,j+2,k)*met(1,i,j+2,k)*dvdrp2 - (mu(i,j-2,k)*met(3,i,j-2,k)*met(1,i,j-2,k)*dudrm2* stry(j-2)*istrx + mu(i,j-2,k)*met(2,i,j-2,k)*met(1,i,j-2,k)*dvdrm2) ) + c1*( mu(i,j+1,k)*met(3,i,j+1,k)*met(1,i,j+1,k)*dudrp1* stry(j+1)*istrx + mu(i,j+1,k)*met(2,i,j+1,k)*met(1,i,j+1,k)*dvdrp1 - (mu(i,j-1,k)*met(3,i,j-1,k)*met(1,i,j-1,k)*dudrm1* stry(j-1)*istrx + mu(i,j-1,k)*met(2,i,j-1,k)*met(1,i,j-1,k)*dvdrm1) ); // rq derivatives (v-eq) // 70 ops, tot=4806 r2 += c2*( la(i,j+2,k)*met(2,i,j+2,k)*met(1,i,j+2,k)*dudrp2 +(2*mu(i,j+2,k)+la(i,j+2,k))*met(3,i,j+2,k)*met(1,i,j+2,k)*dvdrp2 *stry(j+2)*istrx + la(i,j+2,k)*met(4,i,j+2,k)*met(1,i,j+2,k)*dwdrp2*istrx - ( la(i,j-2,k)*met(2,i,j-2,k)*met(1,i,j-2,k)*dudrm2 +(2*mu(i,j-2,k)+la(i,j-2,k))*met(3,i,j-2,k)*met(1,i,j-2,k)*dvdrm2 *stry(j-2)*istrx + la(i,j-2,k)*met(4,i,j-2,k)*met(1,i,j-2,k)*dwdrm2*istrx ) ) + c1*( la(i,j+1,k)*met(2,i,j+1,k)*met(1,i,j+1,k)*dudrp1 +(2*mu(i,j+1,k)+la(i,j+1,k))*met(3,i,j+1,k)*met(1,i,j+1,k)*dvdrp1 *stry(j+1)*istrx + la(i,j+1,k)*met(4,i,j+1,k)*met(1,i,j+1,k)*dwdrp1*istrx - ( la(i,j-1,k)*met(2,i,j-1,k)*met(1,i,j-1,k)*dudrm1 +(2*mu(i,j-1,k)+la(i,j-1,k))*met(3,i,j-1,k)*met(1,i,j-1,k)*dvdrm1 *stry(j-1)*istrx + la(i,j-1,k)*met(4,i,j-1,k)*met(1,i,j-1,k)*dwdrm1*istrx ) ); // rq derivatives (w-eq) // 39 ops, tot=4845 r3 += ( c2*( mu(i,j+2,k)*met(3,i,j+2,k)*met(1,i,j+2,k)*dwdrp2*stry(j+2) + mu(i,j+2,k)*met(4,i,j+2,k)*met(1,i,j+2,k)*dvdrp2 - (mu(i,j-2,k)*met(3,i,j-2,k)*met(1,i,j-2,k)*dwdrm2*stry(j-2) + mu(i,j-2,k)*met(4,i,j-2,k)*met(1,i,j-2,k)*dvdrm2) ) + c1*( mu(i,j+1,k)*met(3,i,j+1,k)*met(1,i,j+1,k)*dwdrp1*stry(j+1) + mu(i,j+1,k)*met(4,i,j+1,k)*met(1,i,j+1,k)*dvdrp1 - (mu(i,j-1,k)*met(3,i,j-1,k)*met(1,i,j-1,k)*dwdrm1*stry(j-1) + mu(i,j-1,k)*met(4,i,j-1,k)*met(1,i,j-1,k)*dvdrm1) ) )*istrx; // pr and qr derivatives at once // in loop: 8*(53+53+43) = 1192 ops, tot=6037 for( int q=1 ; q <= 8 ; q++ ) { // (u-eq) // 53 ops r1 += bope(k,q)*( // pr (2*mu(i,j,q)+la(i,j,q))*met(2,i,j,q)*met(1,i,j,q)*( c2*(u(1,i+2,j,q)-u(1,i-2,j,q)) + c1*(u(1,i+1,j,q)-u(1,i-1,j,q)) )*strx(i)*istry + mu(i,j,q)*met(3,i,j,q)*met(1,i,j,q)*( c2*(u(2,i+2,j,q)-u(2,i-2,j,q)) + c1*(u(2,i+1,j,q)-u(2,i-1,j,q)) ) + mu(i,j,q)*met(4,i,j,q)*met(1,i,j,q)*( c2*(u(3,i+2,j,q)-u(3,i-2,j,q)) + c1*(u(3,i+1,j,q)-u(3,i-1,j,q)) )*istry // qr + mu(i,j,q)*met(3,i,j,q)*met(1,i,j,q)*( c2*(u(1,i,j+2,q)-u(1,i,j-2,q)) + c1*(u(1,i,j+1,q)-u(1,i,j-1,q)) )*stry(j)*istrx + la(i,j,q)*met(2,i,j,q)*met(1,i,j,q)*( c2*(u(2,i,j+2,q)-u(2,i,j-2,q)) + c1*(u(2,i,j+1,q)-u(2,i,j-1,q)) ) ); // (v-eq) // 53 ops r2 += bope(k,q)*( // pr la(i,j,q)*met(3,i,j,q)*met(1,i,j,q)*( c2*(u(1,i+2,j,q)-u(1,i-2,j,q)) + c1*(u(1,i+1,j,q)-u(1,i-1,j,q)) ) + mu(i,j,q)*met(2,i,j,q)*met(1,i,j,q)*( c2*(u(2,i+2,j,q)-u(2,i-2,j,q)) + c1*(u(2,i+1,j,q)-u(2,i-1,j,q)) )*strx(i)*istry // qr + mu(i,j,q)*met(2,i,j,q)*met(1,i,j,q)*( c2*(u(1,i,j+2,q)-u(1,i,j-2,q)) + c1*(u(1,i,j+1,q)-u(1,i,j-1,q)) ) + (2*mu(i,j,q)+la(i,j,q))*met(3,i,j,q)*met(1,i,j,q)*( c2*(u(2,i,j+2,q)-u(2,i,j-2,q)) + c1*(u(2,i,j+1,q)-u(2,i,j-1,q)) )*stry(j)*istrx + mu(i,j,q)*met(4,i,j,q)*met(1,i,j,q)*( c2*(u(3,i,j+2,q)-u(3,i,j-2,q)) + c1*(u(3,i,j+1,q)-u(3,i,j-1,q)) )*istrx ); // (w-eq) // 43 ops r3 += bope(k,q)*( // pr la(i,j,q)*met(4,i,j,q)*met(1,i,j,q)*( c2*(u(1,i+2,j,q)-u(1,i-2,j,q)) + c1*(u(1,i+1,j,q)-u(1,i-1,j,q)) )*istry + mu(i,j,q)*met(2,i,j,q)*met(1,i,j,q)*( c2*(u(3,i+2,j,q)-u(3,i-2,j,q)) + c1*(u(3,i+1,j,q)-u(3,i-1,j,q)) )*strx(i)*istry // qr + mu(i,j,q)*met(3,i,j,q)*met(1,i,j,q)*( c2*(u(3,i,j+2,q)-u(3,i,j-2,q)) + c1*(u(3,i,j+1,q)-u(3,i,j-1,q)) )*stry(j)*istrx + la(i,j,q)*met(4,i,j,q)*met(1,i,j,q)*( c2*(u(2,i,j+2,q)-u(2,i,j-2,q)) + c1*(u(2,i,j+1,q)-u(2,i,j-1,q)) )*istrx ); } // 12 ops, tot=6049 lu(1,i,j,k) = a1*lu(1,i,j,k) + r1*ijac; lu(2,i,j,k) = a1*lu(2,i,j,k) + r2*ijac; lu(3,i,j,k) = a1*lu(3,i,j,k) + r3*ijac; } } #pragma omp for for( int k= kstart; k <= klast-2 ; k++ ) for( int j=jfirst+2; j <= jlast-2 ; j++ ) #pragma simd #pragma ivdep for( int i=ifirst+2; i <= ilast-2 ; i++ ) { // 5 ops float_sw4 ijac = strx(i)*stry(j)/jac(i,j,k); float_sw4 istry = 1/(stry(j)); float_sw4 istrx = 1/(strx(i)); float_sw4 istrxy = istry*istrx; float_sw4 r1 = 0; // pp derivative (u) // 53 ops, tot=58 float_sw4 cof1=(2*mu(i-2,j,k)+la(i-2,j,k))*met(1,i-2,j,k)*met(1,i-2,j,k) *strx(i-2); float_sw4 cof2=(2*mu(i-1,j,k)+la(i-1,j,k))*met(1,i-1,j,k)*met(1,i-1,j,k) *strx(i-1); float_sw4 cof3=(2*mu(i,j,k)+la(i,j,k))*met(1,i,j,k)*met(1,i,j,k) *strx(i); float_sw4 cof4=(2*mu(i+1,j,k)+la(i+1,j,k))*met(1,i+1,j,k)*met(1,i+1,j,k) *strx(i+1); float_sw4 cof5=(2*mu(i+2,j,k)+la(i+2,j,k))*met(1,i+2,j,k)*met(1,i+2,j,k) *strx(i+2); float_sw4 mux1 = cof2 -tf*(cof3+cof1); float_sw4 mux2 = cof1 + cof4+3*(cof3+cof2); float_sw4 mux3 = cof2 + cof5+3*(cof4+cof3); float_sw4 mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(1,i-2,j,k)-u(1,i,j,k)) + mux2*(u(1,i-1,j,k)-u(1,i,j,k)) + mux3*(u(1,i+1,j,k)-u(1,i,j,k)) + mux4*(u(1,i+2,j,k)-u(1,i,j,k)) )*istry; // qq derivative (u) // 43 ops, tot=101 cof1=(mu(i,j-2,k))*met(1,i,j-2,k)*met(1,i,j-2,k)*stry(j-2); cof2=(mu(i,j-1,k))*met(1,i,j-1,k)*met(1,i,j-1,k)*stry(j-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*stry(j); cof4=(mu(i,j+1,k))*met(1,i,j+1,k)*met(1,i,j+1,k)*stry(j+1); cof5=(mu(i,j+2,k))*met(1,i,j+2,k)*met(1,i,j+2,k)*stry(j+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(1,i,j-2,k)-u(1,i,j,k)) + mux2*(u(1,i,j-1,k)-u(1,i,j,k)) + mux3*(u(1,i,j+1,k)-u(1,i,j,k)) + mux4*(u(1,i,j+2,k)-u(1,i,j,k)) )*istrx; // rr derivative (u) // 5*11+14+14=83 ops, tot=184 cof1 = (2*mu(i,j,k-2)+la(i,j,k-2))*met(2,i,j,k-2)*strx(i)*met(2,i,j,k-2)*strx(i) + mu(i,j,k-2)*(met(3,i,j,k-2)*stry(j)*met(3,i,j,k-2)*stry(j)+ met(4,i,j,k-2)*met(4,i,j,k-2)); cof2 = (2*mu(i,j,k-1)+la(i,j,k-1))*met(2,i,j,k-1)*strx(i)*met(2,i,j,k-1)*strx(i) + mu(i,j,k-1)*(met(3,i,j,k-1)*stry(j)*met(3,i,j,k-1)*stry(j)+ met(4,i,j,k-1)*met(4,i,j,k-1) ); cof3 = (2*mu(i,j,k)+la(i,j,k))*met(2,i,j,k)*strx(i)*met(2,i,j,k)*strx(i) + mu(i,j,k)*(met(3,i,j,k)*stry(j)*met(3,i,j,k)*stry(j)+ met(4,i,j,k)*met(4,i,j,k)); cof4 = (2*mu(i,j,k+1)+la(i,j,k+1))*met(2,i,j,k+1)*strx(i)*met(2,i,j,k+1)*strx(i) + mu(i,j,k+1)*(met(3,i,j,k+1)*stry(j)*met(3,i,j,k+1)*stry(j)+ met(4,i,j,k+1)*met(4,i,j,k+1)); cof5 = (2*mu(i,j,k+2)+la(i,j,k+2))*met(2,i,j,k+2)*strx(i)*met(2,i,j,k+2)*strx(i) + mu(i,j,k+2)*( met(3,i,j,k+2)*stry(j)*met(3,i,j,k+2)*stry(j)+ met(4,i,j,k+2)*met(4,i,j,k+2)); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(1,i,j,k-2)-u(1,i,j,k)) + mux2*(u(1,i,j,k-1)-u(1,i,j,k)) + mux3*(u(1,i,j,k+1)-u(1,i,j,k)) + mux4*(u(1,i,j,k+2)-u(1,i,j,k)) )*istrxy; // rr derivative (v) // 42 ops, tot=226 cof1=(mu(i,j,k-2)+la(i,j,k-2))*met(2,i,j,k-2)*met(3,i,j,k-2); cof2=(mu(i,j,k-1)+la(i,j,k-1))*met(2,i,j,k-1)*met(3,i,j,k-1); cof3=(mu(i,j,k)+la(i,j,k))*met(2,i,j,k)*met(3,i,j,k); cof4=(mu(i,j,k+1)+la(i,j,k+1))*met(2,i,j,k+1)*met(3,i,j,k+1); cof5=(mu(i,j,k+2)+la(i,j,k+2))*met(2,i,j,k+2)*met(3,i,j,k+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(2,i,j,k-2)-u(2,i,j,k)) + mux2*(u(2,i,j,k-1)-u(2,i,j,k)) + mux3*(u(2,i,j,k+1)-u(2,i,j,k)) + mux4*(u(2,i,j,k+2)-u(2,i,j,k)) ); // rr derivative (w) // 43 ops, tot=269 cof1=(mu(i,j,k-2)+la(i,j,k-2))*met(2,i,j,k-2)*met(4,i,j,k-2); cof2=(mu(i,j,k-1)+la(i,j,k-1))*met(2,i,j,k-1)*met(4,i,j,k-1); cof3=(mu(i,j,k)+la(i,j,k))*met(2,i,j,k)*met(4,i,j,k); cof4=(mu(i,j,k+1)+la(i,j,k+1))*met(2,i,j,k+1)*met(4,i,j,k+1); cof5=(mu(i,j,k+2)+la(i,j,k+2))*met(2,i,j,k+2)*met(4,i,j,k+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(3,i,j,k-2)-u(3,i,j,k)) + mux2*(u(3,i,j,k-1)-u(3,i,j,k)) + mux3*(u(3,i,j,k+1)-u(3,i,j,k)) + mux4*(u(3,i,j,k+2)-u(3,i,j,k)) )*istry; // pq-derivatives // 38 ops, tot=307 r1 += c2*( mu(i,j+2,k)*met(1,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(2,i+2,j+2,k)-u(2,i-2,j+2,k)) + c1*(u(2,i+1,j+2,k)-u(2,i-1,j+2,k)) ) - mu(i,j-2,k)*met(1,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(2,i+2,j-2,k)-u(2,i-2,j-2,k))+ c1*(u(2,i+1,j-2,k)-u(2,i-1,j-2,k)) ) ) + c1*( mu(i,j+1,k)*met(1,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(2,i+2,j+1,k)-u(2,i-2,j+1,k)) + c1*(u(2,i+1,j+1,k)-u(2,i-1,j+1,k)) ) - mu(i,j-1,k)*met(1,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(2,i+2,j-1,k)-u(2,i-2,j-1,k)) + c1*(u(2,i+1,j-1,k)-u(2,i-1,j-1,k)))); // qp-derivatives // 38 ops, tot=345 r1 += c2*( la(i+2,j,k)*met(1,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(2,i+2,j+2,k)-u(2,i+2,j-2,k)) + c1*(u(2,i+2,j+1,k)-u(2,i+2,j-1,k)) ) - la(i-2,j,k)*met(1,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(2,i-2,j+2,k)-u(2,i-2,j-2,k))+ c1*(u(2,i-2,j+1,k)-u(2,i-2,j-1,k)) ) ) + c1*( la(i+1,j,k)*met(1,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(2,i+1,j+2,k)-u(2,i+1,j-2,k)) + c1*(u(2,i+1,j+1,k)-u(2,i+1,j-1,k)) ) - la(i-1,j,k)*met(1,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(2,i-1,j+2,k)-u(2,i-1,j-2,k)) + c1*(u(2,i-1,j+1,k)-u(2,i-1,j-1,k)))); // pr-derivatives // 130 ops., tot=475 r1 += c2*( (2*mu(i,j,k+2)+la(i,j,k+2))*met(2,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(1,i+2,j,k+2)-u(1,i-2,j,k+2)) + c1*(u(1,i+1,j,k+2)-u(1,i-1,j,k+2)) )*strx(i)*istry + mu(i,j,k+2)*met(3,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(2,i+2,j,k+2)-u(2,i-2,j,k+2)) + c1*(u(2,i+1,j,k+2)-u(2,i-1,j,k+2)) ) + mu(i,j,k+2)*met(4,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(3,i+2,j,k+2)-u(3,i-2,j,k+2)) + c1*(u(3,i+1,j,k+2)-u(3,i-1,j,k+2)) )*istry - ((2*mu(i,j,k-2)+la(i,j,k-2))*met(2,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(1,i+2,j,k-2)-u(1,i-2,j,k-2)) + c1*(u(1,i+1,j,k-2)-u(1,i-1,j,k-2)) )*strx(i)*istry + mu(i,j,k-2)*met(3,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(2,i+2,j,k-2)-u(2,i-2,j,k-2)) + c1*(u(2,i+1,j,k-2)-u(2,i-1,j,k-2)) ) + mu(i,j,k-2)*met(4,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(3,i+2,j,k-2)-u(3,i-2,j,k-2)) + c1*(u(3,i+1,j,k-2)-u(3,i-1,j,k-2)) )*istry ) ) + c1*( (2*mu(i,j,k+1)+la(i,j,k+1))*met(2,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(1,i+2,j,k+1)-u(1,i-2,j,k+1)) + c1*(u(1,i+1,j,k+1)-u(1,i-1,j,k+1)) )*strx(i)*istry + mu(i,j,k+1)*met(3,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(2,i+2,j,k+1)-u(2,i-2,j,k+1)) + c1*(u(2,i+1,j,k+1)-u(2,i-1,j,k+1)) ) + mu(i,j,k+1)*met(4,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(3,i+2,j,k+1)-u(3,i-2,j,k+1)) + c1*(u(3,i+1,j,k+1)-u(3,i-1,j,k+1)) )*istry - ((2*mu(i,j,k-1)+la(i,j,k-1))*met(2,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(1,i+2,j,k-1)-u(1,i-2,j,k-1)) + c1*(u(1,i+1,j,k-1)-u(1,i-1,j,k-1)) )*strx(i)*istry + mu(i,j,k-1)*met(3,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(2,i+2,j,k-1)-u(2,i-2,j,k-1)) + c1*(u(2,i+1,j,k-1)-u(2,i-1,j,k-1)) ) + mu(i,j,k-1)*met(4,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(3,i+2,j,k-1)-u(3,i-2,j,k-1)) + c1*(u(3,i+1,j,k-1)-u(3,i-1,j,k-1)) )*istry ) ); // rp derivatives // 130 ops, tot=605 r1 += ( c2*( (2*mu(i+2,j,k)+la(i+2,j,k))*met(2,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(1,i+2,j,k+2)-u(1,i+2,j,k-2)) + c1*(u(1,i+2,j,k+1)-u(1,i+2,j,k-1)) )*strx(i+2) + la(i+2,j,k)*met(3,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(2,i+2,j,k+2)-u(2,i+2,j,k-2)) + c1*(u(2,i+2,j,k+1)-u(2,i+2,j,k-1)) )*stry(j) + la(i+2,j,k)*met(4,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(3,i+2,j,k+2)-u(3,i+2,j,k-2)) + c1*(u(3,i+2,j,k+1)-u(3,i+2,j,k-1)) ) - ((2*mu(i-2,j,k)+la(i-2,j,k))*met(2,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(1,i-2,j,k+2)-u(1,i-2,j,k-2)) + c1*(u(1,i-2,j,k+1)-u(1,i-2,j,k-1)) )*strx(i-2) + la(i-2,j,k)*met(3,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(2,i-2,j,k+2)-u(2,i-2,j,k-2)) + c1*(u(2,i-2,j,k+1)-u(2,i-2,j,k-1)) )*stry(j) + la(i-2,j,k)*met(4,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(3,i-2,j,k+2)-u(3,i-2,j,k-2)) + c1*(u(3,i-2,j,k+1)-u(3,i-2,j,k-1)) ) ) ) + c1*( (2*mu(i+1,j,k)+la(i+1,j,k))*met(2,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(1,i+1,j,k+2)-u(1,i+1,j,k-2)) + c1*(u(1,i+1,j,k+1)-u(1,i+1,j,k-1)) )*strx(i+1) + la(i+1,j,k)*met(3,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(2,i+1,j,k+2)-u(2,i+1,j,k-2)) + c1*(u(2,i+1,j,k+1)-u(2,i+1,j,k-1)) )*stry(j) + la(i+1,j,k)*met(4,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(3,i+1,j,k+2)-u(3,i+1,j,k-2)) + c1*(u(3,i+1,j,k+1)-u(3,i+1,j,k-1)) ) - ((2*mu(i-1,j,k)+la(i-1,j,k))*met(2,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(1,i-1,j,k+2)-u(1,i-1,j,k-2)) + c1*(u(1,i-1,j,k+1)-u(1,i-1,j,k-1)) )*strx(i-1) + la(i-1,j,k)*met(3,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(2,i-1,j,k+2)-u(2,i-1,j,k-2)) + c1*(u(2,i-1,j,k+1)-u(2,i-1,j,k-1)) )*stry(j) + la(i-1,j,k)*met(4,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(3,i-1,j,k+2)-u(3,i-1,j,k-2)) + c1*(u(3,i-1,j,k+1)-u(3,i-1,j,k-1)) ) ) ) )*istry; // qr derivatives // 82 ops, tot=687 r1 += c2*( mu(i,j,k+2)*met(3,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(1,i,j+2,k+2)-u(1,i,j-2,k+2)) + c1*(u(1,i,j+1,k+2)-u(1,i,j-1,k+2)) )*stry(j)*istrx + la(i,j,k+2)*met(2,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(2,i,j+2,k+2)-u(2,i,j-2,k+2)) + c1*(u(2,i,j+1,k+2)-u(2,i,j-1,k+2)) ) - ( mu(i,j,k-2)*met(3,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(1,i,j+2,k-2)-u(1,i,j-2,k-2)) + c1*(u(1,i,j+1,k-2)-u(1,i,j-1,k-2)) )*stry(j)*istrx + la(i,j,k-2)*met(2,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(2,i,j+2,k-2)-u(2,i,j-2,k-2)) + c1*(u(2,i,j+1,k-2)-u(2,i,j-1,k-2)) ) ) ) + c1*( mu(i,j,k+1)*met(3,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(1,i,j+2,k+1)-u(1,i,j-2,k+1)) + c1*(u(1,i,j+1,k+1)-u(1,i,j-1,k+1)) )*stry(j)*istrx + la(i,j,k+1)*met(2,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(2,i,j+2,k+1)-u(2,i,j-2,k+1)) + c1*(u(2,i,j+1,k+1)-u(2,i,j-1,k+1)) ) - ( mu(i,j,k-1)*met(3,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(1,i,j+2,k-1)-u(1,i,j-2,k-1)) + c1*(u(1,i,j+1,k-1)-u(1,i,j-1,k-1)) )*stry(j)*istrx + la(i,j,k-1)*met(2,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(2,i,j+2,k-1)-u(2,i,j-2,k-1)) + c1*(u(2,i,j+1,k-1)-u(2,i,j-1,k-1)) ) ) ); // rq derivatives // 82 ops, tot=769 r1 += c2*( mu(i,j+2,k)*met(3,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(1,i,j+2,k+2)-u(1,i,j+2,k-2)) + c1*(u(1,i,j+2,k+1)-u(1,i,j+2,k-1)) )*stry(j+2)*istrx + mu(i,j+2,k)*met(2,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(2,i,j+2,k+2)-u(2,i,j+2,k-2)) + c1*(u(2,i,j+2,k+1)-u(2,i,j+2,k-1)) ) - ( mu(i,j-2,k)*met(3,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(1,i,j-2,k+2)-u(1,i,j-2,k-2)) + c1*(u(1,i,j-2,k+1)-u(1,i,j-2,k-1)) )*stry(j-2)*istrx + mu(i,j-2,k)*met(2,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(2,i,j-2,k+2)-u(2,i,j-2,k-2)) + c1*(u(2,i,j-2,k+1)-u(2,i,j-2,k-1)) ) ) ) + c1*( mu(i,j+1,k)*met(3,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(1,i,j+1,k+2)-u(1,i,j+1,k-2)) + c1*(u(1,i,j+1,k+1)-u(1,i,j+1,k-1)) )*stry(j+1)*istrx + mu(i,j+1,k)*met(2,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(2,i,j+1,k+2)-u(2,i,j+1,k-2)) + c1*(u(2,i,j+1,k+1)-u(2,i,j+1,k-1)) ) - ( mu(i,j-1,k)*met(3,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(1,i,j-1,k+2)-u(1,i,j-1,k-2)) + c1*(u(1,i,j-1,k+1)-u(1,i,j-1,k-1)) )*stry(j-1)*istrx + mu(i,j-1,k)*met(2,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(2,i,j-1,k+2)-u(2,i,j-1,k-2)) + c1*(u(2,i,j-1,k+1)-u(2,i,j-1,k-1)) ) ) ); // 4 ops, tot=773 lu(1,i,j,k) = a1*lu(1,i,j,k) + r1*ijac; // v-equation r1 = 0; // pp derivative (v) // 43 ops, tot=816 cof1=(mu(i-2,j,k))*met(1,i-2,j,k)*met(1,i-2,j,k)*strx(i-2); cof2=(mu(i-1,j,k))*met(1,i-1,j,k)*met(1,i-1,j,k)*strx(i-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*strx(i); cof4=(mu(i+1,j,k))*met(1,i+1,j,k)*met(1,i+1,j,k)*strx(i+1); cof5=(mu(i+2,j,k))*met(1,i+2,j,k)*met(1,i+2,j,k)*strx(i+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(2,i-2,j,k)-u(2,i,j,k)) + mux2*(u(2,i-1,j,k)-u(2,i,j,k)) + mux3*(u(2,i+1,j,k)-u(2,i,j,k)) + mux4*(u(2,i+2,j,k)-u(2,i,j,k)) )*istry; // qq derivative (v) // 53 ops, tot=869 cof1=(2*mu(i,j-2,k)+la(i,j-2,k))*met(1,i,j-2,k)*met(1,i,j-2,k) *stry(j-2); cof2=(2*mu(i,j-1,k)+la(i,j-1,k))*met(1,i,j-1,k)*met(1,i,j-1,k) *stry(j-1); cof3=(2*mu(i,j,k)+la(i,j,k))*met(1,i,j,k)*met(1,i,j,k) *stry(j); cof4=(2*mu(i,j+1,k)+la(i,j+1,k))*met(1,i,j+1,k)*met(1,i,j+1,k) *stry(j+1); cof5=(2*mu(i,j+2,k)+la(i,j+2,k))*met(1,i,j+2,k)*met(1,i,j+2,k) *stry(j+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(2,i,j-2,k)-u(2,i,j,k)) + mux2*(u(2,i,j-1,k)-u(2,i,j,k)) + mux3*(u(2,i,j+1,k)-u(2,i,j,k)) + mux4*(u(2,i,j+2,k)-u(2,i,j,k)) )*istrx; // rr derivative (u) // 42 ops, tot=911 cof1=(mu(i,j,k-2)+la(i,j,k-2))*met(2,i,j,k-2)*met(3,i,j,k-2); cof2=(mu(i,j,k-1)+la(i,j,k-1))*met(2,i,j,k-1)*met(3,i,j,k-1); cof3=(mu(i,j,k)+ la(i,j,k) )*met(2,i,j,k)* met(3,i,j,k); cof4=(mu(i,j,k+1)+la(i,j,k+1))*met(2,i,j,k+1)*met(3,i,j,k+1); cof5=(mu(i,j,k+2)+la(i,j,k+2))*met(2,i,j,k+2)*met(3,i,j,k+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(1,i,j,k-2)-u(1,i,j,k)) + mux2*(u(1,i,j,k-1)-u(1,i,j,k)) + mux3*(u(1,i,j,k+1)-u(1,i,j,k)) + mux4*(u(1,i,j,k+2)-u(1,i,j,k)) ); // rr derivative (v) // 83 ops, tot=994 cof1 = (2*mu(i,j,k-2)+la(i,j,k-2))*met(3,i,j,k-2)*stry(j)*met(3,i,j,k-2)*stry(j) + mu(i,j,k-2)*(met(2,i,j,k-2)*strx(i)*met(2,i,j,k-2)*strx(i)+ met(4,i,j,k-2)*met(4,i,j,k-2)); cof2 = (2*mu(i,j,k-1)+la(i,j,k-1))*met(3,i,j,k-1)*stry(j)*met(3,i,j,k-1)*stry(j) + mu(i,j,k-1)*(met(2,i,j,k-1)*strx(i)*met(2,i,j,k-1)*strx(i)+ met(4,i,j,k-1)*met(4,i,j,k-1)); cof3 = (2*mu(i,j,k)+la(i,j,k))*met(3,i,j,k)*stry(j)*met(3,i,j,k)*stry(j) + mu(i,j,k)*(met(2,i,j,k)*strx(i)*met(2,i,j,k)*strx(i)+ met(4,i,j,k)*met(4,i,j,k)); cof4 = (2*mu(i,j,k+1)+la(i,j,k+1))*met(3,i,j,k+1)*stry(j)*met(3,i,j,k+1)*stry(j) + mu(i,j,k+1)*(met(2,i,j,k+1)*strx(i)*met(2,i,j,k+1)*strx(i)+ met(4,i,j,k+1)*met(4,i,j,k+1)); cof5 = (2*mu(i,j,k+2)+la(i,j,k+2))*met(3,i,j,k+2)*stry(j)*met(3,i,j,k+2)*stry(j) + mu(i,j,k+2)*(met(2,i,j,k+2)*strx(i)*met(2,i,j,k+2)*strx(i)+ met(4,i,j,k+2)*met(4,i,j,k+2)); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(2,i,j,k-2)-u(2,i,j,k)) + mux2*(u(2,i,j,k-1)-u(2,i,j,k)) + mux3*(u(2,i,j,k+1)-u(2,i,j,k)) + mux4*(u(2,i,j,k+2)-u(2,i,j,k)) )*istrxy; // rr derivative (w) // 43 ops, tot=1037 cof1=(mu(i,j,k-2)+la(i,j,k-2))*met(3,i,j,k-2)*met(4,i,j,k-2); cof2=(mu(i,j,k-1)+la(i,j,k-1))*met(3,i,j,k-1)*met(4,i,j,k-1); cof3=(mu(i,j,k) +la(i,j,k) )*met(3,i,j,k)* met(4,i,j,k); cof4=(mu(i,j,k+1)+la(i,j,k+1))*met(3,i,j,k+1)*met(4,i,j,k+1); cof5=(mu(i,j,k+2)+la(i,j,k+2))*met(3,i,j,k+2)*met(4,i,j,k+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(3,i,j,k-2)-u(3,i,j,k)) + mux2*(u(3,i,j,k-1)-u(3,i,j,k)) + mux3*(u(3,i,j,k+1)-u(3,i,j,k)) + mux4*(u(3,i,j,k+2)-u(3,i,j,k)) )*istrx; // pq-derivatives // 38 ops, tot=1075 r1 += c2*( la(i,j+2,k)*met(1,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(1,i+2,j+2,k)-u(1,i-2,j+2,k)) + c1*(u(1,i+1,j+2,k)-u(1,i-1,j+2,k)) ) - la(i,j-2,k)*met(1,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(1,i+2,j-2,k)-u(1,i-2,j-2,k))+ c1*(u(1,i+1,j-2,k)-u(1,i-1,j-2,k)) ) ) + c1*( la(i,j+1,k)*met(1,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(1,i+2,j+1,k)-u(1,i-2,j+1,k)) + c1*(u(1,i+1,j+1,k)-u(1,i-1,j+1,k)) ) - la(i,j-1,k)*met(1,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(1,i+2,j-1,k)-u(1,i-2,j-1,k)) + c1*(u(1,i+1,j-1,k)-u(1,i-1,j-1,k)))); // qp-derivatives // 38 ops, tot=1113 r1 += c2*( mu(i+2,j,k)*met(1,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(1,i+2,j+2,k)-u(1,i+2,j-2,k)) + c1*(u(1,i+2,j+1,k)-u(1,i+2,j-1,k)) ) - mu(i-2,j,k)*met(1,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(1,i-2,j+2,k)-u(1,i-2,j-2,k))+ c1*(u(1,i-2,j+1,k)-u(1,i-2,j-1,k)) ) ) + c1*( mu(i+1,j,k)*met(1,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(1,i+1,j+2,k)-u(1,i+1,j-2,k)) + c1*(u(1,i+1,j+1,k)-u(1,i+1,j-1,k)) ) - mu(i-1,j,k)*met(1,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(1,i-1,j+2,k)-u(1,i-1,j-2,k)) + c1*(u(1,i-1,j+1,k)-u(1,i-1,j-1,k)))); // pr-derivatives // 82 ops, tot=1195 r1 += c2*( (la(i,j,k+2))*met(3,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(1,i+2,j,k+2)-u(1,i-2,j,k+2)) + c1*(u(1,i+1,j,k+2)-u(1,i-1,j,k+2)) ) + mu(i,j,k+2)*met(2,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(2,i+2,j,k+2)-u(2,i-2,j,k+2)) + c1*(u(2,i+1,j,k+2)-u(2,i-1,j,k+2)) )*strx(i)*istry - ((la(i,j,k-2))*met(3,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(1,i+2,j,k-2)-u(1,i-2,j,k-2)) + c1*(u(1,i+1,j,k-2)-u(1,i-1,j,k-2)) ) + mu(i,j,k-2)*met(2,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(2,i+2,j,k-2)-u(2,i-2,j,k-2)) + c1*(u(2,i+1,j,k-2)-u(2,i-1,j,k-2)) )*strx(i)*istry ) ) + c1*( (la(i,j,k+1))*met(3,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(1,i+2,j,k+1)-u(1,i-2,j,k+1)) + c1*(u(1,i+1,j,k+1)-u(1,i-1,j,k+1)) ) + mu(i,j,k+1)*met(2,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(2,i+2,j,k+1)-u(2,i-2,j,k+1)) + c1*(u(2,i+1,j,k+1)-u(2,i-1,j,k+1)) )*strx(i)*istry - (la(i,j,k-1)*met(3,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(1,i+2,j,k-1)-u(1,i-2,j,k-1)) + c1*(u(1,i+1,j,k-1)-u(1,i-1,j,k-1)) ) + mu(i,j,k-1)*met(2,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(2,i+2,j,k-1)-u(2,i-2,j,k-1)) + c1*(u(2,i+1,j,k-1)-u(2,i-1,j,k-1)) )*strx(i)*istry ) ); // rp derivatives // 82 ops, tot=1277 r1 += c2*( (mu(i+2,j,k))*met(3,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(1,i+2,j,k+2)-u(1,i+2,j,k-2)) + c1*(u(1,i+2,j,k+1)-u(1,i+2,j,k-1)) ) + mu(i+2,j,k)*met(2,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(2,i+2,j,k+2)-u(2,i+2,j,k-2)) + c1*(u(2,i+2,j,k+1)-u(2,i+2,j,k-1)) )*strx(i+2)*istry - (mu(i-2,j,k)*met(3,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(1,i-2,j,k+2)-u(1,i-2,j,k-2)) + c1*(u(1,i-2,j,k+1)-u(1,i-2,j,k-1)) ) + mu(i-2,j,k)*met(2,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(2,i-2,j,k+2)-u(2,i-2,j,k-2)) + c1*(u(2,i-2,j,k+1)-u(2,i-2,j,k-1)) )*strx(i-2)*istry ) ) + c1*( (mu(i+1,j,k))*met(3,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(1,i+1,j,k+2)-u(1,i+1,j,k-2)) + c1*(u(1,i+1,j,k+1)-u(1,i+1,j,k-1)) ) + mu(i+1,j,k)*met(2,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(2,i+1,j,k+2)-u(2,i+1,j,k-2)) + c1*(u(2,i+1,j,k+1)-u(2,i+1,j,k-1)) )*strx(i+1)*istry - (mu(i-1,j,k)*met(3,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(1,i-1,j,k+2)-u(1,i-1,j,k-2)) + c1*(u(1,i-1,j,k+1)-u(1,i-1,j,k-1)) ) + mu(i-1,j,k)*met(2,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(2,i-1,j,k+2)-u(2,i-1,j,k-2)) + c1*(u(2,i-1,j,k+1)-u(2,i-1,j,k-1)) )*strx(i-1)*istry ) ); // qr derivatives // 130 ops, tot=1407 r1 += c2*( mu(i,j,k+2)*met(2,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(1,i,j+2,k+2)-u(1,i,j-2,k+2)) + c1*(u(1,i,j+1,k+2)-u(1,i,j-1,k+2)) ) + (2*mu(i,j,k+2)+la(i,j,k+2))*met(3,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(2,i,j+2,k+2)-u(2,i,j-2,k+2)) + c1*(u(2,i,j+1,k+2)-u(2,i,j-1,k+2)) )*stry(j)*istrx +mu(i,j,k+2)*met(4,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(3,i,j+2,k+2)-u(3,i,j-2,k+2)) + c1*(u(3,i,j+1,k+2)-u(3,i,j-1,k+2)) )*istrx - ( mu(i,j,k-2)*met(2,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(1,i,j+2,k-2)-u(1,i,j-2,k-2)) + c1*(u(1,i,j+1,k-2)-u(1,i,j-1,k-2)) ) +(2*mu(i,j,k-2)+ la(i,j,k-2))*met(3,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(2,i,j+2,k-2)-u(2,i,j-2,k-2)) + c1*(u(2,i,j+1,k-2)-u(2,i,j-1,k-2)) )*stry(j)*istrx + mu(i,j,k-2)*met(4,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(3,i,j+2,k-2)-u(3,i,j-2,k-2)) + c1*(u(3,i,j+1,k-2)-u(3,i,j-1,k-2)) )*istrx ) ) + c1*( mu(i,j,k+1)*met(2,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(1,i,j+2,k+1)-u(1,i,j-2,k+1)) + c1*(u(1,i,j+1,k+1)-u(1,i,j-1,k+1)) ) + (2*mu(i,j,k+1)+la(i,j,k+1))*met(3,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(2,i,j+2,k+1)-u(2,i,j-2,k+1)) + c1*(u(2,i,j+1,k+1)-u(2,i,j-1,k+1)) )*stry(j)*istrx + mu(i,j,k+1)*met(4,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(3,i,j+2,k+1)-u(3,i,j-2,k+1)) + c1*(u(3,i,j+1,k+1)-u(3,i,j-1,k+1)) )*istrx - ( mu(i,j,k-1)*met(2,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(1,i,j+2,k-1)-u(1,i,j-2,k-1)) + c1*(u(1,i,j+1,k-1)-u(1,i,j-1,k-1)) ) + (2*mu(i,j,k-1)+la(i,j,k-1))*met(3,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(2,i,j+2,k-1)-u(2,i,j-2,k-1)) + c1*(u(2,i,j+1,k-1)-u(2,i,j-1,k-1)) )*stry(j)*istrx + mu(i,j,k-1)*met(4,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(3,i,j+2,k-1)-u(3,i,j-2,k-1)) + c1*(u(3,i,j+1,k-1)-u(3,i,j-1,k-1)) )*istrx ) ); // rq derivatives // 130 ops, tot=1537 r1 += c2*( la(i,j+2,k)*met(2,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(1,i,j+2,k+2)-u(1,i,j+2,k-2)) + c1*(u(1,i,j+2,k+1)-u(1,i,j+2,k-1)) ) +(2*mu(i,j+2,k)+la(i,j+2,k))*met(3,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(2,i,j+2,k+2)-u(2,i,j+2,k-2)) + c1*(u(2,i,j+2,k+1)-u(2,i,j+2,k-1)) )*stry(j+2)*istrx + la(i,j+2,k)*met(4,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(3,i,j+2,k+2)-u(3,i,j+2,k-2)) + c1*(u(3,i,j+2,k+1)-u(3,i,j+2,k-1)) )*istrx - ( la(i,j-2,k)*met(2,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(1,i,j-2,k+2)-u(1,i,j-2,k-2)) + c1*(u(1,i,j-2,k+1)-u(1,i,j-2,k-1)) ) +(2*mu(i,j-2,k)+la(i,j-2,k))*met(3,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(2,i,j-2,k+2)-u(2,i,j-2,k-2)) + c1*(u(2,i,j-2,k+1)-u(2,i,j-2,k-1)) )*stry(j-2)*istrx + la(i,j-2,k)*met(4,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(3,i,j-2,k+2)-u(3,i,j-2,k-2)) + c1*(u(3,i,j-2,k+1)-u(3,i,j-2,k-1)) )*istrx ) ) + c1*( la(i,j+1,k)*met(2,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(1,i,j+1,k+2)-u(1,i,j+1,k-2)) + c1*(u(1,i,j+1,k+1)-u(1,i,j+1,k-1)) ) + (2*mu(i,j+1,k)+la(i,j+1,k))*met(3,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(2,i,j+1,k+2)-u(2,i,j+1,k-2)) + c1*(u(2,i,j+1,k+1)-u(2,i,j+1,k-1)) )*stry(j+1)*istrx +la(i,j+1,k)*met(4,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(3,i,j+1,k+2)-u(3,i,j+1,k-2)) + c1*(u(3,i,j+1,k+1)-u(3,i,j+1,k-1)) )*istrx - ( la(i,j-1,k)*met(2,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(1,i,j-1,k+2)-u(1,i,j-1,k-2)) + c1*(u(1,i,j-1,k+1)-u(1,i,j-1,k-1)) ) + (2*mu(i,j-1,k)+la(i,j-1,k))*met(3,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(2,i,j-1,k+2)-u(2,i,j-1,k-2)) + c1*(u(2,i,j-1,k+1)-u(2,i,j-1,k-1)) )*stry(j-1)*istrx + la(i,j-1,k)*met(4,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(3,i,j-1,k+2)-u(3,i,j-1,k-2)) + c1*(u(3,i,j-1,k+1)-u(3,i,j-1,k-1)) )*istrx ) ); // 4 ops, tot=1541 lu(2,i,j,k) = a1*lu(2,i,j,k) + r1*ijac; // w-equation r1 = 0; // pp derivative (w) // 43 ops, tot=1580 cof1=(mu(i-2,j,k))*met(1,i-2,j,k)*met(1,i-2,j,k)*strx(i-2); cof2=(mu(i-1,j,k))*met(1,i-1,j,k)*met(1,i-1,j,k)*strx(i-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*strx(i); cof4=(mu(i+1,j,k))*met(1,i+1,j,k)*met(1,i+1,j,k)*strx(i+1); cof5=(mu(i+2,j,k))*met(1,i+2,j,k)*met(1,i+2,j,k)*strx(i+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(3,i-2,j,k)-u(3,i,j,k)) + mux2*(u(3,i-1,j,k)-u(3,i,j,k)) + mux3*(u(3,i+1,j,k)-u(3,i,j,k)) + mux4*(u(3,i+2,j,k)-u(3,i,j,k)) )*istry; // qq derivative (w) // 43 ops, tot=1623 cof1=(mu(i,j-2,k))*met(1,i,j-2,k)*met(1,i,j-2,k)*stry(j-2); cof2=(mu(i,j-1,k))*met(1,i,j-1,k)*met(1,i,j-1,k)*stry(j-1); cof3=(mu(i,j,k))*met(1,i,j,k)*met(1,i,j,k)*stry(j); cof4=(mu(i,j+1,k))*met(1,i,j+1,k)*met(1,i,j+1,k)*stry(j+1); cof5=(mu(i,j+2,k))*met(1,i,j+2,k)*met(1,i,j+2,k)*stry(j+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(3,i,j-2,k)-u(3,i,j,k)) + mux2*(u(3,i,j-1,k)-u(3,i,j,k)) + mux3*(u(3,i,j+1,k)-u(3,i,j,k)) + mux4*(u(3,i,j+2,k)-u(3,i,j,k)) )*istrx; // rr derivative (u) // 43 ops, tot=1666 cof1=(mu(i,j,k-2)+la(i,j,k-2))*met(2,i,j,k-2)*met(4,i,j,k-2); cof2=(mu(i,j,k-1)+la(i,j,k-1))*met(2,i,j,k-1)*met(4,i,j,k-1); cof3=(mu(i,j,k)+la(i,j,k))*met(2,i,j,k)*met(4,i,j,k); cof4=(mu(i,j,k+1)+la(i,j,k+1))*met(2,i,j,k+1)*met(4,i,j,k+1); cof5=(mu(i,j,k+2)+la(i,j,k+2))*met(2,i,j,k+2)*met(4,i,j,k+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(1,i,j,k-2)-u(1,i,j,k)) + mux2*(u(1,i,j,k-1)-u(1,i,j,k)) + mux3*(u(1,i,j,k+1)-u(1,i,j,k)) + mux4*(u(1,i,j,k+2)-u(1,i,j,k)) )*istry; // rr derivative (v) // 43 ops, tot=1709 cof1=(mu(i,j,k-2)+la(i,j,k-2))*met(3,i,j,k-2)*met(4,i,j,k-2); cof2=(mu(i,j,k-1)+la(i,j,k-1))*met(3,i,j,k-1)*met(4,i,j,k-1); cof3=(mu(i,j,k)+la(i,j,k))*met(3,i,j,k)*met(4,i,j,k); cof4=(mu(i,j,k+1)+la(i,j,k+1))*met(3,i,j,k+1)*met(4,i,j,k+1); cof5=(mu(i,j,k+2)+la(i,j,k+2))*met(3,i,j,k+2)*met(4,i,j,k+2); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(2,i,j,k-2)-u(2,i,j,k)) + mux2*(u(2,i,j,k-1)-u(2,i,j,k)) + mux3*(u(2,i,j,k+1)-u(2,i,j,k)) + mux4*(u(2,i,j,k+2)-u(2,i,j,k)) )*istrx; // rr derivative (w) // 83 ops, tot=1792 cof1 = (2*mu(i,j,k-2)+la(i,j,k-2))*met(4,i,j,k-2)*met(4,i,j,k-2) + mu(i,j,k-2)*(met(2,i,j,k-2)*strx(i)*met(2,i,j,k-2)*strx(i)+ met(3,i,j,k-2)*stry(j)*met(3,i,j,k-2)*stry(j) ); cof2 = (2*mu(i,j,k-1)+la(i,j,k-1))*met(4,i,j,k-1)*met(4,i,j,k-1) + mu(i,j,k-1)*(met(2,i,j,k-1)*strx(i)*met(2,i,j,k-1)*strx(i)+ met(3,i,j,k-1)*stry(j)*met(3,i,j,k-1)*stry(j) ); cof3 = (2*mu(i,j,k)+la(i,j,k))*met(4,i,j,k)*met(4,i,j,k) + mu(i,j,k)*(met(2,i,j,k)*strx(i)*met(2,i,j,k)*strx(i)+ met(3,i,j,k)*stry(j)*met(3,i,j,k)*stry(j) ); cof4 = (2*mu(i,j,k+1)+la(i,j,k+1))*met(4,i,j,k+1)*met(4,i,j,k+1) + mu(i,j,k+1)*(met(2,i,j,k+1)*strx(i)*met(2,i,j,k+1)*strx(i)+ met(3,i,j,k+1)*stry(j)*met(3,i,j,k+1)*stry(j)); cof5 = (2*mu(i,j,k+2)+la(i,j,k+2))*met(4,i,j,k+2)*met(4,i,j,k+2) + mu(i,j,k+2)*( met(2,i,j,k+2)*strx(i)*met(2,i,j,k+2)*strx(i)+ met(3,i,j,k+2)*stry(j)*met(3,i,j,k+2)*stry(j) ); mux1 = cof2 -tf*(cof3+cof1); mux2 = cof1 + cof4+3*(cof3+cof2); mux3 = cof2 + cof5+3*(cof4+cof3); mux4 = cof4-tf*(cof3+cof5); r1 += i6* ( mux1*(u(3,i,j,k-2)-u(3,i,j,k)) + mux2*(u(3,i,j,k-1)-u(3,i,j,k)) + mux3*(u(3,i,j,k+1)-u(3,i,j,k)) + mux4*(u(3,i,j,k+2)-u(3,i,j,k)) )*istrxy // pr-derivatives // 86 ops, tot=1878 // r1 += + c2*( (la(i,j,k+2))*met(4,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(1,i+2,j,k+2)-u(1,i-2,j,k+2)) + c1*(u(1,i+1,j,k+2)-u(1,i-1,j,k+2)) )*istry + mu(i,j,k+2)*met(2,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(3,i+2,j,k+2)-u(3,i-2,j,k+2)) + c1*(u(3,i+1,j,k+2)-u(3,i-1,j,k+2)) )*strx(i)*istry - ((la(i,j,k-2))*met(4,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(1,i+2,j,k-2)-u(1,i-2,j,k-2)) + c1*(u(1,i+1,j,k-2)-u(1,i-1,j,k-2)) )*istry + mu(i,j,k-2)*met(2,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(3,i+2,j,k-2)-u(3,i-2,j,k-2)) + c1*(u(3,i+1,j,k-2)-u(3,i-1,j,k-2)) )*strx(i)*istry ) ) + c1*( (la(i,j,k+1))*met(4,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(1,i+2,j,k+1)-u(1,i-2,j,k+1)) + c1*(u(1,i+1,j,k+1)-u(1,i-1,j,k+1)) )*istry + mu(i,j,k+1)*met(2,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(3,i+2,j,k+1)-u(3,i-2,j,k+1)) + c1*(u(3,i+1,j,k+1)-u(3,i-1,j,k+1)) )*strx(i)*istry - (la(i,j,k-1)*met(4,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(1,i+2,j,k-1)-u(1,i-2,j,k-1)) + c1*(u(1,i+1,j,k-1)-u(1,i-1,j,k-1)) )*istry + mu(i,j,k-1)*met(2,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(3,i+2,j,k-1)-u(3,i-2,j,k-1)) + c1*(u(3,i+1,j,k-1)-u(3,i-1,j,k-1)) )*strx(i)*istry ) ) // rp derivatives // 79 ops, tot=1957 // r1 += + istry*(c2*( (mu(i+2,j,k))*met(4,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(1,i+2,j,k+2)-u(1,i+2,j,k-2)) + c1*(u(1,i+2,j,k+1)-u(1,i+2,j,k-1)) ) + mu(i+2,j,k)*met(2,i+2,j,k)*met(1,i+2,j,k)*( c2*(u(3,i+2,j,k+2)-u(3,i+2,j,k-2)) + c1*(u(3,i+2,j,k+1)-u(3,i+2,j,k-1)) )*strx(i+2) - (mu(i-2,j,k)*met(4,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(1,i-2,j,k+2)-u(1,i-2,j,k-2)) + c1*(u(1,i-2,j,k+1)-u(1,i-2,j,k-1)) ) + mu(i-2,j,k)*met(2,i-2,j,k)*met(1,i-2,j,k)*( c2*(u(3,i-2,j,k+2)-u(3,i-2,j,k-2)) + c1*(u(3,i-2,j,k+1)-u(3,i-2,j,k-1)) )*strx(i-2) ) ) + c1*( (mu(i+1,j,k))*met(4,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(1,i+1,j,k+2)-u(1,i+1,j,k-2)) + c1*(u(1,i+1,j,k+1)-u(1,i+1,j,k-1)) ) + mu(i+1,j,k)*met(2,i+1,j,k)*met(1,i+1,j,k)*( c2*(u(3,i+1,j,k+2)-u(3,i+1,j,k-2)) + c1*(u(3,i+1,j,k+1)-u(3,i+1,j,k-1)) )*strx(i+1) - (mu(i-1,j,k)*met(4,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(1,i-1,j,k+2)-u(1,i-1,j,k-2)) + c1*(u(1,i-1,j,k+1)-u(1,i-1,j,k-1)) ) + mu(i-1,j,k)*met(2,i-1,j,k)*met(1,i-1,j,k)*( c2*(u(3,i-1,j,k+2)-u(3,i-1,j,k-2)) + c1*(u(3,i-1,j,k+1)-u(3,i-1,j,k-1)) )*strx(i-1) ) ) ) // qr derivatives // 86 ops, tot=2043 // r1 += + c2*( mu(i,j,k+2)*met(3,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(3,i,j+2,k+2)-u(3,i,j-2,k+2)) + c1*(u(3,i,j+1,k+2)-u(3,i,j-1,k+2)) )*stry(j)*istrx + la(i,j,k+2)*met(4,i,j,k+2)*met(1,i,j,k+2)*( c2*(u(2,i,j+2,k+2)-u(2,i,j-2,k+2)) + c1*(u(2,i,j+1,k+2)-u(2,i,j-1,k+2)) )*istrx - ( mu(i,j,k-2)*met(3,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(3,i,j+2,k-2)-u(3,i,j-2,k-2)) + c1*(u(3,i,j+1,k-2)-u(3,i,j-1,k-2)) )*stry(j)*istrx + la(i,j,k-2)*met(4,i,j,k-2)*met(1,i,j,k-2)*( c2*(u(2,i,j+2,k-2)-u(2,i,j-2,k-2)) + c1*(u(2,i,j+1,k-2)-u(2,i,j-1,k-2)) )*istrx ) ) + c1*( mu(i,j,k+1)*met(3,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(3,i,j+2,k+1)-u(3,i,j-2,k+1)) + c1*(u(3,i,j+1,k+1)-u(3,i,j-1,k+1)) )*stry(j)*istrx + la(i,j,k+1)*met(4,i,j,k+1)*met(1,i,j,k+1)*( c2*(u(2,i,j+2,k+1)-u(2,i,j-2,k+1)) + c1*(u(2,i,j+1,k+1)-u(2,i,j-1,k+1)) )*istrx - ( mu(i,j,k-1)*met(3,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(3,i,j+2,k-1)-u(3,i,j-2,k-1)) + c1*(u(3,i,j+1,k-1)-u(3,i,j-1,k-1)) )*stry(j)*istrx + la(i,j,k-1)*met(4,i,j,k-1)*met(1,i,j,k-1)*( c2*(u(2,i,j+2,k-1)-u(2,i,j-2,k-1)) + c1*(u(2,i,j+1,k-1)-u(2,i,j-1,k-1)) )*istrx ) ) // rq derivatives // 79 ops, tot=2122 // r1 += + istrx*(c2*( mu(i,j+2,k)*met(3,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(3,i,j+2,k+2)-u(3,i,j+2,k-2)) + c1*(u(3,i,j+2,k+1)-u(3,i,j+2,k-1)) )*stry(j+2) + mu(i,j+2,k)*met(4,i,j+2,k)*met(1,i,j+2,k)*( c2*(u(2,i,j+2,k+2)-u(2,i,j+2,k-2)) + c1*(u(2,i,j+2,k+1)-u(2,i,j+2,k-1)) ) - ( mu(i,j-2,k)*met(3,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(3,i,j-2,k+2)-u(3,i,j-2,k-2)) + c1*(u(3,i,j-2,k+1)-u(3,i,j-2,k-1)) )*stry(j-2) + mu(i,j-2,k)*met(4,i,j-2,k)*met(1,i,j-2,k)*( c2*(u(2,i,j-2,k+2)-u(2,i,j-2,k-2)) + c1*(u(2,i,j-2,k+1)-u(2,i,j-2,k-1)) ) ) ) + c1*( mu(i,j+1,k)*met(3,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(3,i,j+1,k+2)-u(3,i,j+1,k-2)) + c1*(u(3,i,j+1,k+1)-u(3,i,j+1,k-1)) )*stry(j+1) + mu(i,j+1,k)*met(4,i,j+1,k)*met(1,i,j+1,k)*( c2*(u(2,i,j+1,k+2)-u(2,i,j+1,k-2)) + c1*(u(2,i,j+1,k+1)-u(2,i,j+1,k-1)) ) - ( mu(i,j-1,k)*met(3,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(3,i,j-1,k+2)-u(3,i,j-1,k-2)) + c1*(u(3,i,j-1,k+1)-u(3,i,j-1,k-1)) )*stry(j-1) + mu(i,j-1,k)*met(4,i,j-1,k)*met(1,i,j-1,k)*( c2*(u(2,i,j-1,k+2)-u(2,i,j-1,k-2)) + c1*(u(2,i,j-1,k+1)-u(2,i,j-1,k-1)) ) ) ) ); // 4 ops, tot=2126 lu(3,i,j,k) = a1*lu(3,i,j,k) + r1*ijac; } } #undef mu #undef la #undef jac #undef u #undef lu #undef met #undef strx #undef stry #undef acof #undef bope #undef ghcof }
DRB012-minusminus-var-yes.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http:www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https:github.comLLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* The -- operation is not protected, causing race condition. Data race pair: numNodes2@75 vs. numNodes2@75 */ #include <stdlib.h> int main(int argc, char * argv[]) { int i; int len = 100; int numNodes = len, numNodes2 = 0; int x[len]; int _ret_val_0; if (argc>1) { len=atoi(argv[1]); } #pragma cetus private(i) #pragma loop name main#0 #pragma cetus parallel #pragma omp parallel for private(i) for (i=0; i<len; i ++ ) { if ((i%2)==0) { x[i]=5; } else { x[i]=( - 5); } } #pragma cetus private(i) #pragma loop name main#1 #pragma cetus reduction(+: numNodes2) #pragma cetus parallel #pragma omp parallel for private(i) reduction(+: numNodes2) for (i=(numNodes-1); i>( - 1); -- i) { if (x[i]<=0) { numNodes2 -- ; } } printf("numNodes2 = %d\n", numNodes2); _ret_val_0=0; return _ret_val_0; }
feature.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF EEEEE AAA TTTTT U U RRRR EEEEE % % F E A A T U U R R E % % FFF EEE AAAAA T U U RRRR EEE % % F E A A T U U R R E % % F EEEEE A A T UUU R R EEEEE % % % % % % MagickCore Image Feature 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/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/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/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/feature.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/morphology-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/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a n n y E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of % edges in images. % % The format of the CannyEdgeImage method is: % % Image *CannyEdgeImage(const Image *image,const double radius, % const double sigma,const double lower_percent, % const double upper_percent,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the gaussian smoothing filter. % % o sigma: the sigma of the gaussian smoothing filter. % % o lower_percent: percentage of edge pixels in the lower threshold. % % o upper_percent: percentage of edge pixels in the upper threshold. % % o exception: return any errors or warnings in this structure. % */ typedef struct _CannyInfo { double magnitude, intensity; int orientation; ssize_t x, y; } CannyInfo; static inline MagickBooleanType IsAuthenticPixel(const Image *image, const ssize_t x,const ssize_t y) { if ((x < 0) || (x >= (ssize_t) image->columns)) return(MagickFalse); if ((y < 0) || (y >= (ssize_t) image->rows)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view, MatrixInfo *canny_cache,const ssize_t x,const ssize_t y, const double lower_threshold,ExceptionInfo *exception) { CannyInfo edge, pixel; MagickBooleanType status; register Quantum *q; register ssize_t i; q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); edge.x=x; edge.y=y; if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); for (i=1; i != 0; ) { ssize_t v; i--; status=GetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); for (v=(-1); v <= 1; v++) { ssize_t u; for (u=(-1); u <= 1; u++) { if ((u == 0) && (v == 0)) continue; if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse) continue; /* Not an edge if gradient value is below the lower threshold. */ q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1, exception); if (q == (Quantum *) NULL) return(MagickFalse); status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel); if (status == MagickFalse) return(MagickFalse); if ((GetPixelIntensity(edge_image,q) == 0.0) && (pixel.intensity >= lower_threshold)) { *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); edge.x+=u; edge.y+=v; status=SetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); i++; } } } } return(MagickTrue); } MagickExport Image *CannyEdgeImage(const Image *image,const double radius, const double sigma,const double lower_percent,const double upper_percent, ExceptionInfo *exception) { #define CannyEdgeImageTag "CannyEdge/Image" CacheView *edge_view; CannyInfo element; char geometry[MagickPathExtent]; double lower_threshold, max, min, upper_threshold; Image *edge_image; KernelInfo *kernel_info; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *canny_cache; ssize_t y; 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); /* Filter out noise. */ (void) FormatLocaleString(geometry,MagickPathExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); edge_image=MorphologyImage(image,ConvolveMorphology,1,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (edge_image == (Image *) NULL) return((Image *) NULL); if (TransformImageColorspace(edge_image,GRAYColorspace,exception) == MagickFalse) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } (void) SetImageAlphaChannel(edge_image,OffAlphaChannel,exception); /* Find the intensity gradient of the image. */ canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows, sizeof(CannyInfo),exception); if (canny_cache == (MatrixInfo *) NULL) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } status=MagickTrue; edge_view=AcquireVirtualCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; double dx, dy; register const Quantum *magick_restrict kernel_pixels; ssize_t v; static double Gx[2][2] = { { -1.0, +1.0 }, { -1.0, +1.0 } }, Gy[2][2] = { { +1.0, +1.0 }, { -1.0, -1.0 } }; (void) memset(&pixel,0,sizeof(pixel)); dx=0.0; dy=0.0; kernel_pixels=p; for (v=0; v < 2; v++) { ssize_t u; for (u=0; u < 2; u++) { double intensity; intensity=GetPixelIntensity(edge_image,kernel_pixels+u); dx+=0.5*Gx[v][u]*intensity; dy+=0.5*Gy[v][u]*intensity; } kernel_pixels+=edge_image->columns+1; } pixel.magnitude=hypot(dx,dy); pixel.orientation=0; if (fabs(dx) > MagickEpsilon) { double slope; slope=dy/dx; if (slope < 0.0) { if (slope < -2.41421356237) pixel.orientation=0; else if (slope < -0.414213562373) pixel.orientation=1; else pixel.orientation=2; } else { if (slope > 2.41421356237) pixel.orientation=0; else if (slope > 0.414213562373) pixel.orientation=3; else pixel.orientation=2; } } if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse) continue; p+=GetPixelChannels(edge_image); } } edge_view=DestroyCacheView(edge_view); /* Non-maxima suppression, remove pixels that are not considered to be part of an edge. */ progress=0; (void) GetMatrixElement(canny_cache,0,0,&element); max=element.intensity; min=element.intensity; edge_view=AcquireAuthenticCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo alpha_pixel, beta_pixel, pixel; (void) GetMatrixElement(canny_cache,x,y,&pixel); switch (pixel.orientation) { case 0: default: { /* 0 degrees, north and south. */ (void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel); break; } case 1: { /* 45 degrees, northwest and southeast. */ (void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel); break; } case 2: { /* 90 degrees, east and west. */ (void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel); break; } case 3: { /* 135 degrees, northeast and southwest. */ (void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel); (void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel); break; } } pixel.intensity=pixel.magnitude; if ((pixel.magnitude < alpha_pixel.magnitude) || (pixel.magnitude < beta_pixel.magnitude)) pixel.intensity=0; (void) SetMatrixElement(canny_cache,x,y,&pixel); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif { if (pixel.intensity < min) min=pixel.intensity; if (pixel.intensity > max) max=pixel.intensity; } *q=0; q+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse) status=MagickFalse; } edge_view=DestroyCacheView(edge_view); /* Estimate hysteresis threshold. */ lower_threshold=lower_percent*(max-min)+min; upper_threshold=upper_percent*(max-min)+min; /* Hysteresis threshold. */ edge_view=AcquireAuthenticCacheView(edge_image,exception); for (y=0; y < (ssize_t) edge_image->rows; y++) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; register const Quantum *magick_restrict p; /* Edge if pixel gradient higher than upper threshold. */ p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) continue; status=GetMatrixElement(canny_cache,x,y,&pixel); if (status == MagickFalse) continue; if ((GetPixelIntensity(edge_image,p) == 0.0) && (pixel.intensity >= upper_threshold)) status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold, exception); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } edge_view=DestroyCacheView(edge_view); /* Free resources. */ canny_cache=DestroyMatrixInfo(canny_cache); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e F e a t u r e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageFeatures() returns features for each channel in the image in % each of four directions (horizontal, vertical, left and right diagonals) % for the specified distance. The features include the angular second % moment, contrast, correlation, sum of squares: variance, inverse difference % moment, sum average, sum varience, sum entropy, entropy, difference variance, % difference entropy, information measures of correlation 1, information % measures of correlation 2, and maximum correlation coefficient. You can % access the red channel contrast, for example, like this: % % channel_features=GetImageFeatures(image,1,exception); % contrast=channel_features[RedPixelChannel].contrast[0]; % % Use MagickRelinquishMemory() to free the features buffer. % % The format of the GetImageFeatures method is: % % ChannelFeatures *GetImageFeatures(const Image *image, % const size_t distance,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o distance: the distance. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelFeatures *GetImageFeatures(const Image *image, const size_t distance,ExceptionInfo *exception) { typedef struct _ChannelStatistics { PixelInfo direction[4]; /* horizontal, vertical, left and right diagonals */ } ChannelStatistics; CacheView *image_view; ChannelFeatures *channel_features; ChannelStatistics **cooccurrence, correlation, *density_x, *density_xy, *density_y, entropy_x, entropy_xy, entropy_xy1, entropy_xy2, entropy_y, mean, **Q, *sum, sum_squares, variance; PixelPacket gray, *grays; MagickBooleanType status; register ssize_t i, r; size_t length; unsigned int number_grays; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns < (distance+1)) || (image->rows < (distance+1))) return((ChannelFeatures *) NULL); length=MaxPixelChannels+1UL; channel_features=(ChannelFeatures *) AcquireQuantumMemory(length, sizeof(*channel_features)); if (channel_features == (ChannelFeatures *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_features,0,length* sizeof(*channel_features)); /* Form grays. */ grays=(PixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays)); if (grays == (PixelPacket *) NULL) { channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } for (i=0; i <= (ssize_t) MaxMap; i++) { grays[i].red=(~0U); grays[i].green=(~0U); grays[i].blue=(~0U); grays[i].alpha=(~0U); grays[i].black=(~0U); } 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 (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,r,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { grays[ScaleQuantumToMap(GetPixelRed(image,p))].red= ScaleQuantumToMap(GetPixelRed(image,p)); grays[ScaleQuantumToMap(GetPixelGreen(image,p))].green= ScaleQuantumToMap(GetPixelGreen(image,p)); grays[ScaleQuantumToMap(GetPixelBlue(image,p))].blue= ScaleQuantumToMap(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) grays[ScaleQuantumToMap(GetPixelBlack(image,p))].black= ScaleQuantumToMap(GetPixelBlack(image,p)); if (image->alpha_trait != UndefinedPixelTrait) grays[ScaleQuantumToMap(GetPixelAlpha(image,p))].alpha= ScaleQuantumToMap(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); return(channel_features); } (void) memset(&gray,0,sizeof(gray)); for (i=0; i <= (ssize_t) MaxMap; i++) { if (grays[i].red != ~0U) grays[gray.red++].red=grays[i].red; if (grays[i].green != ~0U) grays[gray.green++].green=grays[i].green; if (grays[i].blue != ~0U) grays[gray.blue++].blue=grays[i].blue; if (image->colorspace == CMYKColorspace) if (grays[i].black != ~0U) grays[gray.black++].black=grays[i].black; if (image->alpha_trait != UndefinedPixelTrait) if (grays[i].alpha != ~0U) grays[gray.alpha++].alpha=grays[i].alpha; } /* Allocate spatial dependence matrix. */ number_grays=gray.red; if (gray.green > number_grays) number_grays=gray.green; if (gray.blue > number_grays) number_grays=gray.blue; if (image->colorspace == CMYKColorspace) if (gray.black > number_grays) number_grays=gray.black; if (image->alpha_trait != UndefinedPixelTrait) if (gray.alpha > number_grays) number_grays=gray.alpha; cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays, sizeof(*cooccurrence)); density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_x)); density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_xy)); density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_y)); Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q)); sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum)); if ((cooccurrence == (ChannelStatistics **) NULL) || (density_x == (ChannelStatistics *) NULL) || (density_xy == (ChannelStatistics *) NULL) || (density_y == (ChannelStatistics *) NULL) || (Q == (ChannelStatistics **) NULL) || (sum == (ChannelStatistics *) NULL)) { if (Q != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); } if (sum != (ChannelStatistics *) NULL) sum=(ChannelStatistics *) RelinquishMagickMemory(sum); if (density_y != (ChannelStatistics *) NULL) density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); if (density_xy != (ChannelStatistics *) NULL) density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); if (density_x != (ChannelStatistics *) NULL) density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); if (cooccurrence != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory( cooccurrence); } grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } (void) memset(&correlation,0,sizeof(correlation)); (void) memset(density_x,0,2*(number_grays+1)*sizeof(*density_x)); (void) memset(density_xy,0,2*(number_grays+1)*sizeof(*density_xy)); (void) memset(density_y,0,2*(number_grays+1)*sizeof(*density_y)); (void) memset(&mean,0,sizeof(mean)); (void) memset(sum,0,number_grays*sizeof(*sum)); (void) memset(&sum_squares,0,sizeof(sum_squares)); (void) memset(density_xy,0,2*number_grays*sizeof(*density_xy)); (void) memset(&entropy_x,0,sizeof(entropy_x)); (void) memset(&entropy_xy,0,sizeof(entropy_xy)); (void) memset(&entropy_xy1,0,sizeof(entropy_xy1)); (void) memset(&entropy_xy2,0,sizeof(entropy_xy2)); (void) memset(&entropy_y,0,sizeof(entropy_y)); (void) memset(&variance,0,sizeof(variance)); for (i=0; i < (ssize_t) number_grays; i++) { cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays, sizeof(**cooccurrence)); Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q)); if ((cooccurrence[i] == (ChannelStatistics *) NULL) || (Q[i] == (ChannelStatistics *) NULL)) break; (void) memset(cooccurrence[i],0,number_grays* sizeof(**cooccurrence)); (void) memset(Q[i],0,number_grays*sizeof(**Q)); } if (i < (ssize_t) number_grays) { for (i--; i >= 0; i--) { if (Q[i] != (ChannelStatistics *) NULL) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); if (cooccurrence[i] != (ChannelStatistics *) NULL) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); } Q=(ChannelStatistics **) RelinquishMagickMemory(Q); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); sum=(ChannelStatistics *) RelinquishMagickMemory(sum); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Initialize spatial dependence matrix. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); for (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; ssize_t offset, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,r,image->columns+ 2*distance,distance+2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } p+=distance*GetPixelChannels(image);; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < 4; i++) { switch (i) { case 0: default: { /* Horizontal adjacency. */ offset=(ssize_t) distance; break; } case 1: { /* Vertical adjacency. */ offset=(ssize_t) (image->columns+2*distance); break; } case 2: { /* Right diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)-distance); break; } case 3: { /* Left diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)+distance); break; } } u=0; v=0; while (grays[u].red != ScaleQuantumToMap(GetPixelRed(image,p))) u++; while (grays[v].red != ScaleQuantumToMap(GetPixelRed(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].red++; cooccurrence[v][u].direction[i].red++; u=0; v=0; while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(image,p))) u++; while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].green++; cooccurrence[v][u].direction[i].green++; u=0; v=0; while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(image,p))) u++; while (grays[v].blue != ScaleQuantumToMap(GetPixelBlue(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].blue++; cooccurrence[v][u].direction[i].blue++; if (image->colorspace == CMYKColorspace) { u=0; v=0; while (grays[u].black != ScaleQuantumToMap(GetPixelBlack(image,p))) u++; while (grays[v].black != ScaleQuantumToMap(GetPixelBlack(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].black++; cooccurrence[v][u].direction[i].black++; } if (image->alpha_trait != UndefinedPixelTrait) { u=0; v=0; while (grays[u].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p))) u++; while (grays[v].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].alpha++; cooccurrence[v][u].direction[i].alpha++; } } p+=GetPixelChannels(image); } } grays=(PixelPacket *) RelinquishMagickMemory(grays); image_view=DestroyCacheView(image_view); if (status == MagickFalse) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Normalize spatial dependence matrix. */ for (i=0; i < 4; i++) { double normalize; register ssize_t y; switch (i) { case 0: default: { /* Horizontal adjacency. */ normalize=2.0*image->rows*(image->columns-distance); break; } case 1: { /* Vertical adjacency. */ normalize=2.0*(image->rows-distance)*image->columns; break; } case 2: { /* Right diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } case 3: { /* Left diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } } normalize=PerceptibleReciprocal(normalize); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { cooccurrence[x][y].direction[i].red*=normalize; cooccurrence[x][y].direction[i].green*=normalize; cooccurrence[x][y].direction[i].blue*=normalize; if (image->colorspace == CMYKColorspace) cooccurrence[x][y].direction[i].black*=normalize; if (image->alpha_trait != UndefinedPixelTrait) cooccurrence[x][y].direction[i].alpha*=normalize; } } } /* Compute texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Angular second moment: measure of homogeneity of the image. */ channel_features[RedPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].red* cooccurrence[x][y].direction[i].red; channel_features[GreenPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].green* cooccurrence[x][y].direction[i].green; channel_features[BluePixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].blue* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].black* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].alpha* cooccurrence[x][y].direction[i].alpha; /* Correlation: measure of linear-dependencies in the image. */ sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red; sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green; sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) sum[y].direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum[y].direction[i].alpha+=cooccurrence[x][y].direction[i].alpha; correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red; correlation.direction[i].green+=x*y* cooccurrence[x][y].direction[i].green; correlation.direction[i].blue+=x*y* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) correlation.direction[i].black+=x*y* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) correlation.direction[i].alpha+=x*y* cooccurrence[x][y].direction[i].alpha; /* Inverse Difference Moment. */ channel_features[RedPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1); channel_features[GreenPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1); channel_features[BluePixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].black/((y-x)*(y-x)+1); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].alpha/((y-x)*(y-x)+1); /* Sum average. */ density_xy[y+x+2].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[y+x+2].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[y+x+2].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[y+x+2].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[y+x+2].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Entropy. */ channel_features[RedPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); channel_features[GreenPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); channel_features[BluePixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].alpha* MagickLog10(cooccurrence[x][y].direction[i].alpha); /* Information Measures of Correlation. */ density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red; density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green; density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->alpha_trait != UndefinedPixelTrait) density_x[x].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; if (image->colorspace == CMYKColorspace) density_x[x].direction[i].black+= cooccurrence[x][y].direction[i].black; density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red; density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green; density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_y[y].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_y[y].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } mean.direction[i].red+=y*sum[y].direction[i].red; sum_squares.direction[i].red+=y*y*sum[y].direction[i].red; mean.direction[i].green+=y*sum[y].direction[i].green; sum_squares.direction[i].green+=y*y*sum[y].direction[i].green; mean.direction[i].blue+=y*sum[y].direction[i].blue; sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue; if (image->colorspace == CMYKColorspace) { mean.direction[i].black+=y*sum[y].direction[i].black; sum_squares.direction[i].black+=y*y*sum[y].direction[i].black; } if (image->alpha_trait != UndefinedPixelTrait) { mean.direction[i].alpha+=y*sum[y].direction[i].alpha; sum_squares.direction[i].alpha+=y*y*sum[y].direction[i].alpha; } } /* Correlation: measure of linear-dependencies in the image. */ channel_features[RedPixelChannel].correlation[i]= (correlation.direction[i].red-mean.direction[i].red* mean.direction[i].red)/(sqrt(sum_squares.direction[i].red- (mean.direction[i].red*mean.direction[i].red))*sqrt( sum_squares.direction[i].red-(mean.direction[i].red* mean.direction[i].red))); channel_features[GreenPixelChannel].correlation[i]= (correlation.direction[i].green-mean.direction[i].green* mean.direction[i].green)/(sqrt(sum_squares.direction[i].green- (mean.direction[i].green*mean.direction[i].green))*sqrt( sum_squares.direction[i].green-(mean.direction[i].green* mean.direction[i].green))); channel_features[BluePixelChannel].correlation[i]= (correlation.direction[i].blue-mean.direction[i].blue* mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue- (mean.direction[i].blue*mean.direction[i].blue))*sqrt( sum_squares.direction[i].blue-(mean.direction[i].blue* mean.direction[i].blue))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].correlation[i]= (correlation.direction[i].black-mean.direction[i].black* mean.direction[i].black)/(sqrt(sum_squares.direction[i].black- (mean.direction[i].black*mean.direction[i].black))*sqrt( sum_squares.direction[i].black-(mean.direction[i].black* mean.direction[i].black))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].correlation[i]= (correlation.direction[i].alpha-mean.direction[i].alpha* mean.direction[i].alpha)/(sqrt(sum_squares.direction[i].alpha- (mean.direction[i].alpha*mean.direction[i].alpha))*sqrt( sum_squares.direction[i].alpha-(mean.direction[i].alpha* mean.direction[i].alpha))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=2; x < (ssize_t) (2*number_grays); x++) { /* Sum average. */ channel_features[RedPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_average[i]+= x*density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].alpha; /* Sum entropy. */ channel_features[RedPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].sum_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Sum variance. */ channel_features[RedPixelChannel].sum_variance[i]+= (x-channel_features[RedPixelChannel].sum_entropy[i])* (x-channel_features[RedPixelChannel].sum_entropy[i])* density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_variance[i]+= (x-channel_features[GreenPixelChannel].sum_entropy[i])* (x-channel_features[GreenPixelChannel].sum_entropy[i])* density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_variance[i]+= (x-channel_features[BluePixelChannel].sum_entropy[i])* (x-channel_features[BluePixelChannel].sum_entropy[i])* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_variance[i]+= (x-channel_features[BlackPixelChannel].sum_entropy[i])* (x-channel_features[BlackPixelChannel].sum_entropy[i])* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_variance[i]+= (x-channel_features[AlphaPixelChannel].sum_entropy[i])* (x-channel_features[AlphaPixelChannel].sum_entropy[i])* density_xy[x].direction[i].alpha; } } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Sum of Squares: Variance */ variance.direction[i].red+=(y-mean.direction[i].red+1)* (y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red; variance.direction[i].green+=(y-mean.direction[i].green+1)* (y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green; variance.direction[i].blue+=(y-mean.direction[i].blue+1)* (y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=(y-mean.direction[i].black+1)* (y-mean.direction[i].black+1)*cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=(y-mean.direction[i].alpha+1)* (y-mean.direction[i].alpha+1)* cooccurrence[x][y].direction[i].alpha; /* Sum average / Difference Variance. */ density_xy[MagickAbsoluteValue(y-x)].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[MagickAbsoluteValue(y-x)].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[MagickAbsoluteValue(y-x)].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[MagickAbsoluteValue(y-x)].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Information Measures of Correlation. */ entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) entropy_xy.direction[i].black-=cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy.direction[i].alpha-= cooccurrence[x][y].direction[i].alpha*MagickLog10( cooccurrence[x][y].direction[i].alpha); entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red* MagickLog10(density_x[x].direction[i].red*density_y[y].direction[i].red)); entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green* MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue* MagickLog10(density_x[x].direction[i].blue*density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy1.direction[i].black-=( cooccurrence[x][y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy1.direction[i].alpha-=( cooccurrence[x][y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); entropy_xy2.direction[i].red-=(density_x[x].direction[i].red* density_y[y].direction[i].red*MagickLog10(density_x[x].direction[i].red* density_y[y].direction[i].red)); entropy_xy2.direction[i].green-=(density_x[x].direction[i].green* density_y[y].direction[i].green*MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue* density_y[y].direction[i].blue*MagickLog10(density_x[x].direction[i].blue* density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy2.direction[i].black-=(density_x[x].direction[i].black* density_y[y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy2.direction[i].alpha-=(density_x[x].direction[i].alpha* density_y[y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); } } channel_features[RedPixelChannel].variance_sum_of_squares[i]= variance.direction[i].red; channel_features[GreenPixelChannel].variance_sum_of_squares[i]= variance.direction[i].green; channel_features[BluePixelChannel].variance_sum_of_squares[i]= variance.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].variance_sum_of_squares[i]= variance.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].variance_sum_of_squares[i]= variance.direction[i].alpha; } /* Compute more texture features. */ (void) memset(&variance,0,sizeof(variance)); (void) memset(&sum_squares,0,sizeof(sum_squares)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Difference variance. */ variance.direction[i].red+=density_xy[x].direction[i].red; variance.direction[i].green+=density_xy[x].direction[i].green; variance.direction[i].blue+=density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=density_xy[x].direction[i].alpha; sum_squares.direction[i].red+=density_xy[x].direction[i].red* density_xy[x].direction[i].red; sum_squares.direction[i].green+=density_xy[x].direction[i].green* density_xy[x].direction[i].green; sum_squares.direction[i].blue+=density_xy[x].direction[i].blue* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) sum_squares.direction[i].black+=density_xy[x].direction[i].black* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum_squares.direction[i].alpha+=density_xy[x].direction[i].alpha* density_xy[x].direction[i].alpha; /* Difference entropy. */ channel_features[RedPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].difference_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Information Measures of Correlation. */ entropy_x.direction[i].red-=(density_x[x].direction[i].red* MagickLog10(density_x[x].direction[i].red)); entropy_x.direction[i].green-=(density_x[x].direction[i].green* MagickLog10(density_x[x].direction[i].green)); entropy_x.direction[i].blue-=(density_x[x].direction[i].blue* MagickLog10(density_x[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_x.direction[i].black-=(density_x[x].direction[i].black* MagickLog10(density_x[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_x.direction[i].alpha-=(density_x[x].direction[i].alpha* MagickLog10(density_x[x].direction[i].alpha)); entropy_y.direction[i].red-=(density_y[x].direction[i].red* MagickLog10(density_y[x].direction[i].red)); entropy_y.direction[i].green-=(density_y[x].direction[i].green* MagickLog10(density_y[x].direction[i].green)); entropy_y.direction[i].blue-=(density_y[x].direction[i].blue* MagickLog10(density_y[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_y.direction[i].black-=(density_y[x].direction[i].black* MagickLog10(density_y[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_y.direction[i].alpha-=(density_y[x].direction[i].alpha* MagickLog10(density_y[x].direction[i].alpha)); } /* Difference variance. */ channel_features[RedPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].red)- (variance.direction[i].red*variance.direction[i].red))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[GreenPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].green)- (variance.direction[i].green*variance.direction[i].green))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[BluePixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].blue)- (variance.direction[i].blue*variance.direction[i].blue))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].black)- (variance.direction[i].black*variance.direction[i].black))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].alpha)- (variance.direction[i].alpha*variance.direction[i].alpha))/ ((double) number_grays*number_grays*number_grays*number_grays); /* Information Measures of Correlation. */ channel_features[RedPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/ (entropy_x.direction[i].red > entropy_y.direction[i].red ? entropy_x.direction[i].red : entropy_y.direction[i].red); channel_features[GreenPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/ (entropy_x.direction[i].green > entropy_y.direction[i].green ? entropy_x.direction[i].green : entropy_y.direction[i].green); channel_features[BluePixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/ (entropy_x.direction[i].blue > entropy_y.direction[i].blue ? entropy_x.direction[i].blue : entropy_y.direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].black-entropy_xy1.direction[i].black)/ (entropy_x.direction[i].black > entropy_y.direction[i].black ? entropy_x.direction[i].black : entropy_y.direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].alpha-entropy_xy1.direction[i].alpha)/ (entropy_x.direction[i].alpha > entropy_y.direction[i].alpha ? entropy_x.direction[i].alpha : entropy_y.direction[i].alpha); channel_features[RedPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].red- entropy_xy.direction[i].red))))); channel_features[GreenPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].green- entropy_xy.direction[i].green))))); channel_features[BluePixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].blue- entropy_xy.direction[i].blue))))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].black- entropy_xy.direction[i].black))))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].alpha- entropy_xy.direction[i].alpha))))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { ssize_t z; for (z=0; z < (ssize_t) number_grays; z++) { register ssize_t y; ChannelStatistics pixel; (void) memset(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Contrast: amount of local variations present in an image. */ if (((y-x) == z) || ((x-y) == z)) { pixel.direction[i].red+=cooccurrence[x][y].direction[i].red; pixel.direction[i].green+=cooccurrence[x][y].direction[i].green; pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) pixel.direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) pixel.direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } /* Maximum Correlation Coefficient. */ if ((fabs(density_x[z].direction[i].red) > MagickEpsilon) && (fabs(density_y[x].direction[i].red) > MagickEpsilon)) Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red* cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/ density_y[x].direction[i].red; if ((fabs(density_x[z].direction[i].green) > MagickEpsilon) && (fabs(density_y[x].direction[i].red) > MagickEpsilon)) Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green* cooccurrence[y][x].direction[i].green/ density_x[z].direction[i].green/density_y[x].direction[i].red; if ((fabs(density_x[z].direction[i].blue) > MagickEpsilon) && (fabs(density_y[x].direction[i].blue) > MagickEpsilon)) Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue* cooccurrence[y][x].direction[i].blue/ density_x[z].direction[i].blue/density_y[x].direction[i].blue; if (image->colorspace == CMYKColorspace) if ((fabs(density_x[z].direction[i].black) > MagickEpsilon) && (fabs(density_y[x].direction[i].black) > MagickEpsilon)) Q[z][y].direction[i].black+=cooccurrence[z][x].direction[i].black* cooccurrence[y][x].direction[i].black/ density_x[z].direction[i].black/density_y[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) if ((fabs(density_x[z].direction[i].alpha) > MagickEpsilon) && (fabs(density_y[x].direction[i].alpha) > MagickEpsilon)) Q[z][y].direction[i].alpha+= cooccurrence[z][x].direction[i].alpha* cooccurrence[y][x].direction[i].alpha/ density_x[z].direction[i].alpha/ density_y[x].direction[i].alpha; } } channel_features[RedPixelChannel].contrast[i]+=z*z* pixel.direction[i].red; channel_features[GreenPixelChannel].contrast[i]+=z*z* pixel.direction[i].green; channel_features[BluePixelChannel].contrast[i]+=z*z* pixel.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].contrast[i]+=z*z* pixel.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].contrast[i]+=z*z* pixel.direction[i].alpha; } /* Maximum Correlation Coefficient. Future: return second largest eigenvalue of Q. */ channel_features[RedPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[GreenPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[BluePixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); } /* Relinquish resources. */ sum=(ChannelStatistics *) RelinquishMagickMemory(sum); for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); return(channel_features); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H o u g h L i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Use HoughLineImage() in conjunction with any binary edge extracted image (we % recommand Canny) to identify lines in the image. The algorithm accumulates % counts for every white pixel for every possible orientation (for angles from % 0 to 179 in 1 degree increments) and distance from the center of the image to % the corner (in 1 px increments) and stores the counts in an accumulator % matrix of angle vs distance. The size of the accumulator is 180x(diagonal/2). % Next it searches this space for peaks in counts and converts the locations % of the peaks to slope and intercept in the normal x,y input image space. Use % the slope/intercepts to find the endpoints clipped to the bounds of the % image. The lines are then drawn. The counts are a measure of the length of % the lines. % % The format of the HoughLineImage method is: % % Image *HoughLineImage(const Image *image,const size_t width, % const size_t height,const size_t threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find line pairs as local maxima in this neighborhood. % % o threshold: the line count threshold. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } static Image *RenderHoughLines(const ImageInfo *image_info,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns=columns; image->rows=rows; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->resolution.x == 0.0 ? 1.0 : image->resolution.x/ DefaultResolution; draw_info->affine.sy=image->resolution.y == 0.0 ? 1.0 : image->resolution.y/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory((size_t) GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { (void) memcpy(draw_info->primitive,GetBlobStreamData(image), (size_t) GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } MagickExport Image *HoughLineImage(const Image *image,const size_t width, const size_t height,const size_t threshold,ExceptionInfo *exception) { #define HoughLineImageTag "HoughLine/Image" CacheView *image_view; char message[MagickPathExtent], path[MagickPathExtent]; const char *artifact; double hough_height; Image *lines_image = NULL; ImageInfo *image_info; int file; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *accumulator; PointInfo center; register ssize_t y; size_t accumulator_height, accumulator_width, line_count; /* Create the accumulator. */ 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); accumulator_width=180; hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? image->rows : image->columns))/2.0); accumulator_height=(size_t) (2.0*hough_height); accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, sizeof(double),exception); if (accumulator == (MatrixInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (NullMatrix(accumulator) == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Populate the accumulator. */ status=MagickTrue; progress=0; center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) { register ssize_t i; for (i=0; i < 180; i++) { double count, radius; radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ (((double) y-center.y)*sin(DegreesToRadians((double) i))); (void) GetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); count++; (void) SetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); } } p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } /* Generate line segments from accumulator. */ file=AcquireUniqueFileResource(path); if (file == -1) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } (void) FormatLocaleString(message,MagickPathExtent, "# Hough line transform: %.20gx%.20g%+.20g\n",(double) width, (double) height,(double) threshold); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MagickPathExtent, "viewbox 0 0 %.20g %.20g\n",(double) image->columns,(double) image->rows); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MagickPathExtent, "# x1,y1 x2,y2 # count angle distance\n"); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; if (threshold != 0) line_count=threshold; for (y=0; y < (ssize_t) accumulator_height; y++) { register ssize_t x; for (x=0; x < (ssize_t) accumulator_width; x++) { double count; (void) GetMatrixElement(accumulator,x,y,&count); if (count >= (double) line_count) { double maxima; SegmentInfo line; ssize_t v; /* Is point a local maxima? */ maxima=count; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((u != 0) || (v !=0)) { (void) GetMatrixElement(accumulator,x+u,y+v,&count); if (count > maxima) { maxima=count; break; } } } if (u < (ssize_t) (width/2)) break; } (void) GetMatrixElement(accumulator,x,y,&count); if (maxima > count) continue; if ((x >= 45) && (x <= 135)) { /* y = (r-x cos(t))/sin(t) */ line.x1=0.0; line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); line.x2=(double) image->columns; line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); } else { /* x = (r-y cos(t))/sin(t) */ line.y1=0.0; line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); line.y2=(double) image->rows; line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); } (void) FormatLocaleString(message,MagickPathExtent, "line %g,%g %g,%g # %g %g %g\n",line.x1,line.y1,line.x2,line.y2, maxima,(double) x,(double) y); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; } } } (void) close(file); /* Render lines to image canvas. */ image_info=AcquireImageInfo(); image_info->background_color=image->background_color; (void) FormatLocaleString(image_info->filename,MagickPathExtent,"%s",path); artifact=GetImageArtifact(image,"background"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"background",artifact); artifact=GetImageArtifact(image,"fill"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"fill",artifact); artifact=GetImageArtifact(image,"stroke"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"stroke",artifact); artifact=GetImageArtifact(image,"strokewidth"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"strokewidth",artifact); lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); artifact=GetImageArtifact(image,"hough-lines:accumulator"); if ((lines_image != (Image *) NULL) && (IsStringTrue(artifact) != MagickFalse)) { Image *accumulator_image; accumulator_image=MatrixToImage(accumulator,exception); if (accumulator_image != (Image *) NULL) AppendImageToList(&lines_image,accumulator_image); } /* Free resources. */ accumulator=DestroyMatrixInfo(accumulator); image_info=DestroyImageInfo(image_info); (void) RelinquishUniqueFileResource(path); return(GetFirstImageInList(lines_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e a n S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MeanShiftImage() delineate arbitrarily shaped clusters in the image. For % each pixel, it visits all the pixels in the neighborhood specified by % the window centered at the pixel and excludes those that are outside the % radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those % that are within the specified color distance from the current mean, and % computes a new x,y centroid from those coordinates and a new mean. This new % x,y centroid is used as the center for a new window. This process iterates % until it converges and the final mean is replaces the (original window % center) pixel value. It repeats this process for the next pixel, etc., % until it processes all pixels in the image. Results are typically better with % colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr. % % The format of the MeanShiftImage method is: % % Image *MeanShiftImage(const Image *image,const size_t width, % const size_t height,const double color_distance, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find pixels in this neighborhood. % % o color_distance: the color distance. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; 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); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) { mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_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(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { PixelInfo mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetPixelInfo(image,&mean_pixel); GetPixelInfoPixel(image,p,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; PixelInfo sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetPixelInfo(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelInfo pixel; status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.alpha+=pixel.alpha; count++; } } } } gamma=PerceptibleReciprocal(count); mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.alpha=gamma*sum_pixel.alpha; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); p+=GetPixelChannels(image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
krb5pa-sha1_fmt_plug.c
/* * Kerberos 5 "PA ENC TIMESTAMP" by magnum (modified by Dhiru) * * Pcap file -> input file: * 1. tshark -r capture.pcapng -T pdml > ~/capture.pdml * 2. krbng2john.py ~/capture.pdml > krb5.in * 3. Run john on krb5.in * * http://www.ietf.org/rfc/rfc4757.txt * http://www.securiteam.com/windowsntfocus/5BP0H0A6KM.html * * Input format is 'user:$krb5pa$etype$user$realm$salt$timestamp+checksum' * * NOTE: Checksum implies last 12 bytes of PA_ENC_TIMESTAMP value in AS-REQ * packet. * * Default Salt: realm + user * * AES-256 encryption & decryption of AS-REQ timestamp in Kerberos v5 * See the following RFC for more details about the crypto & algorithms used: * * RFC3961 - Encryption and Checksum Specifications for Kerberos 5 * RFC3962 - Advanced Encryption Standard (AES) Encryption for Kerberos 5 * * march 09 / kevin devine <wyse101 0x40 gmail.com> * * This software is Copyright (c) 2011 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. * * This software is Copyright (c) 2012 Dhiru Kholia (dhiru at openwall.com) and * released under same terms as above */ #if FMT_EXTERNS_H extern struct fmt_main fmt_krb5pa; #elif FMT_REGISTERS_H john_register_one(&fmt_krb5pa); #else #include <errno.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 64 #endif #endif #include "arch.h" #include "misc.h" #include "formats.h" #include "options.h" #include "common.h" #include "unicode.h" #include "johnswap.h" #include "aes.h" #include "hmac_sha.h" #include "pbkdf2_hmac_sha1.h" #include "loader.h" #include "krb5_common.h" #include "memdbg.h" #define FORMAT_LABEL "krb5pa-sha1" #define FORMAT_NAME "Kerberos 5 AS-REQ Pre-Auth etype 17/18" /* aes-cts-hmac-sha1-96 */ #define FORMAT_TAG "$krb5pa$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 12 #define BINARY_ALIGN 4 #define PLAINTEXT_LENGTH 125 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 4 #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define MAX_SALTLEN 128 #define MAX_REALMLEN 64 #define MAX_USERLEN 64 #define TIMESTAMP_SIZE 44 #define CHECKSUM_SIZE BINARY_SIZE #define TOTAL_LENGTH (14 + 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) + MAX_REALMLEN + MAX_USERLEN + MAX_SALTLEN) static struct fmt_tests tests[] = { {"$krb5pa$18$user1$EXAMPLE.COM$$2a0e68168d1eac344da458599c3a2b33ff326a061449fcbc242b212504e484d45903c6a16e2d593912f56c93883bf697b325193d62a8be9c", "openwall"}, {"$krb5pa$18$user1$EXAMPLE.COM$$a3918bd0381107feedec8db0022bdf3ac56e534ed54d13c62a7013a47713cfc31ef4e7e572f912fa4164f76b335e588bf29c2d17b11c5caa", "openwall"}, {"$krb5pa$18$l33t$EXAMPLE.COM$$98f732b309a1d7ef2355a974842a32894d911e97150f5d57f248e1c2632fbd3735c5f156532ccae0341e6a2d779ca83a06021fe57dafa464", "openwall"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$64dfeee04be2b2e0423814e0df4d0f960885aca4efffe6cb5694c4d34690406071c4968abd2c153ee42d258c5e09a41269bbcd7799f478d3", "password@123"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$AD.EXAMPLE.COMaduser$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, /* etype 17 hash obtained using MiTM etype downgrade attack */ {"$krb5pa$17$user1$EXAMPLE.COM$$c5461873dc13665771b98ba80be53939e906d90ae1ba79cf2e21f0395e50ee56379fbef4d0298cfccfd6cf8f907329120048fd05e8ae5df4", "openwall"}, {NULL}, }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static struct custom_salt { int etype; unsigned char realm[64]; unsigned char user[64]; unsigned char salt[128]; /* realm + user */ unsigned char ct[44]; } *cur_salt; static unsigned char constant[16]; static unsigned char ke_input[16]; static unsigned char ki_input[16]; static void init(struct fmt_main *self) { unsigned char usage[5]; #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt); crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt); // generate 128 bits from 40 bits of "kerberos" string nfold(8 * 8, (unsigned char*)"kerberos", 128, constant); memset(usage, 0, sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0xAA; // used to derive Ke nfold(sizeof(usage) * 8, usage, sizeof(ke_input) * 8, ke_input); memset(usage, 0, sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0x55; // used to derive Ki nfold(sizeof(usage) * 8, usage, sizeof(ki_input) * 8, ki_input); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *data = ciphertext; int type, saltlen = 0; // tag is mandatory if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) return 0; data += FORMAT_TAG_LEN; // etype field, 17 or 18 p = strchr(data, '$'); if (!p || p - data != 2) return 0; type = atoi(data); if (type < 17 || type > 18) return 0; data = p + 1; // user field p = strchr(data, '$'); if (!p || p - data > MAX_USERLEN) return 0; saltlen += p - data; data = p + 1; // realm field p = strchr(data, '$'); if (!p || p - data > MAX_REALMLEN) return 0; saltlen += p - data; data = p + 1; // salt field p = strchr(data, '$'); if (!p) return 0; // if salt is empty, realm.user is used instead if (p - data) saltlen = p - data; data = p + 1; // We support a max. total salt length of 52. // We could opt to emit a warning if rejected here. if (saltlen > MAX_SALTLEN) { static int warned = 0; if (!ldr_in_pot) if (!warned++) fprintf(stderr, "%s: One or more hashes rejected due to salt length limitation\n", FORMAT_LABEL); return 0; } // 56 bytes (112 hex chars) encrypted timestamp + checksum if (strlen(data) != 2 * (TIMESTAMP_SIZE + CHECKSUM_SIZE) || strspn(data, HEXCHARS_all) != strlen(data)) return 0; return 1; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int i; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += FORMAT_TAG_LEN; p = strtokm(ctcopy, "$"); cs.etype = atoi(p); p = strtokm(NULL, "$"); if (p[-1] == '$') cs.user[0] = 0; else { strcpy((char*)cs.user, p); p = strtokm(NULL, "$"); } if (p[-1] == '$') cs.realm[0] = 0; else { strcpy((char*)cs.realm, p); p = strtokm(NULL, "$"); } if (p[-1] == '$') { strcpy((char*)cs.salt, (char*)cs.realm); strcat((char*)cs.salt, (char*)cs.user); } else { strcpy((char*)cs.salt, p); p = strtokm(NULL, "$"); } for (i = 0; i < TIMESTAMP_SIZE; i++) cs.ct[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *split(char *ciphertext, int index, struct fmt_main *pFmt) { static char out[TOTAL_LENGTH + 1]; char in[TOTAL_LENGTH + 1]; char salt[MAX_SALTLEN + 1]; char *data; char *e, *u, *r, *s, *tc; strnzcpy(in, ciphertext, sizeof(in)); tc = strrchr(in, '$'); *tc++ = 0; s = strrchr(in, '$'); *s++ = 0; r = strrchr(in, '$'); *r++ = 0; u = strrchr(in, '$'); *u++ = 0; e = in + 8; /* Default salt is user.realm */ if (!*s) { snprintf(salt, sizeof(salt), "%s%s", r, u); s = salt; } snprintf(out, sizeof(out), "%s%s$%s$%s$%s$%s", FORMAT_TAG, e, u, r, s, tc); data = out + strlen(out) - 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) - 1; strlwr(data); return out; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1 + TIMESTAMP_SIZE * 2; /* skip to checksum field */ for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static char *get_key(int index) { return saved_key[index]; } #define COMMON_GET_HASH_VAR crypt_out #include "common-get-hash.h" static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } /* See "pbkdf2_string_to_key" and "krb5int_dk_decrypt" from krb5-1.15.2 software */ static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { unsigned char tkey[MAX_KEYS_PER_CRYPT][32]; unsigned char base_key[32]; unsigned char Ke[32]; unsigned char plaintext[44]; int key_size, i; int len[MAX_KEYS_PER_CRYPT]; #ifdef SIMD_COEF_32 unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { len[i] = strlen(saved_key[i+index]); pin[i] = (unsigned char*)saved_key[i+index]; pout[i] = tkey[i]; } pbkdf2_sha1_sse((const unsigned char **)pin, len, cur_salt->salt,strlen((char*)cur_salt->salt), 4096, pout, 32, 0); #else for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { len[i] = strlen(saved_key[index+i]); } pbkdf2_sha1((const unsigned char*)saved_key[index], len[0], cur_salt->salt,strlen((char*)cur_salt->salt), 4096, tkey[0], 32, 0); #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { // generate 128 bits from 40 bits of "kerberos" string // This is precomputed in init() //nfold(8 * 8, (unsigned char*)"kerberos", 128, constant); if (cur_salt->etype == 17) key_size = 16; else key_size = 32; dk(base_key, tkey[i], key_size, constant, 32); /* The "well-known constant" used for the DK function is the key usage number, * expressed as four octets in big-endian order, followed by one octet indicated below. * Kc = DK(base-key, usage | 0x99); * Ke = DK(base-key, usage | 0xAA); * Ki = DK(base-key, usage | 0x55); */ // derive Ke for decryption/encryption // This is precomputed in init() //memset(usage, 0, sizeof(usage)); //usage[3] = 0x01; // key number in big-endian format //usage[4] = 0xAA; // used to derive Ke //nfold(sizeof(usage) * 8, usage, sizeof(ke_input) * 8, ke_input); dk(Ke, base_key, key_size, ke_input, 32); // decrypt the AS-REQ timestamp encrypted with 256-bit AES // here is enough to check the string, further computation below is required // to fully verify the checksum krb_decrypt(cur_salt->ct, 44, plaintext, Ke, key_size); // Check a couple bytes from known plain (YYYYMMDDHHMMSSZ) and // bail out if we are out of luck. if (plaintext[22] == '2' && plaintext[23] == '0' && plaintext[36] == 'Z') { unsigned char Ki[32]; unsigned char checksum[20]; // derive Ki used in HMAC-SHA-1 checksum // This is precomputed in init() //memset(usage, 0, sizeof(usage)); //usage[3] = 0x01; // key number in big-endian format //usage[4] = 0x55; // used to derive Ki //nfold(sizeof(usage) * 8, usage, sizeof(ki_input) * 8, ki_input); dk(Ki, base_key, key_size, ki_input, 32); // derive checksum of plaintext hmac_sha1(Ki, key_size, plaintext, 44, checksum, 20); memcpy(crypt_out[index+i], checksum, BINARY_SIZE); } else { memset(crypt_out[index+i], 0, BINARY_SIZE); } } } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_krb5pa = { { 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_SPLIT_UNIFIES_CASE | FMT_OMP, { NULL }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
omp_sort.h
#ifndef OMP_SORT_PP_CLASS_H #define OMP_SORT_PP_CLASS_H #include "pch.h" #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <omp.h> #include <math.h> #define MAX(A, B) (((A) > (B)) ? (A) : (B)) #define MIN(A, B) (((A) > (B)) ? (B) : (A)) #define UP 0 #define DOWN 1 #define VERBOSE 0 int omp_bubble_sort(int *A, int n); int omp_odd_even_sort(int *A, int n); int omp_rank_sort(int *A, int n); int omp_counting_sort(int *x, int n); int swap(int *a, int *b); int bitonic_sort_seq(int start, int length, int *A, int flag); int bitonic_sort_par(int start, int length, int *A, int flag, int m); int bitonic(int *A, int n); static int CmpInt(const void *a, const void *b); void merge(int A[], int B[], int m, int n); void arraymerge(int *a, int size, int *index, int N); int QuickSort(int *a, int size); int RadixSort(int *input, int n); void Mergesort(int *x, int a, int b); void mix_them(int *x, int n, int h, int num_threads); void mix(int *x, int a1, int b1, int a2, int b2); int Mergesort_Omp(int *x, int n); // Bubble sort ------------------------------------------------------------------- int omp_bubble_sort(int *A, int n) { int n_pros = omp_get_num_threads(); int chunk = n / n_pros, bandera = 1, nr = 0, i, j; int aux; while (bandera) { nr++; bandera = 0; #pragma omp parallel for reduction(+:bandera) private(aux) for (j = 0; j < n_pros; j++) { for (i = j; i < n - 1; i = i + n_pros) { if (A[i] > A[i + 1]) { aux = A[i]; A[i] = A[i + 1]; A[i + 1] = aux; ++bandera; } } } } return 0; } // end bubble sort ------------------------------------------------------------------- // odd even transposition sort ------------------------------------------------------------------- int omp_odd_even_sort(int *A, int n) { int sorted, i; sorted = 1; while (sorted != 0) { #pragma omp parallel { sorted = 0; #pragma omp for reduction(+:sorted) for (i = 0; i < n - 1; i += 2) { if (A[i] > A[i + 1]) { int temp = A[i]; A[i] = A[i + 1]; A[i + 1] = temp; sorted++; } } #pragma omp for reduction(+:sorted) for (i = 1; i < n - 1; i += 2) { if (A[i] > A[i + 1]) { int temp = A[i]; A[i] = A[i + 1]; A[i + 1] = temp; sorted++; } } } } return 0; } // end odd even transposition sort ------------------------------------------------------------------- // rank sort ------------------------------------------------------------------- int omp_rank_sort(int *A, int n) { int *y; y = (int *)calloc(n, sizeof(int)); #pragma omp parallel { int threads = omp_get_num_threads(); int rank, i, j, startval, endval, my_num, my_place; rank = omp_get_thread_num(); startval = n * rank / threads; endval = n * (rank + 1) / threads; //printf(" %d %d\n",startval, endval); for (j = startval; j < endval; j++) { my_num = A[j]; my_place = 0; for (i = 0; i < n; i++) { if (my_num > A[i]) my_place++; } y[my_place] = my_num; } } int k; for (k = 0; k < n; k++) { if (y[k] == 0) A[k] = A[k - 1]; else A[k] = y[k]; } free(y); return 0; } //end rank sort ------------------------------------------------------------------- // counting sort ------------------------------------------------------------------- int omp_counting_sort(int *A, int n) { //Enteros en [1,m] y variables int m = 1001, i; int *c = (int*)calloc(m, sizeof(int)); int *b = (int*)calloc(n, sizeof(int)); //printf("1\n"); //Copiando x en b ( solo aki se paraleliza XD ) #pragma omp parallel for private(i) shared(A,b) for (i = 0; i < n; i++) { b[i] = A[i]; } //printf("2\n"); //Contando for (i = 0; i < n; i++) { //printf("%d ", b[i]); c[b[i] - 1]++; //TODO index error -1 } //printf("3\n"); //Suma prefija for (i = 1; i < m; i++) c[i] += c[i - 1]; //printf("4\n"); //Ordenando for (i = 0; i < n; i++) { A[c[b[i] - 1] - 1] = b[i]; c[b[i] - 1]--; } //printf("5\n"); //Liberando arreglos auxiliares free(c); free(b); return 0; } // end counting sort ------------------------------------------------------------------- // bitonic sort ------------------------------------------------------------------- int swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; return 0; } int bitonic_sort_seq(int start, int length, int *A, int flag) { int i; int split_length; if (length == 1) return 1; if (length % 2 != 0) { printf("error\n"); exit(0); } split_length = length / 2; // bitonic split for (i = start; i < start + split_length; i++) { if (flag == UP) { if (A[i] > A[i + split_length]) swap(&A[i], &A[i + split_length]); } else { if (A[i] < A[i + split_length]) swap(&A[i], &A[i + split_length]); } } bitonic_sort_seq(start, split_length, A, flag); bitonic_sort_seq(start + split_length, split_length, A, flag); return 0; } int bitonic_sort_par(int start, int length, int *A, int flag, int m) { int i; int split_length; if (length == 1) { return 0; } // la longitud de la subsecuencia debe ser potencia de 2 if (length % 2 != 0) { exit(0); } split_length = length / 2; // bitonic split #pragma omp parallel for shared(A, flag, start, split_length) private(i) for (i = start; i < start + split_length; i++) { if (flag == UP) { if (A[i] > A[i + split_length]) swap(&A[i], &A[i + split_length]); } else { if (A[i] < A[i + split_length]) swap(&A[i], &A[i + split_length]); } } if (split_length > m) { bitonic_sort_par(start, split_length, A, flag, m); bitonic_sort_par(start + split_length, split_length, A, flag, m); } return 0; } /** \brief Bitonic Sort. Algoritmo de ordenamiento para conjuntos de datos cuya longitus es potencia de 2. */ int bitonic(int *A, int n) { int m; int i, j; int flag; int num_threads; //Numero de hilos con los que se esta trabajando num_threads = omp_get_num_threads(); //n debe ser almenos mayor que el doble de procesadores if (n < num_threads * 2) { return 1; } // particionando m = n / num_threads; //Primer parte del bitonic donde particionamos for (i = 2; i <= m; i = 2 * i) { #pragma omp parallel for shared(i, A) private(j, flag) for (j = 0; j < n; j += i) { if ((j / i) % 2 == 0) flag = UP; else flag = DOWN; bitonic_sort_seq(j, i, A, flag); } } // Segunda parte del bitonic for (i = 2; i <= num_threads; i = 2 * i) { for (j = 0; j < num_threads; j += i) { if ((j / i) % 2 == 0) flag = UP; else flag = DOWN; bitonic_sort_par(j*m, i*m, A, flag, m); } #pragma omp parallel for shared(j) for (j = 0; j < num_threads; j++) { if (j < i) flag = UP; else flag = DOWN; bitonic_sort_seq(j*m, m, A, flag); } } return 0; } // end bitonic sort ------------------------------------------------------------------- // quick sort ------------------------------------------------------------------- static int CmpInt(const void *a, const void *b) { return (*(int*)a - *(int*)b); } /* Merge sorted lists A and B into list A. A must have dim >= m+n */ void merge(int A[], int B[], int m, int n) { int i = 0, j = 0, k = 0, p; int size = m + n; int *C = (int *)malloc(size * sizeof(int)); while (i < m && j < n) { if (A[i] <= B[j]) C[k] = A[i++]; else C[k] = B[j++]; k++; } if (i < m) for (p = i; p < m; p++, k++) C[k] = A[p]; else for (p = j; p < n; p++, k++) C[k] = B[p]; for (i = 0; i < size; i++) A[i] = C[i]; free(C); } /* Merges N sorted sub-sections of array a into final, fully sorted array a */ void arraymerge(int *a, int size, int *index, int N) { int i, j; while (N > 1) { for (i = 0; i < N; i++) index[i] = i * size / N; index[N] = size; #pragma omp parallel for private(i) for (i = 0; i < N; i += 2) { if (VERBOSE) fprintf(stderr, "merging %d and %d, index %d and %d (up to %d)\n", i, i + 1, index[i], index[i + 1], index[i + 2]); merge(a + index[i], a + index[i + 1], index[i + 1] - index[i], index[i + 2] - index[i + 1]); if (VERBOSE) for (j = 0; j < size; j++) fprintf(stderr, "after: %d %d\n", j, a[j]); } N /= 2; } } int QuickSort(int *a, int size) { // set up threads int i = 0; int threads = omp_get_max_threads(); omp_set_num_threads(threads); int *index = (int *)malloc((threads + 1) * sizeof(int)); for (i = 0; i < threads; i++) index[i] = i * size / threads; index[threads] = size; /* Main parallel sort loop */ #pragma omp parallel for private(i) for (i = 0; i < threads; i++) qsort(a + index[i], index[i + 1] - index[i], sizeof(int), CmpInt); /* Merge sorted array pieces */ if (threads > 1) arraymerge(a, size, index, threads); return 0; } // end quick sort ------------------------------------------------------------------- // radix sort int RadixSort(int *input, int n) { int d = 1001; //highest-order digit int b = 10, k = d;//// int *temp = (int*)malloc(k * sizeof(int)); //used in counting sort int *input2 = (int*)malloc(sizeof(int)*n); int *output = (int*)malloc(sizeof(int)*n); int power = ((int)pow(2, b) - 1); int l; int t = omp_get_num_threads(); //UNUSED //omp_set_num_threads(t); //main loop for (l = 0; l < 32 / b; l++) { int slice = l * b; int i, j; if (slice <= d) { #pragma omp parallel { #pragma omp for schedule(guided) private(i) for (i = 0; i < n; i++) input2[i] = (input[i] >> slice) & power; #pragma omp for schedule(guided) private(i) for (i = 0; i < k; i++) temp[i] = 0; #pragma omp for schedule(guided) private(j) for (j = 0; j < n; j++) #pragma omp atomic temp[input2[j]]++; #pragma omp for ordered schedule(guided) private(i) for (i = 1; i < k; i++) #pragma omp ordered temp[i] += temp[i - 1]; } for (j = n - 1; j >= 0; j--) { output[temp[input2[j]] - 1] = input[j]; temp[input2[j]]--; } #pragma omp parallel for schedule(guided) private(j) for (j = 0; j < n; j++) input[j] = output[j]; } } return 0; } //end radix sort ------------------------------------------------------------------- //merge sort ------------------------------------------------------------------- //Funcion para mezclar 2 subvectores ordenados contiguos void mix(int *x, int a1, int b1, int a2, int b2) { //Obteniendo numero de eltos en cada subvector int n1 = b1 - a1 + 1; int n2 = b2 - a2 + 1; //Creando copias de subvectores int *x1 = (int*)calloc(n1, sizeof(int)); int *x2 = (int*)calloc(n2, sizeof(int)); //Copiando subvectores int i, i1 = 0, i2 = 0; for (i = 0; i < n1; i++) x1[i] = x[a1 + i]; for (i = 0; i < n2; i++) x2[i] = x[a2 + i]; //Limpiando iterador i = a1; //Iterando sobre el rango de ambos subvectores while (i1 < n1 && i2 < n2) { //Determinando el elto menor, copiandolo al //buffer y recorriendo su apuntador if (x1[i1] < x2[i2]) { x[i] = x1[i1]; i1++; } else { x[i] = x2[i2]; i2++; } //Incrementando indice de x i++; }//Fin de while sobre ambos subvectores //Terminando el subvector 1 si aun no termina while (i1 < n1) { //Actualizando valor y recorriendo indices x[i] = x1[i1]; i++; i1++; } //Terminando el subvector 2 si aun no termina while (i2 < n2) { //Actualizando valor y recorriendo indices x[i] = x2[i2]; i++; i2++; } //Liberando memoria free(x1); free(x2); } //Mergesort de un subvector en los indices [a,b] void Mergesort(int *x, int a, int b) { //Indices de subvectores int a1, a2, b1, b2; //Numero de eltos int n = b - a + 1; //Evitando el caso trivial if (n > 1) { a1 = a; b1 = (int)(a1 + floor(1.0*n / 2) - 1); a2 = b1 + 1; b2 = b; //Ordenando subarreglos recursivamente Mergesort(x, a1, b1); Mergesort(x, a2, b2); //Mezclando subarreglos ordenados mix(x, a1, b1, a2, b2); }//Fin de caso no trivial } //Funcion para mezclar los subvectores usados en Mergesort_Omp //El fin de esta funcion es decidir un orden adecuado para //mezclar los subvectores ordenados por los threads utilizados //en la funcion Mergesort_Omp. //h es el numero de eltos a ordenar en cada thread: //h = n/num_threads void mix_them(int *x, int n, int h, int num_threads) { //variables de limites de subvectores int a1, b1, a2, b2; //Actuando acorde al numero de threads switch (num_threads) { //No mezcla nada case 1: break; case 2: { //calculando limites a1 = 0; b1 = h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando mix(x, a1, b1, a2, b2); //Fin para 2 threads break; } case 3: { //calculando limites de subvectores 1 y 2 a1 = 0; b1 = h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 1 y 2 = subvector @ mix(x, a1, b1, a2, b2); //calculando limites de subvectores @ y 3 b1 = b2; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores @ y 3 mix(x, a1, b1, a2, b2); //Fin para 3 threads break; } case 4: { //calculando limites de subvectores 1 y 2 a1 = 0; b1 = h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 1 y 2 = subvector @ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 3 y 4 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores 3 y 4 = subvector $ mix(x, a1, b1, a2, b2); //calculando limites de subvectores @ y $ b1 = a1 - 1; a1 = 0; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores @ y $ mix(x, a1, b1, a2, b2); //Fin para 4 threads break; } case 5: { //calculando limites de subvectores 1 y 2 a1 = 0; b1 = h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 1 y 2 = subvector @ mix(x, a1, b1, a2, b2); //calculando limites de subvectores @ y 3 a1 = 0; b1 = b2; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores @ y 3 = subvector $ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 4 y 5 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores 4 y 5 = subvector % mix(x, a1, b1, a2, b2); //calculando limites de subvectores $ y % b1 = a1 - 1; a1 = 0; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores $ y % mix(x, a1, b1, a2, b2); //Fin para 5 threads break; } case 6: { //calculando limites de subvectores 1 y 2 a1 = 0; b1 = h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 1 y 2 = subvector @ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 3 y 4 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 3 y 4 = subvector $ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 5 y 6 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores 5 y 6 = subvector & mix(x, a1, b1, a2, b2); //calculando limites de subvectores @ y $ a1 = 0; b1 = 2 * h - 1; a2 = b1 + 1; b2 = a2 + 2 * h - 1; //mezclando subvectores @ y $ = subvector % mix(x, a1, b1, a2, b2); //calculando limites de subvectores % y & a1 = 0; b1 = b2; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores % y & mix(x, a1, b1, a2, b2); //Fin para 6 threads break; } case 7: { //calculando limites de subvectores 1 y 2 a1 = 0; b1 = h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 1 y 2 = subvector @ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 3 y 4 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 3 y 4 = subvector $ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 5 y 6 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 5 y 6 = subvector & mix(x, a1, b1, a2, b2); //calculando limites de subvectores @ y $ a1 = 0; b1 = 2 * h - 1; a2 = b1 + 1; b2 = a2 + 2 * h - 1; //mezclando subvectores @ y $ = subvector % mix(x, a1, b1, a2, b2); //calculando limites de subvectores & y 7 a1 = b2 + 1; b1 = a1 + 2 * h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores @ y $ = subvector # mix(x, a1, b1, a2, b2); //calculando limites de subvectores % y # a1 = 0; b1 = 4 * h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores % y # mix(x, a1, b1, a2, b2); //Fin para 7 threads break; } case 8: { //calculando limites de subvectores 1 y 2 a1 = 0; b1 = h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 1 y 2 = subvector @ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 3 y 4 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 3 y 4 = subvector $ mix(x, a1, b1, a2, b2); //calculando limites de subvectores 5 y 6 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = a2 + h - 1; //mezclando subvectores 5 y 6 = subvector & mix(x, a1, b1, a2, b2); //calculando limites de subvectores 7 y 8 a1 = b2 + 1; b1 = a1 + h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores 7 y 8 = subvector # mix(x, a1, b1, a2, b2); //calculando limites de subvectores @ y $ a1 = 0; b1 = 2 * h - 1; a2 = b1 + 1; b2 = a2 + 2 * h - 1; //mezclando subvectores @ y $ = subvector % mix(x, a1, b1, a2, b2); //calculando limites de subvectores & y # a1 = b2 + 1; b1 = a1 + 2 * h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores & y # = subvector ~ mix(x, a1, b1, a2, b2); //calculando limites de subvectores % y ~ a1 = 0; b1 = 4 * h - 1; a2 = b1 + 1; b2 = n - 1; //mezclando subvectores % y ~ mix(x, a1, b1, a2, b2); //Fin para 8 threads break; } default: { } } } //Mergesort con openmp int Mergesort_Omp(int *x, int n) { //Obteniendo numero de threads int num_threads = omp_get_max_threads(), i; //Obteniendo # de eltos a ordenar por cada thread int h = n / num_threads; //Indices del arreglo original de inicio y final de cada thread int *I_start = (int*)calloc(num_threads, sizeof(int)); int *I_end = (int*)calloc(num_threads, sizeof(int)); //Llenando el indice de arreglos. Lo llenamos de esta manera para //q el ultimo indice de final sea n-1 for (i = 0; i < num_threads - 1; i++) { I_start[i] = i * h; I_end[i] = I_start[i] + h - 1; } I_start[i] = i * h; I_end[i] = n - 1; //Ordenando los num_threads subarreglos #pragma omp parallel for for (i = 0; i < num_threads; i++) { //Obteniendo numero de thread int my_rank = omp_get_thread_num(); //Ordenando su segmento Mergesort(x, I_start[my_rank], I_end[my_rank]); } //Ordenando los subarreglos entre si mix_them(x, n, h, num_threads); //Liberando memoria free(I_start); free(I_end); return 0; } //end merge sort ------------------------------------------------------------------- int N_OMP_SORT_FUNCS = 8; typedef int(*omp_f) (int*, int); omp_f omp_funcs[] = { &omp_bubble_sort, &omp_odd_even_sort, &QuickSort, &RadixSort, &Mergesort_Omp,&bitonic, &omp_rank_sort, &omp_counting_sort }; const char *omp_funcs_names[] = { "omp_bubble_sort", "omp_odd_even_sort", "QuickSort", "RadixSort", "Mergesort_Omp", "bitonic", "omp_rank_sort", "omp_counting_sort" }; #endif
HelloMP.c
#include <omp.h> // Nur für Hilfsfunktionen #include <stdio.h> #include <stdlib.h> int main(void) { int i; omp_set_num_threads(4); #pragma omp parallel for for (i = 0; i < 4; ++i) { const int id = omp_get_thread_num(); printf("Hello World from thread %d\n", id); if (id == 0) /* Nur im Masterthread ausführen */ printf("There are %d threads\n", omp_get_num_threads()); } return EXIT_SUCCESS; }
teams-1.c
/* { dg-do compile } */ void foo (int x) { bad1: #pragma omp target teams goto bad1; // { dg-error "invalid branch to/from OpenMP structured block" } goto bad2; // { dg-error "invalid entry to OpenMP structured block" } #pragma omp target teams { bad2: ; } #pragma omp target teams { int i; goto ok1; for (i = 0; i < 10; ++i) { ok1: break; } } switch (x) // { dg-error "invalid entry to OpenMP structured block" } { #pragma omp target teams { case 0:; } // { dg-warning "statement will never be executed" } } } void bar (int x) { bad1: #pragma omp target #pragma omp teams goto bad1; // { dg-error "invalid branch to/from OpenMP structured block" } goto bad2; // { dg-error "invalid entry to OpenMP structured block" } #pragma omp target #pragma omp teams { bad2: ; } #pragma omp target #pragma omp teams { int i; goto ok1; for (i = 0; i < 10; ++i) { ok1: break; } } switch (x) // { dg-error "invalid entry to OpenMP structured block" } { #pragma omp target // { dg-warning "statement will never be executed" } #pragma omp teams { case 0:; } } }
GB_unop__identity_int32_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int32_fc64) // op(A') function: GB (_unop_tran__identity_int32_fc64) // C type: int32_t // A type: GxB_FC64_t // cast: int32_t cij = GB_cast_to_int32_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int32_t z = GB_cast_to_int32_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = GB_cast_to_int32_t (creal (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int32_fc64) ( int32_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; int32_t z = GB_cast_to_int32_t (creal (aij)) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; int32_t z = GB_cast_to_int32_t (creal (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int32_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convolution_packnto1_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 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 convolution_packnto1_fp16s_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float sum = 0.f; if (bias_data_ptr) { sum = bias_data_ptr[p]; } vfloat32m2_t _sum = vfmv_v_f_f32m2(0.f, vl); const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * packn; for (int k = 0; k < maxk; k++) { vfloat16m1_t _val = vle16_v_f16m1(sptr + space_ofs[k] * packn, vl); vfloat16m1_t _w = vle16_v_f16m1(kptr, vl); _sum = vfwmacc_vv_f32m2(_sum, _val, _w, vl); kptr += packn; } } #if C906 // TODO std::vector<float> ss(packn); vse32_v_f32m2((float*)ss.data(), _sum, vl); for (int i = 0; i < packn; i++) { sum += ss[i]; } #else sum = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m2_f32m1(vfloat32m1_t(), _sum, vfmv_s_f_f32m1(vfloat32m1_t(), sum, vl), vl)); #endif sum = activation_ss(sum, activation_type, activation_params); outptr[j] = (__fp16)sum; } outptr += outw; } } } static void convolution_packnto1_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data_fp16, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const __fp16* bias_data_ptr = bias_data_fp16; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { __fp16 sum = 0.f; if (bias_data_ptr) { sum = bias_data_ptr[p]; } vfloat16m1_t _sum = vfmv_v_f_f16m1(0.f, vl); const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * packn; for (int k = 0; k < maxk; k++) { vfloat16m1_t _val = vle16_v_f16m1(sptr + space_ofs[k] * packn, vl); vfloat16m1_t _w = vle16_v_f16m1(kptr, vl); _sum = vfmacc_vv_f16m1(_sum, _val, _w, vl); kptr += packn; } } sum = vfmv_f_s_f16m1_f16(vfredsum_vs_f16m1_f16m1(vfloat16m1_t(), _sum, vfmv_s_f_f16m1(vfloat16m1_t(), sum, vl), vl)); sum = activation_ss(sum, activation_type, activation_params); outptr[j] = sum; } outptr += outw; } } }
gemm_mkl.h
/* Copyright (c) 2018 NoobsHPC Authors All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef NBHPC_ICESWORD_OPERATOR_X86_GEMM_H #define NBHPC_ICESWORD_OPERATOR_X86_GEMM_H #include "mkl.h" #include "icesword/utils.h" #include "icesword/operator/gemm.h" #include "icesword/operator/x86/omp_thread.h" namespace noobshpc { namespace icesword { /* row major: mem_a: dim_m * dim_k mem_b: dim_k * dim_n mem_c: dim_m * dim_n col major: mem_a: dim_k * dim_m mem_b: dim_n * dim_k mem_c: dim_n * dim_m matrix(C) = alpha * { matrix(A) + offset_a } * { op(B) + offset_b } + beta * matrix(C) + offset_c */ template<DataType DType> class CBLAS_GEMM <X86, DType> { public: typedef typename DataTrait<X86, DType>::Dtype OP_DType; CBLAS_GEMM() : omp_max_thread(ice_get_max_threads()) {} ~CBLAS_GEMM() {} Status release(void* matrix); void* pack(const void* matrix, const bool col_major, const bool pack_a, const bool trans, const size_t m, const size_t n, const size_t k, const float alpha = 1.f); Status execute(const void* mem_a, const void* mem_b, void* mem_c, const void* mem_oc, const size_t m, const size_t n, const size_t k, const int8_t oa, const int8_t ob, const char oc_mode = 'N', const bool col_major = false, const bool trans_a = false, const bool trans_b = false, const bool pack_a = false, const bool pack_b = false, const float beta = 0.f, const float alpha = 1.f); void* pack(const void* mem_in, const bool col_major, const bool pack_a, const bool trans, const size_t m, const size_t n, const size_t k, const size_t stride, const float alpha = 1.f); /* c = alpha * { op(A) + a_offset_scale * a_offset } * { op(B) + b_offset_scale * b_offset } + beta * c + c_offset */ Status execute(const void* mem_a, const void* mem_b, void* mem_c, const void* mem_oc, const size_t m, // mem_c -> col_major ? width : hight const size_t n, // mem_c -> col_major ? hight : width const size_t k, // matrix a,b common dim const int8_t oa, // offset_a const int8_t ob, // offset_b const char oc_mode, // 'N': none, 'F': fix, 'R': row, 'C': col const bool col_major, // read method: row_major, col_major, same like transpose const bool trans_a, // mem_a need transpose const bool trans_b, // mem_b need transpose const bool pack_a, // a pack optimization const bool pack_b, // b pack optimization const float beta, // scale for old C const float alpha, // scale for compute op(a) * op(b) const size_t lda, // mem_a width, without any trans or read method const size_t ldb, // mem_b width, without any trans or read method const size_t ldc); // mem_c width, without any trans or read method Status convert_mem_s82u8(bool exec_it, void* src, size_t length); void* compute_offset(bool exec_it, bool trans_b, const int8_t ob, const float alpha, const size_t dim_n, const size_t dim_k, const void* mem_b); Status add_offset2mem_c(const bool exec_it, const char oc_mode, const void* mem_in, void* mem_out, const size_t m, const size_t n); private: size_t omp_max_thread; Status execute_check(const void* mem_a, const void* mem_b, void* mem_c, const void* mem_oc, const char oc_mode, const int8_t offset_a, const int8_t offset_b); }; // class end template<DataType DType> Status CBLAS_GEMM<X86, DType>::release(void* matrix) { if (matrix != nullptr) { gfree(matrix); } return S_Success; } template<DataType DType> void* CBLAS_GEMM<X86, DType>::pack(const void* matrix, const bool col_major, const bool pack_a, const bool trans, const size_t m, const size_t n, const size_t k, const float alpha) { auto lda = 0, ldb = 0, stride = 0; if (col_major) { lda = trans ? k : m; ldb = trans ? n : k; } else { lda = trans ? m : k; ldb = trans ? k : n; } stride = pack_a ? lda : ldb; return pack(matrix, col_major, pack_a, trans, m, n, k, stride, alpha); } template<DataType DType> Status CBLAS_GEMM<X86, DType>::execute(const void* mem_a, const void* mem_b, void* mem_c, const void* mem_oc, const size_t m, const size_t n, const size_t k, const int8_t oa, const int8_t ob, const char oc_mode, const bool col_major, const bool trans_a, const bool trans_b, const bool pack_a, const bool pack_b, const float beta, const float alpha) { size_t lda, ldb, ldc, offseta, offsetb; if (col_major) { lda = trans_a ? k : m; ldb = trans_b ? n : k; ldc = m; } else { lda = trans_a ? m : k; ldb = trans_b ? k : n; ldc = n; } #ifdef ICESWORD_VERBOSE LOG(INFO) << "CBLAS_GEMM_VERBOSE {" << " oc_mode:" << oc_mode << " layout:" << (col_major ? 'C' : 'R') << " transa:" << (trans_a ? "true" : "false") << " transb:" << (trans_b ? "true" : "false") << " m:" << m << " n:" << n << " k:" << k << " oa:" << int(oa) << " ob:" << int(ob) << " lda:" << lda << " ldb:" << ldb << " ldc:" << ldc << " beta:" << beta << " alpha:" << alpha << " }"; #endif return execute(mem_a, mem_b, mem_c, mem_oc, m, n, k, oa, ob, oc_mode, col_major, trans_a, trans_b, pack_a, pack_b, beta, alpha, lda, ldb, ldc); } template<DataType DType> Status CBLAS_GEMM<X86, DType>::execute_check(const void* mem_a, const void* mem_b, void* mem_c, const void* mem_oc, const char oc_mode, const int8_t offset_a, const int8_t offset_b) { if (mem_a == nullptr || mem_b == nullptr || mem_c == nullptr) { LOG(ERROR) << "wrong matrix empty pointer !"; return S_InvalidValue; } if (oc_mode != 'N' && mem_oc == nullptr) { LOG(ERROR) << "wrong mem_oc pointer !"; return S_InvalidValue; } if (oc_mode != 'N' && oc_mode != 'F' && oc_mode != 'C' && oc_mode != 'R') { LOG(ERROR) << "wrong mem_oc mode !"; return S_InvalidValue; } if (DType == DT_FLOAT && (offset_a != 0 || offset_b != 0)) { LOG(ERROR) << "float offset a,b don't support !"; return S_InvalidValue; } return S_Success; } template<DataType DType> Status CBLAS_GEMM<X86, DType>::convert_mem_s82u8(bool exec_it, void* src, size_t length) { if (exec_it) { auto memory = static_cast<uint8_t *>(src); if (memory == nullptr) { LOG(FATAL) << "wrong empty pointer !"; return S_InvalidValue; } #pragma omp parallel for collapse(1) for (auto i = 0; i < length; i++) { memory[i] += 128; } } return S_Success; } template<DataType DType> void* CBLAS_GEMM<X86, DType>::compute_offset(bool exec_it, bool trans_b, const int8_t ob, const float alpha, const size_t dim_n, const size_t dim_k, const void* mem_b) { if (exec_it) { if (mem_b == nullptr) { LOG(FATAL) << "wrong empty pointer !"; return nullptr; } auto dst = static_cast<int32_t*>(calloc(dim_n, sizeof(int32_t))); auto b_mem = static_cast<const int8_t*>(mem_b); auto scale = alpha * -128; auto thread_num = omp_max_thread; if (dim_n <= 2) { thread_num = 1; } else if (dim_n < omp_max_thread) { thread_num = dim_n; } if (trans_b) { #pragma omp parallel for collapse(1) num_threads(thread_num) for (auto i = 0; i < dim_n; i++) { int32_t b_dim_k_sum = 0; #pragma omp simd for (auto j = 0; j < dim_k; j++) { b_dim_k_sum += b_mem[i * dim_k + j] + ob; } dst[i] += scale * b_dim_k_sum; } } else { for (auto i = 0; i < dim_k; i++) { #pragma omp parallel for collapse(1) num_threads(thread_num) for (auto j = 0; j < dim_n; j++) { dst[j] += scale * (b_mem[i * dim_n + j] + ob); } } } return dst; } return nullptr; } template<DataType DType> Status CBLAS_GEMM<X86, DType>::add_offset2mem_c(const bool exec_it, const char oc_mode, const void* mem_in, void* mem_out, const size_t dim_m, const size_t dim_n) { if (exec_it && oc_mode == 'C') { if (mem_in == nullptr || mem_out == nullptr) { LOG(FATAL) << "wrong empty pointer !"; return S_InvalidValue; } auto src = static_cast<const int32_t *>(mem_in); auto dst = static_cast<int32_t *>(mem_out); auto thread_num = omp_max_thread; if (dim_m <= 2) { thread_num = 1; } else if (dim_m < omp_max_thread) { thread_num = dim_m; } #pragma omp parallel for collapse(1) num_threads(thread_num) for (auto h = 0; h < dim_m; h++) { #pragma omp simd for (auto w = 0; w < dim_n; w++) { dst[h * dim_n + w] += src[w]; } } } return S_Success; } } // namespace icesword } // namespace noobshpc #endif // NBHPC_ICESWORD_OPERATOR_X86_GEMM_H
rawKeccak_512_fmt_plug.c
/* Keccak-512 cracker patch for JtR. Hacked together during January of 2013 * by Dhiru Kholia <dhiru.kholia at gmail.com>. * * This file is part of John the Ripper password cracker, * Copyright (c) 2012 by Solar Designer * based on rawMD4_fmt.c code, with trivial changes by groszek. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_rawKeccak; #elif FMT_REGISTERS_H john_register_one(&fmt_rawKeccak); #else #include <string.h> #include "arch.h" #include "params.h" #include "common.h" #include "formats.h" #include "options.h" #include "KeccakF-1600-interface.h" #include "KeccakNISTInterface.h" #ifdef _OPENMP #define OMP_SCALE 2048 #include <omp.h> #endif #include "memdbg.h" #define FORMAT_LABEL "Raw-Keccak" #define FORMAT_NAME "" #if defined(__AVX__) #define ALGORITHM_NAME "AVX" #elif defined(__XOP__) #define ALGORITHM_NAME "XOP" #elif defined(__SSE4_1__) #define ALGORITHM_NAME "SSE4.1" #elif defined(__SSSE3__) #define ALGORITHM_NAME "SSSE3" #elif defined(__SSE2__) #define ALGORITHM_NAME "SSE2" #else #define ALGORITHM_NAME "32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define CIPHERTEXT_LENGTH 128 #define BINARY_SIZE 64 #define SALT_SIZE 0 #define BINARY_ALIGN 4 #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests[] = { {"0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e", ""}, {"$keccak$d135bb84d0439dbac432247ee573a23ea7d3c9deb2a968eb31d47c4fb45f1ef4422d6c531b5b9bd6f449ebcc449ea94d0a8f05f62130fda612da53c79659f609", "The quick brown fox jumps over the lazy dog"}, {"$keccak$e4a7e8f5572f4853ef26a862f31687c249b1cd7922df2aac1f4348d8ceef944c74d1949e3465704a5f3f89fb53e0dcce3ea142c90af04c84cc7e548f144f8f0b", "abcd"}, {NULL} }; static int (*saved_key_length); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out) [(BINARY_SIZE + sizeof(ARCH_WORD_32) - 1) / sizeof(ARCH_WORD_32)]; static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt = omp_t * MIN_KEYS_PER_CRYPT; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt = omp_t * MAX_KEYS_PER_CRYPT; #endif saved_key_length = mem_calloc_tiny(sizeof(*saved_key_length) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_out = mem_calloc_tiny(sizeof(*crypt_out) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); KeccakInitialize(); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q; p = ciphertext; if (!strncmp(p, "$keccak$", 8)) p += 8; q = p; while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q && q - p == CIPHERTEXT_LENGTH; } static char *split(char *ciphertext, int index, struct fmt_main *pFmt) { static char out[8 + CIPHERTEXT_LENGTH + 1]; if (!strncmp(ciphertext, "$keccak$", 8)) ciphertext += 8; memcpy(out, "$keccak$", 8); memcpy(out + 8, ciphertext, CIPHERTEXT_LENGTH + 1); strlwr(out + 8); return out; } static void *get_binary(char *ciphertext) { static unsigned char *out; char *p; int i; if (!out) out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD); p = ciphertext + 8; 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] & 0xF; } static int get_hash_1(int index) { return crypt_out[index][0] & 0xFF; } static int get_hash_2(int index) { return crypt_out[index][0] & 0xFFF; } static int get_hash_3(int index) { return crypt_out[index][0] & 0xFFFF; } static int get_hash_4(int index) { return crypt_out[index][0] & 0xFFFFF; } static int get_hash_5(int index) { return crypt_out[index][0] & 0xFFFFFF; } static int get_hash_6(int index) { return crypt_out[index][0] & 0x7FFFFFF; } static void set_key(char *key, int index) { int len = strlen(key); saved_key_length[index] = len; if (len > PLAINTEXT_LENGTH) len = saved_key_length[index] = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, len); } static char *get_key(int index) { saved_key[index][saved_key_length[index]] = 0; return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { Hash(512, (BitSequence *)saved_key[index], saved_key_length[index] * 8, (BitSequence *)crypt_out[index]); } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], BINARY_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_rawKeccak = { { FORMAT_LABEL, FORMAT_NAME, "Keccak 512 " ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, #if FMT_MAIN_VERSION > 9 BINARY_ALIGN, #endif SALT_SIZE, #if FMT_MAIN_VERSION > 9 SALT_ALIGN, #endif MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_SPLIT_UNIFIES_CASE, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, fmt_default_salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif 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, 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 */
ConvolutionRules.h
// Copyright 2016-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #ifndef CONVOLUTIONRULES_H #define CONVOLUTIONRULES_H #include "RectangularRegions.h" template <Int dimension> void Convolution_InputSgToRulesAndOutputSg(SparseGrid<dimension> &inputGrid, SparseGrid<dimension> &outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize) { rules.resize(volume<dimension>(size)); for (auto const &inIter : inputGrid.mp) { auto outRegion = OutputRegionCalculator<dimension>( inIter.first, size, stride, outputSpatialSize); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(inIter.first); auto mapVal = outputGrid.mp.insert(std::make_pair(j, 0)); if (mapVal.second) { mapVal.first->second = outputGrid.ctr++; } rules[rulesOffset].push_back(inIter.second + inputGrid.ctr); rules[rulesOffset].push_back(mapVal.first->second); } } } template <Int dimension> Int Convolution_InputSgsToRulesAndOutputSgs(SparseGrids<dimension> &input_SGs, SparseGrids<dimension> &output_SGs, RuleBook &rules, long *filterSize, long *filterStride, long *input_spatialSize, long *output_spatialSize) { rules.clear(); output_SGs.clear(); Int batchSize = input_SGs.size(); output_SGs.resize(batchSize); Int output_nActive = 0; for (Int i = 0; i < batchSize; i++) { auto &iSG = input_SGs[i]; auto &oSG = output_SGs[i]; oSG.ctr = output_nActive; Convolution_InputSgToRulesAndOutputSg<dimension>( iSG, oSG, rules, filterSize, filterStride, input_spatialSize, output_spatialSize); output_nActive = oSG.ctr; oSG.ctr = 0; } return output_nActive; } template <Int dimension> Int Convolution_InputSgsToRulesAndOutputSgs_OMP( SparseGrids<dimension> &input_SGs, SparseGrids<dimension> &output_SGs, RuleBook &rules, long *filterSize, long *filterStride, long *input_spatialSize, long *output_spatialSize) { rules.clear(); rules.resize(volume<dimension>(filterSize)); output_SGs.clear(); Int batchSize = input_SGs.size(); output_SGs.resize(batchSize); std::vector<RuleBook> rbs(batchSize); { Int i; #pragma omp parallel for private(i) for (i = 0; i < batchSize; i++) Convolution_InputSgToRulesAndOutputSg<dimension>( input_SGs[i], output_SGs[i], rbs[i], filterSize, filterStride, input_spatialSize, output_spatialSize); } Int output_nActive = 0; for (Int i = 0; i < batchSize; i++) { // Parallel assignment: // output_nActive <- output_nActive+output_SGs[i].ctr // output_SGs[i].ctr <- output_nActive Int tmp = output_nActive; output_nActive += output_SGs[i].ctr; output_SGs[i].ctr = tmp; } { Int i; #pragma omp parallel for private(i) for (i = 0; i < (Int)rules.size(); i++) { auto &R = rules[i]; for (Int j = 0; j < batchSize; j++) { auto &r = rbs[j][i]; auto offset = output_SGs[j].ctr; for (Int k = 0; k < (Int)r.size();) { R.push_back(r[k++]); R.push_back(r[k++] + offset); } } } } return output_nActive; } // for each active site, list of (inputFeatureNumber,batchIdx, spatialOffset) // triples template <Int dimension> void SparseToDense_InputSgsToRulesAndOutputSgs( SparseGrids<dimension> &input_SGs, RuleBook &rules, long *spatialSize) { Int batchSize = input_SGs.size(); rules.clear(); rules.resize(batchSize); Point<dimension> lb, ub; for (Int i = 0; i < dimension; ++i) { lb[i] = 0; ub[i] = spatialSize[i] - 1; } auto region = RectangularRegion<dimension>(lb, ub); for (Int batchIdx = 0; batchIdx < batchSize; batchIdx++) { auto &iSG = input_SGs[batchIdx]; for (auto const &inIter : iSG.mp) { rules[batchIdx].push_back(inIter.second + iSG.ctr); rules[batchIdx].push_back(region.offset(inIter.first)); } } } template <Int dimension> void SparseToDense_InputSgsToRulesAndOutputSgs_OMP( SparseGrids<dimension> &input_SGs, RuleBook &rules, long *spatialSize) { Int batchSize = input_SGs.size(); rules.clear(); rules.resize(batchSize); Point<dimension> lb, ub; for (Int i = 0; i < dimension; ++i) { lb[i] = 0; ub[i] = spatialSize[i] - 1; } auto region = RectangularRegion<dimension>(lb, ub); Int batchIdx; #pragma omp parallel for private(batchIdx) for (batchIdx = 0; batchIdx < batchSize; batchIdx++) { auto &iSG = input_SGs[batchIdx]; for (auto const &inIter : iSG.mp) { rules[batchIdx].push_back(inIter.second + iSG.ctr); rules[batchIdx].push_back(region.offset(inIter.first)); } } } #endif /* CONVOLUTIONRULES_H */
Solver.h
#pragma once #include <iostream> #include "common.h" #include "Loss.h" #include "Prox.h" namespace solvers { class Solver { public: Solver(const size_t nfeatures, const std::string& loss, const std::string& prox = "none", const Double proxWeight = 0) : nfeatures_(nfeatures), w_(Vector::Zero(nfeatures_)), loss_(loss), prox_(prox), proxWeight_(proxWeight) { } virtual ~Solver() { } // delete copy constructors Solver(const Solver&) = delete; Solver& operator=(const Solver&) = delete; Solver(Solver&&) = default; Solver& operator=(Solver&&) = default; size_t nfeatures() const { return nfeatures_; } const std::string& loss() const { return loss_; } virtual Vector& w() { return w_; } virtual const Vector& w() const { return w_; } Double* wdata() { return w().data(); } Double computeSquaredNorm() const { return w().squaredNorm(); } Double computeProxPenalty() const { return Prox::computePenalty(w(), prox_); } // for dense data void predict(const size_t dataSize, Double* const outPreds, const Double* const XData) const { const MatrixMap Xmap(XData, dataSize, nfeatures_); Eigen::Map<Vector> preds(outPreds, dataSize); preds = Xmap * w(); } Double computeLoss(const size_t dataSize, const Double* const XData, const Double* const yData) const { Vector preds(dataSize); predict(dataSize, preds.data(), XData); return computeLossImpl(preds, yData); } template <typename SolverT> static void iterateBlock(SolverT& solver, const size_t blockSize, const Double* const XData, const Double* const yData, const int64_t* const idxData) { const MatrixMap Xmap(XData, blockSize, solver.nfeatures()); for (size_t i = 0; i < blockSize; ++i) { solver.iterate(Xmap.row(i), yData[i], idxData[i]); } } template <typename SolverT> static void iterateBlockIndexed(SolverT& solver, const size_t dataSize, const Double* const XData, const Double* const yData, const size_t blockSize, const int64_t* const idxData) { const MatrixMap Xmap(XData, dataSize, solver.nfeatures()); for (size_t i = 0; i < blockSize; ++i) { solver.iterate(Xmap.row(idxData[i]), yData[idxData[i]], idxData[i]); } } template <typename SolverT> static void setQ(SolverT& solver, const size_t n, const Double* const qData) { const VectorMap qMap(qData, n); solver.setQ(qMap); } // for sparse data void predict(const size_t dataSize, Double* const outPreds, const size_t nnz, const int32_t* const Xindptr, const int32_t* const Xindices, const Double* const Xvalues) const { const SpMatrixMap Xmap(dataSize, nfeatures(), nnz, Xindptr, Xindices, Xvalues); Eigen::Map<Vector> preds(outPreds, dataSize); preds = Xmap * w(); } Double computeLoss(const size_t dataSize, const size_t nnz, const int32_t* const Xindptr, const int32_t* const Xindices, const Double* const Xvalues, const Double* const yData) const { Vector preds(dataSize); predict(dataSize, preds.data(), nnz, Xindptr, Xindices, Xvalues); return computeLossImpl(preds, yData); } template <typename SolverT> static void iterateBlock(SolverT& solver, const size_t blockSize, // rows const size_t nnz, const int32_t* const Xindptr, const int32_t* const Xindices, const Double* const Xvalues, const Double* const yData, const int64_t* const idxData) { const SpMatrixMap Xmap(blockSize, solver.nfeatures(), nnz, Xindptr, Xindices, Xvalues); for (size_t i = 0; i < blockSize; ++i) { solver.iterate(Xmap.row(i), yData[i], idxData[i]); } } template <typename SolverT> static void iterateBlockIndexed(SolverT& solver, const size_t dataSize, const size_t nnz, const int32_t* const Xindptr, const int32_t* const Xindices, const Double* const Xvalues, const Double* const yData, const size_t blockSize, const int64_t* const idxData) { const SpMatrixMap Xmap(dataSize, solver.nfeatures(), nnz, Xindptr, Xindices, Xvalues); for (size_t i = 0; i < blockSize; ++i) { solver.iterate(Xmap.row(idxData[i]), yData[idxData[i]], idxData[i]); } } template <typename SolverT> static void initFromX(SolverT& solver, const size_t dataSize, const size_t nnz, const int32_t* const Xindptr, const int32_t* const Xindices, const Double* const Xvalues) { const SpMatrixMap Xmap( dataSize, solver.nfeatures(), nnz, Xindptr, Xindices, Xvalues); solver.initFromX(Xmap); } template <typename SolverT> static void initQ(SolverT& solver, const size_t dataSize, const size_t nnz, const int32_t* const Xindptr, const int32_t* const Xindices, const Double* const Xvalues) { const SpMatrixMap Xmap( dataSize, solver.nfeatures(), nnz, Xindptr, Xindices, Xvalues); solver.initQ(Xmap); } private: Double computeLossImpl(const Vector& preds, const Double* const yData) const { const size_t dataSize = preds.size(); Double loss = 0; #pragma omp parallel for reduction(+:loss) for (size_t i = 0; i < dataSize; ++i) { loss += Loss::computeLoss(loss_, preds(i), yData[i]); } return loss / preds.size(); } const size_t nfeatures_; protected: mutable Vector w_; const std::string loss_; const std::string prox_; const Double proxWeight_; }; template <typename SolverT> class OneVsRest { public: template <typename... Args> OneVsRest(const size_t nclasses, const Args&... args) : nclasses_(nclasses) { solvers_.reserve(nclasses_); for (size_t i = 0; i < nclasses_; ++i) { solvers_.emplace_back(args...); } } size_t nclasses() const { return nclasses_; } void startDecay() { for (auto& solver : solvers_) { solver.startDecay(); } } void decay(const Double multiplier = 0.5) { for (auto& solver : solvers_) { solver.decay(multiplier); } } void iterateBlock(const size_t blockSize, const Double* const XData, const int32_t* const yData, const int64_t* const idxData) { const MatrixMap Xmap(XData, blockSize, solvers_.front().nfeatures()); #pragma omp parallel for for (size_t c = 0; c < nclasses_; ++c) { for (size_t i = 0; i < blockSize; ++i) { solvers_[c].iterate( Xmap.row(i), static_cast<Double>(yData[i] == static_cast<int32_t>(c)), idxData[i]); } } } void iterateBlockIndexed(const size_t dataSize, const Double* const XData, const int32_t* const yData, const size_t blockSize, const int64_t* const idxData) { const MatrixMap Xmap(XData, dataSize, solvers_.front().nfeatures()); #pragma omp parallel for for (size_t c = 0; c < nclasses_; ++c) { for (size_t i = 0; i < blockSize; ++i) { solvers_[c].iterate( Xmap.row(idxData[i]), static_cast<Double>(yData[idxData[i]] == static_cast<int32_t>(c)), idxData[i]); } } } template <typename... Args> void predict(const size_t dataSize, int32_t* const out, Args... Xargs) const { Matrix preds(nclasses_, dataSize); #pragma omp parallel for for (size_t c = 0; c < nclasses_; ++c) { solvers_[c].predict(dataSize, preds.row(c).data(), Xargs...); } #pragma omp parallel for for (size_t i = 0; i < dataSize; ++i) { out[i] = 0; Double m = preds(0, i); for (size_t c = 1; c < nclasses_; ++c) { if (preds(c, i) > m) { m = preds(c, i); out[i] = c; } } } } Double computeLoss(const size_t dataSize, const Double* const XData, const int32_t* const yData) const { Matrix preds(nclasses_, dataSize); #pragma omp parallel for for (size_t c = 0; c < nclasses_; ++c) { solvers_[c].predict(dataSize, preds.row(c).data(), XData); } return computeLossImpl(preds, yData); } Double computeSquaredNorm() const { Double res = 0; #pragma omp parallel for reduction(+:res) for (size_t c = 0; c < nclasses_; ++c) { res += solvers_[c].w().squaredNorm(); } return res; } Double computeProxPenalty() const { Double res = 0; #pragma omp parallel for reduction(+:res) for (size_t c = 0; c < nclasses_; ++c) { res += solvers_[c].computeProxPenalty(); } return res; } private: Double computeLossImpl(const Matrix& preds, const int32_t* const yData) const { const size_t dataSize = preds.cols(); Double loss = 0; #pragma omp parallel for reduction(+:loss) for (size_t i = 0; i < dataSize; ++i) { Double l = 0; for (size_t c = 0; c < nclasses_; ++c) { l += Loss::computeLoss( solvers_[0].loss(), preds(c, i), static_cast<Double>(yData[i] == static_cast<int32_t>(c))); } loss += l; } return loss / dataSize; } const size_t nclasses_; std::vector<SolverT> solvers_; }; }
SpatialMatching.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/SpatialMatching.c" #else #define square(x) ((x)*(x)) #define max(x,y) (((x)>(y)) ? (x) : (y)) #define min(x,y) (((x)>(y)) ? (y) : (x)) static int nn_(SpatialMatching_updateOutput)(lua_State *L) { // get all params THTensor *input1 = luaT_checkudata(L, 2, torch_Tensor); THTensor *input2 = luaT_checkudata(L, 3, torch_Tensor); int maxw = luaT_getfieldcheckint(L, 1, "maxw"); int maxh = luaT_getfieldcheckint(L, 1, "maxh"); int full_output = luaT_getfieldcheckboolean(L, 1, "full_output"); THTensor *output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor); // dims int iwidth = input1->size[2]; int iheight = input1->size[1]; int ichannels = input1->size[0]; // make contiguous //input1 = THTensor_(newContiguous)(input1); //input2 = THTensor_(newContiguous)(input2); //output = THTensor_(newContiguous)(output); // zero output THTensor_(fill)(output, 1e30); // get strides long *i1s = input1->stride; long *i2s = input2->stride; long *os = output->stride; // get pointers real *input1_p = THTensor_(data)(input1); real *input2_p = THTensor_(data)(input2); real *output_p = THTensor_(data)(output); // compute output int x1,y1,x2,y2,k; real dist; if (full_output) { // get halves of window size int halfh1 = ceil((real)maxh/2)-1; int halfh2 = floor((real)maxh/2)+1; int halfw1 = ceil((real)maxw/2)-1; int halfw2 = floor((real)maxw/2)+1; long dy, dx; #pragma omp parallel for private(x1,x2,y2,k,dist,dy,dx) for (y1 = 0; y1 < iheight; y1++) { for (x1 = 0; x1 < iwidth; x1++) { for (y2 = max(0,y1-halfh1); y2 < min(iheight,y1+halfh2); y2++) { for (x2 = max(0,(x1-halfw1)); x2 < min(iwidth,x1+halfw2); x2++) { dist = 0; for (k = 0; k < ichannels; k++) { dist += square(input1_p[k*i1s[0] + y1*i1s[1] + x1*i1s[2]] - input2_p[k*i2s[0] + y2*i2s[1] + x2*i2s[2]]); } dy = y2-y1 + halfh1; dx = x2-x1 + halfw1; output_p[dy*os[2] + dx*os[3] + y1*os[0] + x1*os[1]] = dist; } } } } /* real *input1_p_it_start = input1_p, *input1_p_it_end = input1_p+ichannels*i1s[0]; real *input1_p_it, *input2_p_it; for (y1 = 0; y1 < iheight; y1++) { for (x1 = 0; x1 < iwidth; x1++, ++input1_p_it_start, ++input1_p_it_end) { for (y2 = max(0,y1-halfh1); y2 < min(iheight,y1+halfh2); y2++) { for (x2 = max(0,(x1-halfw1)); x2 < min(iwidth,x1+halfw2); x2++) { dist = 0; for (input1_p_it = input1_p_it_start, input2_p_it=input2_p+y2*i2s[1]+x2*i2s[2]; input1_p_it != input1_p_it_end; input1_p_it += i1s[0], input2_p_it += i2s[0]) { dist += square(*input1_p_it - *input2_p_it); } dy = y2-y1 + halfh1; dx = x2-x1 + halfw1; output_p[dy*os[0] + dx*os[1] + y1*os[2] + x1*os[3]] = dist; } } } } */ } else { #pragma omp parallel for private(y1,x1,x2,y2,k,dist) for (y1 = 0; y1 < iheight; y1++) { for (x1 = 0; x1 < iwidth; x1++) { for (y2 = y1; y2 < y1+maxh; y2++) { for (x2 = x1; x2 < x1+maxw; x2++) { dist = 0; for (k = 0; k < ichannels; k++) { dist += square(input1_p[k*i1s[0] + y1*i1s[1] + x1*i1s[2]] - input2_p[k*i2s[0] + y2*i2s[1] + x2*i2s[2]]); } output_p[(y2-y1)*os[2] + (x2-x1)*os[3] + y1*os[0] + x1*os[1]] = dist; } } } } } // done return 1; } static int nn_(SpatialMatching_updateGradInput)(lua_State *L) { // get all params THTensor *input1 = luaT_checkudata(L, 2, torch_Tensor); THTensor *input2 = luaT_checkudata(L, 3, torch_Tensor); THTensor *gradInput1 = luaT_getfieldcheckudata(L, 1, "gradInput1", torch_Tensor); THTensor *gradInput2 = luaT_getfieldcheckudata(L, 1, "gradInput2", torch_Tensor); THTensor *gradOutput = luaT_checkudata(L, 4, torch_Tensor); int full_output = luaT_getfieldcheckboolean(L, 1, "full_output"); int maxw = luaT_getfieldcheckint(L, 1, "maxw"); int maxh = luaT_getfieldcheckint(L, 1, "maxh"); // dims int iwidth = input1->size[2]; int iheight = input1->size[1]; int ichannels = input1->size[0]; // get strides long *i1s = input1->stride; long *i2s = input2->stride; long *gi1s = gradInput1->stride; long *gi2s = gradInput2->stride; long *gos = gradOutput->stride; // get pointers real *input1_p = THTensor_(data)(input1); real *input2_p = THTensor_(data)(input2); real *gradInput1_p = THTensor_(data)(gradInput1); real *gradInput2_p = THTensor_(data)(gradInput2); real *gradOutput_p = THTensor_(data)(gradOutput); // compute gradients int x1, y1, x2, y2, k; real partial_d; if (full_output) { // get halves of window size int halfh1 = ceil((real)maxh/2)-1; int halfh2 = floor((real)maxh/2)+1; int halfw1 = ceil((real)maxw/2)-1; int halfw2 = floor((real)maxw/2)+1; long dy, dx; //#pragma omp parallel for private(x1,x2,y2,k,dy,dx,partial_d) NO! gradInput has += for (y1 = 0; y1 < iheight; y1++) { for (x1 = 0; x1 < iwidth; x1++) { for (y2 = max(0,y1-halfh1); y2 < min(iheight,y1+halfh2); y2++) { for (x2 = max(0,(x1-halfw1)); x2 < min(iwidth,x1+halfw2); x2++) { dy = y2-y1 + halfh1; dx = x2-x1 + halfw1; for (k=0; k<ichannels; k++) { partial_d = 2*(input1_p[k*i1s[0] + y1*i1s[1] + x1*i1s[2]] - input2_p[k*i2s[0] + y2*i2s[1] + x2*i2s[2]]); partial_d *= gradOutput_p[dy*gos[2] + dx*gos[3] + y1*gos[0] + x1*gos[1]]; gradInput1_p[k*gi1s[0] + y1*gi1s[1] + x1*gi1s[2]] += partial_d; gradInput2_p[k*gi2s[0] + y2*gi2s[1] + x2*gi2s[2]] -= partial_d; } } } } } } else { //#pragma omp parallel for private(x1,x2,y2,k,partial_d) for (y1 = 0; y1 < iheight; y1++) { for (x1 = 0; x1 < iwidth; x1++) { for (y2 = y1; y2 < y1+maxh; y2++) { for (x2 = x1; x2 < x1+maxw; x2++) { for (k = 0; k < ichannels; k++) { partial_d = 2*(input1_p[k*i1s[0] + y1*i1s[1] + x1*i1s[2]] - input2_p[k*i2s[0] + y2*i2s[1] + x2*i2s[2]]); partial_d *= gradOutput_p[(y2-y1)*gos[2]+(x2-x1)*gos[3]+y1*gos[0]+x1*gos[1]]; gradInput1_p[k*gi1s[0] + y1*gi1s[1] + x1*gi1s[2]] += partial_d; gradInput2_p[k*gi2s[0] + y2*gi2s[1] + x2*gi2s[2]] -= partial_d; } } } } } } // done return 1; } static const struct luaL_Reg nn_(SpatialMatching__) [] = { {"SpatialMatching_updateOutput", nn_(SpatialMatching_updateOutput)}, {"SpatialMatching_updateGradInput", nn_(SpatialMatching_updateGradInput)}, {NULL, NULL} }; static void nn_(SpatialMatching_init)(lua_State *L) { luaT_pushmetatable(L, torch_Tensor); luaT_registeratname(L, nn_(SpatialMatching__), "nn"); lua_pop(L,1); } #endif
omp_threadprivate_for.c
// RUN: %libomp-compile-and-run #include "omp_testsuite.h" #include <stdlib.h> #include <stdio.h> static int i; #pragma omp threadprivate(i) int test_omp_threadprivate_for() { int known_sum; int sum; known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; sum = 0; #pragma omp parallel { int sum0 = 0, i0; #pragma omp for for (i0 = 1; i0 <= LOOPCOUNT; i0++) { i = i0; sum0 = sum0 + i; } #pragma omp critical { sum = sum + sum0; } } /* end of parallel */ if (known_sum != sum ) { fprintf(stderr, " known_sum = %d, sum = %d\n", known_sum, sum); } return (known_sum == sum); } /* end of check_threadprivate*/ int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_threadprivate_for()) { num_failed++; } } return num_failed; }
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 32; 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); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_bitmap_select_template.c
//------------------------------------------------------------------------------ // GB_bitmap_select_template: C=select(A,thunk) if A is bitmap or full //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Ab and Cb can be aliased, if A is bitmap and the selection is done in-place. // Ax and Cx are not aliased. // TODO: If done in-place, Cx can be passed as NULL. Then if A is not bitmap, // C->b needs to be allocated, but not C->x. // the following macro is awkward but currently needed for the user_select op: #undef GBI #define GBI(Ai,p,avlen) i { int8_t *Ab = A->b ; GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ; const int64_t avlen = A->vlen ; const int64_t avdim = A->vdim ; const size_t asize = A->type->size ; const int64_t anz = avlen * avdim ; int64_t pA, cnvals = 0 ; #pragma omp parallel for num_threads(nthreads) schedule(static) \ reduction(+:cnvals) for (pA = 0 ; pA < anz ; pA++) { int64_t i = pA % avlen ; int64_t j = pA / avlen ; #if defined ( GB_ENTRY_SELECTOR ) // test the existence and value of A(i,j) int8_t cb = GBB (Ab, pA) && GB_TEST_VALUE_OF_ENTRY (pA) ; #else // test the existence and position of A(i,j) #if defined ( GB_TRIL_SELECTOR ) int8_t cb = GBB (Ab, pA) && (j-i <= ithunk) ; #elif defined ( GB_TRIU_SELECTOR ) int8_t cb = GBB (Ab, pA) && (j-i >= ithunk) ; #elif defined ( GB_DIAG_SELECTOR ) int8_t cb = GBB (Ab, pA) && (j-i == ithunk) ; #elif defined ( GB_OFFDIAG_SELECTOR ) int8_t cb = GBB (Ab, pA) && (j-i != ithunk) ; #else ASSERT (GB_DEAD_CODE) ; #endif #endif Cb [pA] = cb ; cnvals += cb ; // if (Cx != NULL) { // Cx [pA] = Ax [pA] GB_SELECT_ENTRY (Cx, pA, Ax, pA) ; } } (*cnvals_handle)= cnvals ; }
adatm_cpd.c
/****************************************************************************** * INCLUDES *****************************************************************************/ #include "base.h" #include "matrix.h" #include "mttkrp.h" #include "timer.h" #include "thd_info.h" #include "util.h" #include "cpd.h" #include "adatm_base.h" #include "adatm_cpd.h" #include <math.h> #include <omp.h> /****************************************************************************** * SPLATT PRIVATE FUNCTIONS *****************************************************************************/ /** * @brief Resets serial and MPI timers that were activated during some CPD * pre-processing. * * @param rinfo MPI rank information. */ static void p_reset_cpd_timers( rank_info const * const rinfo) { timer_reset(&timers[TIMER_ATA]); #ifdef SPLATT_USE_MPI timer_reset(&timers[TIMER_MPI]); timer_reset(&timers[TIMER_MPI_IDLE]); timer_reset(&timers[TIMER_MPI_COMM]); timer_reset(&timers[TIMER_MPI_ATA]); timer_reset(&timers[TIMER_MPI_REDUCE]); timer_reset(&timers[TIMER_MPI_NORM]); timer_reset(&timers[TIMER_MPI_UPDATE]); timer_reset(&timers[TIMER_MPI_FIT]); MPI_Barrier(rinfo->comm_3d); #endif } /** * @brief Find the Frobenius norm squared of a Kruskal tensor. This equivalent * to via computing <X,X>, the inner product of X with itself. We find * this via \lambda^T (AtA * BtB * ...) \lambda, where * is the Hadamard * product. * * @param nmodes The number of modes in the tensor. * @param lambda The vector of column norms. * @param aTa An array of Gram Matrices (AtA, BtB, ...). * * @return The Frobenius norm of X, squared. */ static val_t p_kruskal_norm( idx_t const nmodes, val_t const * const restrict lambda, matrix_t ** aTa) { idx_t const rank = aTa[0]->J; val_t * const restrict av = aTa[MAX_NMODES]->vals; val_t norm_mats = 0; /* use aTa[MAX_NMODES] as scratch space */ for(idx_t x=0; x < rank*rank; ++x) { av[x] = 1.; } /* aTa[MAX_NMODES] = hada(aTa) */ for(idx_t m=0; m < nmodes; ++m) { val_t const * const restrict atavals = aTa[m]->vals; for(idx_t x=0; x < rank*rank; ++x) { av[x] *= atavals[x]; } } /* now compute lambda^T * aTa[MAX_NMODES] * lambda */ for(idx_t i=0; i < rank; ++i) { for(idx_t j=0; j < rank; ++j) { norm_mats += av[j+(i*rank)] * lambda[i] * lambda[j]; } } return fabs(norm_mats); } /** * @brief Compute the inner product of a Kruskal tensor and an unfactored * tensor. Assumes that 'm1' contains the MTTKRP result along the last * mode of the two input tensors. This naturally follows the end of a * CPD iteration. * * @param nmodes The number of modes in the input tensors. * @param rinfo MPI rank information. * @param thds OpenMP thread data structures. * @param lambda The vector of column norms. * @param mats The Kruskal-tensor matrices. * @param m1 The result of doing MTTKRP along the last mode. * * @return The inner product of the two tensors, computed via: * 1^T hadamard(mats[nmodes-1], m1) \lambda. */ static val_t p_tt_kruskal_inner( idx_t const nmodes, rank_info * const rinfo, thd_info * const thds, val_t const * const restrict lambda, matrix_t ** mats, matrix_t const * const m1) { idx_t const rank = mats[0]->J; idx_t const lastm = nmodes - 1; idx_t const dim = m1->I; val_t const * const m0 = mats[lastm]->vals; val_t const * const mv = m1->vals; val_t myinner = 0; #pragma omp parallel reduction(+:myinner) { int const tid = omp_get_thread_num(); val_t * const restrict accumF = (val_t *) thds[tid].scratch[0]; for(idx_t r=0; r < rank; ++r) { accumF[r] = 0.; } #pragma omp for for(idx_t i=0; i < dim; ++i) { for(idx_t r=0; r < rank; ++r) { accumF[r] += m0[r+(i*rank)] * mv[r+(i*rank)]; } } /* accumulate everything into 'myinner' */ for(idx_t r=0; r < rank; ++r) { myinner += accumF[r] * lambda[r]; } } val_t inner = 0.; #ifdef SPLATT_USE_MPI timer_start(&timers[TIMER_MPI_FIT]); timer_start(&timers[TIMER_MPI_IDLE]); MPI_Barrier(rinfo->comm_3d); timer_stop(&timers[TIMER_MPI_IDLE]); MPI_Allreduce(&myinner, &inner, 1, SPLATT_MPI_VAL, MPI_SUM, rinfo->comm_3d); timer_stop(&timers[TIMER_MPI_FIT]); #else inner = myinner; #endif return inner; } /** * @brief Compute the fit of a Kruskal tensor, Z, to an input tensor, X. This * is computed via 1 - [sqrt(<X,X> + <Z,Z> - 2<X,Z>) / sqrt(<X,X>)]. * * @param nmodes The number of modes in the input tensors. * @param rinfo MPI rank information. * @param thds OpenMP thread data structures. * @param ttnormsq The norm (squared) of the original input tensor, <X,X>. * @param lambda The vector of column norms. * @param mats The Kruskal-tensor matrices. * @param m1 The result of doing MTTKRP along the last mode. * @param aTa An array of matrices (length MAX_NMODES)containing BtB, CtC, etc. * * @return The inner product of the two tensors, computed via: * \lambda^T hadamard(mats[nmodes-1], m1) \lambda. */ static val_t p_calc_fit( idx_t const nmodes, rank_info * const rinfo, thd_info * const thds, val_t const ttnormsq, val_t const * const restrict lambda, matrix_t ** mats, matrix_t const * const m1, matrix_t ** aTa) { timer_start(&timers[TIMER_FIT]); /* First get norm of new model: lambda^T * (hada aTa) * lambda. */ val_t const norm_mats = p_kruskal_norm(nmodes, lambda, aTa); /* Compute inner product of tensor with new model */ val_t const inner = p_tt_kruskal_inner(nmodes, rinfo, thds, lambda, mats,m1); val_t const residual = sqrt(ttnormsq + norm_mats - (2 * inner)); timer_stop(&timers[TIMER_FIT]); return 1 - (residual / sqrt(ttnormsq)); } /****************************************************************************** * AdaTM PUBLIC FUNCTIONS *****************************************************************************/ int splatt_cpd_als_adaptive( splatt_csf const * const tensors, rcsf_seq_adaptive * const rs_seq, splatt_idx_t const n_csf, group_properties const * const grp_prop, splatt_idx_t const n_grp, splatt_idx_t const * const use_csfs, splatt_idx_t const * const use_tags, splatt_idx_t const nfactors, double const * const options, splatt_kruskal * factored) { matrix_t * mats[MAX_NMODES+1]; idx_t nmodes = tensors->nmodes; rank_info rinfo; rinfo.rank = 0; // jli: allocate the maximum space for each update factor matrix. /* allocate factor matrices */ idx_t maxdim = tensors->dims[argmax_elem(tensors->dims, nmodes)]; for(idx_t m=0; m < nmodes; ++m) { mats[m] = (matrix_t *) mat_rand(tensors[0].dims[m], nfactors); } mats[MAX_NMODES] = mat_alloc(maxdim, nfactors); val_t * lambda = (val_t *) splatt_malloc(nfactors * sizeof(val_t)); /* do the factorization! */ factored->fit = cpd_als_iterate_adaptive(tensors, rs_seq, n_csf, grp_prop, n_grp, use_csfs, use_tags, mats, lambda, nfactors, &rinfo, options); /* store output */ factored->rank = nfactors; factored->nmodes = nmodes; factored->lambda = lambda; for(idx_t m=0; m < nmodes; ++m) { factored->dims[m] = tensors->dims[m]; factored->factors[m] = mats[m]->vals; } /* clean up */ mat_free(mats[MAX_NMODES]); for(idx_t m=0; m < nmodes; ++m) { free(mats[m]); /* just the matrix_t ptr, data is safely in factored */ } return SPLATT_SUCCESS; } double cpd_als_iterate_adaptive( splatt_csf const * const tensors, rcsf_seq_adaptive * const rs_seq, splatt_idx_t const n_csf, group_properties const * const grp_prop, splatt_idx_t const n_grp, splatt_idx_t const * const use_csfs, splatt_idx_t const * const use_tags, matrix_t ** mats, val_t * const lambda, idx_t const nfactors, rank_info * const rinfo, double const * const opts) { idx_t const nmodes = tensors[0].nmodes; idx_t const nthreads = (idx_t) opts[SPLATT_OPTION_NTHREADS]; /* Setup thread structures. + 64 bytes is to avoid false sharing. * TODO make this better */ omp_set_num_threads(nthreads); thd_info * thds = thd_init(nthreads, 3, (nfactors * nfactors * sizeof(val_t)) + 64, 0, (nmodes * nfactors * sizeof(val_t)) + 64); matrix_t * m1 = mats[MAX_NMODES]; /* Initialize first A^T * A mats. We redundantly do the first because it * makes communication easier. */ matrix_t * aTa[MAX_NMODES+1]; for(idx_t m=0; m < nmodes; ++m) { aTa[m] = mat_alloc(nfactors, nfactors); mat_aTa(mats[m], aTa[m], rinfo, thds, nthreads); } /* used as buffer space */ aTa[MAX_NMODES] = mat_alloc(nfactors, nfactors); /* Compute input tensor norm */ double oldfit = 0; double fit = 0; val_t ttnormsq = csf_frobsq(tensors); /* setup timers */ p_reset_cpd_timers(rinfo); sp_timer_t itertime; sp_timer_t modetime[MAX_NMODES]; timer_start(&timers[TIMER_CPD]); idx_t const niters = (idx_t) opts[SPLATT_OPTION_NITER]; for(idx_t it=0; it < niters; ++it) { timer_fstart(&itertime); // for(idx_t m=0; m < nmodes; ++m) { for(idx_t m=0; m < nmodes; ++m) { timer_fstart(&modetime[m]); mats[MAX_NMODES]->I = tensors[0].dims[m]; m1->I = mats[m]->I; /* M1 = X * (C o B) */ timer_start(&timers[TIMER_MTTKRP]); mttkrp_csf_adaptive(tensors, rs_seq, n_csf, mats, m, thds, grp_prop, n_grp, use_csfs[m], use_tags[m], opts); timer_stop(&timers[TIMER_MTTKRP]); /* M2 = (CtC .* BtB .* ...)^-1 */ calc_gram_inv(m, nmodes, aTa); /* A = M1 * M2 */ memset(mats[m]->vals, 0, mats[m]->I * nfactors * sizeof(val_t)); mat_matmul(m1, aTa[MAX_NMODES], mats[m]); /* normalize columns and extract lambda */ if(it == 0) { mat_normalize(mats[m], lambda, MAT_NORM_2, rinfo, thds, nthreads); } else { mat_normalize(mats[m], lambda, MAT_NORM_MAX, rinfo, thds,nthreads); } /* update A^T*A */ mat_aTa(mats[m], aTa[m], rinfo, thds, nthreads); timer_stop(&modetime[m]); } /* foreach mode */ fit = p_calc_fit(nmodes, rinfo, thds, ttnormsq, lambda, mats, m1, aTa); timer_stop(&itertime); if(rinfo->rank == 0 && opts[SPLATT_OPTION_VERBOSITY] > SPLATT_VERBOSITY_NONE) { printf(" its = %3"SPLATT_PF_IDX" (%0.3fs) fit = %0.5f delta = %+0.4e\n", it+1, itertime.seconds, fit, fit - oldfit); printf(" mttkrp = %0.3fs\n", timers[TIMER_MTTKRP].seconds); if(opts[SPLATT_OPTION_VERBOSITY] > SPLATT_VERBOSITY_LOW) { for(idx_t m=0; m < nmodes; ++m) { printf(" mode = %1"SPLATT_PF_IDX" (%0.3fs)\n", m+1, modetime[m].seconds); } } } if(it > 0 && fabs(fit - oldfit) < opts[SPLATT_OPTION_TOLERANCE]) { break; } oldfit = fit; } timer_stop(&timers[TIMER_CPD]); printf("CPD = %0.3fs\n", timers[TIMER_CPD].seconds); cpd_post_process(nfactors, nmodes, mats, lambda, thds, nthreads, rinfo); /* CLEAN UP */ for(idx_t m=0; m < nmodes; ++m) { mat_free(aTa[m]); } mat_free(aTa[MAX_NMODES]); thd_free(thds, nthreads); return fit; }
caesar_decode.c
#include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <strings.h> #include <time.h> #include <omp.h> #include "mpi.h" #define CHARS 100000 // caesar decode paralelizado int main(int argc, char * argv[]) { // variables para MPI int myid, numprocs; char hostname[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); // variables int data = CHARS/numprocs; char local[data]; double start, stop; int maxdata = data; // aqui es donde cambiamos la llave para encriptar int llave = 3; char *path_crypt; FILE *crypt_file; char mensaje_enc[CHARS], temp1; int x; if (myid == 0) { // path para el archivo a leer path_crypt = "texto_encriptado.txt"; crypt_file = fopen(path_crypt, "r"); //mensaje por si no encuentra le archivo if (crypt_file == NULL) { printf("ERROR, no se pudo abrir el archivo txt\n"); exit(-1); } fread(mensaje_enc, CHARS, 1, crypt_file); } //dividimos el mensaje MPI_Scatter(mensaje_enc, data, MPI_CHAR, local, data, MPI_CHAR, 0, MPI_COMM_WORLD); start = omp_get_wtime(); // paralelizamos el algoritmo para desencriptar el mensaje #pragma omp parallel for for(x=0; x < maxdata; x++) { temp1 = local[x]; if(temp1 >= 'a' && temp1 <= 'z'){ temp1 = temp1 - llave; if(temp1 > 'z'){ temp1 = temp1 + 'a' - 'z' - 1; } if(temp1 < 'a'){ temp1 = temp1 + 'z' - 'a' + 1; } local[x] = temp1; } else if (temp1 >= 'A' && temp1 <= 'Z'){ temp1 = temp1 - llave; if(temp1 > 'Z'){ temp1 = temp1 + 'A' - 'Z' - 1; } if(temp1 < 'A'){ temp1 = temp1 + 'Z' - 'A' + 1; } local[x] = temp1; } } // recolectamos el mensaje MPI_Gather(local, data, MPI_CHAR, mensaje_enc, data, MPI_CHAR, 0, MPI_COMM_WORLD); if (myid == 0){ printf("Mensaje desencriptado: %s\n", mensaje_enc); fclose(crypt_file); stop = omp_get_wtime(); printf("Tiempo de ejecución de la sección paralela = %f \n", stop-start); } MPI_Finalize(); return 0; }
paint.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP AAA IIIII N N TTTTT % % P P A A I NN N T % % PPPP AAAAA I N N N T % % P A A I N NN T % % P A A IIIII N N T % % % % % % Methods to Paint on an Image % % % % Software Design % % John Cristy % % July 1998 % % % % % % Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/color-private.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/thread-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o o d f i l l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FloodfillPaintImage() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. % However, in many cases two colors may differ by a small amount. The % fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now % interpreted as the same color for the purposes of the floodfill. % % The format of the FloodfillPaintImage method is: % % MagickBooleanType FloodfillPaintImage(Image *image, % const ChannelType channel,const DrawInfo *draw_info, % const MagickPixelPacket target,const ssize_t x_offset, % const ssize_t y_offset,const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o draw_info: the draw info. % % o target: the RGB value of the target color. % % o x_offset,y_offset: the starting location of the operation. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType FloodfillPaintImage(Image *image, const ChannelType channel,const DrawInfo *draw_info, const MagickPixelPacket *target,const ssize_t x_offset,const ssize_t y_offset, const MagickBooleanType invert) { #define MaxStacksize 131072UL #define PushSegmentStack(up,left,right,delta) \ { \ if (s >= (segment_stack+MaxStacksize)) \ ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \ else \ { \ if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \ { \ s->x1=(double) (left); \ s->y1=(double) (up); \ s->x2=(double) (right); \ s->y2=(double) (delta); \ s++; \ } \ } \ } CacheView *floodplane_view, *image_view; ExceptionInfo *exception; Image *floodplane_image; MagickBooleanType skip; MagickPixelPacket fill, pixel; PixelPacket fill_color; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,RGBColorspace); if ((image->matte == MagickFalse) && (draw_info->fill.opacity != OpaqueOpacity)) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); /* Set floodfill state. */ floodplane_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); (void) SetImageAlphaChannel(floodplane_image,OpaqueAlphaChannel); segment_stack=(SegmentInfo *) AcquireQuantumMemory(MaxStacksize, sizeof(*segment_stack)); if (segment_stack == (SegmentInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Push initial segment on stack. */ exception=(&image->exception); x=x_offset; y=y_offset; start=0; s=segment_stack; PushSegmentStack(y,x,x,1); PushSegmentStack(y+1,x,x,-1); GetMagickPixelPacket(image,&fill); GetMagickPixelPacket(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception); while (s > segment_stack) { register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception); q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewVirtualIndexQueue(image_view); p+=x1; q+=x1; for (x=x1; x >= 0; x--) { if (q->opacity == (Quantum) TransparentOpacity) break; SetMagickPixelPacket(image,p,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) == invert) break; q->opacity=(Quantum) TransparentOpacity; p--; q--; } if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y, image->columns-x,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for ( ; x < (ssize_t) image->columns; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; SetMagickPixelPacket(image,p,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) == invert) break; q->opacity=(Quantum) TransparentOpacity; p++; q++; } if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for ( ; x <= x2; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; SetMagickPixelPacket(image,p,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) != invert) break; p++; q++; } } start=x; } while (x <= x2); } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; /* Tile fill color onto floodplane. */ p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) { (void) GetFillColor(draw_info,x,y,&fill_color); SetMagickPixelPacket(image,&fill_color,(IndexPacket *) NULL,&fill); if (image->colorspace == CMYKColorspace) ConvertRGBToCMYK(&fill); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(fill.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(fill.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(fill.blue)); if (((channel & OpacityChannel) != 0) || (draw_info->fill.opacity != OpaqueOpacity)) SetPixelOpacity(q,ClampToQuantum(fill.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum(fill.index)); } p++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } floodplane_view=DestroyCacheView(floodplane_view); image_view=DestroyCacheView(image_view); segment_stack=(SegmentInfo *) RelinquishMagickMemory(segment_stack); floodplane_image=DestroyImage(floodplane_image); return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GradientImage() applies a continuously smooth color transitions along a % vector from one color to another. % % Note, the interface of this method will change in the future to support % more than one transistion. % % The format of the GradientImage method is: % % MagickBooleanType GradientImage(Image *image,const GradientType type, % const SpreadMethod method,const PixelPacket *start_color, % const PixelPacket *stop_color) % % A description of each parameter follows: % % o image: the image. % % o type: the gradient type: linear or radial. % % o spread: the gradient spread meathod: pad, reflect, or repeat. % % o start_color: the start color. % % o stop_color: the stop color. % % This provides a good example of making use of the DrawGradientImage % function and the gradient structure in draw_info. */ static inline double MagickMax(const double x,const double y) { return(x > y ? x : y); } MagickExport MagickBooleanType GradientImage(Image *image, const GradientType type,const SpreadMethod method, const PixelPacket *start_color,const PixelPacket *stop_color) { DrawInfo *draw_info; GradientInfo *gradient; MagickBooleanType status; register ssize_t i; /* Set gradient start-stop end points. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(start_color != (const PixelPacket *) NULL); assert(stop_color != (const PixelPacket *) NULL); draw_info=AcquireDrawInfo(); gradient=(&draw_info->gradient); gradient->type=type; gradient->bounding_box.width=image->columns; gradient->bounding_box.height=image->rows; gradient->gradient_vector.x2=(double) image->columns-1.0; gradient->gradient_vector.y2=(double) image->rows-1.0; if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0)) gradient->gradient_vector.x2=0.0; gradient->center.x=(double) gradient->gradient_vector.x2/2.0; gradient->center.y=(double) gradient->gradient_vector.y2/2.0; gradient->radius=MagickMax(gradient->center.x,gradient->center.y); gradient->spread=method; /* Define the gradient to fill between the stops. */ gradient->number_stops=2; gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops, sizeof(*gradient->stops)); if (gradient->stops == (StopInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) ResetMagickMemory(gradient->stops,0,gradient->number_stops* sizeof(*gradient->stops)); for (i=0; i < (ssize_t) gradient->number_stops; i++) GetMagickPixelPacket(image,&gradient->stops[i].color); SetMagickPixelPacket(image,start_color,(IndexPacket *) NULL, &gradient->stops[0].color); gradient->stops[0].offset=0.0; SetMagickPixelPacket(image,stop_color,(IndexPacket *) NULL, &gradient->stops[1].color); gradient->stops[1].offset=1.0; /* Draw a gradient on the image. */ status=DrawGradientImage(image,draw_info); draw_info=DestroyDrawInfo(draw_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O i l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OilPaintImage() applies a special effect filter that simulates an oil % painting. Each pixel is replaced by the most frequent color occurring % in a circular region defined by radius. % % The format of the OilPaintImage method is: % % Image *OilPaintImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the circular neighborhood. % % o exception: return any errors or warnings in this structure. % */ static size_t **DestroyHistogramThreadSet(size_t **histogram) { register ssize_t i; assert(histogram != (size_t **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (histogram[i] != (size_t *) NULL) histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]); histogram=(size_t **) RelinquishMagickMemory(histogram); return(histogram); } static size_t **AcquireHistogramThreadSet(const size_t count) { register ssize_t i; size_t **histogram, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); histogram=(size_t **) AcquireQuantumMemory(number_threads, sizeof(*histogram)); if (histogram == (size_t **) NULL) return((size_t **) NULL); (void) ResetMagickMemory(histogram,0,number_threads*sizeof(*histogram)); for (i=0; i < (ssize_t) number_threads; i++) { histogram[i]=(size_t *) AcquireQuantumMemory(count, sizeof(**histogram)); if (histogram[i] == (size_t *) NULL) return(DestroyHistogramThreadSet(histogram)); } return(histogram); } MagickExport Image *OilPaintImage(const Image *image,const double radius, ExceptionInfo *exception) { #define NumberPaintBins 256 #define OilPaintImageTag "OilPaint/Image" CacheView *image_view, *paint_view; Image *linear_image, *paint_image; MagickBooleanType status; MagickOffsetType progress; size_t **restrict histograms, width; ssize_t y; /* Initialize painted image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); width=GetOptimalKernelWidth2D(radius,0.5); linear_image=CloneImage(image,0,0,MagickTrue,exception); paint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (paint_image != (Image *) NULL) linear_image=DestroyImage(paint_image); return((Image *) NULL); } if (image->colorspace == sRGBColorspace) (void) TransformImageColorspace(linear_image,RGBColorspace); if (SetImageStorageClass(paint_image,DirectClass) == MagickFalse) { InheritException(exception,&paint_image->exception); linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); return((Image *) NULL); } histograms=AcquireHistogramThreadSet(NumberPaintBins); if (histograms == (size_t **) NULL) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Oil paint image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(linear_image,exception); paint_view=AcquireAuthenticCacheView(paint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(linear_image,paint_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict paint_indexes; register ssize_t x; register PixelPacket *restrict q; register size_t *histogram; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (width/2L),linear_image->columns+width,width,exception); q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); paint_indexes=GetCacheViewAuthenticIndexQueue(paint_view); histogram=histograms[GetOpenMPThreadId()]; for (x=0; x < (ssize_t) linear_image->columns; x++) { register ssize_t i, u; size_t count; ssize_t j, k, v; /* Assign most frequent color. */ i=0; j=0; count=0; (void) ResetMagickMemory(histogram,0,NumberPaintBins*sizeof(*histogram)); for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { k=(ssize_t) ScaleQuantumToChar(PixelIntensityToQuantum(linear_image, p+u+i)); histogram[k]++; if (histogram[k] > count) { j=i+u; count=histogram[k]; } } i+=(ssize_t) (linear_image->columns+width); } *q=(*(p+j)); if (linear_image->colorspace == CMYKColorspace) SetPixelIndex(paint_indexes+x,GetPixelIndex(indexes+x+j)); p++; q++; } if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OilPaintImage) #endif proceed=SetImageProgress(image,OilPaintImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } paint_view=DestroyCacheView(paint_view); image_view=DestroyCacheView(image_view); histograms=DestroyHistogramThreadSet(histograms); linear_image=DestroyImage(linear_image); if (image->colorspace == sRGBColorspace) (void) TransformImageColorspace(paint_image,sRGBColorspace); if (status == MagickFalse) paint_image=DestroyImage(paint_image); return(paint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p a q u e P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpaquePaintImage() changes any pixel that matches color with the color % defined by fill. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the OpaquePaintImage method is: % % MagickBooleanType OpaquePaintImage(Image *image, % const PixelPacket *target,const PixelPacket *fill, % const MagickBooleanType invert) % MagickBooleanType OpaquePaintImageChannel(Image *image, % const ChannelType channel,const PixelPacket *target, % const PixelPacket *fill,const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o target: the RGB value of the target color. % % o fill: the replacement color. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType OpaquePaintImage(Image *image, const MagickPixelPacket *target,const MagickPixelPacket *fill, const MagickBooleanType invert) { return(OpaquePaintImageChannel(image,CompositeChannels,target,fill,invert)); } MagickExport MagickBooleanType OpaquePaintImageChannel(Image *image, const ChannelType channel,const MagickPixelPacket *target, const MagickPixelPacket *fill,const MagickBooleanType invert) { #define OpaquePaintImageTag "Opaque/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(target != (MagickPixelPacket *) NULL); assert(fill != (MagickPixelPacket *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsMagickGray(fill) == MagickFalse)) (void) TransformImageColorspace(image,RGBColorspace); if ((fill->opacity != OpaqueOpacity) && (image->matte == MagickFalse)) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); /* Make image color opaque. */ status=MagickTrue; progress=0; exception=(&image->exception); GetMagickPixelPacket(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) != invert) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(fill->red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(fill->green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(fill->blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(fill->opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum(fill->index)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OpaquePaintImageChannel) #endif proceed=SetImageProgress(image,OpaquePaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the TransparentPaintImage method is: % % MagickBooleanType TransparentPaintImage(Image *image, % const MagickPixelPacket *target,const Quantum opacity, % const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o target: the target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType TransparentPaintImage(Image *image, const MagickPixelPacket *target,const Quantum opacity, const MagickBooleanType invert) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(target != (MagickPixelPacket *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); /* Make image color transparent. */ status=MagickTrue; progress=0; exception=(&image->exception); GetMagickPixelPacket(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) != invert) q->opacity=opacity; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransparentPaintImage) #endif proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e C h r o m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImageChroma() changes the opacity value associated with any % pixel that matches color to the value defined by opacity. % % As there is one fuzz value for the all the channels, the % TransparentPaintImage() API is not suitable for the operations like chroma, % where the tolerance for similarity of two color component (RGB) can be % different, Thus we define this method take two target pixels (one % low and one hight) and all the pixels of an image which are lying between % these two pixels are made transparent. % % The format of the TransparentPaintImage method is: % % MagickBooleanType TransparentPaintImage(Image *image, % const MagickPixelPacket *low,const MagickPixelPacket *hight, % const Quantum opacity,const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o low: the low target color. % % o high: the high target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image, const MagickPixelPacket *low,const MagickPixelPacket *high, const Quantum opacity,const MagickBooleanType invert) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(high != (MagickPixelPacket *) NULL); assert(low != (MagickPixelPacket *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,ResetAlphaChannel); /* Make image color transparent. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType match; MagickPixelPacket pixel; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); GetMagickPixelPacket(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); match=((pixel.red >= low->red) && (pixel.red <= high->red) && (pixel.green >= low->green) && (pixel.green <= high->green) && (pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue : MagickFalse; if (match != invert) q->opacity=opacity; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransparentPaintImageChroma) #endif proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
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; } }
GB_subassign_13.c
//------------------------------------------------------------------------------ // GB_subassign_13: C(I,J)<!M> = scalar ; using S //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Method 13: C(I,J)<!M> = scalar ; using S // M: present // Mask_comp: true // C_replace: false // accum: NULL // A: scalar // S: constructed // C: not bitmap, but can be full since no zombies are inserted in that case // M: not bitmap #include "GB_subassign_methods.h" GrB_Info GB_subassign_13 ( GrB_Matrix C, // input: const GrB_Index *I, const int64_t ni, const int64_t nI, const int Ikind, const int64_t Icolon [3], const GrB_Index *J, const int64_t nj, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], const GrB_Matrix M, const bool Mask_struct, const void *scalar, const GrB_Type atype, GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M //-------------------------------------------------------------------------- // S = C(I,J) //-------------------------------------------------------------------------- GB_EMPTY_TASKLIST ; GB_OK (GB_subassign_symbolic (&S, C, I, ni, J, nj, true, Context)) ; //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GB_MATRIX_WAIT_IF_JUMBLED (M) ; GB_GET_C ; // C must not be bitmap const int64_t Cnvec = C->nvec ; const int64_t *GB_RESTRICT Ch = C->h ; const int64_t *GB_RESTRICT Cp = C->p ; const bool C_is_hyper = (Ch != NULL) ; GB_GET_MASK ; GB_GET_SCALAR ; GB_GET_S ; GrB_BinaryOp accum = NULL ; //-------------------------------------------------------------------------- // Method 13: C(I,J)<!M> = scalar ; using S //-------------------------------------------------------------------------- // Time: Close to optimal; must visit all IxJ, so Omega(|I|*|J|) is // required. The sparsity of !M cannot be exploited. // Methods 13, 15, 17, and 19 are very similar. //-------------------------------------------------------------------------- // Parallel: all IxJ (Methods 01, 03, 13, 15, 17, 19) //-------------------------------------------------------------------------- GB_SUBASSIGN_IXJ_SLICE ; //-------------------------------------------------------------------------- // phase 1: create zombies, update entries, and count pending tuples //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iA_start, iA_end) ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t j = kfirst ; j <= klast ; j++) { //------------------------------------------------------------------ // get jC, the corresponding vector of C //------------------------------------------------------------------ int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; //------------------------------------------------------------------ // get S(iA_start:end,j) and M(iA_start:end,j) //------------------------------------------------------------------ GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; GB_GET_VECTOR_FOR_IXJ (M, iA_start) ; //------------------------------------------------------------------ // C(I(iA_start,iA_end-1),jC)<!M,repl> = scalar //------------------------------------------------------------------ for (int64_t iA = iA_start ; iA < iA_end ; iA++) { //-------------------------------------------------------------- // Get the indices at the top of each list. //-------------------------------------------------------------- int64_t iS = (pS < pS_end) ? GBI (Si, pS, Svlen) : INT64_MAX ; int64_t iM = (pM < pM_end) ? GBI (Mi, pM, Mvlen) : INT64_MAX ; //-------------------------------------------------------------- // find the smallest index of [iS iA iM] (always iA) //-------------------------------------------------------------- int64_t i = iA ; //-------------------------------------------------------------- // get M(i,j) //-------------------------------------------------------------- bool mij ; if (i == iM) { // mij = (bool) M [pM] mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ; GB_NEXT (M) ; } else { // mij not present, implicitly false ASSERT (i < iM) ; mij = false ; } // complement the mask entry mij since Mask_comp is true mij = !mij ; //-------------------------------------------------------------- // assign the entry //-------------------------------------------------------------- if (i == iS) { ASSERT (i == iA) ; { // both S (i,j) and A (i,j) present if (mij) { // ----[C A 1] or [X A 1]--------------------------- // [C A 1]: action: ( =A ): copy A, no accum // [X A 1]: action: ( undelete ): zombie lives GB_C_S_LOOKUP ; GB_noaccum_C_A_1_scalar ; } GB_NEXT (S) ; } } else { ASSERT (i == iA) ; { // S (i,j) is not present, A (i,j) is present if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) task_pending++ ; } } } } } GB_PHASE1_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // phase 2: insert pending tuples //-------------------------------------------------------------------------- GB_PENDING_CUMSUM ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iA_start, iA_end) ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t j = kfirst ; j <= klast ; j++) { //------------------------------------------------------------------ // get jC, the corresponding vector of C //------------------------------------------------------------------ int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; //------------------------------------------------------------------ // get S(iA_start:end,j) and M(iA_start:end,j) //------------------------------------------------------------------ GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; GB_GET_VECTOR_FOR_IXJ (M, iA_start) ; //------------------------------------------------------------------ // C(I(iA_start,iA_end-1),jC)<!M,repl> = scalar //------------------------------------------------------------------ for (int64_t iA = iA_start ; iA < iA_end ; iA++) { //-------------------------------------------------------------- // Get the indices at the top of each list. //-------------------------------------------------------------- int64_t iS = (pS < pS_end) ? GBI (Si, pS, Svlen) : INT64_MAX ; int64_t iM = (pM < pM_end) ? GBI (Mi, pM, Mvlen) : INT64_MAX ; //-------------------------------------------------------------- // find the smallest index of [iS iA iM] (always iA) //-------------------------------------------------------------- int64_t i = iA ; //-------------------------------------------------------------- // get M(i,j) //-------------------------------------------------------------- bool mij ; if (i == iM) { // mij = (bool) M [pM] mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ; GB_NEXT (M) ; } else { // mij not present, implicitly false ASSERT (i < iM) ; mij = false ; } // complement the mask entry mij since Mask_comp is true mij = !mij ; //-------------------------------------------------------------- // assign the entry //-------------------------------------------------------------- if (i == iS) { ASSERT (i == iA) ; { GB_NEXT (S) ; } } else { ASSERT (i == iA) ; { // S (i,j) is not present, A (i,j) is present if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (scalar) ; } } } } } GB_PHASE2_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // finalize the matrix and return result //-------------------------------------------------------------------------- GB_SUBASSIGN_WRAPUP ; }
GB_unop__identity_fp64_uint64.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_fp64_uint64 // op(A') function: GB_unop_tran__identity_fp64_uint64 // C type: double // A type: uint64_t // cast: double cij = (double) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ double // 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) \ double z = (double) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = (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_FP64 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_fp64_uint64 ( double *Cx, // Cx and Ax may be aliased const uint64_t *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 (uint64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; double z = (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 ; uint64_t aij = Ax [p] ; double z = (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_fp64_uint64 ( 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
eavlInfoTopologyPackedMapOp.h
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information. #ifndef EAVL_INFO_TOPOLOGY_PACKED_MAP_OP_H #define EAVL_INFO_TOPOLOGY_PACKED_MAP_OP_H #include "eavlCUDA.h" #include "eavlCellSet.h" #include "eavlCellSetExplicit.h" #include "eavlCellSetAllStructured.h" #include "eavlDataSet.h" #include "eavlArray.h" #include "eavlOpDispatch.h" #include "eavlOperation.h" #include "eavlTopology.h" #include "eavlException.h" #include <time.h> #ifdef HAVE_OPENMP #include <omp.h> #endif #ifndef DOXYGEN template <class CONN> struct eavlInfoTopologyPackedMapOp_CPU { static inline eavlArray::Location location() { return eavlArray::HOST; } template <class F, class IN, class OUT, class INDEX> static void call(int nitems, CONN &conn, const IN inputs, OUT outputs, INDEX indices, F &functor) { int *sparseindices = get<0>(indices).array; #pragma omp parallel for for (int denseindex = 0; denseindex < nitems; ++denseindex) { int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)]; int shapeType = conn.GetShapeType(sparseindex); collect(denseindex, outputs) = functor(shapeType, collect(denseindex, inputs)); } } }; #if defined __CUDACC__ template <class CONN, class F, class IN, class OUT, class INDEX> __global__ void eavlInfoTopologyPackedMapOp_kernel(int nitems, CONN conn, const IN inputs, OUT outputs, INDEX indices, F functor) { int *sparseindices = get<0>(indices).array; const int numThreads = blockDim.x * gridDim.x; const int threadID = blockIdx.x * blockDim.x + threadIdx.x; for (int denseindex = threadID; denseindex < nitems; denseindex += numThreads) { int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)]; int shapeType = conn.GetShapeType(sparseindex); collect(denseindex, outputs) = functor(shapeType, collect(denseindex, inputs)); } } template <class CONN> struct eavlInfoTopologyPackedMapOp_GPU { static inline eavlArray::Location location() { return eavlArray::DEVICE; } template <class F, class IN, class OUT, class INDEX> static void call(int nitems, CONN &conn, const IN inputs, OUT outputs, INDEX indices, F &functor) { int numThreads = 256; dim3 threads(numThreads, 1, 1); dim3 blocks (32, 1, 1); eavlInfoTopologyPackedMapOp_kernel<<< blocks, threads >>>(nitems, conn, inputs, outputs, indices, functor); CUDA_CHECK_ERROR(); } }; #endif #endif // **************************************************************************** // Class: eavlInfoTopologyPackedMapOp // // Purpose: /// Map from one element in a mesh to the same element, with /// topological information passed along to the functor. /// In this packed version of the operation, the inputs on the destination /// topology and the outputs are both compacted, i.e. densely indexed from /// 0 to n-1. // // Programmer: Jeremy Meredith // Creation: August 1, 2013 // // Modifications: // **************************************************************************** template <class I, class O, class INDEX, class F> class eavlInfoTopologyPackedMapOp : public eavlOperation { protected: eavlCellSet *cells; eavlTopology topology; I inputs; O outputs; INDEX indices; F functor; public: eavlInfoTopologyPackedMapOp(eavlCellSet *c, eavlTopology t, I i, O o, INDEX ind, F f) : cells(c), topology(t), inputs(i), outputs(o), indices(ind), functor(f) { } virtual void GoCPU() { eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells); eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells); int n = outputs.first.length(); if (elExp) { eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology); eavlOpDispatch<eavlInfoTopologyPackedMapOp_CPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor); } else if (elStr) { eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology); eavlOpDispatch<eavlInfoTopologyPackedMapOp_CPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor); } } virtual void GoGPU() { #ifdef HAVE_CUDA eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells); eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells); int n = outputs.first.length(); if (elExp) { eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology); conn.shapetype.NeedOnDevice(); conn.connectivity.NeedOnDevice(); conn.mapCellToIndex.NeedOnDevice(); eavlOpDispatch<eavlInfoTopologyPackedMapOp_GPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor); conn.shapetype.NeedOnHost(); conn.connectivity.NeedOnHost(); conn.mapCellToIndex.NeedOnHost(); } else if (elStr) { eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology); eavlOpDispatch<eavlInfoTopologyPackedMapOp_GPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor); } #else THROW(eavlException,"Executing GPU code without compiling under CUDA compiler."); #endif } }; // helper function for type deduction template <class I, class O, class INDEX, class F> eavlInfoTopologyPackedMapOp<I,O,INDEX,F> *new_eavlInfoTopologyPackedMapOp(eavlCellSet *c, eavlTopology t, I i, O o, INDEX indices, F f) { return new eavlInfoTopologyPackedMapOp<I,O,INDEX,F>(c,t,i,o,indices,f); } #endif
elemwise_binary_scalar_op.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. */ /*! * \file elemwise_binary_scalar_op.h * \brief Function definition of elementwise binary scalar operators */ #ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_ #define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_ #include <mxnet/operator_util.h> #include <vector> #include <utility> #include "../mshadow_op.h" #include "../elemwise_op_common.h" #include "elemwise_unary_op.h" namespace mxnet { namespace op { inline bool BinaryScalarStorageType(const nnvm::NodeAttrs& attrs, const int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { CHECK_EQ(in_attrs->size(), 1); CHECK_EQ(out_attrs->size(), 1); const auto in_stype = in_attrs->at(0); auto &out_stype = out_attrs->at(0); bool dispatched = false; if (!dispatched && in_stype == kDefaultStorage) { // dns -> dns dispatched = storage_type_assign(&out_stype, kDefaultStorage, dispatch_mode, DispatchMode::kFCompute); } if (!dispatched && in_stype == kRowSparseStorage) { // rsp -> rsp dispatched = storage_type_assign(&out_stype, kRowSparseStorage, dispatch_mode, DispatchMode::kFComputeEx); // FComputeEx can handle dns output on cpu, too if (dev_mask == cpu::kDevMask && out_stype == kDefaultStorage) { DISPATCH_MODE_ASSIGN_CHECK(dispatch_mode, 0, DispatchMode::kFComputeEx); dispatched = true; } } if (!dispatched && in_stype == kCSRStorage) { // csr -> csr dispatched = storage_type_assign(&out_stype, kCSRStorage, dispatch_mode, DispatchMode::kFComputeEx); // FComputeEx can handle dns output on cpu, too if (dev_mask == cpu::kDevMask && out_stype == kDefaultStorage) { DISPATCH_MODE_ASSIGN_CHECK(dispatch_mode, 0, DispatchMode::kFComputeEx); dispatched = true; } } if (!dispatched) { dispatch_fallback(out_attrs, dispatch_mode); LogStorageFallback(attrs, dev_mask, in_attrs, out_attrs); } return true; } class BinaryScalarOp : public UnaryOp { /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType> static void ComputeExDenseResultRsp(mshadow::Stream<cpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { const double alpha = nnvm::get<double>(attrs.parsed); CHECK_EQ(output.shape(), input.shape()); const int64_t row_count = output.shape()[0]; const int64_t items_per_row = output.shape().Size() / row_count; const DType result_for_zero = OP::Map(DType(0), DType(alpha)); mshadow::Tensor<cpu, 1, DType> input_data = input.data().FlatTo1D<cpu, DType>(stream); mshadow::Tensor<cpu, 1, DType> output_data = output.data().FlatTo1D<cpu, DType>(stream); const int64_t sparse_row_count = input.aux_shape(rowsparse::kIdx).Size(); if (sparse_row_count != row_count) { mshadow::Tensor<cpu, 1, IType> row_indexes = input.aux_data( rowsparse::kIdx).FlatTo1D<cpu, IType>(stream); int64_t input_iter = 0; int64_t output_row = 0; IType next_input_row = 0; while (output_row < row_count) { next_input_row = input_iter < sparse_row_count ? int64_t(row_indexes[input_iter]) : row_count; // Split up into blocks of contiguous data and do those together // Do contiguous dense blocks const int64_t dense_block_count = next_input_row - output_row; if (dense_block_count > 0) { MXNET_ASSIGN_REQ_SWITCH(req, Req, { mxnet_op::Kernel<OpBase::SetToScalar<Req>, cpu>::Launch( stream, items_per_row * dense_block_count, output_data.dptr_ + items_per_row * output_row, result_for_zero); }); output_row += dense_block_count; continue; } // Do contiguous sparse blocks int64_t next_non_contiguous_sparse = input_iter; while (next_non_contiguous_sparse < sparse_row_count - 1) { if (row_indexes[next_non_contiguous_sparse + 1] != row_indexes[next_non_contiguous_sparse] + 1) { break; } ++next_non_contiguous_sparse; } const int64_t sparse_block_count = next_non_contiguous_sparse - input_iter + 1; if (sparse_block_count > 0) { MXNET_ASSIGN_REQ_SWITCH(req, Req, { mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, cpu>::Launch( stream, items_per_row * sparse_block_count, &output_data.dptr_[items_per_row * output_row], &input_data.dptr_[items_per_row * input_iter], DType(alpha)); }); output_row += sparse_block_count; input_iter += sparse_block_count; continue; } } } else { // All rows exist (eventually we don't have to do complex // things to call GPU kernels because we don't need to access row indices) MXNET_ASSIGN_REQ_SWITCH(req, Req, { mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, cpu>::Launch( stream, items_per_row * row_count, output_data.dptr_, input_data.dptr_, DType(alpha)); }); } } /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType> static void ComputeExDenseResultRsp(mshadow::Stream<gpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { LOG(FATAL) << "NOT IMPLEMENTED"; } /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType, typename CType> static void ComputeExDenseResultCsr(mshadow::Stream<cpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { CHECK_EQ(output.shape(), input.shape()); const double alpha = nnvm::get<double>(attrs.parsed); const DType dense_fill_val = OP::Map(DType(0), DType(alpha)); const TBlob column_indexes = input.aux_data(csr::kIdx); const size_t item_count = column_indexes.Size(); // Pre-fill dense with 0-input/output value FillDense<cpu, DType>(stream, output.shape().Size(), dense_fill_val, req, output.data().dptr<DType>()); mshadow::Tensor<cpu, 2, DType> out = AsRowise2D<DType>(stream, output.data()); if (item_count) { const DType *in = input.data().dptr<DType>(); const IType *column_indexes_ptr = column_indexes.dptr<IType>(); const auto row_count = static_cast<size_t>(input.shape()[0]); const TBlob row_starts = input.aux_data(csr::kIndPtr); const CType *row_starts_ptr = row_starts.dptr<CType>(); #pragma omp parallel for for (int i = 0; i < static_cast<int>(row_count); ++i) { const bool last_row = i == static_cast<int>(row_count) - 1; // Split up into blocks of contiguous data and do those together const size_t row_item_start_iter = row_starts_ptr[i]; const size_t input_items_this_row = !last_row ? static_cast<size_t>(row_starts_ptr[i + 1]) - row_item_start_iter : item_count - row_item_start_iter; if (input_items_this_row) { const IType *this_row_column_indexes = column_indexes_ptr + row_item_start_iter; const DType *row_data_start = in + row_item_start_iter; DType *output_this_row = out[i].dptr_; // More overhead to use OMP for small loops, so don't if (input_items_this_row > 1000) { #pragma omp parallel for for (CType j = 0; j < static_cast<CType>(input_items_this_row); ++j) { const IType col = this_row_column_indexes[j]; const DType val = row_data_start[j]; output_this_row[col] = OP::Map(val, DType(alpha)); } } else { for (CType j = 0; j < static_cast<CType>(input_items_this_row); ++j) { const IType col = this_row_column_indexes[j]; const DType val = row_data_start[j]; output_this_row[col] = OP::Map(val, DType(alpha)); } } } } } } /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType, typename CType> static void ComputeExDenseResultCsr(mshadow::Stream<gpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { LOG(FATAL) << "NOT IMPLEMENTED"; } template<typename xpu, typename OP, typename DType, typename IType> static void ComputeExDenseResult(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray output) { mshadow::Stream<xpu> *stream = ctx.get_stream<xpu>(); CHECK_EQ(output.storage_type(), kDefaultStorage); switch (input.storage_type()) { case kRowSparseStorage: { ComputeExDenseResultRsp<OP, DType, IType>(stream, attrs, ctx, input, req, output); break; } case kCSRStorage: { MSHADOW_IDX_TYPE_SWITCH(input.aux_data(csr::kIndPtr).type_flag_, CType, { ComputeExDenseResultCsr<OP, DType, IType, CType>(stream, attrs, ctx, input, req, output); }); break; } default: CHECK(false) << "Unsupported sparse storage type"; break; } } public: template<typename xpu, typename OP> static void Compute(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { DCHECK_EQ(inputs.size(), 1); DCHECK_EQ(outputs.size(), 1); using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.get_stream<xpu>(); const double alpha = nnvm::get<double>(attrs.parsed); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, inputs[0].Size(), outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), DType(alpha)); }); }); } template<typename xpu, typename OP> static void ComputeEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { DCHECK_EQ(inputs.size(), 1); DCHECK_EQ(outputs.size(), 1); const auto in_stype = inputs[0].storage_type(); const auto out_stype = outputs[0].storage_type(); if (req[0] == kNullOp) return; if ((in_stype == kRowSparseStorage && out_stype == kRowSparseStorage) || (in_stype == kCSRStorage && out_stype == kCSRStorage)) { // csr -> csr, or rsp -> rsp UnaryOp::MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Compute<xpu, OP>); } else if (out_stype == kDefaultStorage && typeid(xpu) == typeid(cpu) && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) { MSHADOW_TYPE_SWITCH(outputs[0].data().type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, { ComputeExDenseResult<xpu, OP, DType, IType>(attrs, ctx, inputs[0], req[0], outputs[0]); }); }); } else { LOG(FATAL) << "Not implemented: " << operator_string(attrs, ctx, inputs, req, outputs); } } template<typename xpu, typename OP> static void Backward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.get_stream<xpu>(); const double alpha = nnvm::get<double>(attrs.parsed); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Tensor<xpu, 1, DType> igrad = outputs[0].FlatTo1D<xpu, DType>(s); Tensor<xpu, 1, DType> ograd = inputs[0].FlatTo1D<xpu, DType>(s); Tensor<xpu, 1, DType> lhs = inputs[1].FlatTo1D<xpu, DType>(s); ASSIGN_DISPATCH(igrad, req[0], ograd * F<OP>(lhs, scalar<DType>(DType(alpha)))); }); } }; #define MXNET_OPERATOR_REGISTER_BINARY_SCALAR(name) \ NNVM_REGISTER_OP(name) \ .set_num_inputs(1) \ .set_num_outputs(1) \ .set_attr_parser([](NodeAttrs* attrs) { \ attrs->parsed = std::stod(attrs->dict["scalar"]); \ }) \ .set_attr<nnvm::FInferShape>("FInferShape", ElemwiseShape<1, 1>) \ .set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) \ .set_attr<nnvm::FInplaceOption>("FInplaceOption", \ [](const NodeAttrs& attrs){ \ return std::vector<std::pair<int, int> >{{0, 0}}; \ }) \ .add_argument("data", "NDArray-or-Symbol", "source input") \ .add_argument("scalar", "float", "scalar input") } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_
TRPO_Update.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/time.h> #include "omp.h" #include "TRPO.h" double TRPO_Update(TRPOparam param, double *Result, const size_t NumThreads) { //////////////////// Remarks //////////////////// // Result: Updated Policy Parameters //////////////////// Read Parameters //////////////////// // OpenMP Settings omp_set_num_threads(NumThreads); // Assign Parameters const size_t NumLayers = param.NumLayers; char * AcFunc = param.AcFunc; size_t * LayerSize = param.LayerSize; const size_t NumSamples = param.NumSamples; char * ModelFile = param.ModelFile; char * DataFile = param.DataFile; const double CG_Damping = param.CG_Damping; double ResidualTh = 1e-10; size_t MaxIter = 10; double MaxKL = 0.01; double MaxBackTracks = 10; double AcceptRatio = 0.1; // Dimension of Observation Space const size_t ObservSpaceDim = LayerSize[0]; // Dimension of Action Space const size_t ActionSpaceDim = LayerSize[NumLayers-1]; // Number of Policy Parameters size_t NumParams = NumParamsCalc(param.LayerSize, param.NumLayers); // iterator when traversing through input vector and result vector size_t pos; //////////////////// Memory Allocation - Model //////////////////// // W[i]: Weight Matrix from Layer[i] to Layer[i+1] // B[i]: Bias Vector from Layer[i] to Layer[i+1] // Item (j,k) in W[i] refers to the weight from Neuron #j in Layer[i] to Neuron #k in Layer[i+1] // Item B[k] is the bias of Neuron #k in Layer[i+1] double * W [NumLayers-1]; double * B [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { W[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); B[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // LogStd[i] is the log of std[i] in the policy double * LogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Policy Gradient //////////////////// // The Policy Gradient Vector (PG) is the gradient of Surrogate Loss w.r.t. to policy parameters // -PG is the input to the Conjugate Gradient (CG) function // There is one-to-one correspondence between PG and policy parameters (W and B of neural network, LogStd) double * PGW [NumLayers-1]; double * PGB [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { PGW[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); PGB[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // Allocate Memory for Policy Gradient corresponding to LogStd double * PGLogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Simulation Data //////////////////// // Allocate Memory for Observation and Probability Mean // Observ: list of observations - corresponds to ob_no in modular_rl // Mean: list of probablity mean values - corresponds to the 'mean' part of prob_np in modular_rl // Remarks: due to the specific setting of the experienments in the TRPO paper, // Std is the same for all samples in each simulation iteration, // so we just allocate Std memory space for one sample and use it for all samples. // The general case should be another vector of Std with size NumSamples*ActionSpaceDim double * Observ = (double *) calloc(NumSamples*ObservSpaceDim, sizeof(double)); double * Mean = (double *) calloc(NumSamples*ActionSpaceDim, sizeof(double)); double * Std = (double *) calloc(ActionSpaceDim, sizeof(double)); double * Action = (double *) calloc(NumSamples*ActionSpaceDim, sizeof(double)); double * Advantage = (double *) calloc(NumSamples, sizeof(double)); //////////////////// Memory Allocation - Ordinary Forward and Backward Propagation //////////////////// // Layer[i] : Memory of each layer's outputs, i.e. y_i // GLayer[i]: Gradient of Loss Function w.r.t. the pre-activation values in Layer[i], i.e. d(Loss)/d(x_i) double * Layer [NumLayers]; double * GLayer [NumLayers]; for (size_t i=0; i<NumLayers; ++i) { Layer[i] = (double *) calloc(LayerSize[i], sizeof(double)); GLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); } // GW[i]: Gradient of Loss Function w.r.t to Neural Network Weight W[i] // GB[i]: Gradient of Loss Function w.r.t to Neural Network Bias B[i] // There is one-to-one correspondence between: GW[i] and W[i], GB[i] and B[i], GStd[i] and Std[i] double * GW [NumLayers-1]; double * GB [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { GW[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); GB[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // GLogStd[i]: Gradient of Loss Function w.r.t LogStd[i] double * GLogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Pearlmutter Forward and Backward Propagation //////////////////// // RyLayer[i]: R{} of each layer's outputs, i.e. R{y_i} // RxLayer[i]: R{} of each layer's pre-activated outputs, i.e. R{x_i} // RGLayer[I]: R{} Gradient of KL w.r.t. the pre-activation values in Layer[i], i.e. R{d(KL)/d(x_i)} double * RyLayer [NumLayers]; double * RxLayer [NumLayers]; double * RGLayer [NumLayers]; for (size_t i=0; i<NumLayers; ++i) { RyLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); RxLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); RGLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); } // RGW[i]: R{} Gradient of KL w.r.t. to Neural Network Weight W[i], i.e. R{d(KL)/d(W[i])} // RGB[i]: R{} Gradient of KL w.r.t. to Neural Network Bias B[i], i.e. R{d(KL)/d(B[i])} // There is one-to-one correspondence between: RGW[i] and W[i], RGB[i] and B[i] double * RGW [NumLayers-1]; double * RGB [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { RGW[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); RGB[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // RGLogStd[i]: R{} Gradient of KL w.r.t LogStd[i] double * RGLogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Conjugate Gradient (CG) //////////////////// // These names correspond to the names in the TRPO Python code double * b = (double *) calloc(NumParams, sizeof(double)); double * p = (double *) calloc(NumParams, sizeof(double)); double * r = (double *) calloc(NumParams, sizeof(double)); double * x = (double *) calloc(NumParams, sizeof(double)); double * z = (double *) calloc(NumParams, sizeof(double)); //////////////////// Memory Allocation - Line Search //////////////////// // These names correspond to the names in the TRPO Python code // Note: In Line Search we also need a vector called x // Here we just use the x declared for Conjugate Gradient for simlicity // The x used in Line Search has nothing to do with the x used in CG // They just have the same type and size double * fullstep = (double *) calloc(NumParams, sizeof(double)); double * theta = (double *) calloc(NumParams, sizeof(double)); double * xnew = (double *) calloc(NumParams, sizeof(double)); //////////////////// Load Model //////////////////// // Open Model File that contains Weights, Bias and std FILE *ModelFilePointer = fopen(ModelFile, "r"); if (ModelFilePointer==NULL) { fprintf(stderr, "[ERROR] Cannot open Model File [%s]. \n", ModelFile); return -1; } // Read Weights and Bias from file for (size_t i=0; i<NumLayers-1; ++i) { // Reading Weights W[i]: from Layer[i] to Layer[i+1] size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { fscanf(ModelFilePointer, "%lf", &W[i][j*nextLayerDim+k]); } } // Reading Bias B[i]: from Layer[i] to Layer[i+1] for (size_t k=0; k<nextLayerDim; ++k) { fscanf(ModelFilePointer, "%lf", &B[i][k]); } } // Read LogStd from file for (size_t k=0; k<ActionSpaceDim; ++k) { fscanf(ModelFilePointer, "%lf", &LogStd[k]); } // Close Model File fclose(ModelFilePointer); //////////////////// Load Simulation Data //////////////////// // Open Data File that contains Mean, std and Observation FILE *DataFilePointer = fopen(DataFile, "r"); if (DataFilePointer==NULL) { fprintf(stderr, "[ERROR] Cannot open Data File [%s]. \n", DataFile); return -1; } // Read Mean, Std and Observation - Note that Std = exp(LogStd) // Remarks: Std is the same for all samples, and appears in every line in the data file // so we are writing the same Std again and again to the same place. for (size_t i=0; i<NumSamples; ++i) { // Read Mean for (size_t j=0; j<ActionSpaceDim; ++j) { fscanf(DataFilePointer, "%lf", &Mean[i*ActionSpaceDim+j]); } // Read Std for (size_t j=0; j<ActionSpaceDim; ++j) { fscanf(DataFilePointer, "%lf", &Std[j]); } // Read Observation for (size_t j=0; j<ObservSpaceDim; ++j) { fscanf(DataFilePointer, "%lf", &Observ[i*ObservSpaceDim+j]); } // Read Action for (size_t j=0; j<ActionSpaceDim; ++j) { fscanf(DataFilePointer, "%lf", &Action[i*ActionSpaceDim+j]); } // Read Advantage fscanf(DataFilePointer, "%lf", &Advantage[i]); } // Close Data File fclose(DataFilePointer); //////////////////// Main Computation Begins //////////////////// // Measure Elapsed Time struct timeval tv1, tv2; gettimeofday(&tv1, NULL); //////////////////// Computing Policy Gradient //////////////////// for (size_t iter=0; iter<NumSamples; iter++) { ///////// Ordinary Forward Propagation ///////// // Assign Input Values for (size_t i=0; i<ObservSpaceDim; ++i) Layer[0][i] = Observ[iter*ObservSpaceDim+i]; // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { // Propagate from Layer[i] to Layer[i+1] for (size_t j=0; j<LayerSize[i+1]; ++j) { // Calculating pre-activated value for item[j] in next layer Layer[i+1][j] = B[i][j]; for (size_t k=0; k<LayerSize[i]; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*LayerSize[i+1]+j]; } // Apply Activation Function switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function case 't': {Layer[i+1][j] = tanh(Layer[i+1][j]); break;} // 0.1x Activation Function case 'o': {Layer[i+1][j] = 0.1*Layer[i+1][j]; break;} // sigmoid Activation Function case 's': {Layer[i+1][j] = 1.0/(1+exp(-Layer[i+1][j])); break;} // Default: Activation Function not supported default: { printf("[ERROR] Activation Function for Layer [%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); return -1; } } } } ///////// Ordinary Backward Propagation ///////// // Gradient Initialisation // Assign the derivative of Surrogate Loss w.r.t. Mean (output values from the final layer) and LogStd for (size_t i=0; i<ActionSpaceDim; ++i) { double temp = (Action[iter*ActionSpaceDim+i] - Mean[iter*ActionSpaceDim+i]) / exp(LogStd[i]); GLayer[NumLayers-1][i] = Advantage[iter] * temp / exp(LogStd[i]); GLogStd[i] = Advantage[iter] * (temp * temp - 1); } // Backward Propagation for (size_t i=NumLayers-1; i>0; --i) { // Propagate from Layer[i] to Layer[i-1] for (size_t j=0; j<LayerSize[i]; ++j) { // Differentiate the activation function switch (AcFunc[i]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function: tanh' = 1 - tanh^2 case 't': {GLayer[i][j] = GLayer[i][j] * (1- Layer[i][j] * Layer[i][j]); break;} // 0.1x Activation Function case 'o': {GLayer[i][j] = 0.1 * GLayer[i][j]; break;} // sigmoid Activation Function: sigmoid' = sigmoid * (1 - sigmoid) case 's': {GLayer[i][j] = GLayer[i][j] * Layer[i][j] * (1- Layer[i][j]); break;} // Default: Activation Function not supported default: { fprintf(stderr, "[ERROR] Activation Function for Layer[%zu] is %c. Unsupported.\n", i, AcFunc[i]); return -1; } } // The derivative w.r.t to Bias is the same as that w.r.t. the pre-activated value GB[i-1][j] = GLayer[i][j]; } // Calculate the derivative w.r.t. to Weight for (size_t j=0; j<LayerSize[i-1]; ++j) { for (size_t k=0; k<LayerSize[i]; ++k) { // The Derivative w.r.t. to the weight from Neuron #j in Layer[i-1] to Neuron #k in Layer[i] GW[i-1][j*LayerSize[i]+k] = GLayer[i][k] * Layer[i-1][j]; } } // Calculate the derivative w.r.t. the output values from Layer[i] for (size_t j=0; j<LayerSize[i-1]; ++j) { GLayer[i-1][j] = 0; for (size_t k=0; k<LayerSize[i]; ++k) { // Accumulate the Gradient from Neuron #k in Layer[i] to Neuron #j in Layer[i-1] GLayer[i-1][j] += GLayer[i][k] * W[i-1][j*LayerSize[i]+k]; } } } // Accumulate the Policy Gradient to b pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { b[pos] += GW[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { b[pos] += GB[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { b[pos] += GLogStd[k]; pos++; } } // End of iteration over current sample // Averaging Policy Gradient over the samples - Policy Gradient is held in b // Note this corresponds to -g in the Python code: b = -g #pragma omp parallel for for (size_t i=0; i<pos; ++i) { b[i] = b[i] / (double)NumSamples; } //////////////////// Computing Search Direction //////////////////// ///////// Conjugate Gradient ///////// // This function implements Conjugate Gradient algorithm to solve linear equation Ax=b // x: The Conjugate Gradient Result, i.e. solution x to Ax=b // In TRPO context, x is the Step Direction of the line search (stepdir in the Python code) // b: Vector b in the equation Ax=b // Initialisation double rdotr = 0; for (size_t i=0; i<NumParams; ++i) { p[i] = b[i]; r[i] = b[i]; rdotr += r[i] * r[i]; } // Iterative Solver for (size_t it=0; it<=MaxIter; ++it) { // Calculate Frobenius Norm of x double FrobNorm = 0; #pragma omp parallel for reduction (+:FrobNorm) for (size_t i=0; i<NumParams; ++i) { FrobNorm += x[i] * x[i]; } FrobNorm = sqrt(FrobNorm); printf("CG Iter[%zu] Residual Norm=%.12e, Soln Norm=%.12e\n", it, rdotr, FrobNorm); // Check Termination Condition if (rdotr<ResidualTh || it==MaxIter) { for (size_t i=0; i<NumParams; ++i) z[i] = x[i]; break; } ///////// Fisher Vector Product Computation z = FVP(p) ///////// // Init PGW, PGB, PGLogStd from p // Init z to 0 pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { PGW[i][j*nextLayerDim+k] = p[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { PGB[i][k] = p[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { PGLogStd[k] = p[pos]; z[pos] = 0; pos++; } for (size_t iter=0; iter<NumSamples; iter++) { ///////// Combined Forward Propagation ///////// // Initialise the Input Layer for (size_t i=0; i<ObservSpaceDim; ++i) { Layer[0][i] = Observ[iter*ObservSpaceDim+i]; RxLayer[0][i] = 0; RyLayer[0][i] = 0; } // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { size_t CurrLayerSize = LayerSize[i]; size_t NextLayerSize = LayerSize[i+1]; size_t j, k; // Propagate from Layer[i] to Layer[i+1] #pragma omp parallel for private(j,k) shared(Layer, RxLayer, RyLayer, W, PGW, B, PGB, AcFunc) schedule(static) for (j=0; j<NextLayerSize; ++j) { // Initialise x_j and R{x_j} in next layer // Here we just use y_j's memory space to store x_j temoporarily Layer[i+1][j] = B[i][j]; RxLayer[i+1][j] = PGB[i][j]; for (k=0; k<CurrLayerSize; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += RyLayer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += Layer[i][k] * PGW[i][k*NextLayerSize+j]; } // Calculate y_j and R{y_j} in next layer. Note that R{y_j} depends on y_j switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': { RyLayer[i+1][j] = RxLayer[i+1][j]; break; } // tanh() Activation Function case 't': { Layer[i+1][j] = tanh(Layer[i+1][j]); RyLayer[i+1][j] = RxLayer[i+1][j] * (1 - Layer[i+1][j] * Layer[i+1][j]); break; } // 0.1x Activation Function case 'o': { Layer[i+1][j] = 0.1 * Layer[i+1][j]; RyLayer[i+1][j] = 0.1 * RxLayer[i+1][j]; break; } // sigmoid Activation Function case 's': { Layer[i+1][j] = 1.0 / ( 1 + exp(-Layer[i+1][j]) ); RyLayer[i+1][j] = RxLayer[i+1][j] * Layer[i+1][j] * (1 - Layer[i+1][j]); break; } // Default: Activation Function not supported default: { printf("[ERROR] AC Function for Layer[%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); } } } } ///////// Pearlmutter Backward Propagation ///////// // Gradient Initialisation // Calculating R{} Gradient of KL w.r.t. output values from the final layer, i.e. R{d(KL)/d(mean_i)} for (size_t i=0; i<ActionSpaceDim; ++i) { RGLayer[NumLayers-1][i] = RyLayer[NumLayers-1][i] / Std[i] / Std[i]; } // Backward Propagation for (size_t i=NumLayers-1; i>0; --i) { size_t CurrLayerSize = LayerSize[i]; size_t PrevLayerSize = LayerSize[i-1]; size_t j, k; // Propagate from Layer[i] to Layer[i-1] #pragma omp parallel for private(j) shared(Layer, RGLayer, RGB) schedule(static) for (j=0; j<CurrLayerSize; ++j) { // Calculating R{} Gradient of KL w.r.t. pre-activated values in Layer[i], i.e. R{d(KL)/d(x_i)} // Differentiate the activation function switch (AcFunc[i]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function: tanh' = 1 - tanh^2 case 't': {RGLayer[i][j] = (1-Layer[i][j]*Layer[i][j])*RGLayer[i][j]; break;} // 0.1x Activation Function case 'o': {RGLayer[i][j] = 0.1 * RGLayer[i][j]; break;} // sigmoid Activation Function: sigmoid' = sigmoid * (1 - sigmoid) case 's': {RGLayer[i][j] = RGLayer[i][j]*Layer[i][j]*(1-Layer[i][j]); break;} // Default: Activation Function not supported default: { fprintf(stderr, "[ERROR] AC Function for Layer [%zu] is %c. Unsupported.\n", i, AcFunc[i]); } } // The R{} derivative w.r.t to Bias is the same as that w.r.t. the pre-activated value RGB[i-1][j] = RGLayer[i][j]; } // Calculate the R{} derivative w.r.t. to Weight and the output values from Layer[i] #pragma omp parallel for private(j,k) shared(Layer, RGLayer, W, RGW) schedule(static) for (j=0; j<PrevLayerSize; ++j) { double temp = 0; for (k=0; k<CurrLayerSize; ++k) { // The R{} Derivative w.r.t. to the weight from Neuron #j in Layer[i-1] to Neuron #k in Layer[i] RGW[i-1][j*CurrLayerSize+k] = Layer[i-1][j] * RGLayer[i][k]; // Accumulate the Gradient from Neuron #k in Layer[i] to Neuron #j in Layer[i-1] temp += W[i-1][j*CurrLayerSize+k] * RGLayer[i][k]; } RGLayer[i-1][j] = temp; } } // Accumulate the Fisher-Vector Product to z pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGW[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGB[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { z[pos] += 2 * PGLogStd[k]; pos++; } } // End of iteration over current sample // Averaging Fisher Vector Product over the samples and apply CG Damping #pragma omp parallel for for (size_t i=0; i<pos; ++i) { z[i] = z[i] / (double)NumSamples + CG_Damping * p[i]; } //////////////// FVP Finish // Update x and r double pdotz = 0; #pragma omp parallel for reduction (+:pdotz) for (size_t i=0; i<NumParams; ++i) { pdotz += p[i] * z[i]; } double v = rdotr / pdotz; #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { x[i] += v * p[i]; r[i] -= v * z[i]; } // Update p double newrdotr = 0; #pragma omp parallel for reduction (+:newrdotr) for (size_t i=0; i<NumParams; ++i) { newrdotr += r[i] * r[i]; } double mu = newrdotr / rdotr; #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { p[i] = r[i] + mu * p[i]; } // Update rdotr rdotr = newrdotr; } // Calculate another Fisher Vector Product - code reuse opportunity ///////// Fisher Vector Product Computation z = FVP(x) ///////// // Init PGW, PGB, PGLogStd from x // Init z to 0 pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { PGW[i][j*nextLayerDim+k] = x[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { PGB[i][k] = x[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { PGLogStd[k] = x[pos]; z[pos] = 0; pos++; } for (size_t iter=0; iter<NumSamples; iter++) { ///////// Combined Forward Propagation ///////// // Initialise the Input Layer for (size_t i=0; i<ObservSpaceDim; ++i) { Layer[0][i] = Observ[iter*ObservSpaceDim+i]; RxLayer[0][i] = 0; RyLayer[0][i] = 0; } // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { size_t CurrLayerSize = LayerSize[i]; size_t NextLayerSize = LayerSize[i+1]; size_t j, k; // Propagate from Layer[i] to Layer[i+1] #pragma omp parallel for private(j,k) shared(Layer, RxLayer, RyLayer, W, PGW, B, PGB, AcFunc) schedule(static) for (j=0; j<NextLayerSize; ++j) { // Initialise x_j and R{x_j} in next layer // Here we just use y_j's memory space to store x_j temoporarily Layer[i+1][j] = B[i][j]; RxLayer[i+1][j] = PGB[i][j]; for (k=0; k<CurrLayerSize; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += RyLayer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += Layer[i][k] * PGW[i][k*NextLayerSize+j]; } // Calculate y_j and R{y_j} in next layer. Note that R{y_j} depends on y_j switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': { RyLayer[i+1][j] = RxLayer[i+1][j]; break; } // tanh() Activation Function case 't': { Layer[i+1][j] = tanh(Layer[i+1][j]); RyLayer[i+1][j] = RxLayer[i+1][j] * (1 - Layer[i+1][j] * Layer[i+1][j]); break; } // 0.1x Activation Function case 'o': { Layer[i+1][j] = 0.1 * Layer[i+1][j]; RyLayer[i+1][j] = 0.1 * RxLayer[i+1][j]; break; } // sigmoid Activation Function case 's': { Layer[i+1][j] = 1.0 / ( 1 + exp(-Layer[i+1][j]) ); RyLayer[i+1][j] = RxLayer[i+1][j] * Layer[i+1][j] * (1 - Layer[i+1][j]); break; } // Default: Activation Function not supported default: { printf("[ERROR] AC Function for Layer[%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); } } } } ///////// Pearlmutter Backward Propagation ///////// // Gradient Initialisation // Calculating R{} Gradient of KL w.r.t. output values from the final layer, i.e. R{d(KL)/d(mean_i)} for (size_t i=0; i<ActionSpaceDim; ++i) { RGLayer[NumLayers-1][i] = RyLayer[NumLayers-1][i] / Std[i] / Std[i]; } // Backward Propagation for (size_t i=NumLayers-1; i>0; --i) { size_t CurrLayerSize = LayerSize[i]; size_t PrevLayerSize = LayerSize[i-1]; size_t j, k; // Propagate from Layer[i] to Layer[i-1] #pragma omp parallel for private(j) shared(Layer, RGLayer, RGB) schedule(static) for (j=0; j<CurrLayerSize; ++j) { // Calculating R{} Gradient of KL w.r.t. pre-activated values in Layer[i], i.e. R{d(KL)/d(x_i)} // Differentiate the activation function switch (AcFunc[i]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function: tanh' = 1 - tanh^2 case 't': {RGLayer[i][j] = (1-Layer[i][j]*Layer[i][j])*RGLayer[i][j]; break;} // 0.1x Activation Function case 'o': {RGLayer[i][j] = 0.1 * RGLayer[i][j]; break;} // sigmoid Activation Function: sigmoid' = sigmoid * (1 - sigmoid) case 's': {RGLayer[i][j] = RGLayer[i][j]*Layer[i][j]*(1-Layer[i][j]); break;} // Default: Activation Function not supported default: { fprintf(stderr, "[ERROR] AC Function for Layer [%zu] is %c. Unsupported.\n", i, AcFunc[i]); } } // The R{} derivative w.r.t to Bias is the same as that w.r.t. the pre-activated value RGB[i-1][j] = RGLayer[i][j]; } // Calculate the R{} derivative w.r.t. to Weight and the output values from Layer[i] #pragma omp parallel for private(j,k) shared(Layer, RGLayer, W, RGW) schedule(static) for (j=0; j<PrevLayerSize; ++j) { double temp = 0; for (k=0; k<CurrLayerSize; ++k) { // The R{} Derivative w.r.t. to the weight from Neuron #j in Layer[i-1] to Neuron #k in Layer[i] RGW[i-1][j*CurrLayerSize+k] = Layer[i-1][j] * RGLayer[i][k]; // Accumulate the Gradient from Neuron #k in Layer[i] to Neuron #j in Layer[i-1] temp += W[i-1][j*CurrLayerSize+k] * RGLayer[i][k]; } RGLayer[i-1][j] = temp; } } // Accumulate the Fisher-Vector Product to z pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGW[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGB[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { z[pos] += 2 * PGLogStd[k]; pos++; } } // End of iteration over current sample // Averaging Fisher Vector Product over the samples and apply CG Damping #pragma omp parallel for for (size_t i=0; i<pos; ++i) { z[i] = z[i] / (double)NumSamples + CG_Damping * x[i]; } // Now z holds the Fisher Vector Product, x holds stepdir double shs = 0; #pragma omp parallel for reduction (+:shs) for (size_t i=0; i<NumParams; ++i) { shs += z[i] * x[i]; } shs = shs * 0.5; printf("shs: %.14f\n", shs); // Lagrange Multiplier (lm in Python code) double lm = sqrt(shs / MaxKL); // Compute the 2-norm of the Policy Gradient double gnorm = 0; for (size_t i=0; i<NumParams; ++i) { gnorm += b[i] * b[i]; } gnorm = sqrt(gnorm); printf("lagrange multiplier: %.14f, gnorm: %.14f\n", lm, gnorm); // Full Step #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { fullstep[i] = x[i] / lm; } // Inner product of Negative Policy Gradient -g and Step Direction double neggdotstepdir = 0; #pragma omp parallel for reduction (+:neggdotstepdir) for (size_t i=0; i<NumParams; ++i) { neggdotstepdir += b[i] * x[i]; } //////////////////// Line Search //////////////////// // Init theta to x // If Line Search is unsuccessful, theta remains as x for (size_t i=0; i<NumParams; ++i) theta[i] = x[i]; // Expected Improve Rate Line Search = slope dy/dx at initial point double expected_improve_rate = neggdotstepdir / lm; // Temporarily Save the Model Parameters in x // The x refers to the x in linesearch function in Python code // Note: Although the name is the same, the x here has nothing to do with the x in Conjugate Gradient // Copy the Model Parameters to x pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { x[pos] = W[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { x[pos] = B[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { x[pos] = LogStd[k]; pos++; } // Surrogate Loss of the current Model parameters = -Avg(Advantage) double fval = 0; #pragma omp parallel for reduction (+:fval) for (size_t i=0; i<NumSamples; ++i) { fval += Advantage[i]; } fval = -fval / (double) NumSamples; printf("fval before %.14e\n", fval); // Backtracking Line Search for (size_t i=0; i<MaxBackTracks; ++i) { // Step Fraction double stepfrac = pow(0.5, (double)i); // x New #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { xnew[i] = x[i] + stepfrac * fullstep[i]; } ///////// Compute Surrogate Loss ///////// // Init W, B, LogStd from xnew pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { W[i][j*nextLayerDim+k] = xnew[pos]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { B[i][k] = xnew[pos]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { LogStd[k] = xnew[pos]; pos++; } // Init Surrogate Loss to 0 double surr = 0; for (size_t iter=0; iter<NumSamples; iter++) { ///////// Ordinary Forward Propagation ///////// // Assign Input Values for (size_t i=0; i<ObservSpaceDim; ++i) Layer[0][i] = Observ[iter*ObservSpaceDim+i]; // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { // Propagate from Layer[i] to Layer[i+1] for (size_t j=0; j<LayerSize[i+1]; ++j) { // Calculating pre-activated value for item[j] in next layer Layer[i+1][j] = B[i][j]; for (size_t k=0; k<LayerSize[i]; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*LayerSize[i+1]+j]; } // Apply Activation Function switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function case 't': {Layer[i+1][j] = tanh(Layer[i+1][j]); break;} // 0.1x Activation Function case 'o': {Layer[i+1][j] = 0.1*Layer[i+1][j]; break;} // sigmoid Activation Function case 's': {Layer[i+1][j] = 1.0/(1+exp(-Layer[i+1][j])); break;} // Default: Activation Function not supported default: { printf("[ERROR] Activation Function for Layer [%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); return -1; } } } } // Surrogate Loss Calculation // LoglikelihoodDifference = logp_i - oldlogp_i // Here, logp_i is derived from xnew, oldlogp_i is derived from x (Mean in the simulation data) double LoglikelihoodDifference = 0; for (size_t i=0; i<ActionSpaceDim; ++i) { double temp_x = (Action[iter*ActionSpaceDim+i] - Mean[iter*ActionSpaceDim+i]) / Std[i]; double temp_xnew = (Action[iter*ActionSpaceDim+i] - Layer[NumLayers-1][i]) / exp(LogStd[i]); LoglikelihoodDifference += temp_x*temp_x - temp_xnew*temp_xnew + log(Std[i]) - LogStd[i]; } LoglikelihoodDifference = LoglikelihoodDifference * 0.5; // Accumulate Surrogate Loss surr += exp(LoglikelihoodDifference) * Advantage[iter]; } // Average Surrogate Loss over the samples to get newfval double newfval = -surr / (double) NumSamples; // Improvement in terms of Surrogate Loss double actual_improve = fval - newfval; // Expected Improvement double expected_improve = expected_improve_rate * stepfrac; // Improvement Ratio double ratio = actual_improve / expected_improve; printf("a/e/r %.14f / %.14f / %.14f\n", actual_improve, expected_improve, ratio); // Check breaking condition - has Line Search succeeded? if ( (ratio > AcceptRatio) && (actual_improve > 0) ) { // If Line Search is successful, update parameters and quit for (size_t i=0; i<NumParams; ++i) theta[i] = xnew[i]; break; } } // End of Line Search // Copy theta to Result // Note that these are the updated Model parameters for (size_t i=0; i<NumParams; ++i) Result[i] = theta[i]; gettimeofday(&tv2, NULL); double runtimeS = ((tv2.tv_sec-tv1.tv_sec) * (double)1E6 + (tv2.tv_usec-tv1.tv_usec)) / (double)1E6; //////////////////// Clean Up //////////////////// // Model - From Model File for (size_t i=0; i<NumLayers-1; ++i) { free(W[i]); free(B[i]); } free(LogStd); // Simulation Data - From Data File free(Observ); free(Mean); free(Std); free(Action); free(Advantage); // Forward and Backward Propagation for (size_t i=0; i<NumLayers; ++i) { // Ordinary Forward and Backward Propagation free(Layer[i]); free(GLayer[i]); // Pearlmutter Forward and Backward Propagation free(RxLayer[i]); free(RyLayer[i]); free(RGLayer[i]); } // Gradient for (size_t i=0; i<NumLayers-1; ++i) { // Gradient - temporary storage free(GW[i]); free(GB[i]); // Policy Gradient free(PGW[i]); free(PGB[i]); // Pearlmutter R{} Gradient free(RGW[i]); free(RGB[i]); } // Gradient - LogStd free(GLogStd); free(PGLogStd); free(RGLogStd); // Conjugate Gradient free(b); free(p); free(r); free(x); free(z); // Line Search free(fullstep); free(xnew); free(theta); return runtimeS; }
pmv-openMP-b.c
// Compilar con -O2 y -fopenmp #include <stdlib.h> #include <stdio.h> #include <omp.h> int main(int argc, char** argv){ int i, j; double t1, t2, total; int suma_parcial=0,suma=0; //Leer argumento de entrada (no de componentes del vector) if (argc<2){ printf("Falta tamaño de matriz y vector\n"); exit(-1); } unsigned int N = atoi(argv[1]); // Máximo N =2^32-1=4294967295 (sizeof(unsigned int) = 4 B) double *v1, *v2, **M; v1 = (double*) malloc(N*sizeof(double));// malloc necesita el tamaño en bytes v2 = (double*) malloc(N*sizeof(double)); //si no hay espacio suficiente malloc devuelve NULL M = (double**) malloc(N*sizeof(double *)); if ( (v1==NULL) || (v2==NULL) || (M==NULL) ){ printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } for (i=0; i<N; i++){ M[i] = (double*) malloc(N*sizeof(double)); if ( M[i]==NULL ){ printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } } //A partir de aqui se pueden acceder las componentes de la matriz como M[i][j] #pragma omp parallel private(j) private(i) private(suma_parcial) { //Inicializar matriz y vectores #pragma omp for for(i = 0; i< N; i++) { v1[i] = 2; v2[i] = 0; for(j = 0; j < N; j++ ) { M[i][j] = 2; } } //Medida de tiempo #pragma omp single { t1 = omp_get_wtime(); } //Calcular producto de matriz por vector v2 = M · v1 for(i = 0; i< N; i++) { suma_parcial=0; #pragma omp for for(j=0; j<N;j++) { suma_parcial += M[i][j] * v1[j]; } #pragma omp atomic v2[i] += suma_parcial; } //Medida de tiempo #pragma omp single { t2 = omp_get_wtime(); } } total = t2 - t1; //Imprimir el resultado y el tiempo de ejecución printf("Tiempo(seg.):%11.9f\t / Tamaño:%u\t/ V2[0]=%8.6f V2[%d]=%8.6f\n", total,N,v2[0],N-1,v2[N-1]); free(v1); // libera el espacio reservado para v1 free(v2); // libera el espacio reservado para v2 for (i=0; i<N; i++) free(M[i]); free(M); return 0; }
se_handler.h
/** * Author: Kun Sun (sunkun@szbl.ac.cn) * Date: Mar, 2021 * This program is part of the Ktrim package **/ #include <fstream> #include <sstream> #include <algorithm> #include <thread> #include <stdlib.h> #include <memory.h> #include <omp.h> #include <zlib.h> #include "common.h" #include "util.h" using namespace std; void inline CSEREAD_resize( CSEREAD * cr, int n ) { cr->seq[ n] = 0; cr->qual[n] = 0; cr->size = n; } void find_seed( vector<unsigned int> &seed, CSEREAD *read, const ktrim_param & kp ) { seed.clear(); register char *poffset = read->seq; register char *indexloc = poffset; while( true ) { indexloc = strstr( indexloc, kp.adapter_index1 ); if( indexloc == NULL ) break; seed.push_back( indexloc - poffset ); indexloc ++; } poffset = read->seq + OFFSET_INDEX3; indexloc = poffset; while( true ) { indexloc = strstr( indexloc, kp.adapter_index3 ); if( indexloc == NULL ) break; seed.push_back( indexloc - poffset ); indexloc ++; } sort( seed.begin(), seed.end() ); } void workingThread_SE_C( unsigned int tn, unsigned int start, unsigned int end, CSEREAD *workingReads, ktrim_stat * kstat, writeBuffer * writebuffer, const ktrim_param & kp ) { // fprintf( stderr, "=== working thread %d: %d - %d\n", tn, start, end ), "\n"; writebuffer->b1stored[tn] = 0; register int i, j; register unsigned int last_seed; vector<unsigned int> seed; vector<unsigned int> :: iterator it; const char *p, *q; register CSEREAD * wkr = workingReads + start; for( unsigned int ii=start; ii!=end; ++ii, ++wkr ) { // fprintf( stderr, "working: %d, %s\n", ii, wkr->id ); // quality control p = wkr->qual; j = wkr->size; // update in v1.2: support window check i = get_quality_trim_cycle_se( p, j, kp ); if( i == 0 ) { // not long enough ++ kstat->dropped[ tn ]; continue; } if( i != j ) { // quality-trim occurs CSEREAD_resize( wkr, i); } // looking for seed target, 1 mismatch is allowed for these 2 seeds // which means seq1 and seq2 at least should take 1 perfect seed match find_seed( seed, wkr, kp ); last_seed = impossible_seed; // a position which cannot be in seed for( it=seed.begin(); it!=seed.end(); ++it ) { if( *it != last_seed ) { // fprintf( stderr, " check seed: %d\n", *it ); // as there maybe the same value in seq1_seed and seq2_seed, // use this to avoid re-calculate that pos if( check_mismatch_dynamic_SE_C( wkr, *it, kp ) ) break; last_seed = *it; } } if( it != seed.end() ) { // adapter found ++ kstat->real_adapter[tn]; if( *it >= kp.min_length ) { CSEREAD_resize( wkr, *it ); } else { // drop this read as its length is not enough ++ kstat->dropped[tn]; if( *it <= DIMER_INSERT ) ++ kstat->dimer[tn]; continue; } } else { // seed not found, now check the tail 2, if perfect match, drop these 2; Single-end reads do not check tail 1 i = wkr->size - 2; p = wkr->seq; if( p[i]==kp.adapter_r1[0] && p[i+1]==kp.adapter_r1[1] ) { ++ kstat->tail_adapter[tn]; if( i < kp.min_length ) { ++ kstat->dropped[tn]; continue; } CSEREAD_resize( wkr, i ); } } writebuffer->b1stored[tn] += sprintf( writebuffer->buffer1[tn]+writebuffer->b1stored[tn], "%s%s\n+\n%s\n", wkr->id, wkr->seq, wkr->qual); } } int process_multi_thread_SE_C( const ktrim_param &kp ) { // IO speed-up // ios::sync_with_stdio( false ); // cin.tie( NULL ); // in this version, two data containers are used and auto-swapped for working and loading data CSEREAD *readA = new CSEREAD[ READS_PER_BATCH ]; CSEREAD *readB = new CSEREAD[ READS_PER_BATCH ]; register char *readA_data = new char[ MEM_SE_READSET ]; register char *readB_data = new char[ MEM_SE_READSET ]; for( register int i=0, j=0; i!=READS_PER_BATCH; ++i ) { readA[i].id = readA_data + j; readB[i].id = readB_data + j; j += MAX_READ_ID; readA[i].seq = readA_data + j; readB[i].seq = readB_data + j; j += MAX_READ_CYCLE; readA[i].qual = readA_data + j; readB[i].qual = readB_data + j; j += MAX_READ_CYCLE; } CSEREAD *workingReads, *loadingReads, *swapReads; ktrim_stat kstat; kstat.dropped = new unsigned int [ kp.thread ]; kstat.real_adapter = new unsigned int [ kp.thread ]; kstat.tail_adapter = new unsigned int [ kp.thread ]; kstat.dimer = new unsigned int [ kp.thread ]; // buffer for storing the modified reads per thread writeBuffer writebuffer; writebuffer.buffer1 = new char * [ kp.thread ]; writebuffer.b1stored = new unsigned int [ kp.thread ]; for(unsigned int i=0; i!=kp.thread; ++i) { writebuffer.buffer1[i] = new char[ BUFFER_SIZE_PER_BATCH_READ ]; writebuffer.b1stored[i] = 0; kstat.dropped[i] = 0; kstat.real_adapter[i] = 0; kstat.tail_adapter[i] = 0; kstat.dimer[i] = 0; } // deal with multiple input files vector<string> R1s; extractFileNames( kp.FASTQU, R1s ); unsigned int totalFiles = R1s.size(); //cout << "\033[1;34mINFO: " << totalFiles << " single-end fastq files will be loaded.\033[0m\n"; FILE *fout1; string fileName = kp.outpre; fileName += ".read1.fq"; fout1 = fopen( fileName.c_str(), "wt" ); if( fout1==NULL ) { fprintf( stderr, "\033[1;31mError: write file failed!\033[0m\n" ); fclose( fout1 ); return 103; } register unsigned int line = 0; unsigned int threadCNT = kp.thread - 1; for( unsigned int fileCnt=0; fileCnt!=totalFiles; ++ fileCnt ) { bool file_is_gz = false; FILE *fq; gzFile gfp; register unsigned int i = R1s[fileCnt].size() - 3; register const char * p = R1s[fileCnt].c_str(); if( p[i]=='.' && p[i+1]=='g' && p[i+2]=='z' ) { file_is_gz = true; gfp = gzopen( p, "r" ); if( gfp == NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); return 104; } } else { fq = fopen( p, "rt" ); if( fq == NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); return 104; } } // initialization // get first batch of fastq reads unsigned int loaded; bool metEOF; if( file_is_gz ) { loaded = load_batch_data_SE_GZ( gfp, readA, READS_PER_BATCH ); metEOF = gzeof( gfp ); } else { loaded = load_batch_data_SE_C( fq, readA, READS_PER_BATCH ); metEOF = feof( fq ); } if( loaded == 0 ) break; // fprintf( stderr, "Loaded %d, metEOF=%d\n", loaded, metEOF ); loadingReads = readB; workingReads = readA; bool nextBatch = true; unsigned int threadLoaded; unsigned int NumWkThreads; while( nextBatch ) { // start parallalization omp_set_num_threads( kp.thread ); #pragma omp parallel { unsigned int tn = omp_get_thread_num(); // if EOF is met, then all threads are used for analysis // otherwise 1 thread will do data loading if( metEOF ) { NumWkThreads = kp.thread; unsigned int start = loaded * tn / kp.thread; unsigned int end = loaded * (tn+1) / kp.thread; workingThread_SE_C( tn, start, end, workingReads, &kstat, &writebuffer, kp ); nextBatch = false; } else { // use 1 thread to load file, others for trimming NumWkThreads = threadCNT; if( tn == threadCNT ) { if( file_is_gz ) { threadLoaded = load_batch_data_SE_GZ( gfp, loadingReads, READS_PER_BATCH ); metEOF = gzeof( gfp ); } else { threadLoaded = load_batch_data_SE_C( fq, loadingReads, READS_PER_BATCH ); metEOF = feof( fq ); } nextBatch = (threadLoaded!=0); // fprintf( stderr, "Loaded %d, metEOF=%d\n", threadLoaded, metEOF ); //cerr << "Loading thread: " << threadLoaded << ", " << metEOF << ", " << nextBatch << '\n'; } else { unsigned int start = loaded * tn / threadCNT; unsigned int end = loaded * (tn+1) / threadCNT; workingThread_SE_C( tn, start, end, workingReads, &kstat, &writebuffer, kp ); } } } // parallel body // swap workingReads and loadingReads for next loop swapReads = loadingReads; loadingReads = workingReads; workingReads = swapReads; // write output and update fastq statistics for( unsigned int ii=0; ii!=NumWkThreads; ++ii ) { fwrite( writebuffer.buffer1[ii], sizeof(char), writebuffer.b1stored[ii], fout1 ); } line += loaded; loaded = threadLoaded; //cerr << '\r' << line << " reads loaded"; } if( file_is_gz ) { gzclose( gfp ); } else { fclose( fq ); } } fclose( fout1 ); //cerr << "\rDone: " << line << " lines processed.\n"; // write trim.log int dropped_all=0, real_all=0, tail_all=0, dimer_all=0; for( unsigned int i=0; i!=kp.thread; ++i ) { dropped_all += kstat.dropped[i]; real_all += kstat.real_adapter[i]; tail_all += kstat.tail_adapter[i]; dimer_all += kstat.dimer[i]; } fileName = kp.outpre; fileName += ".trim.log"; ofstream fout( fileName.c_str() ); if( fout.fail() ) { fprintf( stderr, "\033[1;34mError: cannot write log file!\033[0m\n" ); return 105; } fout << "Total\t" << line << '\n' << "Dropped\t" << dropped_all << '\n' << "Aadaptor\t" << real_all << '\n' << "TailHit\t" << tail_all << '\n' << "Dimer\t" << dimer_all << '\n'; fout.close(); //free memory for(unsigned int i=0; i!=kp.thread; ++i) { delete writebuffer.buffer1[i]; } delete [] writebuffer.buffer1; delete [] kstat.dropped; delete [] kstat.real_adapter; delete [] kstat.tail_adapter; delete [] readA; delete [] readB; delete [] readA_data; delete [] readB_data; return 0; } int process_single_thread_SE_C( const ktrim_param &kp ) { // fprintf( stderr, "SINGLE END SINGLE_THREAD MODE ON\n" ); // IO speed-up // ios::sync_with_stdio( false ); // cin.tie( NULL ); CSEREAD *read = new CSEREAD[ READS_PER_BATCH_ST ]; register char *read_data = new char[ MEM_SE_READSET_ST ]; for( register int i=0, j=0; i!=READS_PER_BATCH; ++i ) { read[i].id = read_data + j; j += MAX_READ_ID; read[i].seq = read_data + j; j += MAX_READ_CYCLE; read[i].qual = read_data + j; j += MAX_READ_CYCLE; } ktrim_stat kstat; kstat.dropped = new unsigned int [ 1 ]; kstat.real_adapter = new unsigned int [ 1 ]; kstat.tail_adapter = new unsigned int [ 1 ]; kstat.dimer = new unsigned int [ 1 ]; kstat.dropped[0] = 0; kstat.real_adapter[0] = 0; kstat.tail_adapter[0] = 0; kstat.dimer[0] = 0; // buffer for storing the modified reads per thread writeBuffer writebuffer; writebuffer.buffer1 = new char * [ 1 ]; writebuffer.b1stored = new unsigned int [ 1 ]; writebuffer.buffer1[0] = new char[ BUFFER_SIZE_PER_BATCH_READ_ST ]; // deal with multiple input files vector<string> R1s; extractFileNames( kp.FASTQU, R1s ); unsigned int totalFiles = R1s.size(); //cout << "\033[1;34mINFO: " << totalFiles << " single-end fastq files will be loaded.\033[0m\n"; FILE *fout1; string fileName = kp.outpre; fileName += ".read1.fq"; fout1 = fopen( fileName.c_str(), "wt" ); if( fout1==NULL ) { fprintf( stderr, "\033[1;31mError: write file failed!\033[0m\n" ); fclose( fout1 ); return 103; } //ifstream fq1; register unsigned int line = 0; for( unsigned int fileCnt=0; fileCnt!=totalFiles; ++ fileCnt ) { //fq1.open( R1s[fileCnt].c_str() ); bool file_is_gz = false; FILE *fq; gzFile gfp; register unsigned int i = R1s[fileCnt].size() - 3; register const char * p = R1s[fileCnt].c_str(); if( p[i]=='.' && p[i+1]=='g' && p[i+2]=='z' ) { // fprintf( stderr, "GZ file!\n" ); file_is_gz = true; gfp = gzopen( p, "r" ); if( gfp == NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); return 104; } } else { fq = fopen( p, "rt" ); if( fq == NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); return 104; } } register unsigned int last_seed; vector<unsigned int> seed; vector<unsigned int> :: iterator it; while( true ) { // get fastq reads //unsigned int loaded = load_batch_data_SE( fq1, read, READS_PER_BATCH_ST ); unsigned int loaded; if( file_is_gz ) { loaded = load_batch_data_SE_GZ( gfp, read, READS_PER_BATCH_ST ); // fprintf( stderr, "Loaded=%d\n", loaded ); } else { loaded = load_batch_data_SE_C( fq, read, READS_PER_BATCH_ST ); } if( loaded == 0 ) break; // fprintf( stderr, "Work\n" ); workingThread_SE_C( 0, 0, loaded, read, &kstat, &writebuffer, kp ); // write output and update fastq statistics // fprintf( stderr, "Output\n" ); fwrite( writebuffer.buffer1[0], sizeof(char), writebuffer.b1stored[0], fout1 ); line += loaded; //cerr << '\r' << line << " reads loaded"; //if( fq1.eof() ) break; // fprintf( stderr, "Check\n" ); if( file_is_gz ) { if( gzeof( gfp ) ) break; } else { if( feof( fq ) ) break; } } //fq1.close(); if( file_is_gz ) { gzclose( gfp ); } else { fclose( fq ); } } fclose( fout1 ); //cerr << "\rDone: " << line << " lines processed.\n"; // write trim.log fileName = kp.outpre; fileName += ".trim.log"; ofstream fout( fileName.c_str() ); if( fout.fail() ) { fprintf( stderr, "\033[1;34mError: cannot write log file!\033[0m\n" ); return 105; } fout << "Total\t" << line << '\n' << "Dropped\t" << kstat.dropped[0] << '\n' << "Aadaptor\t" << kstat.real_adapter[0] << '\n' << "TailHit\t" << kstat.tail_adapter[0] << '\n' << "Dimer\t" << kstat.dimer[0] << '\n'; fout.close(); //free memory // delete buffer1; // delete buffer2; // delete fq1buffer; delete [] read; delete [] read_data; return 0; }
GB_unaryop__identity_uint64_uint16.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_uint64_uint16 // op(A') function: GB_tran__identity_uint64_uint16 // C type: uint64_t // A type: uint16_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, aij) \ uint64_t z = (uint64_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_UINT64 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint64_uint16 ( uint64_t *Cx, // Cx and Ax may be aliased uint16_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_uint64_uint16 ( 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
stream.c
/*-----------------------------------------------------------------------*/ /* Program: STREAM */ /* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */ /* Original code developed by John D. McCalpin */ /* Programmers: John D. McCalpin */ /* Joe R. Zagar */ /* */ /* This program measures memory transfer rates in MB/s for simple */ /* computational kernels coded in C. */ /*-----------------------------------------------------------------------*/ /* Copyright 1991-2013: John D. McCalpin */ /*-----------------------------------------------------------------------*/ /* License: */ /* 1. You are free to use this program and/or to redistribute */ /* this program. */ /* 2. You are free to modify this program for your own use, */ /* including commercial use, subject to the publication */ /* restrictions in item 3. */ /* 3. You are free to publish results obtained from running this */ /* program, or from works that you derive from this program, */ /* with the following limitations: */ /* 3a. In order to be referred to as "STREAM benchmark results", */ /* published results must be in conformance to the STREAM */ /* Run Rules, (briefly reviewed below) published at */ /* http://www.cs.virginia.edu/stream/ref.html */ /* and incorporated herein by reference. */ /* As the copyright holder, John McCalpin retains the */ /* right to determine conformity with the Run Rules. */ /* 3b. Results based on modified source code or on runs not in */ /* accordance with the STREAM Run Rules must be clearly */ /* labelled whenever they are published. Examples of */ /* proper labelling include: */ /* "tuned STREAM benchmark results" */ /* "based on a variant of the STREAM benchmark code" */ /* Other comparable, clear, and reasonable labelling is */ /* acceptable. */ /* 3c. Submission of results to the STREAM benchmark web site */ /* is encouraged, but not required. */ /* 4. Use of this program or creation of derived works based on this */ /* program constitutes acceptance of these licensing restrictions. */ /* 5. Absolutely no warranty is expressed or implied. */ /*-----------------------------------------------------------------------*/ # include <stdio.h> # include <unistd.h> # include <math.h> # include <float.h> # include <limits.h> # include <sys/time.h> /*----------------------------------------------------------------------- * INSTRUCTIONS: * * 1) STREAM requires different amounts of memory to run on different * systems, depending on both the system cache size(s) and the * granularity of the system timer. * You should adjust the value of 'STREAM_ARRAY_SIZE' (below) * to meet *both* of the following criteria: * (a) Each array must be at least 4 times the size of the * available cache memory. I don't worry about the difference * between 10^6 and 2^20, so in practice the minimum array size * is about 3.8 times the cache size. * Example 1: One Xeon E3 with 8 MB L3 cache * STREAM_ARRAY_SIZE should be >= 4 million, giving * an array size of 30.5 MB and a total memory requirement * of 91.5 MB. * Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP) * STREAM_ARRAY_SIZE should be >= 20 million, giving * an array size of 153 MB and a total memory requirement * of 458 MB. * (b) The size should be large enough so that the 'timing calibration' * output by the program is at least 20 clock-ticks. * Example: most versions of Windows have a 10 millisecond timer * granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds. * If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec. * This means the each array must be at least 1 GB, or 128M elements. * * Version 5.10 increases the default array size from 2 million * elements to 10 million elements in response to the increasing * size of L3 caches. The new default size is large enough for caches * up to 20 MB. * Version 5.10 changes the loop index variables from "register int" * to "ssize_t", which allows array indices >2^32 (4 billion) * on properly configured 64-bit systems. Additional compiler options * (such as "-mcmodel=medium") may be required for large memory runs. * * Array size can be set at compile time without modifying the source * code for the (many) compilers that support preprocessor definitions * on the compile line. E.g., * gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M * will override the default size of 10M with a new size of 100M elements * per array. */ #ifndef STREAM_ARRAY_SIZE # define STREAM_ARRAY_SIZE 10000000 #endif /* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result * for any iteration after the first, therefore the minimum value * for NTIMES is 2. * There are no rules on maximum allowable values for NTIMES, but * values larger than the default are unlikely to noticeably * increase the reported performance. * NTIMES can also be set on the compile line without changing the source * code using, for example, "-DNTIMES=7". */ #ifdef NTIMES #if NTIMES<=1 # define NTIMES 10 #endif #endif #ifndef NTIMES # define NTIMES 10 #endif /* Users are allowed to modify the "OFFSET" variable, which *may* change the * relative alignment of the arrays (though compilers may change the * effective offset by making the arrays non-contiguous on some systems). * Use of non-zero values for OFFSET can be especially helpful if the * STREAM_ARRAY_SIZE is set to a value close to a large power of 2. * OFFSET can also be set on the compile line without changing the source * code using, for example, "-DOFFSET=56". */ #ifndef OFFSET # define OFFSET 0 #endif /* * 3) Compile the code with optimization. Many compilers generate * unreasonably bad code before the optimizer tightens things up. * If the results are unreasonably good, on the other hand, the * optimizer might be too smart for me! * * For a simple single-core version, try compiling with: * cc -O stream.c -o stream * This is known to work on many, many systems.... * * To use multiple cores, you need to tell the compiler to obey the OpenMP * directives in the code. This varies by compiler, but a common example is * gcc -O -fopenmp stream.c -o stream_omp * The environment variable OMP_NUM_THREADS allows runtime control of the * number of threads/cores used when the resulting "stream_omp" program * is executed. * * To run with single-precision variables and arithmetic, simply add * -DSTREAM_TYPE=float * to the compile line. * Note that this changes the minimum array sizes required --- see (1) above. * * The preprocessor directive "TUNED" does not do much -- it simply causes the * code to call separate functions to execute each kernel. Trivial versions * of these functions are provided, but they are *not* tuned -- they just * provide predefined interfaces to be replaced with tuned code. * * * 4) Optional: Mail the results to mccalpin@cs.virginia.edu * Be sure to include info that will help me understand: * a) the computer hardware configuration (e.g., processor model, memory type) * b) the compiler name/version and compilation flags * c) any run-time information (such as OMP_NUM_THREADS) * d) all of the output from the test case. * * Thanks! * *-----------------------------------------------------------------------*/ # define HLINE "-------------------------------------------------------------\n" # ifndef MIN # define MIN(x,y) ((x)<(y)?(x):(y)) # endif # ifndef MAX # define MAX(x,y) ((x)>(y)?(x):(y)) # endif #ifndef STREAM_TYPE #define STREAM_TYPE double #endif static STREAM_TYPE a[STREAM_ARRAY_SIZE+OFFSET], b[STREAM_ARRAY_SIZE+OFFSET], c[STREAM_ARRAY_SIZE+OFFSET]; static double avgtime[4] = {0}, maxtime[4] = {0}, mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX}; static char *label[4] = {"Copy: ", "Scale: ", "Add: ", "Triad: "}; static double bytes[4] = { 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE }; extern double mysecond(); extern void checkSTREAMresults(); #ifdef TUNED extern void tuned_STREAM_Copy(); extern void tuned_STREAM_Scale(STREAM_TYPE scalar); extern void tuned_STREAM_Add(); extern void tuned_STREAM_Triad(STREAM_TYPE scalar); #endif #ifdef _OPENMP extern int omp_get_num_threads(); #endif int main() { int quantum, checktick(); int BytesPerWord; int k; ssize_t j; STREAM_TYPE scalar; double t, times[4][NTIMES]; /* --- SETUP --- determine precision and check timing --- */ printf(HLINE); printf("STREAM version $Revision: 5.10 $\n"); printf(HLINE); BytesPerWord = sizeof(STREAM_TYPE); printf("This system uses %d bytes per array element.\n", BytesPerWord); printf(HLINE); #ifdef N printf("***** WARNING: ******\n"); printf(" It appears that you set the preprocessor variable N when compiling this code.\n"); printf(" This version of the code uses the preprocessor variable STREAM_ARRAY_SIZE to control the array size\n"); printf(" Reverting to default value of STREAM_ARRAY_SIZE=%llu\n",(unsigned long long) STREAM_ARRAY_SIZE); printf("***** WARNING: ******\n"); #endif printf("Array size = %llu (elements), Offset = %d (elements)\n" , (unsigned long long) STREAM_ARRAY_SIZE, OFFSET); printf("Memory per array = %.1f MiB (= %.1f GiB).\n", BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0), BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0/1024.0)); printf("Total memory required = %.1f MiB (= %.1f GiB).\n", (3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.), (3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024./1024.)); printf("Each kernel will be executed %d times.\n", NTIMES); printf(" The *best* time for each kernel (excluding the first iteration)\n"); printf(" will be used to compute the reported bandwidth.\n"); #ifdef _OPENMP printf(HLINE); #pragma omp parallel { #pragma omp master { k = omp_get_num_threads(); printf ("Number of Threads requested = %i\n",k); } } #endif #ifdef _OPENMP k = 0; #pragma omp parallel #pragma omp atomic k++; printf ("Number of Threads counted = %i\n",k); #endif /* Get initial value for system clock. */ #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) { a[j] = 1.0; b[j] = 2.0; c[j] = 0.0; } printf(HLINE); if ( (quantum = checktick()) >= 1) printf("Your clock granularity/precision appears to be " "%d microseconds.\n", quantum); else { printf("Your clock granularity appears to be " "less than one microsecond.\n"); quantum = 1; } t = mysecond(); #pragma omp parallel for for (j = 0; j < STREAM_ARRAY_SIZE; j++) a[j] = 2.0E0 * a[j]; t = 1.0E6 * (mysecond() - t); printf("Each test below will take on the order" " of %d microseconds.\n", (int) t ); printf(" (= %d clock ticks)\n", (int) (t/quantum) ); printf("Increase the size of the arrays if this shows that\n"); printf("you are not getting at least 20 clock ticks per test.\n"); printf(HLINE); printf("WARNING -- The above is only a rough guideline.\n"); printf("For best results, please be sure you know the\n"); printf("precision of your system timer.\n"); printf(HLINE); /* --- MAIN LOOP --- repeat test cases NTIMES times --- */ scalar = 3.0; for (k=0; k<NTIMES; k++) { times[0][k] = mysecond(); #ifdef TUNED tuned_STREAM_Copy(); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; #endif times[0][k] = mysecond() - times[0][k]; times[1][k] = mysecond(); #ifdef TUNED tuned_STREAM_Scale(scalar); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar*c[j]; #endif times[1][k] = mysecond() - times[1][k]; times[2][k] = mysecond(); #ifdef TUNED tuned_STREAM_Add(); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]+b[j]; #endif times[2][k] = mysecond() - times[2][k]; times[3][k] = mysecond(); #ifdef TUNED tuned_STREAM_Triad(scalar); #else #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j]+scalar*c[j]; #endif times[3][k] = mysecond() - times[3][k]; } /* --- SUMMARY --- */ for (k=1; k<NTIMES; k++) /* note -- skip first iteration */ { for (j=0; j<4; j++) { avgtime[j] = avgtime[j] + times[j][k]; mintime[j] = MIN(mintime[j], times[j][k]); maxtime[j] = MAX(maxtime[j], times[j][k]); } } printf("Function Best Rate MB/s Avg time Min time Max time\n"); for (j=0; j<4; j++) { avgtime[j] = avgtime[j]/(double)(NTIMES-1); printf("%s%12.1f %11.6f %11.6f %11.6f\n", label[j], 1.0E-06 * bytes[j]/mintime[j], avgtime[j], mintime[j], maxtime[j]); } printf(HLINE); /* --- Check Results --- */ checkSTREAMresults(); printf(HLINE); return 0; } # define M 20 int checktick() { int i, minDelta, Delta; double t1, t2, timesfound[M]; /* Collect a sequence of M unique time values from the system. */ for (i = 0; i < M; i++) { t1 = mysecond(); while( ((t2=mysecond()) - t1) < 1.0E-6 ) ; timesfound[i] = t1 = t2; } /* * Determine the minimum difference between these M values. * This result will be our estimate (in microseconds) for the * clock granularity. */ minDelta = 1000000; for (i = 1; i < M; i++) { Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1])); minDelta = MIN(minDelta, MAX(Delta,0)); } return(minDelta); } /* A gettimeofday routine to give access to the wall clock timer on most UNIX-like systems. */ #include <sys/time.h> double mysecond() { struct timeval tp; struct timezone tzp; int i; i = gettimeofday(&tp,&tzp); return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 ); } #ifndef abs #define abs(a) ((a) >= 0 ? (a) : -(a)) #endif void checkSTREAMresults () { STREAM_TYPE aj,bj,cj,scalar; STREAM_TYPE aSumErr,bSumErr,cSumErr; STREAM_TYPE aAvgErr,bAvgErr,cAvgErr; double epsilon; ssize_t j; int k,ierr,err; /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = 3.0; for (k=0; k<NTIMES; k++) { cj = aj; bj = scalar*cj; cj = aj+bj; aj = bj+scalar*cj; } /* accumulate deltas between observed and expected results */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { aSumErr += abs(a[j] - aj); bSumErr += abs(b[j] - bj); cSumErr += abs(c[j] - cj); // if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN } aAvgErr = aSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; bAvgErr = bSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; cAvgErr = cSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE; if (sizeof(STREAM_TYPE) == 4) { epsilon = 1.e-6; } else if (sizeof(STREAM_TYPE) == 8) { epsilon = 1.e-13; } else { printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n",sizeof(STREAM_TYPE)); epsilon = 1.e-6; } err = 0; if (abs(aAvgErr/aj) > epsilon) { err++; printf ("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,abs(aAvgErr)/aj); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(a[j]/aj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,aj,a[j],abs((aj-a[j])/aAvgErr)); } #endif } } printf(" For array a[], %d errors were found.\n",ierr); } if (abs(bAvgErr/bj) > epsilon) { err++; printf ("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,abs(bAvgErr)/bj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(b[j]/bj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,bj,b[j],abs((bj-b[j])/bAvgErr)); } #endif } } printf(" For array b[], %d errors were found.\n",ierr); } if (abs(cAvgErr/cj) > epsilon) { err++; printf ("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,abs(cAvgErr)/cj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<STREAM_ARRAY_SIZE; j++) { if (abs(c[j]/cj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,cj,c[j],abs((cj-c[j])/cAvgErr)); } #endif } } printf(" For array c[], %d errors were found.\n",ierr); } if (err == 0) { printf ("Solution Validates: avg error less than %e on all three arrays\n",epsilon); } #ifdef VERBOSE printf ("Results Validation Verbose Results: \n"); printf (" Expected a(1), b(1), c(1): %f %f %f \n",aj,bj,cj); printf (" Observed a(1), b(1), c(1): %f %f %f \n",a[1],b[1],c[1]); printf (" Rel Errors on a, b, c: %e %e %e \n",abs(aAvgErr/aj),abs(bAvgErr/bj),abs(cAvgErr/cj)); #endif } #ifdef TUNED /* stubs for "tuned" versions of the kernels */ void tuned_STREAM_Copy() { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; } void tuned_STREAM_Scale(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar*c[j]; } void tuned_STREAM_Add() { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]+b[j]; } void tuned_STREAM_Triad(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j=0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j]+scalar*c[j]; } /* end of stubs for the "tuned" versions of the kernels */ #endif
gmapper.c
#define _MODULE_GMAPPER #ifndef CXXFLAGS #define CXXFLAGS "?" #endif #include <assert.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <zlib.h> #include <omp.h> // OMP multithreading #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <getopt.h> #include "../gmapper/gmapper.h" #include "../gmapper/seeds.h" #include "../gmapper/genome.h" #include "../gmapper/mapping.h" #include "../common/hash.h" #include "../common/fasta.h" #include "../common/util.h" #include "../common/version.h" #include "../common/sw-full-common.h" #include "../common/sw-full-cs.h" #include "../common/sw-full-ls.h" #include "../common/sw-vector.h" #include "../common/output.h" #include "../common/input.h" #include "../common/read_hit_heap.h" #include "../common/sw-post.h" /* heaps */ /* typedef struct ptr_and_sz { void * ptr; size_t sz; } ptr_and_sz; */ //DEF_HEAP(uint32_t, char *, out) DEF_HEAP(uint32_t, struct ptr_and_sz, out) /* Get hit stats */ int hit_edit_distance(struct read_hit * rh) { //find how many perfect matches, off by 1 matches and off by 2 matches // int matches; /* # of matches */ // int mismatches; /* # of substitutions */ // int insertions; /* # of insertions */ // int deletions; /* # of deletions */ int edit_distance=0; edit_distance+=rh->sfrp->mismatches; edit_distance+=rh->sfrp->insertions; edit_distance+=rh->sfrp->deletions; assert(edit_distance>=0); return edit_distance; } /* * Free memory allocated by this read. */ void read_free(struct read_entry * re) { free(re->name); free(re->seq); if (re->orig_seq!=re->seq) { free(re->orig_seq); } if (Qflag) { assert(re->qual!=NULL); free(re->qual); if (re->qual!=re->orig_qual) { free(re->orig_qual); } assert(re->plus_line!=NULL); free(re->plus_line); } } void read_free_full(struct read_entry * re, count_t * counter) { if (shrimp_mode == MODE_COLOUR_SPACE && Qflag) { if (re->crossover_score != NULL) { free(re->crossover_score); re->crossover_score = NULL; } } if (re->mapidx[0] != NULL) my_free(re->mapidx[0], n_seeds * re->max_n_kmers * sizeof(re->mapidx[0][0]), counter, "mapidx [%s]", re->name); if (re->mapidx[1] != NULL) my_free(re->mapidx[1], n_seeds * re->max_n_kmers * sizeof(re->mapidx[0][0]), counter, "mapidx [%s]", re->name); read_free_hit_list(re, counter); read_free_anchor_list(re, counter); if (re->n_ranges > 0) free(re->ranges); if (re->n_final_unpaired_hits > 0) { int i; for (i = 0; i < re->n_final_unpaired_hits; i++) free_sfrp(&re->final_unpaired_hits[i].sfrp, re, counter); my_free(re->final_unpaired_hits, re->n_final_unpaired_hits * sizeof(re->final_unpaired_hits[0]), counter, "final_unpaired_hits [%s]", re->name); re->n_final_unpaired_hits = 0; re->final_unpaired_hits = NULL; } free(re->read[0]); free(re->read[1]); read_free(re); } void readpair_free_full(pair_entry * peP, count_t * counterP) { int nip, i; if (peP->n_final_paired_hits > 0) { my_free(peP->final_paired_hits, peP->n_final_paired_hits * sizeof(peP->final_paired_hits[0]), counterP, "final_paired_hits [%s,%s]", peP->re[0]->name, peP->re[1]->name); peP->n_final_paired_hits = 0; peP->final_paired_hits = NULL; } for (nip = 0; nip < 2; nip++) { if (peP->final_paired_hit_pool_size[nip] > 0) { for (i = 0; i < peP->final_paired_hit_pool_size[nip]; i++) { free_sfrp(&peP->final_paired_hit_pool[nip][i].sfrp, peP->re[nip], counterP); if (peP->final_paired_hit_pool[nip][i].n_paired_hit_idx > 0) { my_free(peP->final_paired_hit_pool[nip][i].paired_hit_idx, peP->final_paired_hit_pool[nip][i].n_paired_hit_idx * sizeof(peP->final_paired_hit_pool[nip][i].paired_hit_idx[0]), counterP, "paired_hit_idx [%s]", peP->re[nip]->name); peP->final_paired_hit_pool[nip][i].n_paired_hit_idx = 0; peP->final_paired_hit_pool[nip][i].paired_hit_idx = NULL; } } my_free(peP->final_paired_hit_pool[nip], peP->final_paired_hit_pool_size[nip] * sizeof(peP->final_paired_hit_pool[nip][0]), counterP, "final_paired_hit_pool[%d] [%s,%s]", nip, peP->re[0]->name, peP->re[1]->name); peP->final_paired_hit_pool_size[nip] = 0; peP->final_paired_hit_pool[nip] = NULL; } } read_free_full(peP->re[0], counterP); read_free_full(peP->re[1], counterP); } /* * Reverse read. * * This is useful for dealing with the various possibilities for matepair orientation in a unified way. */ static void read_reverse(struct read_entry * re) { uint32_t * tmp1 = re->read[0]; re->read[0] = re->read[1]; re->read[1] = tmp1; int tmp2 = re->initbp[0]; re->initbp[0] = re->initbp[1]; re->initbp[1] = tmp2; re->input_strand = 1 - re->input_strand; } /* static uint get_contig_number_from_name(char const * c) { int cn; // hack: accept '>' for cn=0 if (*c == '>') return 0; for (cn = 0; cn < num_contigs; cn++) { if (!strcmp(c, contig_names[cn])) break; } return cn; } */ /* * Compute range limitations for this read. */ /* static void read_compute_ranges(struct read_entry * re) { char * r, * r_save, * c, * c_save; uint g_start, g_end; int cn, st; assert(re->range_string != NULL); for (r = strtok_r(re->range_string, " ", &r_save); r != NULL; r = strtok_r(NULL, " ", &r_save)) { c = strtok_r(r, ",", &c_save); // contig name if (c == NULL) continue; cn = get_contig_number_from_name(c); if (cn >= num_contigs) continue; c = strtok_r(NULL, ",", &c_save); // strand if (c == NULL) continue; if (*c == '+') st = 0; else if (*c == '-') st = 1; else continue; c = strtok_r(NULL, ",", &c_save); // g_start if (c == NULL) continue; g_start = (uint)atoll(c); if (g_start == 0) continue; g_start--; c = strtok_r(NULL, ",", &c_save); // g_end if (c == NULL) continue; g_end = (uint)atoll(c); if (g_end == 0) continue; g_end--; re->n_ranges++; re->ranges = (struct range_restriction *)xrealloc(re->ranges, re->n_ranges * sizeof(re->ranges[0])); re->ranges[re->n_ranges - 1].cn = cn; re->ranges[re->n_ranges - 1].st = st; re->ranges[re->n_ranges - 1].g_start = g_start; re->ranges[re->n_ranges - 1].g_end = g_end; } } */ /* Trim a read */ static void trim_read(struct read_entry * re) { re->orig_seq=strdup(re->seq); if (Qflag) { re->orig_qual=strdup(re->qual); } //handle colour space too! int length=strlen(re->seq); int i; for (i=0; i<length-trim_end-trim_front; i++) { re->seq[i]=re->seq[i+trim_front]; if (Qflag) { re->qual[i]=re->qual[i+trim_front]; } } re->seq[i] = '\0'; if (Qflag) { re->qual[i] = '\0'; } return; } /* * Launch the threads that will scan the reads */ static bool launch_scan_threads(fasta_t fasta, fasta_t left_fasta, fasta_t right_fasta) { llint last_nreads, last_time_usecs; bool read_more = true, more_in_left_file = true, more_in_right_file=true; /* initiate the thread buffers */ //thread_output_buffer_sizes = (size_t *)xcalloc_m(sizeof(size_t) * num_threads, "thread_output_buffer_sizes"); thread_output_buffer_sizes = (size_t *) my_calloc(num_threads * sizeof(size_t), &mem_thread_buffer, "thread_output_buffer_sizes"); //thread_output_buffer_filled = (char * *)xcalloc_m(sizeof(char *) * num_threads, "thread_output_buffer_filled"); thread_output_buffer_filled = (char * *) my_calloc(num_threads * sizeof(char *), &mem_thread_buffer, "thread_output_buffer_filled"); //thread_output_buffer = (char * *)xcalloc_m(sizeof(char *) * num_threads, "thread_output_buffer"); thread_output_buffer = (char * *) my_calloc(num_threads * sizeof(char *), &mem_thread_buffer, "thread_output_buffer"); //thread_output_buffer_chunk = (unsigned int *)xcalloc_m(sizeof(unsigned int) * num_threads, "thread_output_buffer_chunk"); thread_output_buffer_chunk = (unsigned int *) my_calloc(num_threads * sizeof(unsigned int), &mem_thread_buffer, "thread_output_buffer_chunk"); unsigned int current_thread_chunk = 1; unsigned int next_chunk_to_print = 1; struct heap_out h; heap_out_init(&h, thread_output_heap_capacity ); if (progress > 0) { fprintf(stderr, "done r/hr r/core-hr\n"); last_nreads = 0; last_time_usecs = gettimeinusecs(); } #pragma omp parallel shared(read_more,more_in_left_file,more_in_right_file, fasta) num_threads(num_threads) { int thread_id = omp_get_thread_num(); struct read_entry * re_buffer; int load, i; //llint before, after; //re_buffer = (struct read_entry *)xmalloc_m(chunk_size * sizeof(re_buffer[0]), "re_buffer"); re_buffer = (read_entry *)my_malloc(chunk_size * sizeof(re_buffer[0]), &mem_thread_buffer, "re_buffer"); while (read_more) { memset(re_buffer, 0, chunk_size * sizeof(re_buffer[0])); //before = rdtsc(); TIME_COUNTER_START(tpg.wait_tc); //Read in this threads 'chunk' #pragma omp critical (fill_reads_buffer) { //after = rdtsc(); //tpg.wait_ticks += MAX(after - before, 0); TIME_COUNTER_STOP(tpg.wait_tc); thread_output_buffer_chunk[thread_id]=current_thread_chunk++; load = 0; assert(chunk_size>2); while (read_more && ((single_reads_file && load < chunk_size) || (!single_reads_file && load < chunk_size-1))) { //if (!fasta_get_next_with_range(fasta, &re_buffer[load].name, &re_buffer[load].seq, &re_buffer[load].is_rna, // &re_buffer[load].range_string, &re_buffer[load].qual)) if (single_reads_file) { if (fasta_get_next_read_with_range(fasta, &re_buffer[load])) { load++; } else { read_more = false; } } else { //read from the left file if (fasta_get_next_read_with_range(left_fasta, &re_buffer[load])) { load++; } else { more_in_left_file = false; } //read from the right file if (fasta_get_next_read_with_range(right_fasta, &re_buffer[load])) { load++; } else { more_in_right_file = false; } //make sure that one is not smaller then the other if (more_in_left_file != more_in_right_file) { fprintf(stderr,"error: when using options -1 and -2, both files specified must have the same number of entries\n"); exit(1); } //keep reading? read_more = more_in_left_file && more_in_right_file; } } nreads += load; // progress reporting if (progress > 0) { nreads_mod += load; if (nreads_mod >= progress) { llint time_usecs = gettimeinusecs(); #pragma omp critical (cs_stderr) { fprintf(stderr, "%lld %d %d.\r", nreads, (int)(((double)(nreads - last_nreads)/(double)(time_usecs - last_time_usecs)) * 3600.0 * 1.0e6), (int)(((double)(nreads - last_nreads)/(double)(time_usecs - last_time_usecs)) * 3600.0 * 1.0e6 * (1/(double)num_threads)) ); } last_nreads = nreads; last_time_usecs = time_usecs; } nreads_mod %= progress; } } // end critical section if (pair_mode != PAIR_NONE) assert(load % 2 == 0); // read even number of reads thread_output_buffer_sizes[thread_id] = thread_output_buffer_initial; //thread_output_buffer[thread_id] = (char *)xmalloc_m(sizeof(char) * thread_output_buffer_sizes[thread_id], "thread_buffer"); thread_output_buffer[thread_id] = (char *) my_malloc(thread_output_buffer_sizes[thread_id] * sizeof(char), &mem_thread_buffer, "thread_output_buffer[]"); thread_output_buffer_filled[thread_id] = thread_output_buffer[thread_id]; thread_output_buffer[thread_id][0] = '\0'; for (i = 0; i < load; i++) { // if running in paired mode and first foot is ignored, ignore this one, too if (pair_mode != PAIR_NONE && i % 2 == 1 && re_buffer[i-1].ignore) { //read_free(&re_buffer[i-1]); read_free(&re_buffer[i]); continue; } //if (!(strcspn(re_buffer[i].seq, "nNxX.") == strlen(re_buffer[i].seq))) { // if (pair_mode != PAIR_NONE && i % 2 == 1) { // read_free(re_buffer+i-1); // read_free(re_buffer+i); // } // continue; //} //Trim the reads if (trim) { if (pair_mode == PAIR_NONE) { trim_read(&re_buffer[i]); } else if (i % 2 == 1){ if (trim_first) { trim_read(&re_buffer[i-1]); } if (trim_second) { trim_read(&re_buffer[i]); } } } if (shrimp_mode == MODE_LETTER_SPACE && trim_illumina) { int trailing_Bs=0; for (int j=0; j<(int)strlen(re_buffer[i].qual); j++) { if (re_buffer[i].qual[j]!='B') { trailing_Bs=0; } else { trailing_Bs+=1; } } if (trailing_Bs>0) { re_buffer[i].seq[strlen(re_buffer[i].seq)-trailing_Bs]='\0'; re_buffer[i].qual[strlen(re_buffer[i].qual)-trailing_Bs]='\0'; } } //compute average quality value re_buffer[i].read_len = strlen(re_buffer[i].seq); if (Qflag && !ignore_qvs && min_avg_qv >= 0) { //fprintf(stderr, "read:[%s] qual:[%s]", re_buffer[i].name, re_buffer[i].qual); re_buffer[i].avg_qv = 0; for (char * c = re_buffer[i].qual; *c != 0; c++) { re_buffer[i].avg_qv += (*c - qual_delta); } //fprintf(stderr, " avg_qv:%d\n", re_buffer[i].avg_qv); } if (Qflag && !ignore_qvs && !no_qv_check) { for (char * c =re_buffer[i].qual; *c !=0; c++) { int qual_value=(*c-qual_delta); if (qual_value<-10 || qual_value>50) { fprintf(stderr,"The qv-offset might be set incorrectly! Currenty qvs are interpreted as PHRED+%d\ and a qv of %d was observed. To disable this error, etiher set the offset correctly or disable this check (see README).\n",qual_delta,qual_value); exit(1); } } } re_buffer[i].max_n_kmers = re_buffer[i].read_len - min_seed_span + 1; re_buffer[i].read[0] = fasta_sequence_to_bitfield(fasta, re_buffer[i].seq); if (shrimp_mode == MODE_COLOUR_SPACE) { re_buffer[i].read_len--; re_buffer[i].max_n_kmers -= 2; // 1st color always discarded from kmers re_buffer[i].min_kmer_pos = 1; re_buffer[i].initbp[0] = fasta_get_initial_base(shrimp_mode,re_buffer[i].seq); re_buffer[i].initbp[1] = re_buffer[i].initbp[0]; re_buffer[i].read[1] = reverse_complement_read_cs(re_buffer[i].read[0], (int8_t)re_buffer[i].initbp[0], (int8_t)re_buffer[i].initbp[1], re_buffer[i].read_len, re_buffer[i].is_rna); } else { re_buffer[i].read[1] = reverse_complement_read_ls(re_buffer[i].read[0], re_buffer[i].read_len, re_buffer[i].is_rna); } if (re_buffer[i].max_n_kmers < 0) re_buffer[i].max_n_kmers = 0; if (re_buffer[i].read_len > 0) re_buffer[i].avg_qv /= re_buffer[i].read_len; //Check if we can actually use this read if (//re_buffer[i].max_n_kmers <= 0 //|| re_buffer[i].read_len > longest_read_len || (Qflag && !ignore_qvs && re_buffer[i].avg_qv < min_avg_qv) // ignore reads with low avg qv ) { if (re_buffer[i].max_n_kmers <= 0) { fprintf(stderr, "warning: skipping read [%s]; smaller then any seed!\n", re_buffer[i].name); re_buffer[i].max_n_kmers=1; } else if (re_buffer[i].read_len > longest_read_len) { fprintf(stderr, "warning: skipping read [%s]; it has length %d, maximum allowed is %d. Use --longest-read ?\n", re_buffer[i].name, re_buffer[i].read_len, longest_read_len); } else { //fprintf(stderr, "skipping read [%s] with avg_qv:%g\n", re_buffer[i].name, (double)re_buffer[i].avg_qv); } if (pair_mode == PAIR_NONE) { #pragma omp atomic total_reads_dropped++; read_free_full(&re_buffer[i], &mem_mapping); } else { #pragma omp atomic total_pairs_dropped++; if (i%2 == 1) { read_free_full(&re_buffer[i-1], &mem_mapping); read_free_full(&re_buffer[i], &mem_mapping); } else { read_free_full(&re_buffer[i], &mem_mapping); re_buffer[i].ignore = true; } } continue; } re_buffer[i].window_len = (uint16_t)abs_or_pct(window_len,re_buffer[i].read_len); // compute position-based crossover scores based on qvs if (shrimp_mode == MODE_COLOUR_SPACE && Qflag && !ignore_qvs) { int j; re_buffer[i].crossover_score = (int *)xmalloc(re_buffer[i].read_len * sizeof(re_buffer[i].crossover_score[0])); for (j = 0; j < re_buffer[i].read_len; j++) { re_buffer[i].crossover_score[j] = (int)(score_alpha * log(pr_err_from_qv(re_buffer[i].qual[j] - qual_delta) / 3.0) / log(2.0)); if (re_buffer[i].crossover_score[j] > -1) { re_buffer[i].crossover_score[j] = -1; } else if (re_buffer[i].crossover_score[j] < 2*crossover_score) { re_buffer[i].crossover_score[j] = 2*crossover_score; } } } if (re_buffer[i].range_string != NULL) { assert(0); // not maintained //read_compute_ranges(&re_buffer[i]); free(re_buffer[i].range_string); re_buffer[i].range_string = NULL; } //free(re_buffer[i].seq); // time to do some mapping! if (pair_mode == PAIR_NONE) { handle_read(&re_buffer[i], unpaired_mapping_options[0], n_unpaired_mapping_options[0]); read_free_full(&re_buffer[i], &mem_mapping); } else if (i % 2 == 1) { pair_entry pe; memset(&pe, 0, sizeof(pe)); if (pair_reverse[pair_mode][0]) read_reverse(&re_buffer[i-1]); if (pair_reverse[pair_mode][1]) read_reverse(&re_buffer[i]); re_buffer[i-1].paired=true; re_buffer[i-1].first_in_pair=true; re_buffer[i-1].mate_pair=&re_buffer[i]; re_buffer[i].paired=true; re_buffer[i].first_in_pair=false; re_buffer[i].mate_pair=&re_buffer[i-1]; pe.re[0] = &re_buffer[i-1]; pe.re[1] = &re_buffer[i]; handle_readpair(&pe, paired_mapping_options, n_paired_mapping_options); readpair_free_full(&pe, &mem_mapping); } } // free unused memory while the buffer waits in the output heap size_t new_size = (thread_output_buffer_filled[thread_id] - thread_output_buffer[thread_id]) + 1; thread_output_buffer[thread_id] = (char *) my_realloc(thread_output_buffer[thread_id], new_size, thread_output_buffer_sizes[thread_id], &mem_thread_buffer, "thread_output_buffer[]"); //fprintf(stdout,"%s",thread_output_buffer[thread_id]); #pragma omp critical { struct heap_out_elem tmp; tmp.key = thread_output_buffer_chunk[thread_id]; //tmp.rest = thread_output_buffer[thread_id]; tmp.rest.ptr = thread_output_buffer[thread_id]; tmp.rest.sz = new_size; //thread_output_buffer_sizes[thread_id]; thread_output_buffer[thread_id] = NULL; heap_out_insert(&h, &tmp); heap_out_get_min(&h, &tmp); while (h.load > 0 && tmp.key == next_chunk_to_print) { heap_out_extract_min(&h, &tmp); //fprintf(stdout, "%s", tmp.rest); fprintf(stdout, "%s", (char *)tmp.rest.ptr); //free(tmp.rest); my_free(tmp.rest.ptr, tmp.rest.sz, &mem_thread_buffer, "thread_output_buffer[]"); next_chunk_to_print++; } } } //free(re_buffer); my_free(re_buffer, chunk_size * sizeof(re_buffer[0]), &mem_thread_buffer, "re_buffer"); } // end parallel section if (progress > 0) fprintf(stderr, "\n"); //assert(h.load == 0); struct heap_out_elem tmp; while (h.load>0) { heap_out_extract_min(&h,&tmp); fprintf(stdout,"%s",(char *)tmp.rest.ptr); //free(tmp.rest); my_free(tmp.rest.ptr, tmp.rest.sz, &mem_thread_buffer, "thread_output_buffer[]"); } heap_out_destroy(&h); //free(thread_output_buffer_sizes); my_free(thread_output_buffer_sizes, sizeof(size_t) * num_threads, &mem_thread_buffer, "thread_output_buffer_sizes"); //free(thread_output_buffer_filled); my_free(thread_output_buffer_filled, sizeof(char *) * num_threads, &mem_thread_buffer, "thread_output_buffer_filled"); //free(thread_output_buffer); my_free(thread_output_buffer, sizeof(char *) * num_threads, &mem_thread_buffer, "thread_output_buffer"); //free(thread_output_buffer_chunk); my_free(thread_output_buffer_chunk, sizeof(unsigned int) * num_threads, &mem_thread_buffer, "thread_output_buffer_chunk"); return true; } static char * thres_to_buff(char * buff, double * thres) { if (IS_ABSOLUTE(*thres)) { sprintf(buff, "%u", -(uint)(*thres)); } else { sprintf(buff, "%.02f%%", *thres); } return buff; } static char * bool_to_buff(char * buff, bool * val) { sprintf(buff, "%s", *val ? "true" : "false"); return buff; } static void print_insert_histogram() { int i; for (i = 0; i < 100; i++) { fprintf(stderr, "[%d-%d]: %.2f%%\n", min_insert_size + i * insert_histogram_bucket_size, min_insert_size + (i + 1) * insert_histogram_bucket_size - 1, total_paired_matches == 0? 0 : ((double)insert_histogram[i] / (double)total_paired_matches) * 100); } } typedef struct tp_stats_t { uint64_t f1_invocs, f1_cells, f1_ticks; double f1_secs, f1_cellspersec; uint64_t f2_invocs, f2_cells, f2_ticks; double f2_secs, f2_cellspersec; uint64_t fwbw_invocs, fwbw_cells, fwbw_ticks; double fwbw_secs, fwbw_cellspersec; double scan_secs, readparse_secs, read_handle_overhead_secs; double anchor_list_secs, hit_list_secs; double region_counts_secs, mp_region_counts_secs, duplicate_removal_secs; double pass1_secs, get_vector_hits_secs, pass2_secs; } tp_stats_t; static void print_statistics() { static char const my_tab[] = " "; //uint64_t f1_invocs[num_threads], f1_cells[num_threads], f1_ticks[num_threads]; //double f1_secs[num_threads], f1_cellspersec[num_threads]; uint64_t f1_total_invocs = 0, f1_total_cells = 0; double f1_total_secs = 0, f1_total_cellspersec = 0; uint64_t f1_calls_bypassed = 0; //uint64_t f2_invocs[num_threads], f2_cells[num_threads], f2_ticks[num_threads]; //double f2_secs[num_threads], f2_cellspersec[num_threads]; uint64_t f2_total_invocs = 0, f2_total_cells = 0; double f2_total_secs = 0, f2_total_cellspersec = 0; //uint64_t fwbw_invocs[num_threads], fwbw_cells[num_threads], fwbw_ticks[num_threads]; //double fwbw_secs[num_threads], fwbw_cellspersec[num_threads]; uint64_t fwbw_total_invocs = 0, fwbw_total_cells = 0; double fwbw_total_secs = 0, fwbw_total_cellspersec = 0; //double scan_secs[num_threads], readparse_secs[num_threads], read_handle_overhead_secs[num_threads]; //double anchor_list_secs[num_threads], hit_list_secs[num_threads]; //double region_counts_secs[num_threads], mp_region_counts_secs[num_threads], duplicate_removal_secs[num_threads]; //double pass1_secs[num_threads], get_vector_hits_secs[num_threads], pass2_secs[num_threads]; double total_scan_secs = 0, total_wait_secs = 0, total_readparse_secs = 0; tp_stats_t * tps = (tp_stats_t *)malloc(num_threads * sizeof(tps[0])); tpg_t * tpgA = (tpg_t *)malloc(num_threads * sizeof(tpgA[0])); double hz; double fasta_load_secs; fasta_stats_t fs; fs = fasta_stats(); fasta_load_secs = fs->total_secs; free(fs); hz = cpuhz(); #pragma omp parallel num_threads(num_threads) shared(hz) { int tid = omp_get_thread_num(); memcpy(&tpgA[tid], &tpg, sizeof(tpg_t)); f1_stats(&tps[tid].f1_invocs, &tps[tid].f1_cells, &tps[tid].f1_secs, NULL); //tps[tid].f1_secs = (double)tps[tid].f1_ticks / hz; tps[tid].f1_cellspersec = (double)tps[tid].f1_cells / tps[tid].f1_secs; if (isnan(tps[tid].f1_cellspersec)) tps[tid].f1_cellspersec = 0; if (shrimp_mode == MODE_COLOUR_SPACE) { sw_full_cs_stats(&tps[tid].f2_invocs, &tps[tid].f2_cells, &tps[tid].f2_secs); post_sw_stats(&tps[tid].fwbw_invocs, &tps[tid].fwbw_cells, &tps[tid].fwbw_secs); } else { sw_full_ls_stats(&tps[tid].f2_invocs, &tps[tid].f2_cells, &tps[tid].f2_secs); tps[tid].fwbw_secs = 0; } //tps[tid].f2_secs = (double)tps[tid].f2_ticks / hz; tps[tid].f2_cellspersec = (double)tps[tid].f2_cells / tps[tid].f2_secs; if (isnan(tps[tid].f2_cellspersec)) tps[tid].f2_cellspersec = 0; //tps[tid].fwbw_secs = (double)tps[tid].fwbw_ticks / hz; if (shrimp_mode == MODE_COLOUR_SPACE) { tps[tid].fwbw_cellspersec = (double)tps[tid].fwbw_cells / tps[tid].fwbw_secs; if (isnan(tps[tid].fwbw_cellspersec)) tps[tid].fwbw_cellspersec = 0; } tps[tid].readparse_secs = ((double)mapping_wallclock_usecs / 1.0e6) - ((double)tpg.read_handle_usecs / 1.0e6) - time_counter_get_secs(&tpg.wait_tc); tps[tid].scan_secs = ((double)tpg.read_handle_usecs / 1.0e6) - tps[tid].f1_secs - tps[tid].f2_secs - tps[tid].fwbw_secs; tps[tid].scan_secs = MAX(0, tps[tid].scan_secs); //tps[tid].anchor_list_secs = (double)tpg.anchor_list_ticks / hz; tps[tid].anchor_list_secs = time_counter_get_secs(&tpg.anchor_list_tc); //tps[tid].hit_list_secs = (double)tpg.hit_list_ticks / hz; tps[tid].hit_list_secs = time_counter_get_secs(&tpg.hit_list_tc); //tps[tid].duplicate_removal_secs = (double)tpg.duplicate_removal_ticks / hz; tps[tid].duplicate_removal_secs = time_counter_get_secs(&tpg.duplicate_removal_tc); //tps[tid].region_counts_secs = (double)tpg.region_counts_ticks / hz; tps[tid].region_counts_secs = time_counter_get_secs(&tpg.region_counts_tc); //tps[tid].mp_region_counts_secs = (double)tpg.mp_region_counts_ticks / hz; tps[tid].mp_region_counts_secs = time_counter_get_secs(&tpg.mp_region_counts_tc); //tps[tid].pass1_secs = (double)tpg.pass1_ticks / hz; tps[tid].pass1_secs = time_counter_get_secs(&tpg.pass1_tc); //tps[tid].get_vector_hits_secs = (double)tpg.get_vector_hits_ticks / hz; tps[tid].get_vector_hits_secs = time_counter_get_secs(&tpg.get_vector_hits_tc); //tps[tid].pass2_secs = (double)tpg.pass2_ticks / hz; tps[tid].pass2_secs = time_counter_get_secs(&tpg.pass2_tc); /* tps[tid].anchor_list_secs = (double)anchor_list_usecs[tid] / 1.0e6; tps[tid].hit_list_secs = (double)hit_list_usecs[tid] / 1.0e6; tps[tid].duplicate_removal_secs = (double)duplicate_removal_usecs[tid] / 1.0e6; tps[tid].region_counts_secs = (double)region_counts_usecs[tid] / 1.0e6; */ tps[tid].read_handle_overhead_secs = tps[tid].scan_secs - tps[tid].region_counts_secs - tps[tid].anchor_list_secs - tps[tid].hit_list_secs - tps[tid].duplicate_removal_secs; } f1_stats(NULL, NULL, NULL, &f1_calls_bypassed); fprintf(stderr, "\nStatistics:\n"); fprintf(stderr, "%sOverall:\n", my_tab); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Load Genome Time:", (double)load_genome_usecs / 1.0e6); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Read Mapping Time:", (double)mapping_wallclock_usecs / 1.0e6); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Reads per hour:", comma_integer((int)(((double)nreads/(double)mapping_wallclock_usecs) * 3600.0 * 1.0e6))); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Reads per core-hour:", comma_integer((int)(((double)nreads/(double)mapping_wallclock_usecs) * 3600.0 * 1.0e6 * (1/(double)num_threads)))); fprintf(stderr, "\n"); int i; for(i = 0; i < num_threads; i++){ total_scan_secs += tps[i].scan_secs; total_readparse_secs += tps[i].readparse_secs; total_wait_secs += time_counter_get_secs(&tpgA[i].wait_tc); f1_total_secs += tps[i].f1_secs; f1_total_invocs += tps[i].f1_invocs; f1_total_cells += tps[i].f1_cells; f2_total_secs += tps[i].f2_secs; f2_total_invocs += tps[i].f2_invocs; f2_total_cells += tps[i].f2_cells; if (shrimp_mode == MODE_COLOUR_SPACE) { fwbw_total_secs += tps[i].fwbw_secs; fwbw_total_invocs += tps[i].fwbw_invocs; fwbw_total_cells += tps[i].fwbw_cells; } else { fwbw_total_secs = 0; fwbw_total_invocs = 0; fwbw_total_cells = 0; } } f1_total_cellspersec = f1_total_secs == 0? 0 : (double)f1_total_cells / f1_total_secs; f2_total_cellspersec = f2_total_secs == 0? 0 : (double)f2_total_cells / f2_total_secs; fwbw_total_cellspersec = fwbw_total_secs == 0? 0 : (double)fwbw_total_cells / fwbw_total_secs; if (Dflag) { fprintf(stderr, "%sPer-Thread Stats:\n", my_tab); fprintf(stderr, "%s%s" "%11s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %25s %25s %25s %9s\n", my_tab, my_tab, "", "ReadParse", "Scan", "Reg Cnts", "MPRegCnt", "Anch List", "Hit List", "Pass1", "Vect Hits", "Pass2", "Dup Remv", "Vector SW", "Scalar SW", "Post SW", "Wait"); fprintf(stderr, "%s%s" "%11s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %15s %9s %15s %9s %15s %9s %9s\n", my_tab, my_tab, "", "Time", "Time", "Time", "Time", "Time", "Time", "Time", "Time", "Time", "Time", "Invocs", "Time", "Invocs", "Time", "Invocs", "Time", "Time"); fprintf(stderr, "\n"); for(i = 0; i < num_threads; i++) { fprintf(stderr, "%s%s" "Thread %-4d %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %15s %9.2f %15s %9.2f %15s %9.2f %9.2f\n", my_tab, my_tab, i, tps[i].readparse_secs, tps[i].scan_secs, tps[i].region_counts_secs, tps[i].mp_region_counts_secs, tps[i].anchor_list_secs, tps[i].hit_list_secs, tps[i].pass1_secs, tps[i].get_vector_hits_secs, tps[i].pass2_secs, tps[i].duplicate_removal_secs, comma_integer(tps[i].f1_invocs), tps[i].f1_secs, comma_integer(tps[i].f2_invocs), tps[i].f2_secs, comma_integer(tps[i].fwbw_invocs), tps[i].fwbw_secs, time_counter_get_secs(&tpgA[i].wait_tc)); } for (i = 0; i < num_threads; i++) { fprintf (stderr, "thrd:%d anchor_list_init_size:(%.2f, %.2f) anchors_discarded:(%.2f, %.2f) big_gaps:(%.2f, %.2f)\n", i, stat_get_mean(&tpgA[i].anchor_list_init_size), stat_get_sample_stddev(&tpgA[i].anchor_list_init_size), stat_get_mean(&tpgA[i].n_anchors_discarded), stat_get_sample_stddev(&tpgA[i].n_anchors_discarded), stat_get_mean(&tpgA[i].n_big_gaps_anchor_list), stat_get_sample_stddev(&tpgA[i].n_big_gaps_anchor_list)); } fprintf(stderr, "\n"); } fprintf(stderr, "%sSpaced Seed Scan:\n", my_tab); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Run-time:", total_scan_secs); fprintf(stderr, "\n"); fprintf(stderr, "%sVector Smith-Waterman:\n", my_tab); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Run-time:", f1_total_secs); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Invocations:", comma_integer(f1_total_invocs)); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Bypassed Calls:", comma_integer(f1_calls_bypassed)); fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab, "Cells Computed:", (double)f1_total_cells / 1.0e6); fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab, "Cells per Second:", f1_total_cellspersec / 1.0e6); fprintf(stderr, "\n"); fprintf(stderr, "%sScalar Smith-Waterman:\n", my_tab); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Run-time:", f2_total_secs); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Invocations:", comma_integer(f2_total_invocs)); fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab, "Cells Computed:", (double)f2_total_cells / 1.0e6); fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab, "Cells per Second:", f2_total_cellspersec / 1.0e6); fprintf(stderr, "\n"); if (shrimp_mode == MODE_COLOUR_SPACE) { fprintf(stderr, "%sForward-Backward:\n", my_tab); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Run-time:", fwbw_total_secs); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Invocations:", comma_integer(fwbw_total_invocs)); fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab, "Cells Computed:", (double)fwbw_total_cells / 1.0e6); fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab, "Cells per Second:", fwbw_total_cellspersec / 1.0e6); fprintf(stderr, "\n"); } fprintf(stderr, "%sMiscellaneous Totals:\n", my_tab); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Fasta Lib Time:", fasta_load_secs); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Read Load Time:", total_readparse_secs); fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab, "Wait Time:", total_wait_secs); fprintf(stderr, "\n"); fprintf(stderr, "%sGeneral:\n", my_tab); if (pair_mode == PAIR_NONE) { fprintf(stderr, "%s%s%-24s" "%s (%.4f%%)\n", my_tab, my_tab, "Reads Matched:", comma_integer(total_reads_matched), (nreads == 0) ? 0 : ((double)total_reads_matched / (double)nreads) * 100); fprintf(stderr, "%s%s%-24s" "%s (%.4f%%)\n", my_tab, my_tab, "... with QV >= 10:", comma_integer(total_reads_matched_conf), (nreads == 0) ? 0 : ((double)total_reads_matched_conf / (double)nreads) * 100); fprintf(stderr, "%s%s%-24s" "%s (%.4f%%)\n", my_tab, my_tab, "Reads Dropped:", comma_integer(total_reads_dropped), (nreads == 0) ? 0 : ((double)total_reads_dropped / (double)nreads) * 100); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Total Matches:", comma_integer(total_single_matches)); fprintf(stderr, "%s%s%-24s" "%.2f\n", my_tab, my_tab, "Avg Hits/Matched Read:", (total_reads_matched == 0) ? 0 : ((double)total_single_matches / (double)total_reads_matched)); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Duplicate Hits Pruned:", comma_integer(total_dup_single_matches)); } else // paired hits { fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab, "Pairs Matched:", comma_integer(total_pairs_matched), (nreads == 0) ? 0 : ((double)total_pairs_matched / (double)(nreads/2)) * 100); fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab, "... with QV >= 10:", comma_integer(total_pairs_matched_conf), (nreads == 0) ? 0 : ((double)total_pairs_matched_conf / (double)(nreads/2)) * 100); fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab, "Pairs Dropped:", comma_integer(total_pairs_dropped), (nreads == 0) ? 0 : ((double)total_pairs_dropped / (double)(nreads/2)) * 100); fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab, "Total Paired Matches:", comma_integer(total_paired_matches)); fprintf(stderr, "%s%s%-40s" "%.2f\n", my_tab, my_tab, "Avg Matches/Pair Matched:", (total_pairs_matched == 0) ? 0 : ((double)total_paired_matches / (double)total_pairs_matched)); fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab, "Duplicate Paired Matches Pruned:", comma_integer(total_dup_paired_matches)); if (half_paired) { fprintf(stderr, "\n"); fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab, "Additional Reads Matched Unpaired:", comma_integer(total_reads_matched), (nreads == 0) ? 0 : ((double)total_reads_matched / (double)nreads) * 100); fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab, "... with QV >= 10:", comma_integer(total_reads_matched_conf), (nreads == 0) ? 0 : ((double)total_reads_matched_conf / (double)nreads) * 100); fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab, "Total Unpaired Matches:", comma_integer(total_single_matches)); fprintf(stderr, "%s%s%-40s" "%.2f\n", my_tab, my_tab, "Avg Matches/Unpaired Matched Read:", (total_reads_matched == 0) ? 0 : ((double)total_single_matches / (double)total_reads_matched)); fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab, "Duplicate Unpaired Matches Pruned:", comma_integer(total_dup_single_matches)); } } fprintf(stderr, "\n"); fprintf(stderr, "%sMemory usage:\n", my_tab); fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab, "Genomemap:", comma_integer(count_get_count(&mem_genomemap))); if (Xflag) { print_insert_histogram(); } free(tps); free(tpgA); } static void usage(char * progname, bool full_usage){ char *slash; int sn; if (n_seeds == 0) load_default_seeds(0); slash = strrchr(progname, '/'); if (slash != NULL) progname = slash + 1; fprintf(stderr, "usage: %s [options/parameters] { <r> | -1 <r1> -2 <r2> } <g1> <g2>...\n", progname); fprintf(stderr, " <r> Reads filename, paired or unpaired\n"); fprintf(stderr, " <r1> Upstream reads filename\n"); fprintf(stderr, " <r2> Downstream reads filename\n"); fprintf(stderr, " <g1> <g2>... Space seperated list of genome filenames\n"); fprintf(stderr, "Parameters:\n"); fprintf(stderr, " -s/--seeds Spaced Seed(s) (default: "); for (sn = 0; sn < n_seeds; sn++) { if (sn > 0) fprintf(stderr, " "); fprintf(stderr, "%s%s\n", seed_to_string(sn), (sn == n_seeds - 1? ")" : ",")); } fprintf(stderr, " -o/--report Maximum Hits per Read (default: %d)\n", DEF_NUM_OUTPUTS); fprintf(stderr, " --max-alignments Max. align. per read (0=all) (default: %d)\n", DEF_MAX_ALIGNMENTS); fprintf(stderr, " -w/--match-window Match Window Length (default: %.02f%%)\n", DEF_WINDOW_LEN); fprintf(stderr, " -n/--cmw-mode Match Mode (default: unpaired:%d paired:%d)\n", DEF_MATCH_MODE_UNPAIRED, DEF_MATCH_MODE_PAIRED); if (full_usage) { fprintf(stderr, " -l/--cmw-overlap Match Window Overlap Length (default: %.02f%%)\n", DEF_WINDOW_OVERLAP); fprintf(stderr, " -a/--anchor-width Anchor Width Limiting Full SW (default: %d; disable: -1)\n", DEF_ANCHOR_WIDTH); fprintf(stderr, "\n"); fprintf(stderr, " -S/--save Save Genome Proj. in File (default: no)\n"); fprintf(stderr, " -L/--load Load Genome Proj. from File (default: no)\n"); fprintf(stderr, " -z/--cutoff Projection List Cut-off Len. (default: %u)\n", DEF_LIST_CUTOFF); } fprintf(stderr, "\n"); fprintf(stderr, " -m/--match SW Match Score (default: %d)\n", shrimp_mode == MODE_LETTER_SPACE? DEF_LS_MATCH_SCORE : DEF_CS_MATCH_SCORE); fprintf(stderr, " -i/--mismatch SW Mismatch Score (default: %d)\n", shrimp_mode == MODE_LETTER_SPACE? DEF_LS_MISMATCH_SCORE : DEF_CS_MISMATCH_SCORE); fprintf(stderr, " -g/--open-r SW Gap Open Score (Reference) (default: %d)\n", shrimp_mode == MODE_LETTER_SPACE? DEF_LS_A_GAP_OPEN : DEF_CS_A_GAP_OPEN); fprintf(stderr, " -q/--open-q SW Gap Open Score (Query) (default: %d)\n", shrimp_mode == MODE_LETTER_SPACE? DEF_LS_B_GAP_OPEN : DEF_CS_B_GAP_OPEN); fprintf(stderr, " -e/--ext-r SW Gap Extend Score(Reference)(default: %d)\n", shrimp_mode == MODE_LETTER_SPACE? DEF_LS_A_GAP_EXTEND : DEF_CS_A_GAP_EXTEND); fprintf(stderr, " -f/--ext-q SW Gap Extend Score (Query) (default: %d)\n", shrimp_mode == MODE_LETTER_SPACE? DEF_LS_B_GAP_EXTEND : DEF_CS_B_GAP_EXTEND); if (shrimp_mode == MODE_COLOUR_SPACE) { fprintf(stderr, " -x/--crossover SW Crossover Score (default: %d)\n", DEF_CS_XOVER_SCORE); } fprintf(stderr, " -r/--cmw-threshold Window Generation Threshold (default: %.02f%%)\n", DEF_WINDOW_GEN_THRESHOLD); if (shrimp_mode == MODE_COLOUR_SPACE) { fprintf(stderr, " -v/--vec-threshold SW Vector Hit Threshold (default: %.02f%%)\n", DEF_SW_VECT_THRESHOLD); } fprintf(stderr, " -h/--full-threshold SW Full Hit Threshold (default: %.02f%%)\n", DEF_SW_FULL_THRESHOLD); fprintf(stderr, "\n"); fprintf(stderr, " -N/--threads Number of Threads (default: %d)\n", DEF_NUM_THREADS); if (full_usage) { fprintf(stderr, " -K/--thread-chunk Thread Chunk Size (default: %d)\n", DEF_CHUNK_SIZE); } fprintf(stderr, "\n"); fprintf(stderr, " -p/--pair-mode Paired Mode (default: %s)\n", pair_mode_string[pair_mode]); fprintf(stderr, " -I/--isize Min and Max Insert Size (default: %d,%d)\n", DEF_MIN_INSERT_SIZE, DEF_MAX_INSERT_SIZE); fprintf(stderr, " --longest-read Maximum read length (default: %d)\n", DEF_LONGEST_READ_LENGTH); fprintf(stderr, " -1/--upstream Upstream read pair file\n"); fprintf(stderr, " -2/--downstream Downstream read pair file\n"); fprintf(stderr, " --un Dump unaligned reads to file\n"); fprintf(stderr, " --al Dump aligned reads to file\n"); fprintf(stderr, " --read-group Attach SAM Read Group name\n"); fprintf(stderr, " --sam-header Use file as SAM header\n"); fprintf(stderr, " --single-best-mapping Report only the best mapping(s), this is not strata (see README)\n"); fprintf(stderr, " --all-contigs Report a maximum of 1 mapping for each read.\n"); fprintf(stderr, " --no-mapping-qualities Do not compute mapping qualities\n"); fprintf(stderr, " --insert-size-dist Specifies the mean and stddev of the insert sizes\n"); fprintf(stderr, " --no-improper-mappings (see README)\n"); if (full_usage) { fprintf(stderr, " --trim-front Trim front of reads by this amount\n"); fprintf(stderr, " --trim-end Trim end of reads by this amount\n"); fprintf(stderr, " --trim-first Trim only first read in pair\n"); fprintf(stderr, " --trim-second Trim only second read in pair\n"); fprintf(stderr, " --min-avg-qv The minimum average quality value of a read\n"); fprintf(stderr, " --progress Display a progress line each <value> reads. (default %d)\n",progress); fprintf(stderr, " --save-mmap Save genome projection to shared memory\n"); fprintf(stderr, " --load-mmap Load genome projection from shared memory\n"); fprintf(stderr, " --indel-taboo-len Prevent indels from starting or ending in the tail\n"); fprintf(stderr, " --shrimp-format Output mappings in SHRiMP format (default: %s)\n",Eflag ? "disabled" : "enabled"); fprintf(stderr, " --qv-offset (see README)\n"); fprintf(stderr, " --sam-header-hd (see README)\n"); fprintf(stderr, " --sam-header-sq (see README)\n"); fprintf(stderr, " --sam-header-rg (see README)\n"); fprintf(stderr, " --sam-header-pg (see README)\n"); fprintf(stderr, " --no-autodetect-input (see README)\n"); } fprintf(stderr, "\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, " -U/--ungapped Perform Ungapped Alignment (default: %s)\n", gapless_sw ? "enabled" : "disabled"); fprintf(stderr, " --global Perform full global alignment (default: %s)\n", Gflag ? "enabled" : "disabled"); fprintf(stderr, " --local Perform local alignment (default: %s)\n", Gflag ? "disabled" : "enabled"); if (shrimp_mode == MODE_COLOUR_SPACE) { fprintf(stderr, " --bfast Try to align like bfast (default: %s)\n", Bflag ? "enabled" : "disabled"); } else { fprintf(stderr, " --trim-illumina Trim trailing B qual values (default: %s)\n", trim_illumina ? "enabled" : "disabled"); } fprintf(stderr, " -C/--negative Negative Strand Aln. Only (default: %s)\n", Cflag ? "enabled" : "disabled"); fprintf(stderr, " -F/--positive Positive Strand Aln. Only (default: %s)\n", Fflag ? "enabled" : "disabled"); fprintf(stderr, " -P/--pretty Pretty Print Alignments (default: %s)\n", Pflag ? "enabled" : "disabled"); fprintf(stderr, " -E/--sam Output SAM Format (default: %s)\n", Eflag ? "enabled" : "disabled"); fprintf(stderr, " -Q/--fastq Reads are in fastq format (default: %s)\n", Qflag ? "enabled" : "disabled"); if (full_usage) { fprintf(stderr, " -R/--print-reads Print Reads in Output (default: %s)\n", Rflag ? "enabled" : "disabled"); // fprintf(stderr, // " -T (does nothing since default) Reverse Tie-break on Negative Strand (default: enabled)\n"); fprintf(stderr, " -t/--tiebreak-off Disable Reverse Tie-break\n"); fprintf(stderr, " on Negative Strand (default: %s)\n",Tflag ? "enabled" : "disabled"); fprintf(stderr, " -X/--isize-hist Print Insert Size Histogram (default: %s)\n", Xflag ? "enabled" : "disabled"); fprintf(stderr, " -Y/--proj-hist Print Genome Proj. Histogram (default: %s)\n", Yflag ? "enabled" : "disabled"); fprintf(stderr, " -Z/--bypass-off Disable Cache Bypass for SW\n"); fprintf(stderr, " Vector Calls (default: %s)\n", hash_filter_calls ? "enabled" : "disabled"); fprintf(stderr, " -H/--spaced-kmers Hash Spaced Kmers in Genome\n"); fprintf(stderr, " Projection (default: %s)\n", Hflag ? "enabled" : "disabled"); fprintf(stderr, " -D/--thread-stats Individual Thread Statistics (default: %s)\n", Dflag ? "enabled" : "disabled"); fprintf(stderr, " -V/--trim-off Disable Automatic Genome\n"); fprintf(stderr, " Index Trimming (default: %s)\n", Vflag ? "enabled" : "disabled"); fprintf(stderr, " --pr-xover Set the Default Crossover Probability\n"); fprintf(stderr, " (default: %.1e)\n", pr_xover); } fprintf(stderr, " --sam-unaligned Unaligned reads in SAM output (default: %s)\n", sam_unaligned ? "enabled" : "disabled"); fprintf(stderr, " --half-paired Output half mapped read pairs (default: %s)\n", half_paired ? "enabled" : "disabled"); fprintf(stderr, " --strata Print only the best scoring hits\n"); fprintf(stderr, " -?/--help Full List of Parameters and Options\n"); exit(1); } static void print_pairing_options(struct pairing_options * options) { char buff[2][100]; fprintf(stderr, "[\n"); fprintf(stderr, " pairing:%s\n", pair_mode_string[options->pair_mode]); fprintf(stderr, " min_insert:%d\n", options->min_insert_size); fprintf(stderr, " max_insert:%d\n", options->max_insert_size); fprintf(stderr, " pass1_num_outputs:%d\n", options->pass1_num_outputs); fprintf(stderr, " pass1_threshold:%s\n", thres_to_buff(buff[0], &options->pass1_threshold)); fprintf(stderr, " pass2_num_outputs:%d\n", options->pass2_num_outputs); fprintf(stderr, " pass2_threshold:%s\n", thres_to_buff(buff[0], &options->pass2_threshold)); fprintf(stderr, " strata:%s\n", bool_to_buff(buff[0], &options->strata)); fprintf(stderr, " save_outputs:%s\n", bool_to_buff(buff[0], &options->save_outputs)); fprintf(stderr, " stop_count:%d\n", options->stop_count); fprintf(stderr, " stop_threshold:%s\n", thres_to_buff(buff[0], &options->stop_threshold)); fprintf(stderr, "]\n"); } static void print_read_mapping_options(struct read_mapping_options_t * options, bool is_paired) { char buff[2][100]; fprintf(stderr, "[\n"); fprintf(stderr, " regions:\n"); //fprintf(stderr, " [\n"); fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->regions.recompute)); //if (!options->regions.recompute) //fprintf(stderr, " ]\n"); //else // fprintf(stderr, ", min_seed:%d, max_seed:%d]\n", // options->regions.min_seed, options->regions.max_seed); fprintf(stderr, " anchor_list:\n"); //fprintf(stderr, " [\n"); fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->anchor_list.recompute)); if (options->anchor_list.recompute) { fprintf(stderr, " collapse:%s\n", bool_to_buff(buff[0], &options->anchor_list.collapse)); fprintf(stderr, " use_region_counts:%s\n", bool_to_buff(buff[0], &options->anchor_list.use_region_counts)); fprintf(stderr, " use_mp_region_counts:%d\n", options->anchor_list.use_mp_region_counts); } //fprintf(stderr, " ]\n"); fprintf(stderr, " hit_list:\n"); //fprintf(stderr, " [\n"); fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->hit_list.recompute)); if (options->hit_list.recompute) { fprintf(stderr, " gapless:%s\n", bool_to_buff(buff[0], &options->hit_list.gapless)); fprintf(stderr, " match_mode:%d\n", options->hit_list.match_mode); fprintf(stderr, " threshold:%s\n", thres_to_buff(buff[0], &options->hit_list.threshold)); } //fprintf(stderr, " ]\n"); fprintf(stderr, " pass1:\n"); //fprintf(stderr, " [\n"); fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->pass1.recompute)); if (options->pass1.recompute) { fprintf(stderr, " threshold:%s\n", thres_to_buff(buff[0], &options->pass1.threshold)); fprintf(stderr, " window_overlap:%s\n", thres_to_buff(buff[1], &options->pass1.window_overlap)); fprintf(stderr, " min_matches:%d\n", options->pass1.min_matches); fprintf(stderr, " gapless:%s\n", bool_to_buff(buff[0], &options->pass1.gapless)); if (is_paired) { fprintf(stderr, " only_paired:%s\n", bool_to_buff(buff[0], &options->pass1.only_paired)); } if (!is_paired) { fprintf(stderr, " num_outputs:%d\n", options->pass1.num_outputs); } } //fprintf(stderr, " ]\n"); fprintf(stderr, " pass2:\n"); //fprintf(stderr, " [\n"); fprintf(stderr, " threshold:%s\n", thres_to_buff(buff[0], &options->pass2.threshold)); if (!is_paired) { fprintf(stderr, " strata:%s\n", bool_to_buff(buff[0], &options->pass2.strata)); fprintf(stderr, " save_outputs:%s\n", bool_to_buff(buff[0], &options->pass2.save_outputs)); fprintf(stderr, " num_outputs:%d\n", options->pass2.num_outputs); } //fprintf(stderr, " ]\n"); if (!is_paired) { fprintf(stderr, " stop:\n"); //fprintf(stderr, " [\n"); fprintf(stderr, " stop_count:%d\n", options->pass2.stop_count); if (options->pass2.stop_count > 0) { fprintf(stderr, " stop_threshold:%s\n", thres_to_buff(buff[0], &options->pass2.stop_threshold)); } //fprintf(stderr, " ]\n"); } fprintf(stderr, "]\n"); } static void print_settings() { char buff[100]; static char const my_tab[] = " "; int sn, i; fprintf(stderr, "Settings:\n"); // Seeds fprintf(stderr, "%s%-40s%s (%d/%d)\n", my_tab, (n_seeds == 1) ? "Spaced Seed (weight/span)" : "Spaced Seeds (weight/span)", seed_to_string(0), seed[0].weight, seed[0].span); for (sn = 1; sn < n_seeds; sn++) { fprintf(stderr, "%s%-40s%s (%d/%d)\n", my_tab, "", seed_to_string(sn), seed[sn].weight, seed[sn].span); } // Global settings fprintf(stderr, "\n"); fprintf(stderr, "%s%-40s%d\n", my_tab, "Number of threads:", num_threads); fprintf(stderr, "%s%-40s%d\n", my_tab, "Thread chunk size:", chunk_size); fprintf(stderr, "%s%-40s%s\n", my_tab, "Window length:", thres_to_buff(buff, &window_len)); fprintf(stderr, "%s%-40s%s\n", my_tab, "Hash filter calls:", hash_filter_calls? "yes" : "no"); fprintf(stderr, "%s%-40s%d%s\n", my_tab, "Anchor width:", anchor_width, anchor_width == -1? " (disabled)" : ""); fprintf(stderr, "%s%-40s%d%s\n", my_tab, "Indel taboo Len:", indel_taboo_len, indel_taboo_len == 0? " (disabled)" : ""); if (list_cutoff < DEF_LIST_CUTOFF) { fprintf(stderr, "%s%-40s%u\n", my_tab, "Index list cutoff length:", list_cutoff); } fprintf(stderr, "%s%-40s%s\n", my_tab, "Gapless mode:", gapless_sw? "yes" : "no"); fprintf(stderr, "%s%-40s%s\n", my_tab, "Global alignment:", Gflag? "yes" : "no"); fprintf(stderr, "%s%-40s%s\n", my_tab, "Region filter:", use_regions? "yes" : "no"); if (use_regions) { fprintf(stderr, "%s%-40s%d\n", my_tab, "Region size:", (1 << region_bits)); fprintf(stderr, "%s%-40s%d\n", my_tab, "Region overlap:", region_overlap); } if (Qflag) { fprintf(stderr, "%s%-40s%s\n", my_tab, "Ignore QVs:", ignore_qvs? "yes" : "no"); } if (Qflag && !ignore_qvs) { fprintf(stderr, "%s%-40s%d%s\n", my_tab, "Minimum average qv:", min_avg_qv, min_avg_qv < 0? " (none)" : ""); //fprintf(stderr, "%s%-40sPHRED+%d\n", my_tab, "QV input encoding:", qual_delta); } fprintf(stderr, "%s%-40s%s\n", my_tab, "Compute mapping qualities:", compute_mapping_qualities? "yes" : "no"); if (compute_mapping_qualities) { fprintf(stderr, "%s%-40s%s\n", my_tab, "All contigs:", all_contigs? "yes" : "no"); fprintf(stderr, "%s%-40s%s\n", my_tab, "Single best mapping:", single_best_mapping? "yes" : "no"); } //fprintf(stderr, "%s%-40s%s\n", my_tab, "Hack:", hack? "yes" : "no"); // Scores fprintf(stderr, "\n"); fprintf(stderr, "%s%-40s%-10d\n", my_tab, "SW Match Score:", match_score); fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Mismatch Score [Prob]:", mismatch_score, pr_mismatch); fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Del Open Score [Prob]:", a_gap_open_score, pr_del_open); fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Ins Open Score [Prob]:", b_gap_open_score, pr_ins_open); fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Del Extend Score [Prob]:", a_gap_extend_score, pr_del_extend); fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Ins Extend Score [Prob]:", b_gap_extend_score, pr_ins_extend); if (shrimp_mode == MODE_COLOUR_SPACE) { fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Crossover Score [Prob]:", crossover_score, pr_xover); } fprintf(stderr, "\n"); if (n_paired_mapping_options > 0) { // paired mapping for (i = 0; i < n_paired_mapping_options; i++) { fprintf(stderr, "Paired mapping options, set [%d]\n", i); print_pairing_options(&paired_mapping_options[i].pairing); print_read_mapping_options(&paired_mapping_options[i].read[0], true); print_read_mapping_options(&paired_mapping_options[i].read[1], true); } if (n_unpaired_mapping_options[0] > 0) { fprintf(stderr, "\n"); for (i = 0; i < n_unpaired_mapping_options[0]; i++) { fprintf(stderr, "Unpaired mapping options for first read in a pair, set [%d]\n", i); print_read_mapping_options(&unpaired_mapping_options[0][i], false); } } if (n_unpaired_mapping_options[1] > 0) { fprintf(stderr, "\n"); for (i = 0; i < n_unpaired_mapping_options[1]; i++) { fprintf(stderr, "Unpaired mapping options for second read in a pair, set [%d]\n", i); print_read_mapping_options(&unpaired_mapping_options[1][i], false); } } } else { for (i = 0; i < n_unpaired_mapping_options[0]; i++) { fprintf(stderr, "Unpaired mapping options, set [%d]\n", i); print_read_mapping_options(&unpaired_mapping_options[0][i], false); } } fprintf(stderr, "\n"); return; fprintf(stderr, "%s%-40s%d\n", my_tab, "Number of Outputs per Read:", num_outputs); fprintf(stderr, "%s%-40s%d\n", my_tab, "Window Generation Mode:", match_mode); if (IS_ABSOLUTE(window_overlap)) { fprintf(stderr, "%s%-40s%u\n", my_tab, "Window Overlap Length:", (uint)-window_overlap); } else { fprintf(stderr, "%s%-40s%.02f%%\n", my_tab, "Window Overlap Length:", window_overlap); } fprintf(stderr, "\n"); if (IS_ABSOLUTE(window_gen_threshold)) { fprintf(stderr, "%s%-40s%u\n", my_tab, "Window Generation Threshold:", (uint)-window_gen_threshold); } else { fprintf(stderr, "%s%-40s%.02f%%\n", my_tab, "Window Generation Threshold:", window_gen_threshold); } if (shrimp_mode == MODE_COLOUR_SPACE) { if (IS_ABSOLUTE(sw_vect_threshold)) { fprintf(stderr, "%s%-40s%u\n", my_tab, "SW Vector Hit Threshold:", (uint)-sw_vect_threshold); } else { fprintf(stderr, "%s%-40s%.02f%%\n", my_tab, "SW Vector Hit Threshold:", sw_vect_threshold); } } if (IS_ABSOLUTE(sw_full_threshold)) { fprintf(stderr, "%s%-40s%u\n", my_tab, shrimp_mode == MODE_COLOUR_SPACE? "SW Full Hit Threshold:" : "SW Hit Threshold", (uint)-sw_full_threshold); } else { fprintf(stderr, "%s%-40s%.02f%%\n", my_tab, shrimp_mode == MODE_COLOUR_SPACE? "SW Full Hit Threshold:" : "SW Hit Threshold", sw_full_threshold); } fprintf(stderr, "\n"); fprintf(stderr, "%s%-40s%s\n", my_tab, "Paired mode:", pair_mode_string[pair_mode]); if (pair_mode != PAIR_NONE) { fprintf(stderr, "%s%-40smin:%d max:%d\n", my_tab, "Insert sizes:", min_insert_size, max_insert_size); if (Xflag) { fprintf(stderr, "%s%-40s%d\n", my_tab, "Bucket size:", insert_histogram_bucket_size); } } fprintf(stderr, "\n"); } static int set_mode_from_string(char const * s) { if (!strcmp(s, "mirna")) { mode_mirna = true; //load_default_mirna_seeds(); Hflag = true; gapless_sw = true; anchor_width = 0; a_gap_open_score = -255; b_gap_open_score = -255; hash_filter_calls = false; match_mode = 1; window_len = 100.0; Gflag = false; compute_mapping_qualities = false; return 1; } else { return 0; } } static void get_pair_mode(char * c, int * pair_mode) { if (c == NULL) { fprintf(stderr, "error: invalid pair mode\n"); exit(1); } if (!strcmp(c, "none")) { *pair_mode = PAIR_NONE; } else if (!strcmp(c, "opp-in")) { *pair_mode = PAIR_OPP_IN; } else if (!strcmp(c, "opp-out")) { *pair_mode = PAIR_OPP_OUT; } else if (!strcmp(c, "col-fw")) { *pair_mode = PAIR_COL_FW; } else if (!strcmp(c, "col-bw")) { *pair_mode = PAIR_COL_BW; } else { fprintf(stderr, "error: unrecognized pair mode (%s)\n", c); exit(1); } } static void get_int(char * c, int * d) { if (c == NULL) { fprintf(stderr, "error: invalid integer\n"); exit(1); } *d = atoi(c); } static void get_threshold(char * c, double * t) { if (c == NULL) { fprintf(stderr, "error: invalid threshold\n"); exit(1); } *t = atof(c); if (*t < 0.0) { fprintf(stderr, "error: invalid threshold [%s]\n", c); exit(1); } if (strcspn(c, "%.") == strlen(c)) *t = -(*t); //absol. } static void get_bool(char * c, bool * b) { if (!strcmp(c, "true") || !strcmp(c, "1")) { *b = true; } else if (!strcmp(c, "false") || !strcmp(c, "0")) { *b = false; } else { fprintf(stderr, "error: invalid bool\n"); exit(1); } } static void get_pairing_options(char * c, struct pairing_options * options) { char * p; if (c == NULL) { fprintf(stderr, "error: invalid pairing options\n"); exit(1); } p = strtok(c, ","); get_pair_mode(p, &options->pair_mode); p = strtok(NULL, ","); get_int(p, &options->min_insert_size); p = strtok(NULL, ","); get_int(p, &options->max_insert_size); p = strtok(NULL, ","); get_int(p, &options->pass1_num_outputs); p = strtok(NULL, ","); get_threshold(p, &options->pass1_threshold); p = strtok(NULL, ","); get_int(p, &options->pass2_num_outputs); p = strtok(NULL, ","); get_threshold(p, &options->pass2_threshold); p = strtok(NULL, ","); get_int(p, &options->stop_count); p = strtok(NULL, ","); get_threshold(p, &options->stop_threshold); p = strtok(NULL, ","); get_bool(p, &options->strata); p = strtok(NULL, ","); get_bool(p, &options->save_outputs); } static void get_read_mapping_options(char * c, struct read_mapping_options_t * options, bool is_paired) { char * p, * q; char * save_ptr; if (c == NULL) { fprintf(stderr, "error: invalid read mapping options\n"); exit(1); } fprintf(stderr, "parsing read_mapping_options [%s] (%s)\n", c, is_paired? "paired" : "unpaired"); // regions q = strtok_r(c, "/", &save_ptr); logit(0, "parsing region options: %s", q); p = strtok(q, ","); get_bool(p, &options->regions.recompute); //if (options->regions.recompute) { //p = strtok(NULL, ","); //get_int(p, &options->regions.min_seed); //p = strtok(NULL, ","); //get_int(p, &options->regions.max_seed); //} // anchor_list q = strtok_r(NULL, "/", &save_ptr); logit(0, "parsing anchor_list options: %s", q); p = strtok(q, ","); get_bool(p, &options->anchor_list.recompute); if (options->anchor_list.recompute) { p = strtok(NULL, ","); get_bool(p, &options->anchor_list.collapse); p = strtok(NULL, ","); get_bool(p, &options->anchor_list.use_region_counts); if (is_paired) { p = strtok(NULL, ","); get_int(p, &options->anchor_list.use_mp_region_counts); } } // hit_list q = strtok_r(NULL, "/", &save_ptr); logit(0, "parsing hit_list options: %s", q); p = strtok(q, ","); get_bool(p, &options->hit_list.recompute); if (options->hit_list.recompute) { p = strtok(NULL, ","); get_bool(p, &options->hit_list.gapless); p = strtok(NULL, ","); get_int(p, &options->hit_list.match_mode); p = strtok(NULL, ","); get_threshold(p, &options->hit_list.threshold); } // pass1 q = strtok_r(NULL, "/", &save_ptr); logit(0, "parsing pass1 options: %s", q); p = strtok(q, ","); get_bool(p, &options->pass1.recompute); if (options->pass1.recompute) { p = strtok(NULL, ","); get_threshold(p, &options->pass1.threshold); p = strtok(NULL, ","); get_threshold(p, &options->pass1.window_overlap); p = strtok(NULL, ","); get_int(p, &options->pass1.min_matches); p = strtok(NULL, ","); get_bool(p, &options->pass1.gapless); if (is_paired) { p = strtok(NULL, ","); get_bool(p, &options->pass1.only_paired); } if (!is_paired) { p = strtok(NULL, ","); get_int(p, &options->pass1.num_outputs); } } // pass2 q = strtok_r(NULL, "/", &save_ptr); logit(0, "parsing pass2 options: %s", q); p = strtok(q, ","); get_threshold(p, &options->pass2.threshold); if (!is_paired) { p = strtok(NULL, ","); get_bool(p, &options->pass2.strata); p = strtok(NULL, ","); get_bool(p, &options->pass2.save_outputs); p = strtok(NULL, ","); get_int(p, &options->pass2.num_outputs); } // stop if (!is_paired) { q = strtok_r(NULL, "/", &save_ptr); logit(0, "parsing stop options: %s", q); p = strtok(q, ","); get_int(p, &options->pass2.stop_count); if (options->pass2.stop_count > 0) { p = strtok(NULL, ","); get_threshold(p, &options->pass2.stop_threshold); } } } int main(int argc, char **argv){ char **genome_files = NULL; int ngenome_files = 0; char *progname = argv[0]; char const * optstr = NULL; char *c, *save_c; int ch; int i, sn, cn; llint before; bool a_gap_open_set, b_gap_open_set; bool a_gap_extend_set, b_gap_extend_set; bool match_score_set, mismatch_score_set, xover_score_set; bool match_mode_set = false; bool qual_delta_set = false; fasta_t fasta = NULL, left_fasta = NULL, right_fasta = NULL; my_alloc_init(64l*1024l*1024l*1024l, 64l*1024l*1024l*1024l); shrimp_args.argc=argc; shrimp_args.argv=argv; set_mode_from_argv(argv, &shrimp_mode); a_gap_open_set = b_gap_open_set = a_gap_extend_set = b_gap_extend_set = false; match_score_set = mismatch_score_set = xover_score_set = false; if (shrimp_mode == MODE_COLOUR_SPACE) { match_score = DEF_CS_MATCH_SCORE; mismatch_score = DEF_CS_MISMATCH_SCORE; a_gap_open_score = DEF_CS_A_GAP_OPEN; b_gap_open_score = DEF_CS_B_GAP_OPEN; a_gap_extend_score = DEF_CS_A_GAP_EXTEND; b_gap_extend_score = DEF_CS_B_GAP_EXTEND; } fasta_reset_stats(); fprintf(stderr, "--------------------------------------------------" "------------------------------\n"); fprintf(stderr, "gmapper: %s.\nSHRiMP %s\n[%s; CXXFLAGS=\"%s\"]\n", get_mode_string(shrimp_mode), SHRIMP_VERSION_STRING, get_compiler(), CXXFLAGS); fprintf(stderr, "--------------------------------------------------" "------------------------------\n"); struct option getopt_long_options[standard_entries+MAX(colour_entries,letter_entries)]; memcpy(getopt_long_options,standard_options,sizeof(standard_options)); //TODO -t -9 -d -Z -D -Y switch(shrimp_mode){ case MODE_COLOUR_SPACE: optstr = "?1:2:s:n:w:l:o:p:m:i:g:q:e:f:h:r:a:z:DCEFHI:K:L:M:N:PRS:TtUVXYZQx:v:"; memcpy(getopt_long_options+standard_entries,colour_space_options,sizeof(colour_space_options)); break; case MODE_LETTER_SPACE: optstr = "?1:2:s:n:w:l:o:p:m:i:g:q:e:f:h:r:a:z:DCEFHI:K:L:M:N:PRS:TtUVXYZQ"; memcpy(getopt_long_options+standard_entries,letter_space_options,sizeof(letter_space_options)); break; case MODE_HELICOS_SPACE: fprintf(stderr,"Helicose currently unsupported\n"); exit(1); break; } //get a copy of the command line size_t size_of_command_line=0; for (i=0; i<argc; i++) { size_of_command_line+=strlen(argv[i])+1; } size_of_command_line++; char command_line[size_of_command_line]; size_t offset=0; for (i=0; i<argc; i++) { offset+=sprintf(command_line+offset,"%s",argv[i]); if (i+1!=argc) { offset+=sprintf(command_line+offset," "); } } assert(offset+1<=size_of_command_line); while ((ch = getopt_long(argc,argv,optstr,getopt_long_options,NULL)) != -1){ switch (ch) { case 9: strata_flag = true; break; case 10: unaligned_reads_file=fopen(optarg,"w"); if (unaligned_reads_file==NULL) { fprintf(stderr,"error: cannot open file \"%s\" for writting\n",optarg); } break; case 11: aligned_reads_file=fopen(optarg,"w"); if (aligned_reads_file==NULL) { fprintf(stderr,"error: cannot open file \"%s\" for writting\n",optarg); } break; case 12: sam_unaligned=true; break; case 13: longest_read_len=atoi(optarg); if (longest_read_len<200) { fprintf(stderr,"error: longest read length must be at least 200\n"); exit(1); } break; case 14: max_alignments=atoi(optarg); break; case 15: logit(0, "as of v2.2.0, --global is on by default"); Gflag = true; break; case 16: Bflag = true; Gflag = true; break; case 17: sam_read_group_name=strdup(optarg); sam_sample_name = strchr(sam_read_group_name,','); if (sam_sample_name==NULL) { fprintf(stderr,"error: sam read group needs to be two values, delimited by commas.\n"); fprintf(stderr," the first value is unique read group identifier\n"); fprintf(stderr," the second is the sample (use pool name where a pool is being sequence\n"); exit(1); } sam_sample_name[0]='\0'; sam_sample_name++; break; case 18: sam_header_filename=optarg; break; case 19: half_paired = false; break; case 20: sam_r2=true; break; case '1': left_reads_filename = optarg; break; case '2': right_reads_filename = optarg; break; case 's': if (strchr(optarg, ',') == NULL) { // allow comma-separated seeds if (optarg[0] == 'w') { int weight = (int)atoi(&optarg[1]); if (!load_default_seeds(weight)) { fprintf(stderr, "error: invalid spaced seed weight (%d)\n", weight); exit(1); } } else { if (!add_spaced_seed(optarg)) { fprintf(stderr, "error: invalid spaced seed \"%s\"\n", optarg); exit (1); } } } else { c = strtok(optarg, ","); do { if (c[0] == 'w') { int weight = (int)atoi(&c[1]); if (!load_default_seeds(weight)) { fprintf(stderr, "error: invalid spaced seed weight (%d)\n", weight); exit(1); } } else { if (!add_spaced_seed(c)) { fprintf(stderr, "error: invalid spaced seed \"%s\"\n", c); exit (1); } } c = strtok(NULL, ","); } while (c != NULL); } break; case 'n': match_mode = atoi(optarg); match_mode_set = true; break; case 'w': window_len = atof(optarg); if (window_len <= 0.0) { fprintf(stderr, "error: invalid window " "length\n"); exit(1); } if (strcspn(optarg, "%.") == strlen(optarg)) window_len = -window_len; //absol. break; case 'o': num_outputs = atoi(optarg); num_tmp_outputs = 20 + num_outputs; break; case 'm': match_score = atoi(optarg); match_score_set = true; break; case 'i': mismatch_score = atoi(optarg); mismatch_score_set = true; break; case 'g': a_gap_open_score = atoi(optarg); a_gap_open_set = true; break; case 'q': b_gap_open_score = atoi(optarg); b_gap_open_set = true; break; case 'e': a_gap_extend_score = atoi(optarg); a_gap_extend_set = true; break; case 'f': b_gap_extend_score = atoi(optarg); b_gap_extend_set = true; break; case 'x': assert(shrimp_mode == MODE_COLOUR_SPACE); crossover_score = atoi(optarg); xover_score_set = true; break; case 'h': sw_full_threshold = atof(optarg); if (sw_full_threshold < 0.0) { fprintf(stderr, "error: invalid s-w full " "hit threshold\n"); exit(1); } if (strcspn(optarg, "%.") == strlen(optarg)) sw_full_threshold = -sw_full_threshold; //absol. break; case 'v': assert(shrimp_mode == MODE_COLOUR_SPACE); sw_vect_threshold = atof(optarg); if (sw_vect_threshold < 0.0) { fprintf(stderr, "error: invalid s-w vector " "hit threshold\n"); exit(1); } if (strcspn(optarg, "%.") == strlen(optarg)) sw_vect_threshold = -sw_vect_threshold; //absol. break; case 'r': window_gen_threshold = atof(optarg); if (window_gen_threshold < 0.0) { fprintf(stderr, "error: invalid window generation threshold [%s]\n", optarg); exit(1); } if (strcspn(optarg, "%.") == strlen(optarg)) window_gen_threshold = -window_gen_threshold; //absol. break; case 'C': if (Fflag) { fprintf(stderr, "error: -C and -F are mutually " "exclusive\n"); exit(1); } Cflag = true; break; case 'F': if (Cflag) { fprintf(stderr, "error: -C and -F are mutually " "exclusive\n"); exit(1); } Fflag = true; break; case 'H': Hflag = true; break; case 'P': Pflag = true; Eflag = false; break; case 'R': Rflag = true; break; case 't': Tflag= false; break; case 'T': Tflag = true; break; /* * New options/parameters since SHRiMP 1.2.1 */ case 'a': anchor_width = atoi(optarg); if (anchor_width < -1 || anchor_width >= 100) { fprintf(stderr, "error: anchor_width requested is invalid (%s)\n", optarg); exit(1); } break; case 'X': Xflag = true; break; case 'Y': Yflag = true; break; case 'l': window_overlap = atof(optarg); if (window_overlap <= 0.0) { fprintf(stderr, "error: invalid window overlap\n"); exit(1); } if (strcspn(optarg, "%.") == strlen(optarg)) window_overlap = -window_overlap; //absol. break; case 'N': num_threads = atoi(optarg); break; case 'K': chunk_size = atoi(optarg); break; case 'S': save_file = optarg; break; case 'L': load_file = optarg; break; case 'D': Dflag = true; break; case '?': usage(progname, true); break; case 'Z': hash_filter_calls = false; break; case 'U': gapless_sw = true; anchor_width = 0; a_gap_open_score = -255; b_gap_open_score = -255; hash_filter_calls = false; break; case 'p': if (!strcmp(optarg, "none")) { pair_mode = PAIR_NONE; } else if (!strcmp(optarg, "opp-in")) { pair_mode = PAIR_OPP_IN; } else if (!strcmp(optarg, "opp-out")) { pair_mode = PAIR_OPP_OUT; } else if (!strcmp(optarg, "col-fw")) { pair_mode = PAIR_COL_FW; } else if (!strcmp(optarg, "col-bw")) { pair_mode = PAIR_COL_BW; } else { fprintf(stderr, "error: unrecognized pair mode (%s)\n", optarg); exit(1); } break; case 'I': c = strtok(optarg, ","); if (c == NULL) crash(1, 0, "format for insert sizes is \"-I 200,1000\"\n"); min_insert_size = atoi(c); if (min_insert_size < 0) { logit(0, "insert sizes must be nonnegative; check README. resetting min_insert_size from [%s] to 0", optarg); min_insert_size = 0; } c = strtok(NULL, ","); if (c == NULL) crash(1, 0, "format for insert sizes is \"-I 200,1000\"\n"); max_insert_size = atoi(c); if (max_insert_size < 0) { logit(0, "insert sizes must be nonnegative; check README. resetting max_insert_size from [%s] to 0", optarg); max_insert_size = 0; } if (min_insert_size > max_insert_size) crash(1, 0, "invalid insert sizes (min:%d,max:%d)\n", min_insert_size, max_insert_size); break; case 'E': // on by default; accept option for bw compatibility logit(0, "as of v2.2.0, -E/--sam is on by default"); Eflag = true; break; case 'z': list_cutoff = atoi(optarg); if (list_cutoff == 0) { fprintf(stderr, "error: invalid list cutoff (%s)\n", optarg); exit(1); } break; case 'V': Vflag = false; break; case 'Q': Qflag = true; break; case 'M': c = strtok(optarg, ","); do { if (!set_mode_from_string(c)) { fprintf(stderr, "error: unrecognized mode (%s)\n", c); exit(1); } match_mode_set = true; c = strtok(NULL, ","); } while (c != NULL); break; case 21: trim_front=atoi(optarg); if (shrimp_mode == MODE_COLOUR_SPACE) { fprintf(stderr,"--trim-front cannot be used in colour space mode!\n"); exit(1); } if (trim_front<0) { fprintf(stderr,"--trim-front value must be positive\n"); exit(1); } if (trim_front>0) trim=true; break; case 22: trim_end=atoi(optarg); if (trim_end<0) { fprintf(stderr,"--trim-end value must be positive\n"); exit(1); } if (trim_end>0) trim=true; break; case 23: trim=true; trim_first=true; trim_second=false; break; case 24: trim=true; trim_second=true; trim_first=false; break; case 25: c = strtok(optarg, ","); if (c == NULL) crash(1, 0, "argmuent for insert-size-dist should be \"mean,stddev\" [%s]", optarg); insert_size_mean = atof(c); c = strtok(NULL, ","); if (c == NULL) crash(1, 0, "argmuent for insert-size-dist should be \"mean,stddev\" [%s]", optarg); insert_size_stddev = atof(c); break; case 26: use_regions = !use_regions; break; case 27: region_overlap = atoi(optarg); if (region_overlap < 0) { fprintf(stderr, "region overlap must be non-negative!\n"); exit(1); } break; case 28: if (n_unpaired_mapping_options[0] > 0 || n_unpaired_mapping_options[1] > 0) { fprintf(stderr, "warning: unpaired mapping options set before paired mapping options! the latter take precedence.\n"); half_paired = true; } n_paired_mapping_options++; paired_mapping_options = (struct readpair_mapping_options_t *) //xrealloc(paired_mapping_options, n_paired_mapping_options * sizeof(paired_mapping_options[0])); my_realloc(paired_mapping_options, n_paired_mapping_options * sizeof(paired_mapping_options[0]), (n_paired_mapping_options - 1) * sizeof(paired_mapping_options[0]), &mem_small, "paired_mapping_options"); c = strtok_r(optarg, ";", &save_c); get_pairing_options(c, &paired_mapping_options[n_paired_mapping_options - 1].pairing); c = strtok_r(NULL, ";", &save_c); get_read_mapping_options(c, &paired_mapping_options[n_paired_mapping_options - 1].read[0], true); c = strtok_r(NULL, ";", &save_c); get_read_mapping_options(c, &paired_mapping_options[n_paired_mapping_options - 1].read[1], true); // HACK SETTINGS pair_mode = paired_mapping_options[0].pairing.pair_mode; break; case 29: int nip; c = strtok(optarg, ";"); if (c == NULL || (*c != '0' && *c != '1')) { fprintf(stderr, "error: invalid unpaired mapping options:[%s]\n", optarg); exit(1); } if (n_paired_mapping_options > 0) half_paired = true; nip = (*c == '0'? 0 : 1); n_unpaired_mapping_options[nip]++; unpaired_mapping_options[nip] = (struct read_mapping_options_t *) //xrealloc(unpaired_mapping_options[nip], n_unpaired_mapping_options[nip] * sizeof(unpaired_mapping_options[nip][0])); my_realloc(unpaired_mapping_options[nip], n_unpaired_mapping_options[nip] * sizeof(unpaired_mapping_options[nip][0]), (n_unpaired_mapping_options[nip] - 1) * sizeof(unpaired_mapping_options[nip][0]), &mem_small, "unpaired_mapping_options[%d]", nip); c = strtok(NULL, ";"); get_read_mapping_options(c, &unpaired_mapping_options[nip][n_unpaired_mapping_options[nip] - 1], false); break; case 30: min_avg_qv = atoi(optarg); if (min_avg_qv < -2 || min_avg_qv > 40) { fprintf(stderr, "error: invalid minimum average quality value (%s)\n", optarg); } break; case 31: extra_sam_fields = true; break; case 32: region_bits = atoi(optarg); if (region_bits < 8 || region_bits > 20) { crash(1, 0, "invalid number of region bits: %s; must be between 8 and 20", optarg); } n_regions = (1 << (32 - region_bits)); break; case 33: progress = atoi(optarg); break; case 34: save_mmap = optarg; break; case 35: load_mmap = optarg; break; case 36: indel_taboo_len = atoi(optarg); if (indel_taboo_len < 0) crash(1, 0, "invalid indel taboo len: [%s]", optarg); break; case 37: single_best_mapping = true; break; case 38: all_contigs = true; break; case 39: compute_mapping_qualities = false; break; case 40: Eflag = false; break; case 41: // half-paired: accept option for bw compatibility logit(0, "as of v2.2.0, --half-paired is on by default"); half_paired = true; break; case 42: // no-improper-mappings improper_mappings = false; break; case 43: // qual value offset qual_delta = atoi(optarg); qual_delta_set = true; break; case 44: // sam-header-hd sam_header_hd = fopen(optarg, "r"); if (sam_header_hd == NULL) crash(1, 1, "cannot open sam header file with HD lines [%s]", optarg); break; case 45: // sam-header-sq sam_header_sq = fopen(optarg, "r"); if (sam_header_sq == NULL) crash(1, 1, "cannot open sam header file with SQ lines [%s]", optarg); break; case 46: // sam-header-rg sam_header_rg = fopen(optarg, "r"); if (sam_header_rg == NULL) crash(1, 1, "cannot open sam header file with RG lines [%s]", optarg); break; case 47: // sam-header-pg sam_header_pg = fopen(optarg, "r"); if (sam_header_pg == NULL) crash(1, 1, "cannot open sam header file with PG lines [%s]", optarg); break; case 48: // no-autodetect-input autodetect_input = false; break; case 3: trim_illumina=true; break; case 123: no_qv_check=true; break; case 124: // local alignment Gflag = false; break; case 125: // --ignore-qvs ignore_qvs = true; break; case 126: pr_xover = atof(optarg); break; default: usage(progname, false); } } argc -= optind; argv += optind; if ((pair_mode != PAIR_NONE || !single_reads_file) && (chunk_size % 2) != 0) { logit(0, "in paired mode or if using options -1 and -2, the thread chunk size must be even; adjusting it to [%d]", chunk_size + 1); chunk_size++; } if (!Gflag && compute_mapping_qualities) { logit(0, "mapping qualities are not available in local alignment mode; disabling them"); compute_mapping_qualities = false; } if (Gflag && gapless_sw) { fprintf(stderr,"error: cannot use global (or bfast) and ungapped mode at the same time!\n"); usage(progname,false); } if (sam_unaligned && !Eflag) { fprintf(stderr,"error: when using flag --sam-unaligned must also use -E/--sam\n"); usage(progname,false); } if (right_reads_filename != NULL || left_reads_filename !=NULL) { if (right_reads_filename == NULL || left_reads_filename == NULL ){ fprintf(stderr,"error: when using \"%s\" must also specify \"%s\"\n", (left_reads_filename != NULL) ? "-1" : "-2", (left_reads_filename != NULL) ? "-2" : "-1"); usage(progname,false); } single_reads_file=false; if (strcmp(right_reads_filename,"-")==0 && strcmp(left_reads_filename,"-")==0) { fprintf(stderr,"error: both -1 and -2 arguments cannot be stdin (\"-\")\n"); usage(progname,false); } } if (!match_mode_set) { match_mode = (pair_mode == PAIR_NONE? DEF_MATCH_MODE_UNPAIRED : DEF_MATCH_MODE_PAIRED); } if (pair_mode == PAIR_NONE && (!trim_first || !trim_second)) { fprintf(stderr,"error: cannot use --trim-first or --trim-second in unpaired mode\n"); usage(progname,false); } // set up insert size histogram if (Xflag && pair_mode == PAIR_NONE) { fprintf(stderr, "warning: insert histogram not available in unpaired mode; ignoring\n"); Xflag = false; } if (pair_mode != PAIR_NONE) { insert_histogram_bucket_size = ceil_div(max_insert_size - min_insert_size + 1, 100); for (i = 0; i < 100; i++) { insert_histogram[i] = 1; insert_histogram_load += insert_histogram[i]; } } if(load_file != NULL && n_seeds != 0){ fprintf(stderr,"error: cannot specify seeds when loading genome map\n"); usage(progname,false); } if (n_seeds == 0 && load_file == NULL && load_mmap == NULL) { if (mode_mirna) load_default_mirna_seeds(); else load_default_seeds(0); } if (Hflag){ init_seed_hash_mask(); } if (save_file != NULL && load_file != NULL && list_cutoff == DEF_LIST_CUTOFF){ fprintf(stderr,"error: -L and -S allowed together only if list_cutoff is specified\n"); exit(1); } if (load_file != NULL && (save_file != NULL || save_mmap != NULL)) { // args: none if (argc != 0) { fprintf(stderr, "error: when using both -L and -S, no extra files can be given\n"); usage(progname, false); } } else if (load_file != NULL || load_mmap != NULL) { // args: reads file if (argc == 0 && single_reads_file) { fprintf(stderr,"error: read_file not specified\n"); usage(progname, false); } else if (argc == 1) { if (single_reads_file) { reads_filename = argv[0]; } else { fprintf(stderr,"error: cannot specify a reads file when using -L, -1 and -2\n"); usage(progname,false); } } } else if (save_file != NULL) { // args: genome file(s) if (argc == 0){ fprintf(stderr, "error: genome_file(s) not specified\n"); usage(progname,false); } genome_files = &argv[0]; ngenome_files = argc; } else if (single_reads_file) { // args: reads file, genome file(s) if (argc < 2) { fprintf(stderr, "error: %sgenome_file(s) not specified\n", (argc == 0) ? "reads_file, " : ""); usage(progname, false); } reads_filename = argv[0]; genome_files = &argv[1]; ngenome_files = argc - 1; } else { if( argc < 1) { fprintf(stderr, "error: genome_file(s) not specified\n"); usage(progname, false); } genome_files = &argv[0]; ngenome_files = argc; } if (!Cflag && !Fflag) { Cflag = Fflag = true; } if (pair_mode != PAIR_NONE && (!Cflag || !Fflag)) { fprintf(stderr, "warning: in paired mode, both strands must be inspected; ignoring -C and -F\n"); Cflag = Fflag = true; } /* if (pair_mode == PAIR_NONE && half_paired) { fprintf(stderr, "error: cannot use option half-paired in non-paired mode!\n"); exit(1); } */ if (pair_mode == PAIR_NONE && sam_r2) { fprintf(stderr, "error: cannot use option sam-r2 in non-paired mode!\n"); exit(1); } if (shrimp_mode == MODE_LETTER_SPACE) { sw_vect_threshold = sw_full_threshold; } if (Eflag && Pflag) { fprintf(stderr,"-E and -P are incompatable\n"); exit(1); } if (Eflag && Rflag) { fprintf(stderr,"-E and -R are incompatable\n"); exit(1); } if (!valid_spaced_seeds()) { fprintf(stderr, "error: invalid spaced seed\n"); if (!Hflag) fprintf(stderr, " for longer seeds, try using the -H flag\n"); exit(1); } if (!IS_ABSOLUTE(window_len) && window_len < 100.0) { fprintf(stderr, "error: window length < 100%% of read length\n"); exit(1); } if (!IS_ABSOLUTE(window_overlap) && window_overlap > 100.0) { fprintf(stderr, "warning: window overlap length > 100%% of window_length; resetting to 100%%\n"); window_overlap = 100.0; } if ((pair_mode == PAIR_NONE && (match_mode < 1 || match_mode > 2)) || (pair_mode != PAIR_NONE && (match_mode < 2 || match_mode > 4))) { fprintf(stderr, "error: invalid match mode [pair_mode=%d;match_mode=%d]\n", pair_mode, match_mode); exit(1); } if (num_outputs < 1) { fprintf(stderr, "error: invalid maximum hits per read\n"); exit(1); } if (a_gap_open_score > 0 || b_gap_open_score > 0) { fprintf(stderr, "error: invalid gap open penalty\n"); exit(1); } if (a_gap_extend_score > 0 || b_gap_extend_score > 0) { fprintf(stderr, "error: invalid gap extend penalty\n"); exit(1); } if (!IS_ABSOLUTE(sw_full_threshold) && sw_full_threshold > 100.0) { fprintf(stderr, "error: invalid s-w full hit threshold\n"); exit(1); } if (shrimp_mode == MODE_COLOUR_SPACE && !IS_ABSOLUTE(sw_vect_threshold) && sw_vect_threshold > 100.0) { fprintf(stderr, "error: invalid s-w vector threshold\n"); exit(1); } if (!IS_ABSOLUTE(window_gen_threshold) && window_gen_threshold > 100.0) { fprintf(stderr, "error: invalid window generation threshold\n"); exit(1); } if ((IS_ABSOLUTE(window_gen_threshold) && IS_ABSOLUTE(sw_full_threshold) && -window_gen_threshold > -sw_full_threshold) || (!IS_ABSOLUTE(window_gen_threshold) && !IS_ABSOLUTE(sw_full_threshold) && window_gen_threshold > sw_full_threshold)) { //fprintf(stderr, "warning: window generation threshold is larger than sw threshold\n"); } if ((a_gap_open_set && !b_gap_open_set) || (a_gap_extend_set && !b_gap_extend_set)) { fputc('\n', stderr); } if (a_gap_open_set && !b_gap_open_set) { fprintf(stderr, "Notice: Gap open penalty set for reference but not query; assuming symmetry.\n"); b_gap_open_score = a_gap_open_score; } if (a_gap_extend_set && !b_gap_extend_set) { fprintf(stderr, "Notice: Gap extend penalty set for reference but not query; assuming symmetry.\n"); b_gap_extend_score = a_gap_extend_score; } if ((a_gap_open_set && !b_gap_open_set) || (a_gap_extend_set && !b_gap_extend_set)) { fputc('\n', stderr); } /* Set probabilities from scores */ if (shrimp_mode == MODE_COLOUR_SPACE) { // CS: pr_xover ~= .03 => alpha => pr_mismatch => rest //pr_xover = .03; score_alpha = (double)crossover_score / (log(pr_xover/3)/log(2.0)); pr_mismatch = 1.0/(1.0 + 1.0/3.0 * pow(2.0, ((double)match_score - (double)mismatch_score)/score_alpha)); } else { // LS: pr_mismatch ~= .01 => alpha => rest pr_mismatch = .01; score_alpha = ((double)match_score - (double)mismatch_score)/(log((1 - pr_mismatch)/(pr_mismatch/3.0))/log(2.0)); } score_beta = (double)match_score - 2 * score_alpha - score_alpha * log(1 - pr_mismatch)/log(2.0); pr_del_open = pow(2.0, (double)a_gap_open_score/score_alpha); pr_ins_open = pow(2.0, (double)b_gap_open_score/score_alpha); pr_del_extend = pow(2.0, (double)a_gap_extend_score/score_alpha); pr_ins_extend = pow(2.0, ((double)b_gap_extend_score - score_beta)/score_alpha); //score_difference_mq_cutoff = (int)rint(10.0 * score_alpha); #ifdef DEBUG_SCORES fprintf(stderr, "probabilities from scores:\talpha=%.9g\tbeta=%.9g\n", score_alpha, score_beta); if (shrimp_mode == MODE_COLOUR_SPACE) fprintf(stderr, "pr_xover=%.9g\n", pr_xover); fprintf(stderr, "pr_mismatch=%.9g\npr_del_open=%.9g\tpr_del_extend=%.9g\t(pr_del1=%.9g)\npr_ins_open=%.9g\tpr_ins_extend=%.9g\t(pr_ins1=%.9g)\n", pr_mismatch, pr_del_open, pr_del_extend, pr_del_open*pr_del_extend, pr_ins_open, pr_ins_extend, pr_ins_open*pr_ins_extend); // sanity check: fprintf(stderr, "scores from probabilities:\n"); fprintf(stderr, "match_score=%g\nmismatch_score=%g\n", 2 * score_alpha + score_beta + score_alpha * log(1 - pr_mismatch) / log(2.0), 2 * score_alpha + score_beta + score_alpha * log(pr_mismatch/3) / log(2.0)); if (shrimp_mode == MODE_COLOUR_SPACE) fprintf(stderr, "crossover_score=%g\n", score_alpha * log(pr_xover/3) / log(2.0)); fprintf(stderr, "a_gap_open_score=%g\ta_gap_extend_score=%g\nb_gap_open_score=%g\tb_gap_extend_score=%g\n", score_alpha * log(pr_del_open) / log(2.0), score_alpha * log(pr_del_extend) / log(2.0), score_alpha * log(pr_ins_open) / log(2.0), score_alpha * log(pr_ins_extend) / log(2.0) + score_beta); #endif // set up new options structure // THIS SHOULD EVENTUALLY BE MERGED INTO OPTION READING if (n_unpaired_mapping_options[0] == 0 && n_paired_mapping_options == 0) { if (pair_mode == PAIR_NONE) { n_unpaired_mapping_options[0]++; //unpaired_mapping_options[0] = (struct read_mapping_options_t *)xcalloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0])); unpaired_mapping_options[0] = (struct read_mapping_options_t *) my_calloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]), &mem_small, "unpaired_mapping_options[0]"); unpaired_mapping_options[0][0].regions.recompute = (match_mode == 2 && use_regions); //unpaired_mapping_options[0][0].regions.min_seed = -1; //unpaired_mapping_options[0][0].regions.max_seed = -1; unpaired_mapping_options[0][0].anchor_list.recompute = true; unpaired_mapping_options[0][0].anchor_list.collapse = true; unpaired_mapping_options[0][0].anchor_list.use_region_counts = (match_mode == 2 && use_regions); unpaired_mapping_options[0][0].anchor_list.use_mp_region_counts = 0; unpaired_mapping_options[0][0].hit_list.recompute = true; unpaired_mapping_options[0][0].hit_list.gapless = gapless_sw; unpaired_mapping_options[0][0].hit_list.match_mode = match_mode; unpaired_mapping_options[0][0].hit_list.threshold = window_gen_threshold; unpaired_mapping_options[0][0].pass1.recompute = true; unpaired_mapping_options[0][0].pass1.only_paired = false; unpaired_mapping_options[0][0].pass1.gapless = gapless_sw; unpaired_mapping_options[0][0].pass1.min_matches = match_mode; // this is 1 or 2 in unpaired mode unpaired_mapping_options[0][0].pass1.num_outputs = num_tmp_outputs; unpaired_mapping_options[0][0].pass1.threshold = sw_vect_threshold; unpaired_mapping_options[0][0].pass1.window_overlap = window_overlap; unpaired_mapping_options[0][0].pass2.strata = strata_flag; unpaired_mapping_options[0][0].pass2.save_outputs = false; unpaired_mapping_options[0][0].pass2.num_outputs = num_outputs; unpaired_mapping_options[0][0].pass2.threshold = sw_full_threshold; unpaired_mapping_options[0][0].pass2.stop_count = 0; } else { n_paired_mapping_options++; //paired_mapping_options = (struct readpair_mapping_options_t *)xcalloc(n_paired_mapping_options * sizeof(paired_mapping_options[0])); paired_mapping_options = (struct readpair_mapping_options_t *) my_calloc(n_paired_mapping_options * sizeof(paired_mapping_options[0]), &mem_small, "paired_mapping_options"); paired_mapping_options[0].pairing.pair_mode = pair_mode; paired_mapping_options[0].pairing.min_insert_size = min_insert_size; paired_mapping_options[0].pairing.max_insert_size = max_insert_size; paired_mapping_options[0].pairing.strata = strata_flag; paired_mapping_options[0].pairing.save_outputs = compute_mapping_qualities; paired_mapping_options[0].pairing.pass1_num_outputs = num_tmp_outputs; paired_mapping_options[0].pairing.pass2_num_outputs = num_outputs; paired_mapping_options[0].pairing.pass1_threshold = sw_vect_threshold; paired_mapping_options[0].pairing.pass2_threshold = sw_full_threshold; paired_mapping_options[0].read[0].regions.recompute = use_regions && match_mode != 2; //paired_mapping_options[0].read[0].regions.min_seed = -1; //paired_mapping_options[0].read[0].regions.max_seed = -1; paired_mapping_options[0].read[0].anchor_list.recompute = true; paired_mapping_options[0].read[0].anchor_list.collapse = true; paired_mapping_options[0].read[0].anchor_list.use_region_counts = use_regions && match_mode != 2; if (use_regions) { paired_mapping_options[0].read[0].anchor_list.use_mp_region_counts = (match_mode == 4 && !half_paired? 1 : match_mode == 3 && half_paired? 2 : match_mode == 3 && !half_paired? 3 : 0); } paired_mapping_options[0].read[0].hit_list.recompute = true; paired_mapping_options[0].read[0].hit_list.gapless = gapless_sw; paired_mapping_options[0].read[0].hit_list.match_mode = (match_mode == 4? 2 : match_mode == 3? 3 : 1); paired_mapping_options[0].read[0].hit_list.threshold = window_gen_threshold; paired_mapping_options[0].read[0].pass1.recompute = true; paired_mapping_options[0].read[0].pass1.only_paired = true; paired_mapping_options[0].read[0].pass1.gapless = gapless_sw; paired_mapping_options[0].read[0].pass1.min_matches = (match_mode == 4? 2 : 1); paired_mapping_options[0].read[0].pass1.threshold = sw_vect_threshold; paired_mapping_options[0].read[0].pass1.window_overlap = window_overlap; paired_mapping_options[0].read[0].pass2.strata = strata_flag; paired_mapping_options[0].read[0].pass2.threshold = sw_full_threshold * 0.5; paired_mapping_options[0].read[1] = paired_mapping_options[0].read[0]; if (!half_paired) { paired_mapping_options[0].pairing.stop_count = 0; } else // half_paired { paired_mapping_options[0].pairing.stop_count = 1; paired_mapping_options[0].pairing.stop_threshold = 101.0; //paired_mapping_options[0].pairing.pass2_threshold; n_unpaired_mapping_options[0]++; n_unpaired_mapping_options[1]++; //unpaired_mapping_options[0] = (struct read_mapping_options_t *)xcalloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0])); unpaired_mapping_options[0] = (struct read_mapping_options_t *) my_calloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]), &mem_small, "unpaired_mapping_options[0]"); //unpaired_mapping_options[1] = (struct read_mapping_options_t *)xcalloc(n_unpaired_mapping_options[1] * sizeof(unpaired_mapping_options[1][0])); unpaired_mapping_options[1] = (struct read_mapping_options_t *) my_calloc(n_unpaired_mapping_options[1] * sizeof(unpaired_mapping_options[1][0]), &mem_small, "unpaired_mapping_options[1]"); unpaired_mapping_options[0][0].regions.recompute = false; unpaired_mapping_options[0][0].anchor_list.recompute = false; unpaired_mapping_options[0][0].hit_list.recompute = false; unpaired_mapping_options[0][0].pass1.recompute = true; unpaired_mapping_options[0][0].pass1.gapless = gapless_sw; unpaired_mapping_options[0][0].pass1.min_matches = 2; unpaired_mapping_options[0][0].pass1.only_paired = false; unpaired_mapping_options[0][0].pass1.num_outputs = num_tmp_outputs; unpaired_mapping_options[0][0].pass1.threshold = sw_vect_threshold; unpaired_mapping_options[0][0].pass1.window_overlap = window_overlap; unpaired_mapping_options[0][0].pass2.strata = strata_flag; unpaired_mapping_options[0][0].pass2.save_outputs = compute_mapping_qualities; unpaired_mapping_options[0][0].pass2.num_outputs = num_outputs; unpaired_mapping_options[0][0].pass2.threshold = sw_full_threshold; unpaired_mapping_options[0][0].pass2.stop_count = 0; unpaired_mapping_options[1][0] = unpaired_mapping_options[0][0]; } } } if(load_file == NULL && load_mmap == NULL) { print_settings(); } if (load_file != NULL && save_mmap != NULL) { exit(genome_load_map_save_mmap(load_file, save_mmap) == true ? 0 : 1); } before = gettimeinusecs(); if (load_mmap != NULL) { genome_load_mmap(load_mmap); } else if (load_file != NULL){ if (strchr(load_file, ',') == NULL) { //use prefix int buf_size = strlen(load_file) + 20; //char * genome_name = (char *)xmalloc(sizeof(char)*buf_size); char genome_name[buf_size]; strncpy(genome_name,load_file,buf_size); strncat(genome_name,".genome",buf_size); fprintf(stderr,"Loading genome from %s\n",genome_name); if (!load_genome_map(genome_name)){ fprintf(stderr, "error: loading from genome file \"%s\"\n", genome_name); exit (1); } //free(genome_name); int seed_count = 0; //char * seed_name = (char *)xmalloc(sizeof(char)*buf_size); char seed_name[buf_size]; //char * buff = (char *)xmalloc(sizeof(char)*buf_size); char buff[buf_size]; strncpy(seed_name,load_file,buf_size); strncat(seed_name,".seed.",buf_size); sprintf(buff,"%d",seed_count); strncat(seed_name,buff,buf_size); FILE *f = fopen(seed_name,"r"); while(f != NULL){ fclose(f); fprintf(stderr,"Loading seed from %s\n",seed_name); if (!load_genome_map_seed(seed_name)) { fprintf(stderr, "error: loading from map file \"%s\"\n", seed_name); exit (1); } seed_count++; strncpy(seed_name,load_file,buf_size); strncat(seed_name,".seed.",buf_size); sprintf(buff,"%d",seed_count); strncat(seed_name,buff,buf_size); f = fopen(seed_name,"r"); } //free(seed_name); //free(buff); } else { c = strtok(load_file, ","); fprintf(stderr,"Loading genome from %s\n",c); if (!load_genome_map(c)){ fprintf(stderr, "error: loading from genome file \"%s\"\n", c); exit (1); } c = strtok(NULL, ","); do { fprintf(stderr,"Loading seed from %s\n",c); if (!load_genome_map_seed(c)) { fprintf(stderr, "error: loading from map file \"%s\"\n", c); exit (1); } c = strtok(NULL, ","); } while (c != NULL); } if (Hflag) { init_seed_hash_mask(); } //print_settings(); } else { if (!load_genome(genome_files,ngenome_files)){ exit(1); } } load_genome_usecs += (gettimeinusecs() - before); // initialize general search tree for contig offsets gen_st_init(&contig_offsets_gen_st, 17, contig_offsets, num_contigs); // // Automatic genome index trimming // if (Vflag && save_file == NULL && list_cutoff == DEF_LIST_CUTOFF) { // this will be a mapping job; enable automatic trimming long long unsigned int total_genome_len = 0; int max_seed_weight = 0; for (i = 0; i < num_contigs; i++) { total_genome_len += (long long unsigned int)genome_len[i]; } if (Hflag) { max_seed_weight = HASH_TABLE_POWER; } else { for (sn = 0; sn < n_seeds; sn++) { if (seed[sn].weight > max_seed_weight) { max_seed_weight = seed[sn].weight; } } } // cutoff := max (1000, 100*(total_genome_len/4^max_seed_weight)) list_cutoff = 1000; if ((uint32_t)((100llu * total_genome_len)/power(4, max_seed_weight)) > list_cutoff) { list_cutoff = (uint32_t)((100llu * total_genome_len)/power(4, max_seed_weight)); } //fprintf(stderr, " %-40s%d\n", "Trimming index lists longer than:", list_cutoff); //fprintf(stderr, "\n"); } if (load_file != NULL || load_mmap != NULL) { print_settings(); } if (Yflag) print_genomemap_stats(); if (save_file != NULL) { if (list_cutoff != DEF_LIST_CUTOFF) { fprintf(stderr, "\nTrimming index lists longer than: %u\n", list_cutoff); trim_genome(); } fprintf(stderr,"Saving genome map to %s\n",save_file); if(!save_genome_map(save_file)){ exit(1); } exit(0); } // compute total genome size for (cn = 0; cn < num_contigs; cn++) total_genome_size += genome_len[cn]; //TODO setup need max window and max read len //int longest_read_len = 2000; int max_window_len = (int)abs_or_pct(window_len,longest_read_len); // open input files, and set Qflag accordingly if (single_reads_file) { fasta = fasta_open(reads_filename, shrimp_mode, Qflag, autodetect_input? &Qflag : NULL); if (fasta == NULL) { crash(1, 1, "failed to open read file [%s]", reads_filename); } else { fprintf(stderr, "- Processing read file [%s]\n", reads_filename); } } else { left_fasta = fasta_open(left_reads_filename, shrimp_mode, Qflag, autodetect_input? &Qflag : NULL); if (left_fasta == NULL) { crash(1, 1, "failed to open read file [%s]", left_reads_filename); } right_fasta = fasta_open(right_reads_filename, shrimp_mode, Qflag); if (right_fasta == NULL) { crash(1, 1, "failed to open read file [%s]", right_reads_filename); } // WHY? the code above sets both ->space to shrimp_mode anyhow //if (right_fasta->space != left_fasta->space) { // fprintf(stderr,"error: when using -1 and -2, both files must be either only colour space or only letter space!\n"); // return (false); //} fasta = left_fasta; fprintf(stderr, "- Processing read files [%s , %s]\n", left_reads_filename, right_reads_filename); } // set default quality value delta if (Qflag) { if (!qual_delta_set) { if (shrimp_mode == MODE_LETTER_SPACE) qual_delta = DEF_LS_QUAL_DELTA; else qual_delta = DEF_CS_QUAL_DELTA; logit(0, "quality value format not set explicitly; using PHRED+%d", qual_delta); } else { logit(0, "quality value format set to PHRED+%d", qual_delta); } } #pragma omp parallel shared(longest_read_len,max_window_len,a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score,\ match_score, mismatch_score,shrimp_mode,crossover_score,anchor_width) num_threads(num_threads) { // init thread-private globals memset(&tpg, 0, sizeof(tpg_t)); tpg.wait_tc.type = DEF_FAST_TIME_COUNTER; tpg.region_counts_tc.type = DEF_FAST_TIME_COUNTER; tpg.mp_region_counts_tc.type = DEF_FAST_TIME_COUNTER; tpg.anchor_list_tc.type = DEF_FAST_TIME_COUNTER; tpg.hit_list_tc.type = DEF_FAST_TIME_COUNTER; tpg.get_vector_hits_tc.type = DEF_FAST_TIME_COUNTER; tpg.pass1_tc.type = DEF_FAST_TIME_COUNTER; tpg.pass2_tc.type = DEF_FAST_TIME_COUNTER; tpg.duplicate_removal_tc.type = DEF_FAST_TIME_COUNTER; /* region handling */ if (use_regions) { region_map_id = 0; for (int number_in_pair = 0; number_in_pair < 2; number_in_pair++) for (int st = 0; st < 2; st++) //region_map[number_in_pair][st] = (int32_t *)xcalloc(n_regions * sizeof(region_map[0][0][0])); region_map[number_in_pair][st] = (region_map_t *) my_calloc(n_regions * sizeof(region_map[0][0][0]), &mem_mapping, "region_map"); } if (f1_setup(max_window_len, longest_read_len, a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score, match_score, shrimp_mode == MODE_LETTER_SPACE? mismatch_score : match_score + crossover_score, shrimp_mode == MODE_COLOUR_SPACE, true)) { fprintf(stderr, "failed to initialise vector Smith-Waterman (%s)\n", strerror(errno)); exit(1); } int ret; if (shrimp_mode == MODE_COLOUR_SPACE) { /* XXX - a vs. b gap */ ret = sw_full_cs_setup(max_window_len, longest_read_len, a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score, match_score, mismatch_score, crossover_score, true, anchor_width, indel_taboo_len); } else { ret = sw_full_ls_setup(max_window_len, longest_read_len, a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score, match_score, mismatch_score, true, anchor_width); } if (ret) { fprintf(stderr, "failed to initialise scalar Smith-Waterman (%s)\n", strerror(errno)); exit(1); } /* post_sw */ if (shrimp_mode == MODE_COLOUR_SPACE) { post_sw_setup(max_window_len + longest_read_len, pr_mismatch, pr_xover, pr_del_open, pr_del_extend, pr_ins_open, pr_ins_extend, Qflag && !ignore_qvs, use_sanger_qvs, qual_vector_offset, qual_delta, true); } } char * output; if (Eflag){ int i; if (sam_header_filename != NULL) { FILE * sam_header_file = fopen(sam_header_filename, "r"); if (sam_header_file == NULL) { perror("Failed to open sam header file "); exit(1); } cat(sam_header_file, stdout); fclose(sam_header_file); } else { // HD line if (sam_header_hd != NULL) { cat(sam_header_hd, stdout); } else { fprintf(stdout,"@HD\tVN:%s\tSO:%s\n","1.0","unsorted"); } // SQ lines if (sam_header_sq != NULL) { cat(sam_header_sq, stdout); } else { for(i = 0; i < num_contigs; i++){ fprintf(stdout,"@SQ\tSN:%s\tLN:%u\n",contig_names[i],genome_len[i]); } } // RG lines if (sam_header_rg != NULL) { cat(sam_header_rg, stdout); } else if (sam_read_group_name != NULL) { fprintf(stdout, "@RG\tID:%s\tSM:%s\n", sam_read_group_name, sam_sample_name); } // PG lines if (sam_header_pg != NULL) { cat(sam_header_pg, stdout); } else { fprintf(stdout, "@PG\tID:%s\tVN:%s\tCL:%s\n", "gmapper", SHRIMP_VERSION_STRING, command_line); } } } else { output = output_format_line(Rflag); puts(output); free(output); } before = gettimeinusecs(); bool launched = launch_scan_threads(fasta, left_fasta, right_fasta); if (!launched) { fprintf(stderr,"error: a fatal error occured while launching scan thread(s)!\n"); exit(1); } mapping_wallclock_usecs += (gettimeinusecs() - before); if (single_reads_file) { fasta_close(fasta); } else { fasta_close(left_fasta); fasta_close(right_fasta); } print_statistics(); #pragma omp parallel shared(longest_read_len,max_window_len,a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score, \ match_score, mismatch_score,shrimp_mode,crossover_score,anchor_width) num_threads(num_threads) { sw_vector_cleanup(); if (shrimp_mode==MODE_COLOUR_SPACE) { sw_full_cs_cleanup(); post_sw_cleanup(); } sw_full_ls_cleanup(); f1_free(); if (use_regions) { for (int number_in_pair = 0; number_in_pair < 2; number_in_pair++) for (int st = 0; st < 2; st++) //free(region_map[number_in_pair][st]); my_free(region_map[number_in_pair][st], n_regions * sizeof(region_map[0][0][0]), &mem_mapping, "region_map"); } } gen_st_delete(&contig_offsets_gen_st); if (load_mmap != NULL) { // munmap? } else { free_genome(); //free(seed); if (Hflag) { int sn; for (sn = 0; sn < n_seeds; sn++) { my_free(seed_hash_mask[sn], BPTO32BW(max_seed_span) * sizeof(seed_hash_mask[sn][0]), &mem_small, "seed_hash_mask[%d]", sn); } my_free(seed_hash_mask, n_seeds * sizeof(seed_hash_mask[0]), &mem_small, "seed_hash_mask"); } my_free(seed, n_seeds * sizeof(seed[0]), &mem_small, "seed"); } //free(paired_mapping_options); my_free(paired_mapping_options, n_paired_mapping_options * sizeof(paired_mapping_options[0]), &mem_small, "paired_mapping_options"); //free(unpaired_mapping_options[0]); my_free(unpaired_mapping_options[0], n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]), &mem_small, "unpaired_mapping_options[0]"); //free(unpaired_mapping_options[1]); my_free(unpaired_mapping_options[1], n_unpaired_mapping_options[1] * sizeof(unpaired_mapping_options[0][0]), &mem_small, "unpaired_mapping_options[1]"); if (sam_read_group_name != NULL) free(sam_read_group_name); // close some files if (aligned_reads_file != NULL) fclose(aligned_reads_file); if (unaligned_reads_file != NULL) fclose(unaligned_reads_file); if (sam_header_hd != NULL) fclose(sam_header_hd); if (sam_header_sq != NULL) fclose(sam_header_sq); if (sam_header_rg != NULL) fclose(sam_header_rg); if (sam_header_pg != NULL) fclose(sam_header_pg); #ifdef MYALLOC_ENABLE_CRT fprintf(stderr, "crt_mem: %lld\n", (long long)crt_mem); #endif #ifndef NDEBUG fprintf(stderr, "mem_genomemap: max=%lld crt=%lld\n", (long long)count_get_max(&mem_genomemap), (long long)count_get_count(&mem_genomemap)); fprintf(stderr, "mem_mapping: max=%lld crt=%lld\n", (long long)count_get_max(&mem_mapping), (long long)count_get_count(&mem_mapping)); fprintf(stderr, "mem_thread_buffer: max=%lld crt=%lld\n", (long long)count_get_max(&mem_thread_buffer), (long long)count_get_count(&mem_thread_buffer)); fprintf(stderr, "mem_small: max=%lld crt=%lld\n", (long long)count_get_max(&mem_small), (long long)count_get_count(&mem_small)); fprintf(stderr, "mem_sw: max=%lld crt=%lld\n", (long long)count_get_max(&mem_sw), (long long)count_get_count(&mem_sw)); #endif return 0; }
GB_sparse_add_template.c
//------------------------------------------------------------------------------ // GB_sparse_add_template: C=A+B, C<M>=A+B when C is sparse/hypersparse //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // C is sparse or hypersparse: // ------------------------------------------ // C = A + B // ------------------------------------------ // sparse . sparse sparse // ------------------------------------------ // C <M> = A + B // ------------------------------------------ // sparse sparse sparse sparse // sparse sparse sparse bitmap // sparse sparse sparse full // sparse sparse bitmap sparse // sparse sparse bitmap bitmap // sparse sparse bitmap full // sparse sparse full sparse // sparse sparse full bitmap // sparse sparse full full // sparse bitmap sparse sparse // sparse full sparse sparse // ------------------------------------------ // C <!M> = A + B // ------------------------------------------ // sparse bitmap sparse sparse // sparse full sparse sparse // If all four matrices are sparse/hypersparse, and C<!M>=A+B is being // computed, then M is passed in as NULL to GB_add_phase*. GB_add_sparsity // returns apply_mask as false. The methods below do not handle the case when // C is sparse, M is sparse, and !M is used. All other uses of !M when M // is sparse result in a bitmap structure for C, and this is handled by // GB_bitmap_add_template. // For this case: the mask is done later, so C=A+B is computed here: // ------------------------------------------ // C <!M> = A + B // ------------------------------------------ // sparse sparse sparse sparse (mask later) { //-------------------------------------------------------------------------- // phase1: count entries in each C(:,j) // phase2: compute C //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(C_nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < C_ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- int64_t kfirst = TaskList [taskid].kfirst ; int64_t klast = TaskList [taskid].klast ; bool fine_task = (klast == -1) ; int64_t len ; if (fine_task) { // a fine task operates on a slice of a single vector klast = kfirst ; len = TaskList [taskid].len ; } else { // a coarse task operates on one or more whole vectors len = vlen ; } //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get j, the kth vector of C //------------------------------------------------------------------ int64_t j = GBH (Ch, k) ; #if defined ( GB_PHASE_1_OF_2 ) int64_t cjnz = 0 ; #else int64_t pC, pC_end ; if (fine_task) { // A fine task computes a slice of C(:,j) pC = TaskList [taskid ].pC ; pC_end = TaskList [taskid+1].pC ; ASSERT (Cp [k] <= pC && pC <= pC_end && pC_end <= Cp [k+1]) ; } else { // The vectors of C are never sliced for a coarse task. pC = Cp [k ] ; pC_end = Cp [k+1] ; } int64_t cjnz = pC_end - pC ; if (cjnz == 0) continue ; #endif //------------------------------------------------------------------ // get A(:,j) //------------------------------------------------------------------ int64_t pA = -1, pA_end = -1 ; if (fine_task) { // A fine task operates on Ai,Ax [pA...pA_end-1], which is // a subset of the vector A(:,j) pA = TaskList [taskid].pA ; pA_end = TaskList [taskid].pA_end ; } else { // A coarse task operates on the entire vector A (:,j) int64_t kA = (C_to_A == NULL) ? j : C_to_A [k] ; if (kA >= 0) { pA = GBP (Ap, kA, vlen) ; pA_end = GBP (Ap, kA+1, vlen) ; } } int64_t ajnz = pA_end - pA ; // nnz in A(:,j) for this slice int64_t pA_start = pA ; bool adense = (ajnz == len) ; // get the first and last indices in A(:,j) for this vector int64_t iA_first = -1, iA_last = -1 ; if (ajnz > 0) { iA_first = GBI (Ai, pA, vlen) ; iA_last = GBI (Ai, pA_end-1, vlen) ; } //------------------------------------------------------------------ // get B(:,j) //------------------------------------------------------------------ int64_t pB = -1, pB_end = -1 ; if (fine_task) { // A fine task operates on Bi,Bx [pB...pB_end-1], which is // a subset of the vector B(:,j) pB = TaskList [taskid].pB ; pB_end = TaskList [taskid].pB_end ; } else { // A coarse task operates on the entire vector B (:,j) int64_t kB = (C_to_B == NULL) ? j : C_to_B [k] ; if (kB >= 0) { pB = GBP (Bp, kB, vlen) ; pB_end = GBP (Bp, kB+1, vlen) ; } } int64_t bjnz = pB_end - pB ; // nnz in B(:,j) for this slice int64_t pB_start = pB ; bool bdense = (bjnz == len) ; // get the first and last indices in B(:,j) for this vector int64_t iB_first = -1, iB_last = -1 ; if (bjnz > 0) { iB_first = GBI (Bi, pB, vlen) ; iB_last = GBI (Bi, pB_end-1, vlen) ; } //------------------------------------------------------------------ // get M(:,j) if M is sparse or hypersparse //------------------------------------------------------------------ bool sparse_mask_is_easy = false ; int64_t pM = -1 ; int64_t pM_end = -1 ; if (M_is_sparse_or_hyper) { if (fine_task) { // A fine task operates on Mi,Mx [pM...pM_end-1], // which is a subset of the vector M(:,j) pM = TaskList [taskid].pM ; pM_end = TaskList [taskid].pM_end ; } else { int64_t kM = -1 ; if (Ch_is_Mh) { // Ch is the same as Mh (a deep copy) ASSERT (Ch != NULL) ; ASSERT (M_is_hyper) ; ASSERT (Ch [k] == M->h [k]) ; kM = k ; } else { kM = (C_to_M == NULL) ? j : C_to_M [k] ; } if (kM >= 0) { pM = GBP (Mp, kM , vlen) ; pM_end = GBP (Mp, kM+1, vlen) ; } } // The "easy mask" condition requires M to be sparse/hyper // and structural. A and B cannot be bitmap. Also one of // the following 3 conditions must hold: // (1) all entries are present in A(:,j) and B == M // (2) all entries are present in B(:,j) and A == M // (3) both A and B are aliased to M sparse_mask_is_easy = Mask_struct && // M must be structural !A_is_bitmap && // A must not be bitmap !B_is_bitmap && // B must not be bitmap ((adense && B == M) || // one of 3 conditions holds (bdense && A == M) || (A == M && B == M)) ; // TODO: add the condition above to GB_add_sparsity, // where adense/bdense are true for the whole matrix // (adense is true if A is full, or sparse/hypersparse with // all entries present). The test here is done vector by // vector, for each A(:,j) and B(:,j). This is a finer grain // test, as compared to a test for all of A and B. } //------------------------------------------------------------------ // C(:,j)<optional mask> = A (:,j) + B (:,j) or subvector //------------------------------------------------------------------ if (M == NULL) { //-------------------------------------------------------------- // M is not present, or !M is sparse but not applied here //-------------------------------------------------------------- // ------------------------------------------ // C = A + B // ------------------------------------------ // sparse . sparse sparse // ------------------------------------------ // C <!M> = A + B // ------------------------------------------ // sparse sparse sparse sparse (mask later) // If all four matrices are sparse or hypersparse, and // Mask_comp is true, the mask M is passed in to this method as // NULL. C=A+B is computed with no mask, and !M is applied // later. // A and B are both sparse or hypersparse, not bitmap or // full, but individual vectors of A and B might have all // entries present (adense and/or bdense). ASSERT (A_is_sparse || A_is_hyper) ; ASSERT (B_is_sparse || B_is_hyper) ; #if defined ( GB_PHASE_1_OF_2 ) if (A_and_B_are_disjoint) { // only used by GB_wait, which computes A+T where T is the // matrix of pending tuples for A. The pattern of pending // tuples is always disjoint with the pattern of A. cjnz = ajnz + bjnz ; } else #endif if (adense && bdense) { //---------------------------------------------------------- // Method01: A(:,j) and B(:,j) dense: thus C(:,j) dense //---------------------------------------------------------- ASSERT (ajnz == bjnz) ; ASSERT (iA_first == iB_first) ; ASSERT (iA_last == iB_last ) ; #if defined ( GB_PHASE_1_OF_2 ) cjnz = ajnz ; #else ASSERT (cjnz == ajnz) ; GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < ajnz ; p++) { // C (i,j) = A (i,j) + B (i,j) int64_t i = p + iA_first ; Ci [pC + p] = i ; ASSERT (Ai [pA + p] == i) ; ASSERT (Bi [pB + p] == i) ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA + p, A_iso) ; GB_LOAD_B (bij, Bx, pB + p, B_iso) ; GB_BINOP (GB_CX (pC + p), aij, bij, i, j) ; #endif } #endif } else if (adense) { //---------------------------------------------------------- // Method02: A(:,j) dense, B(:,j) sparse: C(:,j) dense //---------------------------------------------------------- #if defined ( GB_PHASE_1_OF_2 ) cjnz = ajnz ; #else ASSERT (cjnz == ajnz) ; GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < ajnz ; p++) { int64_t i = p + iA_first ; Ci [pC + p] = i ; ASSERT (Ai [pA + p] == i) ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA+p, A_iso) ; GB_BINOP (GB_CX (pC+p), aij, beta_scalar, i, j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC+p), Ax, pA+p, A_iso) ; } #endif #endif } GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < bjnz ; p++) { // C (i,j) = A (i,j) + B (i,j) int64_t i = Bi [pB + p] ; int64_t ii = i - iA_first ; ASSERT (Ai [pA + ii] == i) ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA + ii, A_iso) ; GB_LOAD_B (bij, Bx, pB + p, B_iso) ; GB_BINOP (GB_CX (pC + ii), aij, bij, i, j) ; #endif } #endif } else if (bdense) { //---------------------------------------------------------- // Method03: A(:,j) sparse, B(:,j) dense: C(:,j) dense //---------------------------------------------------------- #if defined ( GB_PHASE_1_OF_2 ) cjnz = bjnz ; #else ASSERT (cjnz == bjnz) ; GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < bjnz ; p++) { int64_t i = p + iB_first ; Ci [pC + p] = i ; ASSERT (Bi [pB + p] == i) ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB+p, B_iso) ; GB_BINOP (GB_CX (pC+p), alpha_scalar, bij, i, j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC+p), Bx, pB+p, B_iso) ; } #endif #endif } GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < ajnz ; p++) { // C (i,j) = A (i,j) + B (i,j) int64_t i = Ai [pA + p] ; int64_t ii = i - iB_first ; ASSERT (Bi [pB + ii] == i) ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA + p, A_iso) ; GB_LOAD_B (bij, Bx, pB + ii, B_iso) ; GB_BINOP (GB_CX (pC + ii), aij, bij, i, j) ; #endif } #endif } else if (ajnz == 0) { //---------------------------------------------------------- // Method04: A(:,j) is empty //---------------------------------------------------------- #if defined ( GB_PHASE_1_OF_2 ) cjnz = bjnz ; #else ASSERT (cjnz == bjnz) ; memcpy (Ci + pC, Bi + pB, bjnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < bjnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB+p, B_iso) ; GB_BINOP (GB_CX (pC+p), alpha_scalar, bij, Bi [pB+p], j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC+p), Bx, pB+p, B_iso) ; } #endif } #endif #endif } else if (bjnz == 0) { //---------------------------------------------------------- // Method05: B(:,j) is empty //---------------------------------------------------------- #if defined ( GB_PHASE_1_OF_2 ) cjnz = ajnz ; #else ASSERT (cjnz == ajnz) ; memcpy (Ci + pC, Ai + pA, ajnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < ajnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA+p, A_iso) ; GB_BINOP (GB_CX (pC+p), aij, beta_scalar, Ai [pA+p], j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC+p), Ax, pA+p, A_iso) ; } #endif } #endif #endif } else if (iA_last < iB_first) { //---------------------------------------------------------- // Method06: last A(:,j) comes before 1st B(:,j) //---------------------------------------------------------- #if defined ( GB_PHASE_1_OF_2 ) cjnz = ajnz + bjnz ; #else ASSERT (cjnz == ajnz + bjnz) ; memcpy (Ci + pC, Ai + pA, ajnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < ajnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA+p, A_iso) ; GB_BINOP (GB_CX (pC+p), aij, beta_scalar, Ai [pA+p], j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC+p), Ax, pA+p, A_iso) ; } #endif } #endif pC += ajnz ; memcpy (Ci + pC, Bi + pB, bjnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < bjnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB+p, B_iso) ; GB_BINOP (GB_CX (pC+p), alpha_scalar, bij, Bi [pB+p], j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC+p), Bx, pB+p, B_iso) ; } #endif } #endif #endif } else if (iB_last < iA_first) { //---------------------------------------------------------- // Method07: last B(:,j) comes before 1st A(:,j) //---------------------------------------------------------- #if defined ( GB_PHASE_1_OF_2 ) cjnz = ajnz + bjnz ; #else ASSERT (cjnz == ajnz + bjnz) ; memcpy (Ci + pC, Bi + pB, bjnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < bjnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB+p, B_iso) ; GB_BINOP (GB_CX (pC+p), alpha_scalar, bij, Bi [pB+p], j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC+p), Bx, pB+p, B_iso) ; } #endif } #endif pC += bjnz ; memcpy (Ci + pC, Ai + pA, ajnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < ajnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA+p, A_iso) ; GB_BINOP (GB_CX (pC+p), aij, beta_scalar, Ai [pA+p], j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC+p), Ax, pA+p, A_iso) ; } #endif } #endif #endif } #if defined ( GB_PHASE_1_OF_2 ) else if (ajnz > 32 * bjnz) { //---------------------------------------------------------- // Method08: A(:,j) is much denser than B(:,j) //---------------------------------------------------------- // cjnz = ajnz + bjnz - nnz in the intersection cjnz = ajnz + bjnz ; for ( ; pB < pB_end ; pB++) { int64_t i = Bi [pB] ; // find i in A(:,j) int64_t pright = pA_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Ai, pA, pright, found) ; if (found) cjnz-- ; } } else if (bjnz > 32 * ajnz) { //---------------------------------------------------------- // Method09: B(:,j) is much denser than A(:,j) //---------------------------------------------------------- // cjnz = ajnz + bjnz - nnz in the intersection cjnz = ajnz + bjnz ; for ( ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // find i in B(:,j) int64_t pright = pB_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Bi, pB, pright, found) ; if (found) cjnz-- ; } } #endif else { //---------------------------------------------------------- // Method10: A(:,j) and B(:,j) about the same sparsity //---------------------------------------------------------- while (pA < pA_end && pB < pB_end) { int64_t iA = Ai [pA] ; int64_t iB = Bi [pB] ; if (iA < iB) { #if defined ( GB_PHASE_2_OF_2 ) Ci [pC] = iA ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (iA,j) = A(iA,j) + beta GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_BINOP (GB_CX (pC), aij, beta_scalar, iA, j) ; } #else { // C (iA,j) = A (iA,j) GB_COPY_A_TO_C (GB_CX (pC), Ax, pA, A_iso) ; } #endif #endif #endif pA++ ; } else if (iA > iB) { #if defined ( GB_PHASE_2_OF_2 ) Ci [pC] = iB ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (iB,j) = alpha + B(iB,j) GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), alpha_scalar, bij, iB, j) ; } #else { // C (iB,j) = B (iB,j) GB_COPY_B_TO_C (GB_CX (pC), Bx, pB, B_iso) ; } #endif #endif #endif pB++ ; } else { // C (i,j) = A (i,j) + B (i,j) #if defined ( GB_PHASE_2_OF_2 ) Ci [pC] = iB ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), aij, bij, iB, j) ; #endif #endif pA++ ; pB++ ; } #if defined ( GB_PHASE_2_OF_2 ) pC++ ; #else cjnz++ ; #endif } //---------------------------------------------------------- // A (:,j) or B (:,j) have entries left; not both //---------------------------------------------------------- ajnz = (pA_end - pA) ; bjnz = (pB_end - pB) ; ASSERT (ajnz == 0 || bjnz == 0) ; #if defined ( GB_PHASE_1_OF_2 ) cjnz += ajnz + bjnz ; #else memcpy (Ci + pC, Ai + pA, ajnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD for (int64_t p = 0 ; p < ajnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA+p, A_iso) ; GB_BINOP (GB_CX (pC+p), aij, beta_scalar, Ai [pA+p], j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC+p), Ax, pA+p, A_iso) ; } #endif } #endif memcpy (Ci + pC, Bi + pB, bjnz * sizeof (int64_t)) ; #ifndef GB_ISO_ADD for (int64_t p = 0 ; p < bjnz ; p++) { #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB+p, B_iso) ; GB_BINOP (GB_CX (pC+p), alpha_scalar, bij, Bi [pB+p], j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC+p), Bx, pB+p, B_iso) ; } #endif } #endif ASSERT (pC + ajnz + bjnz == pC_end) ; #endif } } else if (sparse_mask_is_easy) { //-------------------------------------------------------------- // special case: M is present and very easy to use //-------------------------------------------------------------- // ------------------------------------------ // C <M> = A + B // ------------------------------------------ // sparse sparse sparse sparse // sparse sparse sparse full // sparse sparse full sparse // sparse sparse full full // A and B are sparse, hypersparse or full, not bitmap. ASSERT (!A_is_bitmap) ; ASSERT (!B_is_bitmap) ; ASSERT (Mask_struct) ; int64_t mjnz = pM_end - pM ; // nnz (M (:,j)) #if defined ( GB_PHASE_1_OF_2 ) // M is structural, and sparse or hypersparse, so every entry // in the mask is guaranteed to appear in A+B. The symbolic // count is thus trivial. cjnz = mjnz ; #else // copy the pattern into C (:,j) int64_t pC_start = pC ; int64_t pM_start = pM ; memcpy (Ci + pC, Mi + pM, mjnz * sizeof (int64_t)) ; int64_t pA_offset = pA_start - iA_first ; int64_t pB_offset = pB_start - iB_first ; if (adense && B == M) { //---------------------------------------------------------- // Method11: A dense, B == M //---------------------------------------------------------- GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < mjnz ; p++) { int64_t pM = p + pM_start ; int64_t pC = p + pC_start ; int64_t i = Mi [pM] ; ASSERT (GB_mcast (Mx, pM, msize)) ; ASSERT (GBI (Ai, pA_offset + i, vlen) == i) ; ASSERT (GBI (Bi, pM, vlen) == i) ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA_offset + i, A_iso) ; GB_LOAD_B (bij, Bx, pM, B_iso) ; GB_BINOP (GB_CX (pC), aij, bij, i, j) ; #endif } } else if (bdense && A == M) { //---------------------------------------------------------- // Method12: B dense, A == M //---------------------------------------------------------- GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < mjnz ; p++) { int64_t pM = p + pM_start ; int64_t pC = p + pC_start ; int64_t i = Mi [pM] ; ASSERT (GB_mcast (Mx, pM, msize)) ; ASSERT (GBI (Ai, pM, vlen) == i) ; ASSERT (GBI (Bi, pB_offset + i, vlen) == i) ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pM, A_iso) ; GB_LOAD_B (bij, Bx, pB_offset + i, B_iso) ; GB_BINOP (GB_CX (pC), aij, bij, i, j) ; #endif } } else // (A == M) && (B == M) { //---------------------------------------------------------- // Method13: A == M == B: all three matrices the same //---------------------------------------------------------- #ifndef GB_ISO_ADD GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = 0 ; p < mjnz ; p++) { int64_t pM = p + pM_start ; int64_t pC = p + pC_start ; #if GB_OP_IS_SECOND GB_LOAD_B (t, Bx, pM, B_iso) ; #else GB_LOAD_A (t, Ax, pM, A_iso) ; #endif GB_BINOP (GB_CX (pC), t, t, Mi [pM], j) ; } #endif } #endif } else if (M_is_sparse_or_hyper) { //-------------------------------------------------------------- // Method14: C and M are sparse or hypersparse //-------------------------------------------------------------- // ------------------------------------------ // C <M> = A + B // ------------------------------------------ // sparse sparse sparse sparse (*) // sparse sparse sparse bitmap (*) // sparse sparse sparse full (*) // sparse sparse bitmap sparse (*) // sparse sparse bitmap bitmap (+) // sparse sparse bitmap full (+) // sparse sparse full sparse (*) // sparse sparse full bitmap (+) // sparse sparse full full (+) // (*) This method is efficient except when either A or B are // sparse, and when M is sparse but with many entries. When M // is sparse and either A or B are sparse, the method is // designed to be very efficient when M is very sparse compared // with A and/or B. It traverses all entries in the sparse M, // and (for sparse A or B) does a binary search for entries in // A or B. In that case, if M has many entries, the mask M // should be ignored, and C=A+B should be computed without any // mask. The test for when to use M here should ignore A or B // if they are bitmap or full. // (+) TODO: if C and M are sparse/hyper, and A and B are // both bitmap/full, then use GB_emult_04_template instead, // but with (Ab [p] || Bb [p]) instead of (Ab [p] && Bb [p]). // A and B can have any sparsity pattern (hypersparse, // sparse, bitmap, or full). for ( ; pM < pM_end ; pM++) { //---------------------------------------------------------- // get M(i,j) for A(i,j) + B (i,j) //---------------------------------------------------------- int64_t i = Mi [pM] ; bool mij = GB_mcast (Mx, pM, msize) ; if (!mij) continue ; //---------------------------------------------------------- // get A(i,j) //---------------------------------------------------------- bool afound ; if (adense) { // A is dense, bitmap, or full; use quick lookup pA = pA_start + (i - iA_first) ; afound = GBB (Ab, pA) ; } else if (A == M) { // A is aliased to M pA = pM ; afound = true ; } else { // A is sparse; use binary search. This is slow unless // M is very sparse compared with A. int64_t apright = pA_end - 1 ; GB_BINARY_SEARCH (i, Ai, pA, apright, afound) ; } ASSERT (GB_IMPLIES (afound, GBI (Ai, pA, vlen) == i)) ; //---------------------------------------------------------- // get B(i,j) //---------------------------------------------------------- bool bfound ; if (bdense) { // B is dense; use quick lookup pB = pB_start + (i - iB_first) ; bfound = GBB (Bb, pB) ; } else if (B == M) { // B is aliased to M pB = pM ; bfound = true ; } else { // B is sparse; use binary search. This is slow unless // M is very sparse compared with B. int64_t bpright = pB_end - 1 ; GB_BINARY_SEARCH (i, Bi, pB, bpright, bfound) ; } ASSERT (GB_IMPLIES (bfound, GBI (Bi, pB, vlen) == i)) ; //---------------------------------------------------------- // C(i,j) = A(i,j) + B(i,j) //---------------------------------------------------------- if (afound && bfound) { // C (i,j) = A (i,j) + B (i,j) #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), aij, bij, i, j) ; #endif pC++ ; #endif } else if (afound) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_BINOP (GB_CX (pC), aij, beta_scalar, i, j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC), Ax, pA, A_iso) ; } #endif #endif pC++ ; #endif } else if (bfound) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), alpha_scalar, bij, i, j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC), Bx, pB, B_iso) ; } #endif #endif pC++ ; #endif } } #if defined ( GB_PHASE_2_OF_2 ) ASSERT (pC == pC_end) ; #endif } else { //-------------------------------------------------------------- // M is bitmap or full, for either C<M>=A+B or C<!M>=A+B //-------------------------------------------------------------- // ------------------------------------------ // C <M> = A + B // ------------------------------------------ // sparse bitmap sparse sparse // sparse full sparse sparse // ------------------------------------------ // C <!M> = A + B // ------------------------------------------ // sparse bitmap sparse sparse // sparse full sparse sparse // This method is very efficient for any mask, and should // always be used if M is bitmap or full, even if the mask must // also be applied later in GB_mask or GB_accum_mask. // Exploiting the mask here adds no extra search time, and it // reduces the size of C on output. // GB_GET_MIJ: get M(i,j) where M is bitmap or full #undef GB_GET_MIJ #define GB_GET_MIJ(i) \ int64_t pM = pM_start + i ; \ bool mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ; \ if (Mask_comp) mij = !mij ; // A and B are sparse or hypersparse, not bitmap or full, // but individual vectors of A and B might have all entries // present (adense and/or bdense). ASSERT (A_is_sparse || A_is_hyper) ; ASSERT (B_is_sparse || B_is_hyper) ; int64_t pM_start = j * vlen ; if (adense && bdense) { //---------------------------------------------------------- // Method15: A(:,j) and B(:,j) dense, M bitmap/full //---------------------------------------------------------- ASSERT (ajnz == bjnz) ; ASSERT (iA_first == iB_first) ; ASSERT (iA_last == iB_last ) ; for (int64_t p = 0 ; p < ajnz ; p++) { int64_t i = p + iA_first ; ASSERT (Ai [pA + p] == i) ; ASSERT (Bi [pB + p] == i) ; GB_GET_MIJ (i) ; if (mij) { // C (i,j) = A (i,j) + B (i,j) #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA + p, A_iso) ; GB_LOAD_B (bij, Bx, pB + p, B_iso) ; GB_BINOP (GB_CX (pC), aij, bij, i, j) ; #endif pC++ ; #endif } } } else if (ajnz == 0) { //---------------------------------------------------------- // Method16: A(:,j) is empty, M bitmap/full //---------------------------------------------------------- for ( ; pB < pB_end ; pB++) { int64_t i = Bi [pB] ; GB_GET_MIJ (i) ; if (mij) { // C (i,j) = B (i,j), or alpha + B(i,j) #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), alpha_scalar, bij, i, j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC), Bx, pB, B_iso) ; } #endif #endif pC++ ; #endif } } } else if (bjnz == 0) { //---------------------------------------------------------- // Method17: B(:,j) is empty, M bitmap/full //---------------------------------------------------------- for ( ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; GB_GET_MIJ (i) ; if (mij) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_BINOP (GB_CX (pC), aij, beta_scalar, i, j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC), Ax, pA, A_iso) ; } #endif #endif pC++ ; #endif } } } else if (iA_last < iB_first) { //---------------------------------------------------------- // Method18:last A(:,j) before 1st B(:,j), M bitmap/full //---------------------------------------------------------- for ( ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; GB_GET_MIJ (i) ; if (mij) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_BINOP (GB_CX (pC), aij, beta_scalar, i, j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC), Ax, pA, A_iso) ; } #endif #endif pC++ ; #endif } } for ( ; pB < pB_end ; pB++) { int64_t i = Bi [pB] ; GB_GET_MIJ (i) ; if (mij) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), alpha_scalar, bij, i, j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC), Bx, pB, B_iso) ; } #endif #endif pC++ ; #endif } } } else if (iB_last < iA_first) { //---------------------------------------------------------- // Method19:last B(:,j) before 1st A(:,j), M bitmap/full //---------------------------------------------------------- for ( ; pB < pB_end ; pB++) { int64_t i = Bi [pB] ; GB_GET_MIJ (i) ; if (mij) { // C (i,j) = B (i,j), or alpha + B(i,j) #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = alpha + B(i,j) GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), alpha_scalar, bij, i, j) ; } #else { // C (i,j) = B (i,j) GB_COPY_B_TO_C (GB_CX (pC), Bx, pB, B_iso) ; } #endif #endif pC++ ; #endif } } for ( ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; GB_GET_MIJ (i) ; if (mij) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = i ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (i,j) = A(i,j) + beta GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_BINOP (GB_CX (pC), aij, beta_scalar, i, j) ; } #else { // C (i,j) = A (i,j) GB_COPY_A_TO_C (GB_CX (pC), Ax, pA, A_iso) ; } #endif #endif pC++ ; #endif } } } else { //---------------------------------------------------------- // Method20: merge A(:,j) and B(:,j), M bitmap/full //---------------------------------------------------------- while (pA < pA_end && pB < pB_end) { int64_t iA = Ai [pA] ; int64_t iB = Bi [pB] ; if (iA < iB) { GB_GET_MIJ (iA) ; if (mij) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = iA ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (iA,j) = A(iA,j) + beta GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_BINOP (GB_CX (pC), aij, beta_scalar, iA, j); } #else { // C (iA,j) = A (iA,j) GB_COPY_A_TO_C (GB_CX (pC), Ax, pA, A_iso) ; } #endif #endif pC++ ; #endif } pA++ ; } else if (iA > iB) { GB_GET_MIJ (iB) ; if (mij) { // C (iB,j) = B (iB,j), or alpha + B(iB,j) #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = iB ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (iB,j) = alpha + B(iB,j) GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), alpha_scalar, bij, iB, j) ; } #else { // C (iB,j) = B (iB,j) GB_COPY_B_TO_C (GB_CX (pC), Bx, pB, B_iso) ; } #endif #endif pC++ ; #endif } pB++ ; } else { GB_GET_MIJ (iB) ; if (mij) { // C (i,j) = A (i,j) + B (i,j) #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = iB ; #ifndef GB_ISO_ADD GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), aij, bij, iB, j) ; #endif pC++ ; #endif } pA++ ; pB++ ; } } //---------------------------------------------------------- // A (:,j) or B (:,j) have entries left; not both //---------------------------------------------------------- for ( ; pA < pA_end ; pA++) { int64_t iA = Ai [pA] ; GB_GET_MIJ (iA) ; if (mij) { #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = iA ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (iA,j) = A(iA,j) + beta GB_LOAD_A (aij, Ax, pA, A_iso) ; GB_BINOP (GB_CX (pC), aij, beta_scalar, iA, j) ; } #else { // C (iA,j) = A (iA,j) GB_COPY_A_TO_C (GB_CX (pC), Ax, pA, A_iso) ; } #endif #endif pC++ ; #endif } } for ( ; pB < pB_end ; pB++) { int64_t iB = Bi [pB] ; GB_GET_MIJ (iB) ; if (mij) { // C (iB,j) = B (iB,j), or alpha + B(iB,j) #if defined ( GB_PHASE_1_OF_2 ) cjnz++ ; #else Ci [pC] = iB ; #ifndef GB_ISO_ADD #ifdef GB_EWISEUNION { // C (iB,j) = alpha + B(iB,j) GB_LOAD_B (bij, Bx, pB, B_iso) ; GB_BINOP (GB_CX (pC), alpha_scalar, bij, iB, j) ; } #else { // C (iB,j) = B (iB,j) GB_COPY_B_TO_C (GB_CX (pC), Bx, pB, B_iso) ; } #endif #endif pC++ ; #endif } } } } //------------------------------------------------------------------ // final count of nnz (C (:,j)) //------------------------------------------------------------------ #if defined ( GB_PHASE_1_OF_2 ) if (fine_task) { TaskList [taskid].pC = cjnz ; } else { Cp [k] = cjnz ; } #endif } } }
ptc.c
/*! \file \brief The OpenMP triangle counting routine \date Started 1/14/2018 \author George \version\verbatim $Id: cmdline.c 20946 2017-05-10 23:12:48Z karypis $ \endverbatim */ #include "tc.h" #define SBSIZE 64 #define DBSIZE 8 /*************************************************************************/ /*! Reorders the vertices in the graph in inc degree order and returns the re-ordered graph in which the adjancency lists are sorted in increasing order. In addition, a diagonal entry is added to each row to make the code that follows tighter. */ /*************************************************************************/ gk_graph_t *ptc_Preprocess(params_t *params, vault_t *vault) { int32_t vi, nvtxs, nthreads, maxdegree=0, csrange=0; ssize_t *xadj, *nxadj, *psums; int32_t *adjncy, *nadjncy, *perm=NULL, *iperm=NULL, *chunkptr=NULL; int32_t *gcounts; gk_graph_t *graph; nthreads = params->nthreads; nvtxs = vault->graph->nvtxs; xadj = vault->graph->xadj; adjncy = vault->graph->adjncy; graph = gk_graph_Create(); graph->nvtxs = nvtxs; graph->xadj = nxadj = gk_zmalloc(nvtxs+1, "nxadj"); graph->adjncy = nadjncy = gk_i32malloc(nvtxs+xadj[nvtxs], "nadjncy"); perm = gk_i32malloc(nvtxs, "perm"); /* perm[old-vtx-num] => new-vtx-num */ iperm = gk_i32malloc(nvtxs, "iperm"); /* iperm[new-vtx-num] => old-vtx-num */ /* Determine maxdegree/csrange */ #pragma omp parallel for schedule(static,4096) default(none) \ shared(nvtxs, xadj) \ reduction(max: maxdegree) for (vi=0; vi<nvtxs; vi++) maxdegree = gk_max(maxdegree, (int32_t)(xadj[vi+1]-xadj[vi])); csrange = maxdegree+1; csrange = 16*((csrange+15)/16); /* get the per thread arrays to be alligned at the start of the cache line */ gcounts = gk_i32malloc(nthreads*csrange, "gcounts"); psums = gk_zmalloc(nthreads, "psums"); #pragma omp parallel default(none) \ shared(vault, nvtxs, nthreads, maxdegree, csrange, xadj, adjncy, nxadj, nadjncy, \ perm, iperm, gcounts, psums, chunkptr, stdout) { int32_t vi, vistart, viend, vj, nedges, nchunks; int32_t ti, di, ci, dstart, dend; int32_t *counts, *buffer; ssize_t ej, ejend, psum, chunksize; #if defined(_OPENMP) int mytid = omp_get_thread_num(); #else int mytid = 0; #endif vistart = mytid*((nvtxs+nthreads-1)/nthreads); viend = gk_min(nvtxs, (mytid+1)*((nvtxs+nthreads-1)/nthreads)); dstart = mytid*((csrange+nthreads-1)/nthreads); dend = gk_min(csrange, (mytid+1)*((csrange+nthreads-1)/nthreads)); /* Compute the local counts */ counts = gcounts + mytid*csrange; gk_i32set(csrange, 0, counts); for (vi=vistart; vi<viend; vi++) counts[xadj[vi+1]-xadj[vi]]++; #pragma omp barrier /* Compute the partial sum of the range assigned to each thread */ for (psum=0, ti=0; ti<nthreads; ti++) { counts = gcounts + ti*csrange; for (di=dstart; di<dend; di++) psum += counts[di]; } psums[mytid] = psum; #pragma omp barrier #pragma omp single for (ti=1; ti<nthreads; ti++) psums[ti] += psums[ti-1]; #pragma omp barrier /* Compute the actual prefix sums of the range assigned to each thread. This is done from right to left to get it into the desired exclusive prefix sum stage. */ psum = psums[mytid]; for (di=dend-1; di>=dstart; di--) { counts = gcounts + (nthreads-1)*csrange; for (ti=nthreads-1; ti>=0; ti--) { psum -= counts[di]; counts[di] = psum; counts -= csrange; } } #pragma omp barrier /* Create the perm/iperm arrays and the nxadj array of the re-ordered graph */ counts = gcounts + mytid*csrange; /* TODO: This can be optimized by pre-sorting the per-thread vertices according to their degree and processing them in increasing degree order */ for (vi=vistart; vi<viend; vi++) { perm[vi] = counts[xadj[vi+1]-xadj[vi]]++; nxadj[perm[vi]] = xadj[vi+1]-xadj[vi]+1; /* the +1 is for the diagonal */ iperm[perm[vi]] = vi; } #pragma omp barrier #pragma omp barrier /* compute the local sums and their prefix sums */ for (psum=0, vi=vistart; vi<viend; vi++) psum += nxadj[vi]; psums[mytid] = psum; #pragma omp barrier #pragma omp single for (ti=1; ti<nthreads; ti++) psums[ti] += psums[ti-1]; #pragma omp barrier /* Compute the actual prefix sums of the nxadj[] array assigned to each thread. This is done from right to left to get it into the desired exclusive prefix sum stage. */ psum = psums[mytid]; if (mytid == nthreads-1) nxadj[nvtxs] = psum; for (vi=viend-1; vi>=vistart; vi--) { psum -= nxadj[vi]; nxadj[vi] = psum; } #pragma omp barrier /* Compute the chunk-based partitioning of the work for the reordered/sorted graph */ chunksize = 1+psums[nthreads-1]/(100*nthreads); for (nchunks=0, psum=0, vi=vistart; vi<viend; vi++) { if ((psum += nxadj[vi+1]-nxadj[vi]) >= chunksize) { nchunks++; psum = 0; } } psums[mytid] = nchunks+1; #pragma omp barrier #pragma omp single for (ti=1; ti<nthreads; ti++) psums[ti] += psums[ti-1]; #pragma omp barrier #pragma omp single chunkptr = gk_i32malloc(psums[nthreads-1]+1, "chunkptr"); #pragma omp barrier nchunks = psums[mytid]; chunkptr[nchunks] = viend; for (psum=0, vi=viend-1; vi>=vistart; vi--) { if ((psum += nxadj[vi+1]-nxadj[vi]) >= chunksize) { chunkptr[--nchunks] = vi; psum = 0; } } if (mytid == 0) chunkptr[0] = 0; #pragma omp barrier nchunks = psums[nthreads-1]; /* this is the total # of chunks */ /* #pragma omp single { for (vi=0; vi<nchunks; vi++) { printf("%4d: %6d - %6d [%5d: %zd]\n", vi, chunkptr[vi], chunkptr[vi+1], chunkptr[vi+1]-chunkptr[vi], nxadj[chunkptr[vi+1]]-nxadj[chunkptr[vi]]); } } #pragma omp barrier */ /* create the reordered/sorted graph by processing the chunks in parallel */ #pragma omp for schedule(dynamic, 1) nowait for (ci=nchunks-1; ci>=0; ci--) { for (vi=chunkptr[ci]; vi<chunkptr[ci+1]; vi++) { vj = iperm[vi]; buffer = nadjncy+nxadj[vi]; for (nedges=0, ej=xadj[vj], ejend=xadj[vj+1]; ej<ejend; ej++, nedges++) buffer[nedges] = perm[adjncy[ej]]; buffer[nedges++] = vi; /* put the diagonal */ if (nedges > 1) gk_i32sorti(nedges, buffer); /* sort adjncy list */ } } } gk_free((void **)&perm, &iperm, &gcounts, &psums, &chunkptr, LTERM); return graph; } /*************************************************************************/ /*! The hash-map-based triangle-counting routine that uses the JIK triangle enumeration scheme. This version implements the following: - It does not store location information in L - Adds diagonal entries in U to make loops tighter - Reverts the order within U's adjancency lists to allow ++ traversal */ /*************************************************************************/ int64_t ptc_MapJIK(params_t *params, vault_t *vault) { int32_t vi, vj, nvtxs, startv; ssize_t ei, ej; int64_t ntriangles=0; ssize_t *xadj, *uxadj; int32_t *adjncy; int32_t l2, maxhmsize=0; gk_graph_t *graph; uint64_t nprobes=0; gk_startwctimer(vault->timer_pp); graph = ptc_Preprocess(params, vault); gk_stopwctimer(vault->timer_pp); nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; uxadj = gk_zmalloc(nvtxs, "uxadj"); /* the locations of the upper triangular part */ gk_startwctimer(vault->timer_tc); /* populate uxadj[] and determine the size of the hash-map */ startv = nvtxs; #pragma omp parallel for schedule(dynamic,1024) \ default(none) \ shared(nvtxs, xadj, adjncy, uxadj) \ private(vj, ei, ej) \ reduction(max: maxhmsize) \ reduction(min: startv) for (vi=nvtxs-1; vi>=0; vi--) { for (ei=xadj[vi+1]-1; adjncy[ei]>vi; ei--); uxadj[vi] = ei; maxhmsize = gk_max(maxhmsize, (int32_t)(xadj[vi+1]-uxadj[vi])); startv = (uxadj[vi] != xadj[vi] ? vi : startv); /* flip the order of Adj(vi)'s upper triangular adjacency list */ for (ej=xadj[vi+1]-1; ei<ej; ei++, ej--) { vj = adjncy[ei]; adjncy[ei] = adjncy[ej]; adjncy[ej] = vj; } } /* convert the hash-map is converted into a format that is compatible with a bitwise AND operation */ for (l2=1; maxhmsize>(1<<l2); l2++); maxhmsize = (1<<(l2+4))-1; printf("& compatible maxhmsize: %"PRId32", startv: %d\n", maxhmsize, startv); #pragma omp parallel default(none) \ shared(params, vault, nvtxs, xadj, adjncy, uxadj, maxhmsize, startv, stdout) \ reduction(+: ntriangles, nprobes) { int32_t vi, vj, vk, vl, nlocal; ssize_t ei, eiend, eistart, ej, ejend, ejstart; int32_t l, nc; int32_t l2=1, hmsize=(1<<(l2+4))-1, *hmap; #if defined(_OPENMP) int mytid = omp_get_thread_num(); #else int mytid = 0; #endif hmap = gk_i32smalloc(maxhmsize+1, 0, "hmap"); /* Phase 1: Count triangles for vj < nvtxs-maxhmsize */ #pragma omp for schedule(dynamic,SBSIZE) nowait for (vj=startv; vj<nvtxs-maxhmsize; vj++) { if (xadj[vj+1]-uxadj[vj] == 1 || xadj[vj] == uxadj[vj]) continue; /* adjust hmsize if needed */ if (xadj[vj+1]-uxadj[vj] > (1<<l2)) { for (++l2; (xadj[vj+1]-uxadj[vj])>(1<<l2); l2++); hmsize = (1<<(l2+4))-1; } /* hash Adj(vj) */ for (nc=0, ej=uxadj[vj], ejend=xadj[vj+1]-1; ej<ejend; ej++) { vk = adjncy[ej]; for (l=(vk&hmsize); hmap[l]!=0; l=((l+1)&hmsize), nc++); hmap[l] = vk; } nlocal = 0; /* find intersections */ if (nc > 0) { /* we had collisions */ for (ej=xadj[vj], ejend=uxadj[vj]; ej<ejend; ej++) { vi = adjncy[ej]; for (ei=uxadj[vi]; adjncy[ei]>vj; ei++) { vk = adjncy[ei]; for (l=vk&hmsize; hmap[l]!=0 && hmap[l]!=vk; l=((l+1)&hmsize)); if (hmap[l] == vk) nlocal++; } nprobes += ei-uxadj[vi]; } /* reset hash */ for (ej=uxadj[vj], ejend=xadj[vj+1]-1; ej<ejend; ej++) { vk = adjncy[ej]; for (l=(vk&hmsize); hmap[l]!=vk; l=((l+1)&hmsize)); hmap[l] = 0; } } else { /* there were no collisons */ for (ej=xadj[vj], ejend=uxadj[vj]; ej<ejend; ej++) { vi = adjncy[ej]; #ifdef TC_VECOPT for (eiend=uxadj[vi]; adjncy[eiend]>vj; eiend++); for (ei=uxadj[vi]; ei<eiend; ei++) #else for (ei=uxadj[vi]; adjncy[ei]>vj; ei++) #endif { vk = adjncy[ei]; nlocal += (hmap[vk&hmsize] == vk); } nprobes += ei-uxadj[vi]; } /* reset hash */ for (ej=uxadj[vj], ejend=xadj[vj+1]-1; ej<ejend; ej++) hmap[adjncy[ej]&hmsize] = 0; } if (nlocal > 0) ntriangles += nlocal; } /* Phase 2: Count triangles for the last hmsize vertices, which can be done faster by using hmap as a direct map array. */ hmap -= (nvtxs - maxhmsize); #pragma omp for schedule(dynamic,DBSIZE) nowait for (vj=nvtxs-1; vj>=nvtxs-maxhmsize; vj--) { if (xadj[vj+1]-uxadj[vj] == 1 || xadj[vj] == uxadj[vj]) continue; nlocal = 0; if (xadj[vj+1]-uxadj[vj] == nvtxs-vj) { /* complete row */ /* find intersections */ for (ej=xadj[vj], ejend=uxadj[vj]; ej<ejend; ej++) { vi = adjncy[ej]; for (ei=uxadj[vi]; adjncy[ei]>vj; ei++); nlocal += ei-uxadj[vi]; nprobes += ei-uxadj[vi]; } } else { /* hash Adj(vj) */ for (ej=uxadj[vj], ejend=xadj[vj+1]-1; ej<ejend; ej++) hmap[adjncy[ej]] = 1; /* find intersections */ for (ej=xadj[vj], ejend=uxadj[vj]; ej<ejend; ej++) { vi = adjncy[ej]; #ifdef TC_VECOPT for (eiend=uxadj[vi]; adjncy[eiend]>vj; eiend++); for (ei=uxadj[vi]; ei<eiend; ei++) #else for (ei=uxadj[vi]; adjncy[ei]>vj; ei++) #endif nlocal += hmap[adjncy[ei]]; nprobes += ei-uxadj[vi]; } /* reset hash */ for (ej=uxadj[vj], ejend=xadj[vj+1]-1; ej<ejend; ej++) hmap[adjncy[ej]] = 0; } if (nlocal > 0) ntriangles += nlocal; } hmap += (nvtxs - maxhmsize); gk_free((void **)&hmap, LTERM); } gk_stopwctimer(vault->timer_tc); gk_graph_Free(&graph); gk_free((void **)&uxadj, LTERM); vault->nprobes = nprobes; return ntriangles; }
Distribution.h
// // Created by Tobias Hahnen on 2019-08-06. // #pragma once #ifndef AIOLOS_DISTRIBUTION_H #define AIOLOS_DISTRIBUTION_H #include "Scheme1.h" #include "Scheme2.h" #include "Scheme3.h" /** * CANNOT SPLIT FILE IN DEFINITION (.h) AND IMPLEMENTATION (.cpp)! * See: https://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible */ namespace GLCM { /** * Calculates the degree of concentration of a GLCM (equals the Z-function from the paper) * * @param glcm the GLCM, to work on * @return the degree of concentration * * NOBUG: Do not change x/y to unsigned => would break everything! * REVIEW: Usage does not depend on specific Mat-Type (CT nor RT) */ double concentration_degree(const cv::Mat1d& glcm) { double value = 0; #pragma omp parallel for collapse(2) reduction(+:value) for (int x = 0; x < glcm.cols; x++) { for (int y = 0; y < glcm.rows; y++) { value += ( pow((y+1)-(x+1), 2) * glcm(y, x) ); } } return value; } /** * Calculates the degree of concentration of a GLCM using an increasing function (equals the Z-function from the paper) * * @param glcm the GLCM, to work on * @param inc the incresing function * @return the degree of concentration * * NOBUG: Do not change x/y to unsigned => would break everything! * REVIEW: Usage does not depend on specific Mat-Type (CT nor RT) */ /*double concentration_degree(const cv::Mat1d& glcm, double (*inc)(int, int)) { double value = 0; #pragma omp parallel for collapse(2) reduction(+:value) for (int x = 0; x < glcm.cols; x++) { for (int y = 0; y < glcm.rows; y++) { value += ( inc(x+1, y+1) * glcm(y, x) ); } } return value; }*/ /** * Calculates values for all the given angles of Z(cv::Mat1d&) (equals the Z'-function from the paper) * * @tparam T single channel type: char/uchar, short/ushort, int * @param image the given image * @param angle_distribution all possible orientation angles * @param impl which implementation of the GLCM shall be used * @param max_radius the given maximum radius * @param begin the lowest angle, a GLCM shall be calculated for */ template <typename T> void calc_angle_dist(const cv::Mat_<T>& image, std::vector<double>& angle_distribution, Implementation impl, unsigned int max_radius, unsigned int begin) { int max_gray = Util::max_gray_value(image); // Outer loop beginning with range.first, ending after range.second #pragma omp parallel for shared(max_gray) for (unsigned int theta = 0; theta < angle_distribution.size(); theta++) { double theta_rad = (begin + theta) * CV_PI / 180; double value = 0.0; #pragma omp parallel for shared(max_gray, theta_rad) reduction(+:value) for (unsigned int r = 1; r <= max_radius; r++) { cv::Mat1d glcm(max_gray, max_gray, 0.0); // Which implementation of the paper shall be used! switch (impl) { case SCHEME1: Scheme1::GLCM(image, glcm, r, theta_rad); break; case SCHEME2: Scheme2::GLCM(image, glcm, r, theta_rad); break; case SCHEME3: Scheme3::GLCM(image, glcm, r, theta_rad); break; case STANDARD: Standard::GLCM(image, glcm, r, theta_rad); } value += concentration_degree(glcm); } angle_distribution[theta] = value; } } /** * Calculates the distribution for every angle R1 ... R2 (in degrees) * * @param image the given image * @param impl which implementation of the GLCM shall be used * @param max_radius the given maximum radius * @param range the range, which angles shall be considered * @return the filled vector of values (size: range.second - range.first + 1) */ std::vector<double> getAngleDistribution(const cv::Mat& image, Implementation impl, unsigned int max_radius, const Range& range) { std::vector<double> orientation_distribution(range.second - range.first + 1); auto begin = static_cast<unsigned int>(range.first); switch (image.type() & CV_MAT_DEPTH_MASK) { case CV_8SC1: calc_angle_dist((cv::Mat_<char>&) image, orientation_distribution, impl, max_radius, begin); break; case CV_8UC1: calc_angle_dist((cv::Mat_<uchar>&) image, orientation_distribution, impl, max_radius, begin); break; case CV_16SC1: calc_angle_dist((cv::Mat_<short>&) image, orientation_distribution, impl, max_radius, begin); break; case CV_16UC1: calc_angle_dist((cv::Mat_<ushort>&) image, orientation_distribution, impl, max_radius, begin); break; case CV_32SC1: calc_angle_dist((cv::Mat_<int>&) image, orientation_distribution, impl, max_radius, begin); break; default: throw std::logic_error("[GLCM::getAngleDistribution_] Unsupported Mat-type!"); } #if AIOLOS_DEBUG_ANGLE_DISTRIBUTION for (unsigned int i = 0; i < orientation_distribution.size(); i++) { std::cout << "Winkel " << range.first + i << "°: " << orientation_distribution[i] << std::endl; } #endif return orientation_distribution; } } #endif //AIOLOS_DISTRIBUTION_H
dds.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD DDDD SSSSS % % D D D D SS % % D D D D SSS % % D D D D SS % % DDDD DDDD SSSSS % % % % % % Read/Write Microsoft Direct Draw Surface Image Format % % % % Software Design % % Bianca van Schaik % % March 2008 % % Dirk Lemstra % % September 2013 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" #include "magick/transform.h" /* Definitions */ #define DDSD_CAPS 0x00000001 #define DDSD_HEIGHT 0x00000002 #define DDSD_WIDTH 0x00000004 #define DDSD_PITCH 0x00000008 #define DDSD_PIXELFORMAT 0x00001000 #define DDSD_MIPMAPCOUNT 0x00020000 #define DDSD_LINEARSIZE 0x00080000 #define DDSD_DEPTH 0x00800000 #define DDPF_ALPHAPIXELS 0x00000001 #define DDPF_FOURCC 0x00000004 #define DDPF_RGB 0x00000040 #define DDPF_LUMINANCE 0x00020000 #define FOURCC_DXT1 0x31545844 #define FOURCC_DXT3 0x33545844 #define FOURCC_DXT5 0x35545844 #define DDSCAPS_COMPLEX 0x00000008 #define DDSCAPS_TEXTURE 0x00001000 #define DDSCAPS_MIPMAP 0x00400000 #define DDSCAPS2_CUBEMAP 0x00000200 #define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400 #define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800 #define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000 #define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000 #define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000 #define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000 #define DDSCAPS2_VOLUME 0x00200000 #ifndef SIZE_MAX #define SIZE_MAX ((size_t) -1) #endif /* Structure declarations. */ typedef struct _DDSPixelFormat { size_t flags, fourcc, rgb_bitcount, r_bitmask, g_bitmask, b_bitmask, alpha_bitmask; } DDSPixelFormat; typedef struct _DDSInfo { size_t flags, height, width, pitchOrLinearSize, depth, mipmapcount, ddscaps1, ddscaps2; DDSPixelFormat pixelformat; } DDSInfo; typedef struct _DDSColors { unsigned char r[4], g[4], b[4], a[4]; } DDSColors; typedef struct _DDSVector4 { float x, y, z, w; } DDSVector4; typedef struct _DDSVector3 { float x, y, z; } DDSVector3; typedef struct _DDSSourceBlock { unsigned char start, end, error; } DDSSourceBlock; typedef struct _DDSSingleColourLookup { DDSSourceBlock sources[2]; } DDSSingleColourLookup; typedef MagickBooleanType DDSDecoder(Image *, DDSInfo *, ExceptionInfo *); static const DDSSingleColourLookup DDSLookup_5_4[] = { { { { 0, 0, 0 }, { 0, 0, 0 } } }, { { { 0, 0, 1 }, { 0, 1, 1 } } }, { { { 0, 0, 2 }, { 0, 1, 0 } } }, { { { 0, 0, 3 }, { 0, 1, 1 } } }, { { { 0, 0, 4 }, { 0, 2, 1 } } }, { { { 1, 0, 3 }, { 0, 2, 0 } } }, { { { 1, 0, 2 }, { 0, 2, 1 } } }, { { { 1, 0, 1 }, { 0, 3, 1 } } }, { { { 1, 0, 0 }, { 0, 3, 0 } } }, { { { 1, 0, 1 }, { 1, 2, 1 } } }, { { { 1, 0, 2 }, { 1, 2, 0 } } }, { { { 1, 0, 3 }, { 0, 4, 0 } } }, { { { 1, 0, 4 }, { 0, 5, 1 } } }, { { { 2, 0, 3 }, { 0, 5, 0 } } }, { { { 2, 0, 2 }, { 0, 5, 1 } } }, { { { 2, 0, 1 }, { 0, 6, 1 } } }, { { { 2, 0, 0 }, { 0, 6, 0 } } }, { { { 2, 0, 1 }, { 2, 3, 1 } } }, { { { 2, 0, 2 }, { 2, 3, 0 } } }, { { { 2, 0, 3 }, { 0, 7, 0 } } }, { { { 2, 0, 4 }, { 1, 6, 1 } } }, { { { 3, 0, 3 }, { 1, 6, 0 } } }, { { { 3, 0, 2 }, { 0, 8, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 0 }, { 0, 9, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 2 }, { 0, 10, 1 } } }, { { { 3, 0, 3 }, { 0, 10, 0 } } }, { { { 3, 0, 4 }, { 2, 7, 1 } } }, { { { 4, 0, 4 }, { 2, 7, 0 } } }, { { { 4, 0, 3 }, { 0, 11, 0 } } }, { { { 4, 0, 2 }, { 1, 10, 1 } } }, { { { 4, 0, 1 }, { 1, 10, 0 } } }, { { { 4, 0, 0 }, { 0, 12, 0 } } }, { { { 4, 0, 1 }, { 0, 13, 1 } } }, { { { 4, 0, 2 }, { 0, 13, 0 } } }, { { { 4, 0, 3 }, { 0, 13, 1 } } }, { { { 4, 0, 4 }, { 0, 14, 1 } } }, { { { 5, 0, 3 }, { 0, 14, 0 } } }, { { { 5, 0, 2 }, { 2, 11, 1 } } }, { { { 5, 0, 1 }, { 2, 11, 0 } } }, { { { 5, 0, 0 }, { 0, 15, 0 } } }, { { { 5, 0, 1 }, { 1, 14, 1 } } }, { { { 5, 0, 2 }, { 1, 14, 0 } } }, { { { 5, 0, 3 }, { 0, 16, 0 } } }, { { { 5, 0, 4 }, { 0, 17, 1 } } }, { { { 6, 0, 3 }, { 0, 17, 0 } } }, { { { 6, 0, 2 }, { 0, 17, 1 } } }, { { { 6, 0, 1 }, { 0, 18, 1 } } }, { { { 6, 0, 0 }, { 0, 18, 0 } } }, { { { 6, 0, 1 }, { 2, 15, 1 } } }, { { { 6, 0, 2 }, { 2, 15, 0 } } }, { { { 6, 0, 3 }, { 0, 19, 0 } } }, { { { 6, 0, 4 }, { 1, 18, 1 } } }, { { { 7, 0, 3 }, { 1, 18, 0 } } }, { { { 7, 0, 2 }, { 0, 20, 0 } } }, { { { 7, 0, 1 }, { 0, 21, 1 } } }, { { { 7, 0, 0 }, { 0, 21, 0 } } }, { { { 7, 0, 1 }, { 0, 21, 1 } } }, { { { 7, 0, 2 }, { 0, 22, 1 } } }, { { { 7, 0, 3 }, { 0, 22, 0 } } }, { { { 7, 0, 4 }, { 2, 19, 1 } } }, { { { 8, 0, 4 }, { 2, 19, 0 } } }, { { { 8, 0, 3 }, { 0, 23, 0 } } }, { { { 8, 0, 2 }, { 1, 22, 1 } } }, { { { 8, 0, 1 }, { 1, 22, 0 } } }, { { { 8, 0, 0 }, { 0, 24, 0 } } }, { { { 8, 0, 1 }, { 0, 25, 1 } } }, { { { 8, 0, 2 }, { 0, 25, 0 } } }, { { { 8, 0, 3 }, { 0, 25, 1 } } }, { { { 8, 0, 4 }, { 0, 26, 1 } } }, { { { 9, 0, 3 }, { 0, 26, 0 } } }, { { { 9, 0, 2 }, { 2, 23, 1 } } }, { { { 9, 0, 1 }, { 2, 23, 0 } } }, { { { 9, 0, 0 }, { 0, 27, 0 } } }, { { { 9, 0, 1 }, { 1, 26, 1 } } }, { { { 9, 0, 2 }, { 1, 26, 0 } } }, { { { 9, 0, 3 }, { 0, 28, 0 } } }, { { { 9, 0, 4 }, { 0, 29, 1 } } }, { { { 10, 0, 3 }, { 0, 29, 0 } } }, { { { 10, 0, 2 }, { 0, 29, 1 } } }, { { { 10, 0, 1 }, { 0, 30, 1 } } }, { { { 10, 0, 0 }, { 0, 30, 0 } } }, { { { 10, 0, 1 }, { 2, 27, 1 } } }, { { { 10, 0, 2 }, { 2, 27, 0 } } }, { { { 10, 0, 3 }, { 0, 31, 0 } } }, { { { 10, 0, 4 }, { 1, 30, 1 } } }, { { { 11, 0, 3 }, { 1, 30, 0 } } }, { { { 11, 0, 2 }, { 4, 24, 0 } } }, { { { 11, 0, 1 }, { 1, 31, 1 } } }, { { { 11, 0, 0 }, { 1, 31, 0 } } }, { { { 11, 0, 1 }, { 1, 31, 1 } } }, { { { 11, 0, 2 }, { 2, 30, 1 } } }, { { { 11, 0, 3 }, { 2, 30, 0 } } }, { { { 11, 0, 4 }, { 2, 31, 1 } } }, { { { 12, 0, 4 }, { 2, 31, 0 } } }, { { { 12, 0, 3 }, { 4, 27, 0 } } }, { { { 12, 0, 2 }, { 3, 30, 1 } } }, { { { 12, 0, 1 }, { 3, 30, 0 } } }, { { { 12, 0, 0 }, { 4, 28, 0 } } }, { { { 12, 0, 1 }, { 3, 31, 1 } } }, { { { 12, 0, 2 }, { 3, 31, 0 } } }, { { { 12, 0, 3 }, { 3, 31, 1 } } }, { { { 12, 0, 4 }, { 4, 30, 1 } } }, { { { 13, 0, 3 }, { 4, 30, 0 } } }, { { { 13, 0, 2 }, { 6, 27, 1 } } }, { { { 13, 0, 1 }, { 6, 27, 0 } } }, { { { 13, 0, 0 }, { 4, 31, 0 } } }, { { { 13, 0, 1 }, { 5, 30, 1 } } }, { { { 13, 0, 2 }, { 5, 30, 0 } } }, { { { 13, 0, 3 }, { 8, 24, 0 } } }, { { { 13, 0, 4 }, { 5, 31, 1 } } }, { { { 14, 0, 3 }, { 5, 31, 0 } } }, { { { 14, 0, 2 }, { 5, 31, 1 } } }, { { { 14, 0, 1 }, { 6, 30, 1 } } }, { { { 14, 0, 0 }, { 6, 30, 0 } } }, { { { 14, 0, 1 }, { 6, 31, 1 } } }, { { { 14, 0, 2 }, { 6, 31, 0 } } }, { { { 14, 0, 3 }, { 8, 27, 0 } } }, { { { 14, 0, 4 }, { 7, 30, 1 } } }, { { { 15, 0, 3 }, { 7, 30, 0 } } }, { { { 15, 0, 2 }, { 8, 28, 0 } } }, { { { 15, 0, 1 }, { 7, 31, 1 } } }, { { { 15, 0, 0 }, { 7, 31, 0 } } }, { { { 15, 0, 1 }, { 7, 31, 1 } } }, { { { 15, 0, 2 }, { 8, 30, 1 } } }, { { { 15, 0, 3 }, { 8, 30, 0 } } }, { { { 15, 0, 4 }, { 10, 27, 1 } } }, { { { 16, 0, 4 }, { 10, 27, 0 } } }, { { { 16, 0, 3 }, { 8, 31, 0 } } }, { { { 16, 0, 2 }, { 9, 30, 1 } } }, { { { 16, 0, 1 }, { 9, 30, 0 } } }, { { { 16, 0, 0 }, { 12, 24, 0 } } }, { { { 16, 0, 1 }, { 9, 31, 1 } } }, { { { 16, 0, 2 }, { 9, 31, 0 } } }, { { { 16, 0, 3 }, { 9, 31, 1 } } }, { { { 16, 0, 4 }, { 10, 30, 1 } } }, { { { 17, 0, 3 }, { 10, 30, 0 } } }, { { { 17, 0, 2 }, { 10, 31, 1 } } }, { { { 17, 0, 1 }, { 10, 31, 0 } } }, { { { 17, 0, 0 }, { 12, 27, 0 } } }, { { { 17, 0, 1 }, { 11, 30, 1 } } }, { { { 17, 0, 2 }, { 11, 30, 0 } } }, { { { 17, 0, 3 }, { 12, 28, 0 } } }, { { { 17, 0, 4 }, { 11, 31, 1 } } }, { { { 18, 0, 3 }, { 11, 31, 0 } } }, { { { 18, 0, 2 }, { 11, 31, 1 } } }, { { { 18, 0, 1 }, { 12, 30, 1 } } }, { { { 18, 0, 0 }, { 12, 30, 0 } } }, { { { 18, 0, 1 }, { 14, 27, 1 } } }, { { { 18, 0, 2 }, { 14, 27, 0 } } }, { { { 18, 0, 3 }, { 12, 31, 0 } } }, { { { 18, 0, 4 }, { 13, 30, 1 } } }, { { { 19, 0, 3 }, { 13, 30, 0 } } }, { { { 19, 0, 2 }, { 16, 24, 0 } } }, { { { 19, 0, 1 }, { 13, 31, 1 } } }, { { { 19, 0, 0 }, { 13, 31, 0 } } }, { { { 19, 0, 1 }, { 13, 31, 1 } } }, { { { 19, 0, 2 }, { 14, 30, 1 } } }, { { { 19, 0, 3 }, { 14, 30, 0 } } }, { { { 19, 0, 4 }, { 14, 31, 1 } } }, { { { 20, 0, 4 }, { 14, 31, 0 } } }, { { { 20, 0, 3 }, { 16, 27, 0 } } }, { { { 20, 0, 2 }, { 15, 30, 1 } } }, { { { 20, 0, 1 }, { 15, 30, 0 } } }, { { { 20, 0, 0 }, { 16, 28, 0 } } }, { { { 20, 0, 1 }, { 15, 31, 1 } } }, { { { 20, 0, 2 }, { 15, 31, 0 } } }, { { { 20, 0, 3 }, { 15, 31, 1 } } }, { { { 20, 0, 4 }, { 16, 30, 1 } } }, { { { 21, 0, 3 }, { 16, 30, 0 } } }, { { { 21, 0, 2 }, { 18, 27, 1 } } }, { { { 21, 0, 1 }, { 18, 27, 0 } } }, { { { 21, 0, 0 }, { 16, 31, 0 } } }, { { { 21, 0, 1 }, { 17, 30, 1 } } }, { { { 21, 0, 2 }, { 17, 30, 0 } } }, { { { 21, 0, 3 }, { 20, 24, 0 } } }, { { { 21, 0, 4 }, { 17, 31, 1 } } }, { { { 22, 0, 3 }, { 17, 31, 0 } } }, { { { 22, 0, 2 }, { 17, 31, 1 } } }, { { { 22, 0, 1 }, { 18, 30, 1 } } }, { { { 22, 0, 0 }, { 18, 30, 0 } } }, { { { 22, 0, 1 }, { 18, 31, 1 } } }, { { { 22, 0, 2 }, { 18, 31, 0 } } }, { { { 22, 0, 3 }, { 20, 27, 0 } } }, { { { 22, 0, 4 }, { 19, 30, 1 } } }, { { { 23, 0, 3 }, { 19, 30, 0 } } }, { { { 23, 0, 2 }, { 20, 28, 0 } } }, { { { 23, 0, 1 }, { 19, 31, 1 } } }, { { { 23, 0, 0 }, { 19, 31, 0 } } }, { { { 23, 0, 1 }, { 19, 31, 1 } } }, { { { 23, 0, 2 }, { 20, 30, 1 } } }, { { { 23, 0, 3 }, { 20, 30, 0 } } }, { { { 23, 0, 4 }, { 22, 27, 1 } } }, { { { 24, 0, 4 }, { 22, 27, 0 } } }, { { { 24, 0, 3 }, { 20, 31, 0 } } }, { { { 24, 0, 2 }, { 21, 30, 1 } } }, { { { 24, 0, 1 }, { 21, 30, 0 } } }, { { { 24, 0, 0 }, { 24, 24, 0 } } }, { { { 24, 0, 1 }, { 21, 31, 1 } } }, { { { 24, 0, 2 }, { 21, 31, 0 } } }, { { { 24, 0, 3 }, { 21, 31, 1 } } }, { { { 24, 0, 4 }, { 22, 30, 1 } } }, { { { 25, 0, 3 }, { 22, 30, 0 } } }, { { { 25, 0, 2 }, { 22, 31, 1 } } }, { { { 25, 0, 1 }, { 22, 31, 0 } } }, { { { 25, 0, 0 }, { 24, 27, 0 } } }, { { { 25, 0, 1 }, { 23, 30, 1 } } }, { { { 25, 0, 2 }, { 23, 30, 0 } } }, { { { 25, 0, 3 }, { 24, 28, 0 } } }, { { { 25, 0, 4 }, { 23, 31, 1 } } }, { { { 26, 0, 3 }, { 23, 31, 0 } } }, { { { 26, 0, 2 }, { 23, 31, 1 } } }, { { { 26, 0, 1 }, { 24, 30, 1 } } }, { { { 26, 0, 0 }, { 24, 30, 0 } } }, { { { 26, 0, 1 }, { 26, 27, 1 } } }, { { { 26, 0, 2 }, { 26, 27, 0 } } }, { { { 26, 0, 3 }, { 24, 31, 0 } } }, { { { 26, 0, 4 }, { 25, 30, 1 } } }, { { { 27, 0, 3 }, { 25, 30, 0 } } }, { { { 27, 0, 2 }, { 28, 24, 0 } } }, { { { 27, 0, 1 }, { 25, 31, 1 } } }, { { { 27, 0, 0 }, { 25, 31, 0 } } }, { { { 27, 0, 1 }, { 25, 31, 1 } } }, { { { 27, 0, 2 }, { 26, 30, 1 } } }, { { { 27, 0, 3 }, { 26, 30, 0 } } }, { { { 27, 0, 4 }, { 26, 31, 1 } } }, { { { 28, 0, 4 }, { 26, 31, 0 } } }, { { { 28, 0, 3 }, { 28, 27, 0 } } }, { { { 28, 0, 2 }, { 27, 30, 1 } } }, { { { 28, 0, 1 }, { 27, 30, 0 } } }, { { { 28, 0, 0 }, { 28, 28, 0 } } }, { { { 28, 0, 1 }, { 27, 31, 1 } } }, { { { 28, 0, 2 }, { 27, 31, 0 } } }, { { { 28, 0, 3 }, { 27, 31, 1 } } }, { { { 28, 0, 4 }, { 28, 30, 1 } } }, { { { 29, 0, 3 }, { 28, 30, 0 } } }, { { { 29, 0, 2 }, { 30, 27, 1 } } }, { { { 29, 0, 1 }, { 30, 27, 0 } } }, { { { 29, 0, 0 }, { 28, 31, 0 } } }, { { { 29, 0, 1 }, { 29, 30, 1 } } }, { { { 29, 0, 2 }, { 29, 30, 0 } } }, { { { 29, 0, 3 }, { 29, 30, 1 } } }, { { { 29, 0, 4 }, { 29, 31, 1 } } }, { { { 30, 0, 3 }, { 29, 31, 0 } } }, { { { 30, 0, 2 }, { 29, 31, 1 } } }, { { { 30, 0, 1 }, { 30, 30, 1 } } }, { { { 30, 0, 0 }, { 30, 30, 0 } } }, { { { 30, 0, 1 }, { 30, 31, 1 } } }, { { { 30, 0, 2 }, { 30, 31, 0 } } }, { { { 30, 0, 3 }, { 30, 31, 1 } } }, { { { 30, 0, 4 }, { 31, 30, 1 } } }, { { { 31, 0, 3 }, { 31, 30, 0 } } }, { { { 31, 0, 2 }, { 31, 30, 1 } } }, { { { 31, 0, 1 }, { 31, 31, 1 } } }, { { { 31, 0, 0 }, { 31, 31, 0 } } } }; static const DDSSingleColourLookup DDSLookup_6_4[] = { { { { 0, 0, 0 }, { 0, 0, 0 } } }, { { { 0, 0, 1 }, { 0, 1, 0 } } }, { { { 0, 0, 2 }, { 0, 2, 0 } } }, { { { 1, 0, 1 }, { 0, 3, 1 } } }, { { { 1, 0, 0 }, { 0, 3, 0 } } }, { { { 1, 0, 1 }, { 0, 4, 0 } } }, { { { 1, 0, 2 }, { 0, 5, 0 } } }, { { { 2, 0, 1 }, { 0, 6, 1 } } }, { { { 2, 0, 0 }, { 0, 6, 0 } } }, { { { 2, 0, 1 }, { 0, 7, 0 } } }, { { { 2, 0, 2 }, { 0, 8, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 0 }, { 0, 9, 0 } } }, { { { 3, 0, 1 }, { 0, 10, 0 } } }, { { { 3, 0, 2 }, { 0, 11, 0 } } }, { { { 4, 0, 1 }, { 0, 12, 1 } } }, { { { 4, 0, 0 }, { 0, 12, 0 } } }, { { { 4, 0, 1 }, { 0, 13, 0 } } }, { { { 4, 0, 2 }, { 0, 14, 0 } } }, { { { 5, 0, 1 }, { 0, 15, 1 } } }, { { { 5, 0, 0 }, { 0, 15, 0 } } }, { { { 5, 0, 1 }, { 0, 16, 0 } } }, { { { 5, 0, 2 }, { 1, 15, 0 } } }, { { { 6, 0, 1 }, { 0, 17, 0 } } }, { { { 6, 0, 0 }, { 0, 18, 0 } } }, { { { 6, 0, 1 }, { 0, 19, 0 } } }, { { { 6, 0, 2 }, { 3, 14, 0 } } }, { { { 7, 0, 1 }, { 0, 20, 0 } } }, { { { 7, 0, 0 }, { 0, 21, 0 } } }, { { { 7, 0, 1 }, { 0, 22, 0 } } }, { { { 7, 0, 2 }, { 4, 15, 0 } } }, { { { 8, 0, 1 }, { 0, 23, 0 } } }, { { { 8, 0, 0 }, { 0, 24, 0 } } }, { { { 8, 0, 1 }, { 0, 25, 0 } } }, { { { 8, 0, 2 }, { 6, 14, 0 } } }, { { { 9, 0, 1 }, { 0, 26, 0 } } }, { { { 9, 0, 0 }, { 0, 27, 0 } } }, { { { 9, 0, 1 }, { 0, 28, 0 } } }, { { { 9, 0, 2 }, { 7, 15, 0 } } }, { { { 10, 0, 1 }, { 0, 29, 0 } } }, { { { 10, 0, 0 }, { 0, 30, 0 } } }, { { { 10, 0, 1 }, { 0, 31, 0 } } }, { { { 10, 0, 2 }, { 9, 14, 0 } } }, { { { 11, 0, 1 }, { 0, 32, 0 } } }, { { { 11, 0, 0 }, { 0, 33, 0 } } }, { { { 11, 0, 1 }, { 2, 30, 0 } } }, { { { 11, 0, 2 }, { 0, 34, 0 } } }, { { { 12, 0, 1 }, { 0, 35, 0 } } }, { { { 12, 0, 0 }, { 0, 36, 0 } } }, { { { 12, 0, 1 }, { 3, 31, 0 } } }, { { { 12, 0, 2 }, { 0, 37, 0 } } }, { { { 13, 0, 1 }, { 0, 38, 0 } } }, { { { 13, 0, 0 }, { 0, 39, 0 } } }, { { { 13, 0, 1 }, { 5, 30, 0 } } }, { { { 13, 0, 2 }, { 0, 40, 0 } } }, { { { 14, 0, 1 }, { 0, 41, 0 } } }, { { { 14, 0, 0 }, { 0, 42, 0 } } }, { { { 14, 0, 1 }, { 6, 31, 0 } } }, { { { 14, 0, 2 }, { 0, 43, 0 } } }, { { { 15, 0, 1 }, { 0, 44, 0 } } }, { { { 15, 0, 0 }, { 0, 45, 0 } } }, { { { 15, 0, 1 }, { 8, 30, 0 } } }, { { { 15, 0, 2 }, { 0, 46, 0 } } }, { { { 16, 0, 2 }, { 0, 47, 0 } } }, { { { 16, 0, 1 }, { 1, 46, 0 } } }, { { { 16, 0, 0 }, { 0, 48, 0 } } }, { { { 16, 0, 1 }, { 0, 49, 0 } } }, { { { 16, 0, 2 }, { 0, 50, 0 } } }, { { { 17, 0, 1 }, { 2, 47, 0 } } }, { { { 17, 0, 0 }, { 0, 51, 0 } } }, { { { 17, 0, 1 }, { 0, 52, 0 } } }, { { { 17, 0, 2 }, { 0, 53, 0 } } }, { { { 18, 0, 1 }, { 4, 46, 0 } } }, { { { 18, 0, 0 }, { 0, 54, 0 } } }, { { { 18, 0, 1 }, { 0, 55, 0 } } }, { { { 18, 0, 2 }, { 0, 56, 0 } } }, { { { 19, 0, 1 }, { 5, 47, 0 } } }, { { { 19, 0, 0 }, { 0, 57, 0 } } }, { { { 19, 0, 1 }, { 0, 58, 0 } } }, { { { 19, 0, 2 }, { 0, 59, 0 } } }, { { { 20, 0, 1 }, { 7, 46, 0 } } }, { { { 20, 0, 0 }, { 0, 60, 0 } } }, { { { 20, 0, 1 }, { 0, 61, 0 } } }, { { { 20, 0, 2 }, { 0, 62, 0 } } }, { { { 21, 0, 1 }, { 8, 47, 0 } } }, { { { 21, 0, 0 }, { 0, 63, 0 } } }, { { { 21, 0, 1 }, { 1, 62, 0 } } }, { { { 21, 0, 2 }, { 1, 63, 0 } } }, { { { 22, 0, 1 }, { 10, 46, 0 } } }, { { { 22, 0, 0 }, { 2, 62, 0 } } }, { { { 22, 0, 1 }, { 2, 63, 0 } } }, { { { 22, 0, 2 }, { 3, 62, 0 } } }, { { { 23, 0, 1 }, { 11, 47, 0 } } }, { { { 23, 0, 0 }, { 3, 63, 0 } } }, { { { 23, 0, 1 }, { 4, 62, 0 } } }, { { { 23, 0, 2 }, { 4, 63, 0 } } }, { { { 24, 0, 1 }, { 13, 46, 0 } } }, { { { 24, 0, 0 }, { 5, 62, 0 } } }, { { { 24, 0, 1 }, { 5, 63, 0 } } }, { { { 24, 0, 2 }, { 6, 62, 0 } } }, { { { 25, 0, 1 }, { 14, 47, 0 } } }, { { { 25, 0, 0 }, { 6, 63, 0 } } }, { { { 25, 0, 1 }, { 7, 62, 0 } } }, { { { 25, 0, 2 }, { 7, 63, 0 } } }, { { { 26, 0, 1 }, { 16, 45, 0 } } }, { { { 26, 0, 0 }, { 8, 62, 0 } } }, { { { 26, 0, 1 }, { 8, 63, 0 } } }, { { { 26, 0, 2 }, { 9, 62, 0 } } }, { { { 27, 0, 1 }, { 16, 48, 0 } } }, { { { 27, 0, 0 }, { 9, 63, 0 } } }, { { { 27, 0, 1 }, { 10, 62, 0 } } }, { { { 27, 0, 2 }, { 10, 63, 0 } } }, { { { 28, 0, 1 }, { 16, 51, 0 } } }, { { { 28, 0, 0 }, { 11, 62, 0 } } }, { { { 28, 0, 1 }, { 11, 63, 0 } } }, { { { 28, 0, 2 }, { 12, 62, 0 } } }, { { { 29, 0, 1 }, { 16, 54, 0 } } }, { { { 29, 0, 0 }, { 12, 63, 0 } } }, { { { 29, 0, 1 }, { 13, 62, 0 } } }, { { { 29, 0, 2 }, { 13, 63, 0 } } }, { { { 30, 0, 1 }, { 16, 57, 0 } } }, { { { 30, 0, 0 }, { 14, 62, 0 } } }, { { { 30, 0, 1 }, { 14, 63, 0 } } }, { { { 30, 0, 2 }, { 15, 62, 0 } } }, { { { 31, 0, 1 }, { 16, 60, 0 } } }, { { { 31, 0, 0 }, { 15, 63, 0 } } }, { { { 31, 0, 1 }, { 24, 46, 0 } } }, { { { 31, 0, 2 }, { 16, 62, 0 } } }, { { { 32, 0, 2 }, { 16, 63, 0 } } }, { { { 32, 0, 1 }, { 17, 62, 0 } } }, { { { 32, 0, 0 }, { 25, 47, 0 } } }, { { { 32, 0, 1 }, { 17, 63, 0 } } }, { { { 32, 0, 2 }, { 18, 62, 0 } } }, { { { 33, 0, 1 }, { 18, 63, 0 } } }, { { { 33, 0, 0 }, { 27, 46, 0 } } }, { { { 33, 0, 1 }, { 19, 62, 0 } } }, { { { 33, 0, 2 }, { 19, 63, 0 } } }, { { { 34, 0, 1 }, { 20, 62, 0 } } }, { { { 34, 0, 0 }, { 28, 47, 0 } } }, { { { 34, 0, 1 }, { 20, 63, 0 } } }, { { { 34, 0, 2 }, { 21, 62, 0 } } }, { { { 35, 0, 1 }, { 21, 63, 0 } } }, { { { 35, 0, 0 }, { 30, 46, 0 } } }, { { { 35, 0, 1 }, { 22, 62, 0 } } }, { { { 35, 0, 2 }, { 22, 63, 0 } } }, { { { 36, 0, 1 }, { 23, 62, 0 } } }, { { { 36, 0, 0 }, { 31, 47, 0 } } }, { { { 36, 0, 1 }, { 23, 63, 0 } } }, { { { 36, 0, 2 }, { 24, 62, 0 } } }, { { { 37, 0, 1 }, { 24, 63, 0 } } }, { { { 37, 0, 0 }, { 32, 47, 0 } } }, { { { 37, 0, 1 }, { 25, 62, 0 } } }, { { { 37, 0, 2 }, { 25, 63, 0 } } }, { { { 38, 0, 1 }, { 26, 62, 0 } } }, { { { 38, 0, 0 }, { 32, 50, 0 } } }, { { { 38, 0, 1 }, { 26, 63, 0 } } }, { { { 38, 0, 2 }, { 27, 62, 0 } } }, { { { 39, 0, 1 }, { 27, 63, 0 } } }, { { { 39, 0, 0 }, { 32, 53, 0 } } }, { { { 39, 0, 1 }, { 28, 62, 0 } } }, { { { 39, 0, 2 }, { 28, 63, 0 } } }, { { { 40, 0, 1 }, { 29, 62, 0 } } }, { { { 40, 0, 0 }, { 32, 56, 0 } } }, { { { 40, 0, 1 }, { 29, 63, 0 } } }, { { { 40, 0, 2 }, { 30, 62, 0 } } }, { { { 41, 0, 1 }, { 30, 63, 0 } } }, { { { 41, 0, 0 }, { 32, 59, 0 } } }, { { { 41, 0, 1 }, { 31, 62, 0 } } }, { { { 41, 0, 2 }, { 31, 63, 0 } } }, { { { 42, 0, 1 }, { 32, 61, 0 } } }, { { { 42, 0, 0 }, { 32, 62, 0 } } }, { { { 42, 0, 1 }, { 32, 63, 0 } } }, { { { 42, 0, 2 }, { 41, 46, 0 } } }, { { { 43, 0, 1 }, { 33, 62, 0 } } }, { { { 43, 0, 0 }, { 33, 63, 0 } } }, { { { 43, 0, 1 }, { 34, 62, 0 } } }, { { { 43, 0, 2 }, { 42, 47, 0 } } }, { { { 44, 0, 1 }, { 34, 63, 0 } } }, { { { 44, 0, 0 }, { 35, 62, 0 } } }, { { { 44, 0, 1 }, { 35, 63, 0 } } }, { { { 44, 0, 2 }, { 44, 46, 0 } } }, { { { 45, 0, 1 }, { 36, 62, 0 } } }, { { { 45, 0, 0 }, { 36, 63, 0 } } }, { { { 45, 0, 1 }, { 37, 62, 0 } } }, { { { 45, 0, 2 }, { 45, 47, 0 } } }, { { { 46, 0, 1 }, { 37, 63, 0 } } }, { { { 46, 0, 0 }, { 38, 62, 0 } } }, { { { 46, 0, 1 }, { 38, 63, 0 } } }, { { { 46, 0, 2 }, { 47, 46, 0 } } }, { { { 47, 0, 1 }, { 39, 62, 0 } } }, { { { 47, 0, 0 }, { 39, 63, 0 } } }, { { { 47, 0, 1 }, { 40, 62, 0 } } }, { { { 47, 0, 2 }, { 48, 46, 0 } } }, { { { 48, 0, 2 }, { 40, 63, 0 } } }, { { { 48, 0, 1 }, { 41, 62, 0 } } }, { { { 48, 0, 0 }, { 41, 63, 0 } } }, { { { 48, 0, 1 }, { 48, 49, 0 } } }, { { { 48, 0, 2 }, { 42, 62, 0 } } }, { { { 49, 0, 1 }, { 42, 63, 0 } } }, { { { 49, 0, 0 }, { 43, 62, 0 } } }, { { { 49, 0, 1 }, { 48, 52, 0 } } }, { { { 49, 0, 2 }, { 43, 63, 0 } } }, { { { 50, 0, 1 }, { 44, 62, 0 } } }, { { { 50, 0, 0 }, { 44, 63, 0 } } }, { { { 50, 0, 1 }, { 48, 55, 0 } } }, { { { 50, 0, 2 }, { 45, 62, 0 } } }, { { { 51, 0, 1 }, { 45, 63, 0 } } }, { { { 51, 0, 0 }, { 46, 62, 0 } } }, { { { 51, 0, 1 }, { 48, 58, 0 } } }, { { { 51, 0, 2 }, { 46, 63, 0 } } }, { { { 52, 0, 1 }, { 47, 62, 0 } } }, { { { 52, 0, 0 }, { 47, 63, 0 } } }, { { { 52, 0, 1 }, { 48, 61, 0 } } }, { { { 52, 0, 2 }, { 48, 62, 0 } } }, { { { 53, 0, 1 }, { 56, 47, 0 } } }, { { { 53, 0, 0 }, { 48, 63, 0 } } }, { { { 53, 0, 1 }, { 49, 62, 0 } } }, { { { 53, 0, 2 }, { 49, 63, 0 } } }, { { { 54, 0, 1 }, { 58, 46, 0 } } }, { { { 54, 0, 0 }, { 50, 62, 0 } } }, { { { 54, 0, 1 }, { 50, 63, 0 } } }, { { { 54, 0, 2 }, { 51, 62, 0 } } }, { { { 55, 0, 1 }, { 59, 47, 0 } } }, { { { 55, 0, 0 }, { 51, 63, 0 } } }, { { { 55, 0, 1 }, { 52, 62, 0 } } }, { { { 55, 0, 2 }, { 52, 63, 0 } } }, { { { 56, 0, 1 }, { 61, 46, 0 } } }, { { { 56, 0, 0 }, { 53, 62, 0 } } }, { { { 56, 0, 1 }, { 53, 63, 0 } } }, { { { 56, 0, 2 }, { 54, 62, 0 } } }, { { { 57, 0, 1 }, { 62, 47, 0 } } }, { { { 57, 0, 0 }, { 54, 63, 0 } } }, { { { 57, 0, 1 }, { 55, 62, 0 } } }, { { { 57, 0, 2 }, { 55, 63, 0 } } }, { { { 58, 0, 1 }, { 56, 62, 1 } } }, { { { 58, 0, 0 }, { 56, 62, 0 } } }, { { { 58, 0, 1 }, { 56, 63, 0 } } }, { { { 58, 0, 2 }, { 57, 62, 0 } } }, { { { 59, 0, 1 }, { 57, 63, 1 } } }, { { { 59, 0, 0 }, { 57, 63, 0 } } }, { { { 59, 0, 1 }, { 58, 62, 0 } } }, { { { 59, 0, 2 }, { 58, 63, 0 } } }, { { { 60, 0, 1 }, { 59, 62, 1 } } }, { { { 60, 0, 0 }, { 59, 62, 0 } } }, { { { 60, 0, 1 }, { 59, 63, 0 } } }, { { { 60, 0, 2 }, { 60, 62, 0 } } }, { { { 61, 0, 1 }, { 60, 63, 1 } } }, { { { 61, 0, 0 }, { 60, 63, 0 } } }, { { { 61, 0, 1 }, { 61, 62, 0 } } }, { { { 61, 0, 2 }, { 61, 63, 0 } } }, { { { 62, 0, 1 }, { 62, 62, 1 } } }, { { { 62, 0, 0 }, { 62, 62, 0 } } }, { { { 62, 0, 1 }, { 62, 63, 0 } } }, { { { 62, 0, 2 }, { 63, 62, 0 } } }, { { { 63, 0, 1 }, { 63, 63, 1 } } }, { { { 63, 0, 0 }, { 63, 63, 0 } } } }; static const DDSSingleColourLookup* DDS_LOOKUP[] = { DDSLookup_5_4, DDSLookup_6_4, DDSLookup_5_4 }; /* Macros */ #define C565_r(x) (((x) & 0xF800) >> 11) #define C565_g(x) (((x) & 0x07E0) >> 5) #define C565_b(x) ((x) & 0x001F) #define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2)) #define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4)) #define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2)) #define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1) #define FixRange(min, max, steps) \ if (min > max) \ min = max; \ if ((ssize_t) max - min < steps) \ max = MagickMin(min + steps, 255); \ if ((ssize_t) max - min < steps) \ min = MagickMax(0, (ssize_t) max - steps) #define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z) #define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \ = value #define VectorInit3(vector, value) vector.x = vector.y = vector.z = value #define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \ g && mask.b_bitmask == b && mask.alpha_bitmask == a) /* Forward declarations */ static MagickBooleanType ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3, DDSVector4 *,DDSVector4 *,unsigned char *,size_t), ReadDDSInfo(Image *,DDSInfo *), ReadDXT1(Image *,DDSInfo *,ExceptionInfo *), ReadDXT3(Image *,DDSInfo *,ExceptionInfo *), ReadDXT5(Image *,DDSInfo *,ExceptionInfo *), ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *), ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *), SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), WriteDDSImage(const ImageInfo *,Image *), WriteMipmaps(Image *,const size_t,const size_t,const size_t, const MagickBooleanType,const MagickBooleanType,ExceptionInfo *); static void RemapIndices(const ssize_t *,const unsigned char *,unsigned char *), WriteDDSInfo(Image *,const size_t,const size_t,const size_t), WriteFourCC(Image *,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *), WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *), WriteUncompressed(Image *,ExceptionInfo *); static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x + right.x; destination->y = left.y + right.y; destination->z = left.z + right.z; destination->w = left.w + right.w; } static inline void VectorClamp(DDSVector4 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); value->w = MagickMin(1.0f,MagickMax(0.0f,value->w)); } static inline void VectorClamp3(DDSVector3 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); } static inline void VectorCopy43(const DDSVector4 source, DDSVector3 *destination) { destination->x = source.x; destination->y = source.y; destination->z = source.z; } static inline void VectorCopy44(const DDSVector4 source, DDSVector4 *destination) { destination->x = source.x; destination->y = source.y; destination->z = source.z; destination->w = source.w; } static inline void VectorNegativeMultiplySubtract(const DDSVector4 a, const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination) { destination->x = c.x - (a.x * b.x); destination->y = c.y - (a.y * b.y); destination->z = c.z - (a.z * b.z); destination->w = c.w - (a.w * b.w); } static inline void VectorMultiply(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x * right.x; destination->y = left.y * right.y; destination->z = left.z * right.z; destination->w = left.w * right.w; } static inline void VectorMultiply3(const DDSVector3 left, const DDSVector3 right, DDSVector3 *destination) { destination->x = left.x * right.x; destination->y = left.y * right.y; destination->z = left.z * right.z; } static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination) { destination->x = (a.x * b.x) + c.x; destination->y = (a.y * b.y) + c.y; destination->z = (a.z * b.z) + c.z; destination->w = (a.w * b.w) + c.w; } static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b, const DDSVector3 c, DDSVector3 *destination) { destination->x = (a.x * b.x) + c.x; destination->y = (a.y * b.y) + c.y; destination->z = (a.z * b.z) + c.z; } static inline void VectorReciprocal(const DDSVector4 value, DDSVector4 *destination) { destination->x = 1.0f / value.x; destination->y = 1.0f / value.y; destination->z = 1.0f / value.z; destination->w = 1.0f / value.w; } static inline void VectorSubtract(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x - right.x; destination->y = left.y - right.y; destination->z = left.z - right.z; destination->w = left.w - right.w; } static inline void VectorSubtract3(const DDSVector3 left, const DDSVector3 right, DDSVector3 *destination) { destination->x = left.x - right.x; destination->y = left.y - right.y; destination->z = left.z - right.z; } static inline void VectorTruncate(DDSVector4 *value) { value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x); value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y); value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z); value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w); } static inline void VectorTruncate3(DDSVector3 *value) { value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x); value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y); value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z); } static void CalculateColors(unsigned short c0, unsigned short c1, DDSColors *c, MagickBooleanType ignoreAlpha) { c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0; c->r[0] = (unsigned char) C565_red(c0); c->g[0] = (unsigned char) C565_green(c0); c->b[0] = (unsigned char) C565_blue(c0); c->r[1] = (unsigned char) C565_red(c1); c->g[1] = (unsigned char) C565_green(c1); c->b[1] = (unsigned char) C565_blue(c1); if (ignoreAlpha != MagickFalse || c0 > c1) { c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3); c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3); c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3); c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3); c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3); c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3); } else { c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2); c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2); c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2); c->r[3] = c->g[3] = c->b[3] = 0; c->a[3] = 255; } } static size_t CompressAlpha(const size_t min, const size_t max, const size_t steps, const ssize_t *alphas, unsigned char* indices) { unsigned char codes[8]; ssize_t i; size_t error, index, j, least, value; codes[0] = (unsigned char) min; codes[1] = (unsigned char) max; codes[6] = 0; codes[7] = 255; for (i=1; i < (ssize_t) steps; i++) codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps); error = 0; for (i=0; i<16; i++) { if (alphas[i] == -1) { indices[i] = 0; continue; } value = alphas[i]; least = SIZE_MAX; index = 0; for (j=0; j<8; j++) { size_t dist; dist = value - (size_t)codes[j]; dist *= dist; if (dist < least) { least = dist; index = j; } } indices[i] = (unsigned char)index; error += least; } return error; } static void CompressClusterFit(const size_t count, const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle, const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end, unsigned char *indices) { DDSVector3 axis; DDSVector4 grid, gridrcp, half, onethird_onethird2, pointsWeights[16], two, twonineths, twothirds_twothirds2, xSumwSum; float bestError = 1e+37f; size_t bestIteration = 0, besti = 0, bestj = 0, bestk = 0, iterationIndex; ssize_t i; unsigned char *o, order[128], unordered[16]; VectorInit(half,0.5f); VectorInit(two,2.0f); VectorInit(onethird_onethird2,1.0f/3.0f); onethird_onethird2.w = 1.0f/9.0f; VectorInit(twothirds_twothirds2,2.0f/3.0f); twothirds_twothirds2.w = 4.0f/9.0f; VectorInit(twonineths,2.0f/9.0f); grid.x = 31.0f; grid.y = 63.0f; grid.z = 31.0f; grid.w = 0.0f; gridrcp.x = 1.0f/31.0f; gridrcp.y = 1.0f/63.0f; gridrcp.z = 1.0f/31.0f; gridrcp.w = 0.0f; xSumwSum.x = 0.0f; xSumwSum.y = 0.0f; xSumwSum.z = 0.0f; xSumwSum.w = 0.0f; ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0); for (iterationIndex = 0;;) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,1) \ num_threads(GetMagickResourceLimit(ThreadResource)) #endif for (i=0; i < (ssize_t) count; i++) { DDSVector4 part0, part1, part2; size_t ii, j, k, kmin; VectorInit(part0,0.0f); for(ii=0; ii < (size_t) i; ii++) VectorAdd(pointsWeights[ii],part0,&part0); VectorInit(part1,0.0f); for (j=(size_t) i;;) { if (j == 0) { VectorCopy44(pointsWeights[0],&part2); kmin = 1; } else { VectorInit(part2,0.0f); kmin = j; } for (k=kmin;;) { DDSVector4 a, alpha2_sum, alphax_sum, alphabeta_sum, b, beta2_sum, betax_sum, e1, e2, factor, part3; float error; VectorSubtract(xSumwSum,part2,&part3); VectorSubtract(part3,part1,&part3); VectorSubtract(part3,part0,&part3); VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum); VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum); VectorInit(alpha2_sum,alphax_sum.w); VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum); VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum); VectorInit(beta2_sum,betax_sum.w); VectorAdd(part1,part2,&alphabeta_sum); VectorInit(alphabeta_sum,alphabeta_sum.w); VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum); VectorMultiply(alpha2_sum,beta2_sum,&factor); VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor, &factor); VectorReciprocal(factor,&factor); VectorMultiply(alphax_sum,beta2_sum,&a); VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a); VectorMultiply(a,factor,&a); VectorMultiply(betax_sum,alpha2_sum,&b); VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b); VectorMultiply(b,factor,&b); VectorClamp(&a); VectorMultiplyAdd(grid,a,half,&a); VectorTruncate(&a); VectorMultiply(a,gridrcp,&a); VectorClamp(&b); VectorMultiplyAdd(grid,b,half,&b); VectorTruncate(&b); VectorMultiply(b,gridrcp,&b); VectorMultiply(b,b,&e1); VectorMultiply(e1,beta2_sum,&e1); VectorMultiply(a,a,&e2); VectorMultiplyAdd(e2,alpha2_sum,e1,&e1); VectorMultiply(a,b,&e2); VectorMultiply(e2,alphabeta_sum,&e2); VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2); VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2); VectorMultiplyAdd(two,e2,e1,&e2); VectorMultiply(e2,metric,&e2); error = e2.x + e2.y + e2.z; if (error < bestError) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (DDS_CompressClusterFit) #endif { if (error < bestError) { VectorCopy43(a,start); VectorCopy43(b,end); bestError = error; besti = i; bestj = j; bestk = k; bestIteration = iterationIndex; } } } if (k == count) break; VectorAdd(pointsWeights[k],part2,&part2); k++; } if (j == count) break; VectorAdd(pointsWeights[j],part1,&part1); j++; } } if (bestIteration != iterationIndex) break; iterationIndex++; if (iterationIndex == 8) break; VectorSubtract3(*end,*start,&axis); if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order, iterationIndex) == MagickFalse) break; } o = order + (16*bestIteration); for (i=0; i < (ssize_t) besti; i++) unordered[o[i]] = 0; for (i=besti; i < (ssize_t) bestj; i++) unordered[o[i]] = 2; for (i=bestj; i < (ssize_t) bestk; i++) unordered[o[i]] = 3; for (i=bestk; i < (ssize_t) count; i++) unordered[o[i]] = 1; RemapIndices(map,unordered,indices); } static void CompressRangeFit(const size_t count, const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle, const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end, unsigned char *indices) { float d, bestDist, max, min, val; DDSVector3 codes[4], grid, gridrcp, half, dist; ssize_t i; size_t bestj, j; unsigned char closest[16]; VectorInit3(half,0.5f); grid.x = 31.0f; grid.y = 63.0f; grid.z = 31.0f; gridrcp.x = 1.0f/31.0f; gridrcp.y = 1.0f/63.0f; gridrcp.z = 1.0f/31.0f; if (count > 0) { VectorCopy43(points[0],start); VectorCopy43(points[0],end); min = max = Dot(points[0],principle); for (i=1; i < (ssize_t) count; i++) { val = Dot(points[i],principle); if (val < min) { VectorCopy43(points[i],start); min = val; } else if (val > max) { VectorCopy43(points[i],end); max = val; } } } VectorClamp3(start); VectorMultiplyAdd3(grid,*start,half,start); VectorTruncate3(start); VectorMultiply3(*start,gridrcp,start); VectorClamp3(end); VectorMultiplyAdd3(grid,*end,half,end); VectorTruncate3(end); VectorMultiply3(*end,gridrcp,end); codes[0] = *start; codes[1] = *end; codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f)); codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f)); codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f)); codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f)); codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f)); codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f)); for (i=0; i < (ssize_t) count; i++) { bestDist = 1e+37f; bestj = 0; for (j=0; j < 4; j++) { dist.x = (points[i].x - codes[j].x) * metric.x; dist.y = (points[i].y - codes[j].y) * metric.y; dist.z = (points[i].z - codes[j].z) * metric.z; d = Dot(dist,dist); if (d < bestDist) { bestDist = d; bestj = j; } } closest[i] = (unsigned char) bestj; } RemapIndices(map, closest, indices); } static void ComputeEndPoints(const DDSSingleColourLookup *lookup[], const unsigned char *color, DDSVector3 *start, DDSVector3 *end, unsigned char *index) { ssize_t i; size_t c, maxError = SIZE_MAX; for (i=0; i < 2; i++) { const DDSSourceBlock* sources[3]; size_t error = 0; for (c=0; c < 3; c++) { sources[c] = &lookup[c][color[c]].sources[i]; error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error); } if (error > maxError) continue; start->x = (float) sources[0]->start / 31.0f; start->y = (float) sources[1]->start / 63.0f; start->z = (float) sources[2]->start / 31.0f; end->x = (float) sources[0]->end / 31.0f; end->y = (float) sources[1]->end / 63.0f; end->z = (float) sources[2]->end / 31.0f; *index = (unsigned char) (2*i); maxError = error; } } static void ComputePrincipleComponent(const float *covariance, DDSVector3 *principle) { DDSVector4 row0, row1, row2, v; ssize_t i; row0.x = covariance[0]; row0.y = covariance[1]; row0.z = covariance[2]; row0.w = 0.0f; row1.x = covariance[1]; row1.y = covariance[3]; row1.z = covariance[4]; row1.w = 0.0f; row2.x = covariance[2]; row2.y = covariance[4]; row2.z = covariance[5]; row2.w = 0.0f; VectorInit(v,1.0f); for (i=0; i < 8; i++) { DDSVector4 w; float a; w.x = row0.x * v.x; w.y = row0.y * v.x; w.z = row0.z * v.x; w.w = row0.w * v.x; w.x = (row1.x * v.y) + w.x; w.y = (row1.y * v.y) + w.y; w.z = (row1.z * v.y) + w.z; w.w = (row1.w * v.y) + w.w; w.x = (row2.x * v.z) + w.x; w.y = (row2.y * v.z) + w.y; w.z = (row2.z * v.z) + w.z; w.w = (row2.w * v.z) + w.w; a = (float) PerceptibleReciprocal(MagickMax(w.x,MagickMax(w.y,w.z))); v.x = w.x * a; v.y = w.y * a; v.z = w.z * a; v.w = w.w * a; } VectorCopy43(v,principle); } static void ComputeWeightedCovariance(const size_t count, const DDSVector4 *points, float *covariance) { DDSVector3 centroid; float total; size_t i; total = 0.0f; VectorInit3(centroid,0.0f); for (i=0; i < count; i++) { total += points[i].w; centroid.x += (points[i].x * points[i].w); centroid.y += (points[i].y * points[i].w); centroid.z += (points[i].z * points[i].w); } if( total > 1.192092896e-07F) { centroid.x /= total; centroid.y /= total; centroid.z /= total; } for (i=0; i < 6; i++) covariance[i] = 0.0f; for (i = 0; i < count; i++) { DDSVector3 a, b; a.x = points[i].x - centroid.x; a.y = points[i].y - centroid.y; a.z = points[i].z - centroid.z; b.x = points[i].w * a.x; b.y = points[i].w * a.y; b.z = points[i].w * a.z; covariance[0] += a.x*b.x; covariance[1] += a.x*b.y; covariance[2] += a.x*b.z; covariance[3] += a.y*b.y; covariance[4] += a.y*b.z; covariance[5] += a.z*b.z; } } static MagickBooleanType ConstructOrdering(const size_t count, const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights, DDSVector4 *xSumwSum, unsigned char *order, size_t iteration) { float dps[16], f; ssize_t i; size_t j; unsigned char c, *o, *p; o = order + (16*iteration); for (i=0; i < (ssize_t) count; i++) { dps[i] = Dot(points[i],axis); o[i] = (unsigned char)i; } for (i=0; i < (ssize_t) count; i++) { for (j=i; j > 0 && dps[j] < dps[j - 1]; j--) { f = dps[j]; dps[j] = dps[j - 1]; dps[j - 1] = f; c = o[j]; o[j] = o[j - 1]; o[j - 1] = c; } } for (i=0; i < (ssize_t) iteration; i++) { MagickBooleanType same; p = order + (16*i); same = MagickTrue; for (j=0; j < count; j++) { if (o[j] != p[j]) { same = MagickFalse; break; } } if (same != MagickFalse) return MagickFalse; } xSumwSum->x = 0; xSumwSum->y = 0; xSumwSum->z = 0; xSumwSum->w = 0; for (i=0; i < (ssize_t) count; i++) { DDSVector4 v; j = (size_t) o[i]; v.x = points[j].w * points[j].x; v.y = points[j].w * points[j].y; v.z = points[j].w * points[j].z; v.w = points[j].w * 1.0f; VectorCopy44(v,&pointsWeights[i]); VectorAdd(*xSumwSum,v,xSumwSum); } return MagickTrue; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D D S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDDS() returns MagickTrue if the image format type, identified by the % magick string, is DDS. % % The format of the IsDDS method is: % % MagickBooleanType IsDDS(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 IsDDS(const unsigned char *magick, const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"DDS ", 4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDDSImage() reads a DirectDraw Surface 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 ReadDDSImage method is: % % Image *ReadDDSImage(const ImageInfo *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 Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status, cubemap = MagickFalse, volume = MagickFalse, matte; CompressionType compression; DDSInfo dds_info; DDSDecoder *decoder; size_t n, num_images; /* 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); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ if (ReadDDSInfo(image, &dds_info) != MagickTrue) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) cubemap = MagickTrue; if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) volume = MagickTrue; (void) SeekBlob(image, 128, SEEK_SET); /* Determine pixel format */ if (dds_info.pixelformat.flags & DDPF_RGB) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { matte = MagickTrue; decoder = ReadUncompressedRGBA; } else { matte = MagickTrue; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { /* Not sure how to handle this */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } else { matte = MagickFalse; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_FOURCC) { switch (dds_info.pixelformat.fourcc) { case FOURCC_DXT1: { matte = MagickFalse; compression = DXT1Compression; decoder = ReadDXT1; break; } case FOURCC_DXT3: { matte = MagickTrue; compression = DXT3Compression; decoder = ReadDXT3; break; } case FOURCC_DXT5: { matte = MagickTrue; compression = DXT5Compression; decoder = ReadDXT5; break; } default: { /* Unknown FOURCC */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } } } else { /* Neither compressed nor uncompressed... thus unsupported */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } num_images = 1; if (cubemap) { /* Determine number of faces defined in the cubemap */ num_images = 0; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; } if (volume) num_images = dds_info.depth; if ((num_images == 0) || (num_images > GetBlobSize(image))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireMagickResource(ListLengthResource,num_images) == MagickFalse) ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit"); for (n = 0; n < num_images; n++) { if (n != 0) { if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Start a new image */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } image->matte = matte; image->compression = compression; image->columns = dds_info.width; image->rows = dds_info.height; image->storage_class = DirectClass; image->endian = LSBEndian; image->depth = 8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) SetImageBackgroundColor(image); if ((decoder)(image, &dds_info, exception) != MagickTrue) { (void) CloseBlob(image); if (n == 0) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info) { size_t hdr_size, required; /* Seek to start of header */ (void) SeekBlob(image, 4, SEEK_SET); /* Check header field */ hdr_size = ReadBlobLSBLong(image); if (hdr_size != 124) return MagickFalse; /* Fill in DDS info struct */ dds_info->flags = ReadBlobLSBLong(image); /* Check required flags */ required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT); if ((dds_info->flags & required) != required) return MagickFalse; dds_info->height = ReadBlobLSBLong(image); dds_info->width = ReadBlobLSBLong(image); dds_info->pitchOrLinearSize = ReadBlobLSBLong(image); dds_info->depth = ReadBlobLSBLong(image); dds_info->mipmapcount = ReadBlobLSBLong(image); (void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */ /* Read pixel format structure */ hdr_size = ReadBlobLSBLong(image); if (hdr_size != 32) return MagickFalse; dds_info->pixelformat.flags = ReadBlobLSBLong(image); dds_info->pixelformat.fourcc = ReadBlobLSBLong(image); dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image); dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image); dds_info->ddscaps1 = ReadBlobLSBLong(image); dds_info->ddscaps2 = ReadBlobLSBLong(image); (void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */ return MagickTrue; } static MagickBooleanType ReadDXT1(Image *image,DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; PixelPacket *q; ssize_t i, x; size_t bits; ssize_t j, y; unsigned char code; unsigned short c0, c1; for (y = 0; y < (ssize_t) image->rows; y += 4) { for (x = 0; x < (ssize_t) image->columns; x += 4) { /* Get 4x4 patch of pixels to write on */ q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x), MagickMin(4,image->rows-y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickFalse); if (EOFBlob(image) != MagickFalse) break; /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if (((x + i) < (ssize_t) image->columns) && ((y + j) < (ssize_t) image->rows)) { code=(unsigned char) ((bits >> ((j*4+i)*2)) & 0x3); SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code])); if ((colors.a[code] != 0) && (image->matte == MagickFalse)) image->matte=MagickTrue; /* Correct matte */ q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } if (EOFBlob(image) != MagickFalse) break; } return(SkipDXTMipmaps(image,dds_info,8,exception)); } static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; PixelPacket *q; ssize_t i, x; unsigned char alpha; size_t a0, a1, bits, code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = ReadBlobLSBLong(image); a1 = ReadBlobLSBLong(image); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); if (EOFBlob(image) != MagickFalse) break; /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value: multiply 0..15 by 17 to get range 0..255 */ if (j < 2) alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf); else alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } if (EOFBlob(image) != MagickFalse) break; } return(SkipDXTMipmaps(image,dds_info,16,exception)); } static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); if (EOFBlob(image) != MagickFalse) break; /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } if (EOFBlob(image) != MagickFalse) break; } return(SkipDXTMipmaps(image,dds_info,16,exception)); } static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t x, y; unsigned short color; if (dds_info->pixelformat.rgb_bitcount == 8) (void) SetImageType(image,GrayscaleType); else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask( dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000)) ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 8) SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image))); else if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); SetPixelRed(q,ScaleCharToQuantum((unsigned char) (((color >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 5) >> 10)/63.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (dds_info->pixelformat.rgb_bitcount == 32) (void) ReadBlobByte(image); } SetPixelAlpha(q,QuantumRange); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } return(SkipRGBMipmaps(image,dds_info,3,exception)); } static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t alphaBits, x, y; unsigned short color; alphaBits=0; if (dds_info->pixelformat.rgb_bitcount == 16) { if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000)) alphaBits=1; else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00)) { alphaBits=2; (void) SetImageType(image,GrayscaleMatteType); } else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000)) alphaBits=4; else ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); } for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); if (alphaBits == 1) { SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 1) >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 6) >> 11)/31.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else if (alphaBits == 2) { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (color >> 8))); SetPixelGray(q,ScaleCharToQuantum((unsigned char)color)); } else { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (((color >> 12)/15.0)*255))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 4) >> 12)/15.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 8) >> 12)/15.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 12) >> 12)/15.0)*255))); } } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } return(SkipRGBMipmaps(image,dds_info,4,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDDSImage() adds attributes for the DDS image format to % the list of supported formats. The attributes 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 RegisterDDSImage method is: % % RegisterDDSImage(void) % */ ModuleExport size_t RegisterDDSImage(void) { MagickInfo *entry; entry = SetMagickInfo("DDS"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->seekable_stream=MagickTrue; entry->description = ConstantString("Microsoft DirectDraw Surface"); entry->magick_module = ConstantString("DDS"); (void) RegisterMagickInfo(entry); entry = SetMagickInfo("DXT1"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->seekable_stream=MagickTrue; entry->description = ConstantString("Microsoft DirectDraw Surface"); entry->magick_module = ConstantString("DDS"); (void) RegisterMagickInfo(entry); entry = SetMagickInfo("DXT5"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->seekable_stream=MagickTrue; entry->description = ConstantString("Microsoft DirectDraw Surface"); entry->magick_module = ConstantString("DDS"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } static void RemapIndices(const ssize_t *map, const unsigned char *source, unsigned char *target) { ssize_t i; for (i = 0; i < 16; i++) { if (map[i] == -1) target[i] = 3; else target[i] = source[map[i]]; } } /* Skip the mipmap images for compressed (DXTn) dds files */ static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageWarning,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; if (SeekBlob(image,offset,SEEK_CUR) < 0) break; if ((w == 1) && (h == 1)) break; w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } /* Skip the mipmap images for uncompressed (RGB or RGBA) dds files */ static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; if (SeekBlob(image,offset,SEEK_CUR) < 0) break; w = DIV2(w); h = DIV2(h); if ((w == 1) && (h == 1)) break; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDDSImage() removes format registrations made by the % DDS module from the list of supported formats. % % The format of the UnregisterDDSImage method is: % % UnregisterDDSImage(void) % */ ModuleExport void UnregisterDDSImage(void) { (void) UnregisterMagickInfo("DDS"); (void) UnregisterMagickInfo("DXT1"); (void) UnregisterMagickInfo("DXT5"); } static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5, size_t max5, size_t min7, size_t max7) { ssize_t i; size_t err5, err7, j; unsigned char indices5[16], indices7[16]; FixRange(min5,max5,5); err5 = CompressAlpha(min5,max5,5,alphas,indices5); FixRange(min7,max7,7); err7 = CompressAlpha(min7,max7,7,alphas,indices7); if (err7 < err5) { for (i=0; i < 16; i++) { unsigned char index; index = indices7[i]; if( index == 0 ) indices5[i] = 1; else if (index == 1) indices5[i] = 0; else indices5[i] = 9 - index; } min5 = max7; max5 = min7; } (void) WriteBlobByte(image,(unsigned char) min5); (void) WriteBlobByte(image,(unsigned char) max5); for(i=0; i < 2; i++) { size_t value = 0; for (j=0; j < 8; j++) { size_t index = (size_t) indices5[j + i*8]; value |= ( index << 3*j ); } for (j=0; j < 3; j++) { size_t byte = (value >> 8*j) & 0xff; (void) WriteBlobByte(image,(unsigned char) byte); } } } static void WriteCompressed(Image *image, const size_t count, DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit) { float covariance[16]; DDSVector3 end, principle, start; DDSVector4 metric; unsigned char indices[16]; VectorInit(metric,1.0f); VectorInit3(start,0.0f); VectorInit3(end,0.0f); ComputeWeightedCovariance(count,points,covariance); ComputePrincipleComponent(covariance,&principle); if (clusterFit == MagickFalse || count == 0) CompressRangeFit(count,points,map,principle,metric,&start,&end,indices); else CompressClusterFit(count,points,map,principle,metric,&start,&end,indices); WriteIndices(image,start,end,indices); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format. % % The format of the WriteBMPImage method is: % % MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteDDSImage(const ImageInfo *image_info, Image *image) { const char *option; size_t compression, columns, maxMipmaps, mipmaps, pixelFormat, rows; MagickBooleanType clusterFit, status, weightByAlpha; 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); pixelFormat=DDPF_FOURCC; compression=FOURCC_DXT5; if (!image->matte) compression=FOURCC_DXT1; if (LocaleCompare(image_info->magick,"dxt1") == 0) compression=FOURCC_DXT1; if (image_info->compression == DXT1Compression) compression=FOURCC_DXT1; else if (image_info->compression == NoCompression) pixelFormat=DDPF_RGB; option=GetImageOption(image_info,"dds:compression"); if (option != (char *) NULL) { if (LocaleCompare(option,"dxt1") == 0) compression=FOURCC_DXT1; if (LocaleCompare(option,"none") == 0) pixelFormat=DDPF_RGB; } clusterFit=MagickFalse; weightByAlpha=MagickFalse; if (pixelFormat == DDPF_FOURCC) { option=GetImageOption(image_info,"dds:cluster-fit"); if (IsStringTrue(option) != MagickFalse) { clusterFit=MagickTrue; if (compression != FOURCC_DXT1) { option=GetImageOption(image_info,"dds:weight-by-alpha"); if (IsStringTrue(option) != MagickFalse) weightByAlpha=MagickTrue; } } } maxMipmaps=SIZE_MAX; mipmaps=0; if ((image->columns & (image->columns - 1)) == 0 && (image->rows & (image->rows - 1)) == 0) { option=GetImageOption(image_info,"dds:mipmaps"); if (option != (char *) NULL) maxMipmaps=StringToUnsignedLong(option); if (maxMipmaps != 0) { columns=image->columns; rows=image->rows; while ((columns != 1 || rows != 1) && mipmaps != maxMipmaps) { columns=DIV2(columns); rows=DIV2(rows); mipmaps++; } } } WriteDDSInfo(image,pixelFormat,compression,mipmaps); WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha, &image->exception); if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps, clusterFit,weightByAlpha,&image->exception) == MagickFalse) return(MagickFalse); (void) CloseBlob(image); return(MagickTrue); } static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MaxTextExtent]; ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (format == DDPF_FOURCC) flags=flags | DDSD_LINEARSIZE; else flags=flags | DDSD_PITCH; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->matte) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (pixelFormat == DDPF_FOURCC) { /* Compressed DDS requires linear compressed size of first image */ if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1, (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*8)); else /* DXT5 */ (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1, (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*16)); } else { /* Uncompressed DDS requires byte pitch of first image */ if (image->matte != MagickFalse) (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 4)); else (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 3)); } (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) memset(software,0,sizeof(software)); (void) CopyMagickString(software,"IMAGEMAGICK",MaxTextExtent); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) /* bitcount / masks */ (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->matte != MagickFalse) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) /* ddscaps2 + reserved region */ (void) WriteBlobLSBLong(image,0x00); } static void WriteFourCC(Image *image, const size_t compression, const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { const PixelPacket *p; ssize_t x; ssize_t i, y, bx, by; for (y=0; y < (ssize_t) image->rows; y+=4) { for (x=0; x < (ssize_t) image->columns; x+=4) { MagickBooleanType match; DDSVector4 point, points[16]; size_t count = 0, max5 = 0, max7 = 0, min5 = 255, min7 = 255, columns = 4, rows = 4; ssize_t alphas[16], map[16]; unsigned char alpha; if (x + columns >= image->columns) columns = image->columns - x; if (y + rows >= image->rows) rows = image->rows - y; p=GetVirtualPixels(image,x,y,columns,rows,exception); if (p == (const PixelPacket *) NULL) break; for (i=0; i<16; i++) { map[i] = -1; alphas[i] = -1; } for (by=0; by < (ssize_t) rows; by++) { for (bx=0; bx < (ssize_t) columns; bx++) { if (compression == FOURCC_DXT5) alpha = ScaleQuantumToChar(GetPixelAlpha(p)); else alpha = 255; if (compression == FOURCC_DXT5) { if (alpha < min7) min7 = alpha; if (alpha > max7) max7 = alpha; if (alpha != 0 && alpha < min5) min5 = alpha; if (alpha != 255 && alpha > max5) max5 = alpha; } alphas[4*by + bx] = (size_t)alpha; point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f; point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f; point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f; point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f; p++; match = MagickFalse; for (i=0; i < (ssize_t) count; i++) { if ((points[i].x == point.x) && (points[i].y == point.y) && (points[i].z == point.z) && (alpha >= 128 || compression == FOURCC_DXT5)) { points[i].w += point.w; map[4*by + bx] = i; match = MagickTrue; break; } } if (match != MagickFalse) continue; points[count].x = point.x; points[count].y = point.y; points[count].z = point.z; points[count].w = point.w; map[4*by + bx] = count; count++; } } for (i=0; i < (ssize_t) count; i++) points[i].w = sqrt(points[i].w); if (compression == FOURCC_DXT5) WriteAlphas(image,alphas,min5,max5,min7,max7); if (count == 1) WriteSingleColorFit(image,points,map); else WriteCompressed(image,count,points,map,clusterFit); } } } static void WriteImageData(Image *image, const size_t pixelFormat, const size_t compression, const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { if (pixelFormat == DDPF_FOURCC) WriteFourCC(image,compression,clusterFit,weightByAlpha,exception); else WriteUncompressed(image,exception); } static inline size_t ClampToLimit(const float value, const size_t limit) { size_t result = (int) (value + 0.5f); if (result < 0.0f) return(0); if (result > limit) return(limit); return result; } static inline size_t ColorTo565(const DDSVector3 point) { size_t r = ClampToLimit(31.0f*point.x,31); size_t g = ClampToLimit(63.0f*point.y,63); size_t b = ClampToLimit(31.0f*point.z,31); return (r << 11) | (g << 5) | b; } static void WriteIndices(Image *image, const DDSVector3 start, const DDSVector3 end, unsigned char* indices) { ssize_t i; size_t a, b; unsigned char remapped[16]; const unsigned char *ind; a = ColorTo565(start); b = ColorTo565(end); for (i=0; i<16; i++) { if( a < b ) remapped[i] = (indices[i] ^ 0x1) & 0x3; else if( a == b ) remapped[i] = 0; else remapped[i] = indices[i]; } if( a < b ) Swap(a,b); (void) WriteBlobByte(image,(unsigned char) (a & 0xff)); (void) WriteBlobByte(image,(unsigned char) (a >> 8)); (void) WriteBlobByte(image,(unsigned char) (b & 0xff)); (void) WriteBlobByte(image,(unsigned char) (b >> 8)); for (i=0; i<4; i++) { ind = remapped + 4*i; (void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) | (ind[3] << 6)); } } static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps, const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { Image* resize_image; ssize_t i; size_t columns, rows; columns = image->columns; rows = image->rows; for (i=0; i< (ssize_t) mipmaps; i++) { resize_image = ResizeImage(image,DIV2(columns),DIV2(rows),TriangleFilter,1.0, exception); if (resize_image == (Image *) NULL) return(MagickFalse); DestroyBlob(resize_image); resize_image->blob=ReferenceBlob(image->blob); WriteImageData(resize_image,pixelFormat,compression,weightByAlpha, clusterFit,exception); resize_image=DestroyImage(resize_image); columns = DIV2(columns); rows = DIV2(rows); } return(MagickTrue); } static void WriteSingleColorFit(Image *image, const DDSVector4* points, const ssize_t* map) { DDSVector3 start, end; ssize_t i; unsigned char color[3], index, indexes[16], indices[16]; color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255); color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255); color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255); index=0; ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index); for (i=0; i< 16; i++) indexes[i]=index; RemapIndices(map,indexes,indices); WriteIndices(image,start,end,indices); } static void WriteUncompressed(Image *image, ExceptionInfo *exception) { const PixelPacket *p; ssize_t x; ssize_t y; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p))); if (image->matte) (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p))); p++; } } }
convolution_pack8to1_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 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 convolution_pack8to1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_int8, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { int* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); const signed char* kptr = weight_data_int8.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const signed char* sptr = m.row<const signed char>(i * stride_h) + j * stride_w * 8; for (int k = 0; k < maxk; k++) { int8x8_t _val = vld1_s8(sptr + space_ofs[k] * 8); int8x8_t _w = vld1_s8(kptr); int16x8_t _s8 = vmull_s8(_val, _w); _sum0 = vaddw_s16(_sum0, vget_low_s16(_s8)); _sum1 = vaddw_s16(_sum1, vget_high_s16(_s8)); kptr += 8; } } int32x4_t _sum = vaddq_s32(_sum0, _sum1); #if __aarch64__ int sum = vaddvq_s32(_sum); // dot #else int32x2_t _ss = vadd_s32(vget_low_s32(_sum), vget_high_s32(_sum)); _ss = vpadd_s32(_ss, _ss); int sum = vget_lane_s32(_ss, 0); #endif outptr[j] = sum; } outptr += outw; } } }
parallelEnvironment.c
/***************************************************************************** * * * Mixed-mode OpenMP/MPI MicroBenchmark Suite - Version 1.0 * * * * produced by * * * * Mark Bull, Jim Enright and Fiona Reid * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: markb@epcc.ed.ac.uk, fiona@epcc.ed.ac.uk * * * * * * Copyright 2012, The University of Edinburgh * * * * * * 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. * * * ****************************************************************************/ /*-----------------------------------------------------------*/ /* Contains variables and routines for the parallel */ /* environment. */ /* Routines to setup the MPI and OpenMP programming */ /* environment. */ /* Header file = parallelEnvironment.h */ /*-----------------------------------------------------------*/ #include "parallelEnvironment.h" #include "output.h" /*-----------------------------------------------------------*/ /* initParallelEnv */ /* */ /* Initialises the MPI and OpenMP environments. */ /* Finds the total number of MPI processes and */ /* OpenMP threads. */ /* Also finds the ID of each MPI process and OpenMP thread. */ /*-----------------------------------------------------------*/ int initParallelEnv(){ /* Setup MPI programming environment */ MPI_Init_thread(NULL, NULL, MPI_THREAD_MULTIPLE, &threadSupport); comm = MPI_COMM_WORLD; MPI_Comm_size(comm, &numMPIprocs); MPI_Comm_rank(comm, &myMPIRank); /*Find the number of bytes for an int */ sizeInteger = sizeof(int); /* Find the processor name of each MPI process */ MPI_Get_processor_name(myProcName, &procNameLen); /* Use processor name to create a communicator * across node boundaries. */ setupCommunicators(); /* setup OpenMP programming environment */ #pragma omp parallel default(none) \ shared(numThreads,globalIDarray,myMPIRank) { numThreads = omp_get_num_threads(); myThreadID = omp_get_thread_num(); /* Allocate space for globalIDarray */ #pragma omp single { globalIDarray = (int *)malloc(numThreads * sizeof(int)); } /*calculate the globalID for each thread */ globalIDarray[myThreadID] = (myMPIRank * numThreads) + myThreadID; } /* set parallel info in benchmark report type */ setParallelInfo(numMPIprocs,threadSupport,numThreads); return 0; } /*-----------------------------------------------------------*/ /* finaliseParallelEnv */ /* */ /* Closes the MPI programming environment. */ /* */ /*-----------------------------------------------------------*/ int finaliseParallelEnv(){ /* finalise the MPI programming environment */ MPI_Finalize(); /*free the space created for globalIDarray...*/ free(globalIDarray); return 0; } /*-----------------------------------------------------------*/ /* findRank */ /* */ /* Finds the MPI ranks which will take part in the pingping */ /* or pingpong benchmarks based on the numbers read from the */ /* input file. */ /*-----------------------------------------------------------*/ int findRank(int rankIn){ int CalcRank; /* Figure out actual MPI rank */ if (rankIn < 0){ CalcRank = numMPIprocs + rankIn; } else{ CalcRank = rankIn; } /* Check if findRank is too big or still -ve */ if (CalcRank > (numMPIprocs-1)){ printf("Warning: Rank input greater than total process count.\n"); printf("Using Rank = %d ", numMPIprocs-1); CalcRank = numMPIprocs - 1; } else if(CalcRank < 0){ printf("Warning: MPI process offset greater than total process count.\n"); printf("Using Rank = 0 "); CalcRank = 0; } return CalcRank; } /*-----------------------------------------------------------*/ /* findNeighbourRanks */ /* */ /* This creates a cartesian topology and finds the left */ /* and right neighbours of each process. */ /*-----------------------------------------------------------*/ int findNeighbours(){ int dims[1]; int periods[1]; int reorder; /* find a good process distribution */ dims[0] = 0; /* zero so that dims_create tries to rearrange */ MPI_Dims_create(numMPIprocs, 1, dims); /* set periods equal to TURE for periodic boundary conditions ... */ periods[0] = TRUE; /* ...and reorder = FALSE */ reorder = FALSE; /* Create the cartesian topology */ MPI_Cart_create(comm, 1, dims, periods, reorder, &commCart); /* Find the ranks of the left and right neighbour */ MPI_Cart_shift(commCart, 0, 1, &leftNeighbour, &rightNeighbour); return 0; } /*-----------------------------------------------------------*/ /* benchmarkSupport */ /* */ /* This function compares the level of thread support */ /* needed by a particular benchmark with the level provided */ /* by the implementation. */ /*-----------------------------------------------------------*/ int benchmarkSupport(int required){ int benchSupport; if (required <= threadSupport){ benchSupport = TRUE; } else { benchSupport = FALSE; } return benchSupport; } /*-----------------------------------------------------------*/ /* compareProcNames */ /* */ /* Compares the names of 2 processes to check if they are on */ /* the same node or not. */ /*-----------------------------------------------------------*/ int compareProcNames(int rankA, int rankB){ int sameNode; char recvProcName[MPI_MAX_PROCESSOR_NAME]; /* Rank B sends procName to Rank A */ if (myMPIRank == rankB){ MPI_Send(myProcName, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, rankA, TAG, comm); } else if (myMPIRank == rankA){ MPI_Recv(recvProcName, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, rankB, TAG, comm, &status); /* Rank B compares the two processor names */ if (strcmp(myProcName,recvProcName) == 0){ sameNode = TRUE; } else{ sameNode = FALSE; } } /* Rank A then broadcasts its sameNode value to the other processes */ MPI_Bcast(&sameNode, 1, MPI_INT, rankA, comm); return sameNode; } /*-----------------------------------------------------------*/ /* setupCommunicators */ /* */ /* This creates two new communicators. */ /* The first gives a local communicator for processes on */ /* the same node. */ /* The second uses the local rank to give a communicator */ /* across node boundaries. */ /* */ /* e.g. for 16 nodes each with 2 processors, this routine */ /* will give 16 local communicators of size 2 and */ /* 2 communicators of size 2 across nodes. */ /*-----------------------------------------------------------*/ int setupCommunicators(){ int procHash; /* Get hash from processor name */ procHash = procNameToHash(); /* Comm_split using procHash as colour to get * local communicator. */ MPI_Comm_split(comm, procHash, 0, &localComm); /* Find ranks of processes in localComm */ MPI_Comm_rank(localComm, &localCommRank); /* Find the size of localComm (for use in calculating multi datasize) */ MPI_Comm_size(localComm, &localCommSize); /* Use localRank as colour to get communicator across nodes. */ MPI_Comm_split(comm, localCommRank, 0, &crossComm); /* Find ranks of processes in crossComm */ MPI_Comm_rank(crossComm, &crossCommRank); return 0; } /*-----------------------------------------------------------*/ /* procNameToHash */ /* */ /* Creates an integer hash for each process. */ /* Each process on the same node will have the same hash */ /* value. */ /*-----------------------------------------------------------*/ int procNameToHash(){ int procHash,i; /* Initialise hash to 0 */ procHash = 0; for (i=0; i<procNameLen; i++){ procHash = (7 * procHash) + (int)(myProcName[i]); } return procHash; } /*-----------------------------------------------------------*/ /* exchangeWorldRanks */ /* */ /* Finds the MPI_COMM_WORLD ranks of the processes */ /* participating in the multi-pingpong and multi-pingping */ /* benchmarks. */ /*-----------------------------------------------------------*/ int exchangeWorldRanks(int nodeA, int nodeB, int *otherWorldRank){ int destRank; if (crossCommRank == nodeA){ destRank = nodeB; } else if (crossCommRank == nodeB){ destRank = nodeA; } if (crossCommRank == nodeA || crossCommRank == nodeB){ /* Start send of comm_world rank to destRank in crossComm */ MPI_Isend(&myMPIRank, 1, MPI_INT, destRank, TAG, crossComm, &requestID); /* Then wait for message from destRank and store in otherWorldRank. */ MPI_Recv(otherWorldRank, 1, MPI_INT, destRank, TAG, crossComm, &status); MPI_Wait(&requestID, &status); } return 0; } /*-----------------------------------------------------------*/ /* sendProcName */ /* */ /* Sends the processor name from processes in destNode */ /* of crossComm to srcNode. */ /*-----------------------------------------------------------*/ int sendProcName(int destNode, int srcNode, char *destProcName){ /* MPI processes under srcNode of crossComm send their * processor name to destNode. */ if (crossCommRank == srcNode){ MPI_Send(myProcName, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, \ destNode, TAG, crossComm); } else if (crossCommRank == destNode){ MPI_Recv(destProcName, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, \ srcNode, TAG, crossComm, &status); } } /*-----------------------------------------------------------*/ /* checkCrossCommBalance */ /* */ /* Checks if there's a balance in the number of processes */ /* in crossComm nodes. */ /*-----------------------------------------------------------*/ int crossCommBalance(int nodeA, int nodeB){ int localCommSize, otherLocalCommSize; int crossCommBalance; /* Find the size of localComm */ MPI_Comm_size(localComm, &localCommSize); /* Master process on nodeB sends localCommSize */ if ((crossCommRank == nodeB) && (localCommRank == 0)){ MPI_Send(&localCommSize, 1, MPI_INT, nodeA, TAG, crossComm); } /* Master process on nodeA... */ else if ((crossCommRank == nodeA) && (localCommRank == 0)){ /* 1) receives nodeB's localCommSize */ MPI_Recv(&otherLocalCommSize, 1, MPI_INT, nodeB, TAG, \ crossComm, &status); /* 2) Test for balance by comparing otherLocalCommSize * to localCommSize. */ if (localCommSize == otherLocalCommSize){ /* Set balance to TRUE */ crossCommBalance = TRUE; } else{ crossCommBalance = FALSE; } /* 3) Send balance to master commWorld process. * Only need explicit send if commWorld is not same * process as master process on nodeA. */ if (myMPIRank != 0){ MPI_Send(&crossCommBalance, 1, MPI_INT, 0, TAG, comm); } } /* Master commWorld process.. */ if (myMPIRank == 0){ /* Receives balance variable if not same process as * master process on nodeA. */ if ((crossCommRank != nodeA) && (localCommRank != 0)){ MPI_Recv(&crossCommRank, 1, MPI_INT, MPI_ANY_SOURCE, \ TAG, comm, &status); } } /* Broadcast balance to all processes */ MPI_Bcast(&crossCommBalance, 1, MPI_INT, 0, comm); return crossCommBalance; }
decorate.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD EEEEE CCCC OOO RRRR AAA TTTTT EEEEE % % D D E C O O R R A A T E % % D D EEE C O O RRRR AAAAA T EEE % % D D E C O O R R A A T E % % DDDD EEEEE CCCC OOO R R A A T EEEEE % % % % % % MagickCore Image Decoration Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % 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 "magick/studio.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/color-private.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/decorate.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/quantum.h" #include "magick/resource_.h" #include "magick/thread-private.h" #include "magick/transform.h" /* Define declarations. */ #define AccentuateModulate ScaleCharToQuantum(80) #define HighlightModulate ScaleCharToQuantum(125) #define ShadowModulate ScaleCharToQuantum(135) #define DepthModulate ScaleCharToQuantum(185) #define TroughModulate ScaleCharToQuantum(110) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B o r d e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BorderImage() surrounds the image with a border of the color defined by % the bordercolor member of the image structure. The width and height % of the border are defined by the corresponding members of the border_info % structure. % % The format of the BorderImage method is: % % Image *BorderImage(const Image *image,const RectangleInfo *border_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o border_info: Define the width and height of the border. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BorderImage(const Image *image, const RectangleInfo *border_info,ExceptionInfo *exception) { Image *border_image, *clone_image; FrameInfo frame_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(border_info != (RectangleInfo *) NULL); frame_info.width=image->columns+(border_info->width << 1); frame_info.height=image->rows+(border_info->height << 1); frame_info.x=(ssize_t) border_info->width; frame_info.y=(ssize_t) border_info->height; frame_info.inner_bevel=0; frame_info.outer_bevel=0; clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); clone_image->matte_color=image->border_color; border_image=FrameImage(clone_image,&frame_info,exception); clone_image=DestroyImage(clone_image); if (border_image != (Image *) NULL) border_image->matte_color=image->matte_color; return(border_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F r a m e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FrameImage() adds a simulated three-dimensional border around the image. % The color of the border is defined by the matte_color member of image. % Members width and height of frame_info specify the border width of the % vertical and horizontal sides of the frame. Members inner and outer % indicate the width of the inner and outer shadows of the frame. % % The format of the FrameImage method is: % % Image *FrameImage(const Image *image,const FrameInfo *frame_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o frame_info: Define the width and height of the frame and its bevels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *FrameImage(const Image *image,const FrameInfo *frame_info, ExceptionInfo *exception) { #define FrameImageTag "Frame/Image" CacheView *image_view, *frame_view; Image *frame_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket accentuate, border, highlight, matte, shadow, trough; register ssize_t x; size_t bevel_width, height, width; ssize_t y; /* Check frame geometry. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(frame_info != (FrameInfo *) NULL); if ((frame_info->outer_bevel < 0) || (frame_info->inner_bevel < 0)) ThrowImageException(OptionError,"FrameIsLessThanImageSize"); bevel_width=(size_t) (frame_info->outer_bevel+frame_info->inner_bevel); x=(ssize_t) frame_info->width-frame_info->x-bevel_width; y=(ssize_t) frame_info->height-frame_info->y-bevel_width; if ((x < (ssize_t) image->columns) || (y < (ssize_t) image->rows)) ThrowImageException(OptionError,"FrameIsLessThanImageSize"); /* Initialize framed image attributes. */ frame_image=CloneImage(image,frame_info->width,frame_info->height,MagickTrue, exception); if (frame_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(frame_image,DirectClass) == MagickFalse) { InheritException(exception,&frame_image->exception); frame_image=DestroyImage(frame_image); return((Image *) NULL); } if ((IsPixelGray(&frame_image->border_color) == MagickFalse) && (IsGrayColorspace(frame_image->colorspace) != MagickFalse)) (void) SetImageColorspace(frame_image,sRGBColorspace); if ((frame_image->border_color.opacity != OpaqueOpacity) && (frame_image->matte == MagickFalse)) (void) SetImageAlphaChannel(frame_image,OpaqueAlphaChannel); frame_image->page=image->page; if ((image->page.width != 0) && (image->page.height != 0)) { frame_image->page.width+=frame_image->columns-image->columns; frame_image->page.height+=frame_image->rows-image->rows; } /* Initialize 3D effects color. */ GetMagickPixelPacket(frame_image,&matte); matte.colorspace=sRGBColorspace; SetMagickPixelPacket(frame_image,&image->matte_color,(IndexPacket *) NULL, &matte); GetMagickPixelPacket(frame_image,&border); border.colorspace=sRGBColorspace; SetMagickPixelPacket(frame_image,&image->border_color,(IndexPacket *) NULL, &border); GetMagickPixelPacket(frame_image,&accentuate); accentuate.red=(MagickRealType) (QuantumScale*((QuantumRange- AccentuateModulate)*matte.red+(QuantumRange*AccentuateModulate))); accentuate.green=(MagickRealType) (QuantumScale*((QuantumRange- AccentuateModulate)*matte.green+(QuantumRange*AccentuateModulate))); accentuate.blue=(MagickRealType) (QuantumScale*((QuantumRange- AccentuateModulate)*matte.blue+(QuantumRange*AccentuateModulate))); accentuate.opacity=matte.opacity; GetMagickPixelPacket(frame_image,&highlight); highlight.red=(MagickRealType) (QuantumScale*((QuantumRange- HighlightModulate)*matte.red+(QuantumRange*HighlightModulate))); highlight.green=(MagickRealType) (QuantumScale*((QuantumRange- HighlightModulate)*matte.green+(QuantumRange*HighlightModulate))); highlight.blue=(MagickRealType) (QuantumScale*((QuantumRange- HighlightModulate)*matte.blue+(QuantumRange*HighlightModulate))); highlight.opacity=matte.opacity; GetMagickPixelPacket(frame_image,&shadow); shadow.red=QuantumScale*matte.red*ShadowModulate; shadow.green=QuantumScale*matte.green*ShadowModulate; shadow.blue=QuantumScale*matte.blue*ShadowModulate; shadow.opacity=matte.opacity; GetMagickPixelPacket(frame_image,&trough); trough.red=QuantumScale*matte.red*TroughModulate; trough.green=QuantumScale*matte.green*TroughModulate; trough.blue=QuantumScale*matte.blue*TroughModulate; trough.opacity=matte.opacity; if (image->colorspace == CMYKColorspace) { ConvertRGBToCMYK(&matte); ConvertRGBToCMYK(&border); ConvertRGBToCMYK(&accentuate); ConvertRGBToCMYK(&highlight); ConvertRGBToCMYK(&shadow); ConvertRGBToCMYK(&trough); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); frame_view=AcquireAuthenticCacheView(frame_image,exception); height=(size_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+ frame_info->inner_bevel); if (height != 0) { register IndexPacket *magick_restrict frame_indexes; register ssize_t x; register PixelPacket *magick_restrict q; /* Draw top of ornamental border. */ q=QueueCacheViewAuthenticPixels(frame_view,0,0,frame_image->columns, height,exception); frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view); if (q != (PixelPacket *) NULL) { /* Draw top of ornamental border. */ for (y=0; y < (ssize_t) frame_info->outer_bevel; y++) { for (x=0; x < (ssize_t) (frame_image->columns-y); x++) { if (x < y) SetPixelPacket(frame_image,&highlight,q,frame_indexes); else SetPixelPacket(frame_image,&accentuate,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) frame_image->columns; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } for (y=0; y < (ssize_t) (frame_info->y-bevel_width); y++) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_image->columns-2*frame_info->outer_bevel; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } for (y=0; y < (ssize_t) frame_info->inner_bevel; y++) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } width=image->columns+((size_t) frame_info->inner_bevel << 1)- y; for (x=0; x < (ssize_t) width; x++) { if (x < y) SetPixelPacket(frame_image,&shadow,q,frame_indexes); else SetPixelPacket(frame_image,&trough,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_info->width-frame_info->x-image->columns-bevel_width; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } (void) SyncCacheViewAuthenticPixels(frame_view,exception); } } /* Draw sides of ornamental border. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,frame_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict frame_indexes; register ssize_t x; register PixelPacket *magick_restrict q; /* Initialize scanline with matte color. */ if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(frame_view,0,frame_info->y+y, frame_image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view); for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->inner_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } /* Set frame interior pixels. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelPacket(frame_image,&border,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->inner_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_info->width-frame_info->x-image->columns-bevel_width; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } if (SyncCacheViewAuthenticPixels(frame_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FrameImage) #endif proceed=SetImageProgress(image,FrameImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } height=(size_t) (frame_info->inner_bevel+frame_info->height- frame_info->y-image->rows-bevel_width+frame_info->outer_bevel); if (height != 0) { register IndexPacket *magick_restrict frame_indexes; register ssize_t x; register PixelPacket *magick_restrict q; /* Draw bottom of ornamental border. */ q=QueueCacheViewAuthenticPixels(frame_view,0,(ssize_t) (frame_image->rows- height),frame_image->columns,height,exception); if (q != (PixelPacket *) NULL) { /* Draw bottom of ornamental border. */ frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view); for (y=frame_info->inner_bevel-1; y >= 0; y--) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < y; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++) { if (x >= (ssize_t) (image->columns+2*frame_info->inner_bevel-y)) SetPixelPacket(frame_image,&highlight,q,frame_indexes); else SetPixelPacket(frame_image,&accentuate,q,frame_indexes); q++; frame_indexes++; } width=frame_info->width-frame_info->x-image->columns-bevel_width; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } height=frame_info->height-frame_info->y-image->rows-bevel_width; for (y=0; y < (ssize_t) height; y++) { for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } width=frame_image->columns-2*frame_info->outer_bevel; for (x=0; x < (ssize_t) width; x++) { SetPixelPacket(frame_image,&matte,q,frame_indexes); q++; frame_indexes++; } for (x=0; x < (ssize_t) frame_info->outer_bevel; x++) { SetPixelPacket(frame_image,&shadow,q,frame_indexes); q++; frame_indexes++; } } for (y=frame_info->outer_bevel-1; y >= 0; y--) { for (x=0; x < y; x++) { SetPixelPacket(frame_image,&highlight,q,frame_indexes); q++; frame_indexes++; } for ( ; x < (ssize_t) frame_image->columns; x++) { if (x >= (ssize_t) (frame_image->columns-y)) SetPixelPacket(frame_image,&shadow,q,frame_indexes); else SetPixelPacket(frame_image,&trough,q,frame_indexes); q++; frame_indexes++; } } (void) SyncCacheViewAuthenticPixels(frame_view,exception); } } frame_view=DestroyCacheView(frame_view); image_view=DestroyCacheView(image_view); x=(ssize_t) (frame_info->outer_bevel+(frame_info->x-bevel_width)+ frame_info->inner_bevel); y=(ssize_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+ frame_info->inner_bevel); if (status != MagickFalse) status=CompositeImage(frame_image,image->compose,image,x,y); if (status == MagickFalse) frame_image=DestroyImage(frame_image); return(frame_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RaiseImage() creates a simulated three-dimensional button-like effect % by lightening and darkening the edges of the image. Members width and % height of raise_info define the width of the vertical and horizontal % edge of the effect. % % The format of the RaiseImage method is: % % MagickBooleanType RaiseImage(const Image *image, % const RectangleInfo *raise_info,const MagickBooleanType raise) % % A description of each parameter follows: % % o image: the image. % % o raise_info: Define the width and height of the raise area. % % o raise: A value other than zero creates a 3-D raise effect, % otherwise it has a lowered effect. % */ MagickExport MagickBooleanType RaiseImage(Image *image, const RectangleInfo *raise_info,const MagickBooleanType raise) { #define AccentuateFactor ScaleCharToQuantum(135) #define HighlightFactor ScaleCharToQuantum(190) #define ShadowFactor ScaleCharToQuantum(190) #define RaiseImageTag "Raise/Image" #define TroughFactor ScaleCharToQuantum(135) CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; Quantum foreground, background; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(raise_info != (RectangleInfo *) NULL); if ((image->columns <= (raise_info->width << 1)) || (image->rows <= (raise_info->height << 1))) ThrowBinaryException(OptionError,"ImageSizeMustExceedBevelWidth", image->filename); foreground=QuantumRange; background=(Quantum) 0; if (raise == MagickFalse) { foreground=(Quantum) 0; background=QuantumRange; } if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); /* Raise image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,raise_info->height,1) #endif for (y=0; y < (ssize_t) raise_info->height; y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < y; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); q++; } for ( ; x < (ssize_t) (image->columns-y); x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*AccentuateFactor+(MagickRealType) foreground* (QuantumRange-AccentuateFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*AccentuateFactor+(MagickRealType) foreground* (QuantumRange-AccentuateFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*AccentuateFactor+(MagickRealType) foreground* (QuantumRange-AccentuateFactor)))); q++; } for ( ; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RaiseImage) #endif proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows-2*raise_info->height,1) #endif for (y=(ssize_t) raise_info->height; y < (ssize_t) (image->rows-raise_info->height); y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) raise_info->width; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); q++; } for ( ; x < (ssize_t) (image->columns-raise_info->width); x++) q++; for ( ; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RaiseImage) #endif proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows-raise_info->height,1) #endif for (y=(ssize_t) (image->rows-raise_info->height); y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) (image->rows-y); x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground* (QuantumRange-HighlightFactor)))); q++; } for ( ; x < (ssize_t) (image->columns-(image->rows-y)); x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*TroughFactor+(MagickRealType) background* (QuantumRange-TroughFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*TroughFactor+(MagickRealType) background* (QuantumRange-TroughFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*TroughFactor+(MagickRealType) background* (QuantumRange-TroughFactor)))); q++; } for ( ; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelRed(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelGreen(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType) GetPixelBlue(q)*ShadowFactor+(MagickRealType) background* (QuantumRange-ShadowFactor)))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RaiseImage) #endif proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
GB_unaryop__lnot_int8_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_int8_fp32 // op(A') function: GB_tran__lnot_int8_fp32 // C type: int8_t // A type: float // cast: int8_t cij ; GB_CAST_SIGNED(cij,aij,8) // unaryop: cij = !(aij != 0) #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 != 0) ; // casting #define GB_CASTING(z, x) \ int8_t z ; GB_CAST_SIGNED(z,x,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 (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT8 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int8_fp32 ( int8_t *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_int8_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
solver.c
// solver.c - CPHIS solver implementation #include <cphis.h> #include <solver.h> #include <conf.h> #include <aux.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif static CphisError CphisSolverCleanupScale(CphisSolver solver, int scale) { int skipAscale = 0; if ( scale == solver->conf->numScales - 1 && solver->conf->scales[2*scale] == 0 ) { skipAscale = 1; } if (!skipAscale && solver->Ascale[scale]) { CphisMatDestroy(solver->Ascale[scale]); } if (solver->Aresidual[scale]) CphisMatDestroy(solver->Aresidual[scale]); if (solver->Arhs[scale]) CphisMatDestroy(solver->Arhs[scale]); if (solver->r[scale]) CphisVecDestroy(solver->r[scale]); if (solver->e[scale]) CphisVecDestroy(solver->e[scale]); if (solver->fscale[scale]) CphisVecDestroy(solver->fscale[scale]); if (solver->uscale[scale]) CphisVecDestroy(solver->uscale[scale]); if (solver->urhs[scale]) CphisVecDestroy(solver->urhs[scale]); return CPHIS_SUCCESS; } static CphisError CphisSolverSetupScale(CphisSolver solver, int scale) { CphisError err; // Make sure that it is always safe to abort. solver->Ascale[scale] = NULL; solver->Aresidual[scale] = NULL; solver->Arhs[scale] = NULL; solver->r[scale] = NULL; solver->e[scale] = NULL; solver->fscale[scale] = NULL; solver->uscale[scale] = NULL; solver->urhs[scale] = NULL; // Prepare creation of matrices and vectors. const CphisBackendType type = solver->A->type; const CphisIndex numElements = solver->A->numElements; const CphisIndex *elements = solver->A->elements; // Gather some information about the scale. // Number of local d.o.f. in the system const int numLocalDOF = solver->conf->numLocalDOF; // Number of matrix rows const CphisIndex numRows = numElements*numLocalDOF; // Number of local d.o.f. that are smoothed on this scale const int numLocalDOFScale = solver->conf->scales[2*scale + 1] - solver->conf->scales[2*scale] + 1; // Minimum local d.o.f. that is smoothed on this scale const int minLocalDOFScale = solver->conf->scales[2*scale]; // Maximum local d.o.f. that is smoothed on this scale const int maxLocalDOFScale = solver->conf->scales[2*scale + 1]; // Number of local d.o.f. in the residual, i.e., in all lower scales combined int numLocalDOFResidual = -1; if (scale > 0) { numLocalDOFResidual = solver->conf->scales[2*(scale - 1) + 1] + 1; } // Maximum local d.o.f. in the residual, i.e., in any of the lower scales int maxLocalDOFResidual = -1; if (scale > 0) { maxLocalDOFResidual = solver->conf->scales[2*(scale - 1) + 1]; } // Is the scale of HSS-type, i.e., does it smooth only a subset of its local // d.o.f.? const int isHSSType = minLocalDOFScale != 0; // Is this an error correction scale, i.e., one that starts with an initial // guess of zero? const int isErrorCorrectionScale = scale < solver->conf->numScales - 1; // Number of local d.o.f. in this scale that will affect the residual int numLocalDOFScaleToResidual; if (isErrorCorrectionScale) { // Only the smoothed local d.o.f. affect the residual. numLocalDOFScaleToResidual = numLocalDOFScale; } else { // All local d.o.f. affect the residual. numLocalDOFScaleToResidual = maxLocalDOFScale + 1; } // Minimum local d.o.f. that will affect the residual int minLocalDOFScaleToResidual; if (isErrorCorrectionScale) { minLocalDOFScaleToResidual = minLocalDOFScale; } else { minLocalDOFScaleToResidual = 0; } // If the highest scale includes all lower d.o.f. (as in standard // p-multigrid), Ascale[numScales - 1] is equal to the original system matrix, // so we do not have to create a copy. int skipAscale = 0; if (scale == solver->conf->numScales - 1 && !isHSSType) { solver->Ascale[scale] = solver->A; skipAscale = 1; } if (!skipAscale) { err = CphisMatCreate( &solver->Ascale[scale], numElements, elements, numLocalDOFScale, numLocalDOFScale, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } // Aresidual, r, and e are only needed on higher scales, and their size is // determined by the maximum local d.o.f. in the next lower scale. if (scale > 0) { err = CphisVecCreate( &solver->r[scale], numElements, elements, numLocalDOFResidual, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } err = CphisVecCreate( &solver->e[scale], numElements, elements, numLocalDOFResidual, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } err = CphisMatCreate( &solver->Aresidual[scale], numElements, elements, numLocalDOFResidual, numLocalDOFScaleToResidual, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } // Arhs, fscale, and uscale are only needed on HSS-type scales. Their size is // determined by the number of local d.o.f. that are smoothed on the current // scale. if (isHSSType) { err = CphisVecCreate( &solver->fscale[scale], numElements, elements, numLocalDOFScale, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } err = CphisVecCreate( &solver->uscale[scale], numElements, elements, numLocalDOFScale, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } err = CphisVecCreate( &solver->urhs[scale], numElements, elements, minLocalDOFScale, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } err = CphisMatCreate( &solver->Arhs[scale], numElements, elements, numLocalDOFScale, minLocalDOFScale, type, NULL ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } // Extract the matrix blocks. for (CphisIndex i = 0; i < numRows; i++) { const int rowLocalDOF = i%numLocalDOF; if (rowLocalDOF > maxLocalDOFScale) { // Matrix row belongs to a higher scale, so we skip it. continue; } // Get matrix entries in this row. const CphisIndex *cols; const CphisScalar *vals; CphisIndex numEntries; err = CphisMatGetData( solver->A, i, &cols, &vals, &numEntries ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } // Check if the row belongs to the current scale and/or to lower scales. const int isRowInScale = rowLocalDOF >= minLocalDOFScale; const int isRowInResidual = rowLocalDOF <= maxLocalDOFResidual; for (CphisIndex j = 0; j < numEntries; j++) { const int colLocalDOF = cols[j]%numLocalDOF; if (colLocalDOF > maxLocalDOFScale) { // Column belongs to a higher scale, so we skip it. continue; } // Check if the row belongs to the current scale. const int isColInScale = colLocalDOF >= minLocalDOFScale; CphisIndex iBlock, jBlock; if (!skipAscale && isRowInScale && isColInScale) { // Entry goes to Ascale. iBlock = (i/numLocalDOF)*numLocalDOFScale + rowLocalDOF - minLocalDOFScale; jBlock = (cols[j]/numLocalDOF)*numLocalDOFScale + colLocalDOF - minLocalDOFScale; err = CphisMatSet( solver->Ascale[scale], iBlock, jBlock, vals[j] ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } if (isRowInResidual && (!isErrorCorrectionScale || isColInScale)) { // Entry goes to Aresidual. iBlock = (i/numLocalDOF)*numLocalDOFResidual + rowLocalDOF; jBlock = (cols[j]/numLocalDOF)*numLocalDOFScaleToResidual + colLocalDOF - minLocalDOFScaleToResidual; err = CphisMatSet( solver->Aresidual[scale], iBlock, jBlock, vals[j] ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } if (isRowInScale && !isColInScale) { // Entry goes to Arhs. iBlock = (i/numLocalDOF)*numLocalDOFScale + rowLocalDOF - minLocalDOFScale; jBlock = (cols[j]/numLocalDOF)*minLocalDOFScale + colLocalDOF; err = CphisMatSet( solver->Arhs[scale], iBlock, jBlock, vals[j] ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } } } // Finalize matrices. if (!skipAscale) { err = CphisMatFinalize(solver->Ascale[scale]); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } if (scale > 0) { err = CphisMatFinalize(solver->Aresidual[scale]); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } if (isHSSType) { err = CphisMatFinalize(solver->Arhs[scale]); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } } // Set up scale solver. err = CphisScaleSolverSetup( solver->conf->solvers[scale], solver->Ascale[scale] ); if (err) { CphisSolverCleanupScale(solver, scale); CPHISCHECK(err); } return CPHIS_SUCCESS; } CphisError CphisSolverCreate( CphisSolver *solver, const CphisConf conf, const CphisMat A ) { CphisError err; #ifdef _OPENMP const double tStart = omp_get_wtime(); #endif *solver = malloc(sizeof(struct _CphisSolver)); if (!(*solver)) { CPHISCHECK(CPHIS_FAILED_ALLOC); } // Make sure that it is always safe to clean up. (*solver)->rfull = NULL; (*solver)->Ascale = NULL; (*solver)->Aresidual = NULL; (*solver)->Arhs = NULL; (*solver)->r = NULL; (*solver)->e = NULL; (*solver)->fscale = NULL; (*solver)->uscale = NULL; (*solver)->urhs = NULL; (*solver)->iterCoarseScale = 0; err = CphisVecCreate( &(*solver)->rfull, A->numElements, A->elements, A->numLocalDOFRange, A->type, NULL );CPHISCHECK(err); // Allocate arrays for matrix and vector handles. // The only possible errors here are failed allocations. err = CPHIS_FAILED_ALLOC; (*solver)->Ascale = malloc(conf->numScales*sizeof(CphisMat)); if (!(*solver)->Ascale) goto cphis_solver_create_cleanup; (*solver)->Aresidual = malloc(conf->numScales*sizeof(CphisMat)); if (!(*solver)->Aresidual) goto cphis_solver_create_cleanup; (*solver)->Arhs = malloc(conf->numScales*sizeof(CphisMat)); if (!(*solver)->Arhs) goto cphis_solver_create_cleanup; (*solver)->r = malloc(conf->numScales*sizeof(CphisVec)); if (!(*solver)->r) goto cphis_solver_create_cleanup; (*solver)->e = malloc(conf->numScales*sizeof(CphisVec)); if (!(*solver)->e) goto cphis_solver_create_cleanup; (*solver)->fscale = malloc(conf->numScales*sizeof(CphisVec)); if (!(*solver)->fscale) goto cphis_solver_create_cleanup; (*solver)->uscale = malloc(conf->numScales*sizeof(CphisVec)); if (!(*solver)->uscale) goto cphis_solver_create_cleanup; (*solver)->urhs = malloc(conf->numScales*sizeof(CphisVec)); if (!(*solver)->urhs) goto cphis_solver_create_cleanup; (*solver)->conf = conf; (*solver)->A = A; // Set up scales. for (int s = 0; s < conf->numScales; s++) { err = CphisSolverSetupScale(*solver, s); if (err) { // Clean up and abort. for (s--; s >= 0; s--) { CphisSolverCleanupScale(*solver, s); } goto cphis_solver_create_cleanup; } } // Initialize timers. memset((*solver)->timers, 0, CPHIS_NUM_TIMERS*sizeof(double)); #ifdef _OPENMP const double tEnd = omp_get_wtime(); (*solver)->timers[CPHIS_TIMER_SETUP] += tEnd - tStart; #endif return CPHIS_SUCCESS; cphis_solver_create_cleanup: CphisVecDestroy((*solver)->rfull); free((*solver)->Ascale); free((*solver)->Aresidual); free((*solver)->Arhs); free((*solver)->r); free((*solver)->e); free((*solver)->fscale); free((*solver)->uscale); free((*solver)->urhs); free(*solver); CPHISCHECK(err); return err; // Suppress compiler warning (missing return statement). } CphisError CphisSolverDestroy(CphisSolver solver) { // Clean up scales. for (int s = 0; s < solver->conf->numScales; s++) { CphisSolverCleanupScale(solver, s); } CphisVecDestroy(solver->rfull); free(solver); return CPHIS_SUCCESS; } CphisError CphisSolverSetTolRel(CphisSolver solver, CphisReal tol) { solver->conf->rtol = tol; return CPHIS_SUCCESS; } CphisError CphisSolverSetTolAbs(CphisSolver solver, CphisReal tol) { solver->conf->atol = tol; return CPHIS_SUCCESS; } static CphisError CphisSolverSolveCoarseScale( const CphisSolver solver, const CphisVec f, const CphisVec u ) { CphisError err; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#0: Beginning coarse scale solve\n"); } #ifdef _OPENMP const double tStart = omp_get_wtime(); #endif CphisConvergenceFlag flag; CphisReal residual; int iter; err = CphisScaleSolverSolve( solver->conf->solvers[0], f, u, &flag, &residual, &iter );CPHISCHECK(err); solver->iterCoarseScale += iter; #ifdef _OPENMP const double tEnd = omp_get_wtime(); solver->timers[CPHIS_TIMER_COARSE_SOLVE] += tEnd - tStart; #endif if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf( "#0: Finished coarse scale solve\n (residual = %e, %d iter.)\n", residual, iter ); if (flag != CPHIS_CONVERGED) { CphisPrintf("#0: The coarse scale solver did not converge!\n"); } } return CPHIS_SUCCESS; } static CphisError CphisSolverSmoothHSS( const CphisSolver solver, const CphisVec f, CphisVec u, int scale, int isZeroInitialGuess ) { CphisError err; CphisScalar *fData, *fscaleData, *uData, *uscaleData, *urhsData; err = CphisVecGetData(f, &fData);CPHISCHECK(err); err = CphisVecGetData(solver->fscale[scale], &fscaleData);CPHISCHECK(err); err = CphisVecGetData(u, &uData);CPHISCHECK(err); err = CphisVecGetData(solver->uscale[scale], &uscaleData);CPHISCHECK(err); err = CphisVecGetData(solver->urhs[scale], &urhsData);CPHISCHECK(err); CphisIndex numElements; err = CphisVecGetNumElements(f, &numElements);CPHISCHECK(err); int numLocalDOFfu, numLocalDOFfuscale, numLocalDOFurhs; err = CphisVecGetNumLocalDOF(f, &numLocalDOFfu);CPHISCHECK(err); err = CphisVecGetNumLocalDOF( solver->fscale[scale], &numLocalDOFfuscale );CPHISCHECK(err); err = CphisVecGetNumLocalDOF( solver->urhs[scale], &numLocalDOFurhs );CPHISCHECK(err); if (!isZeroInitialGuess) { // We need to move the d.o.f. that are not smoothed on this scale to the // right-hand side. // First, split u into uscale and urhs. #pragma omp parallel for for (CphisIndex k = 0; k < numElements; k++) { for (int l = 0; l < numLocalDOFfu; l++) { const CphisIndex row = k*numLocalDOFfu + l; if (l < numLocalDOFurhs) { // Entry goes to urhs. urhsData[k*numLocalDOFurhs + l] = uData[row]; } else { // Entry goes to uscale. uscaleData[k*numLocalDOFfuscale + l - numLocalDOFurhs] = uData[row]; } } } // Compute right-hand side. err = CphisMatVec( solver->Arhs[scale], solver->urhs[scale], solver->fscale[scale] );CPHISCHECK(err); for (CphisIndex k = 0; k < numElements; k++) { for (int l = numLocalDOFurhs; l < numLocalDOFfu; l++) { fscaleData[k*numLocalDOFfuscale + l - numLocalDOFurhs] = fData[k*numLocalDOFfu + l] - fscaleData[k*numLocalDOFfuscale + l - numLocalDOFurhs]; } } } else { err = CphisVecSetAll(solver->uscale[scale], 0.0);CPHISCHECK(err); // Get fscale. for (CphisIndex k = 0; k < numElements; k++) { for (int l = numLocalDOFurhs; l < numLocalDOFfu; l++) { fscaleData[k*numLocalDOFfuscale + l - numLocalDOFurhs] = fData[k*numLocalDOFfu + l]; } } } // Apply the smoother to the smaller system. err = CphisScaleSolverSolve( solver->conf->solvers[scale], solver->fscale[scale], solver->uscale[scale], NULL, NULL, NULL );CPHISCHECK(err); // Use values from uscale to update u. #pragma omp parallel for for (CphisIndex k = 0; k < numElements; k++) { for (int l = numLocalDOFurhs; l < numLocalDOFfu; l++) { uData[k*numLocalDOFfu + l] = uscaleData[k*numLocalDOFfuscale + l - numLocalDOFurhs]; } } return CPHIS_SUCCESS; } static CphisError CphisSolverPresmooth( const CphisSolver solver, const CphisVec f, CphisVec u, int scale ) { CphisError err; if (solver->conf->nu1 == 0) return CPHIS_SUCCESS; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Presmoothing\n", scale); } #ifdef _OPENMP const double tStart = omp_get_wtime(); #endif // Prepare smoother. err = CphisScaleSolverSetTol( solver->conf->solvers[scale], 0.0 );CPHISCHECK(err); err = CphisScaleSolverSetMaxIter( solver->conf->solvers[scale], solver->conf->nu1 );CPHISCHECK(err); const int isHSSType = solver->conf->scales[2*scale] != 0; if (isHSSType) { const int isErrorCorrectionScale = scale < solver->conf->numScales - 1; err = CphisSolverSmoothHSS( solver, f, u, scale, isErrorCorrectionScale );CPHISCHECK(err); } else { // On standard p-multigrid scales, all we have to do is smooth call the // smoother. err = CphisScaleSolverSolve( solver->conf->solvers[scale], f, u, NULL, NULL, NULL );CPHISCHECK(err); } #ifdef _OPENMP const double tEnd = omp_get_wtime(); solver->timers[CPHIS_TIMER_PRESMOOTH] += tEnd - tStart; #endif return CPHIS_SUCCESS; } static CphisError CphisSolverComputeRestrictedResidual( const CphisSolver solver, const CphisVec f, const CphisVec u, int scale ) { CphisError err; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Computing restricted residual\n", scale); } #ifdef _OPENMP const double tStart = omp_get_wtime(); #endif const int isHSSType = solver->conf->scales[2*scale] != 0; const int isErrorCorrectionScale = scale < solver->conf->numScales - 1; if (isHSSType && isErrorCorrectionScale) { // Compute residual directly from uscale. err = CphisMatVec( solver->Aresidual[scale], solver->uscale[scale], solver->r[scale] );CPHISCHECK(err); } else { // We need to incorporate all of u in the residual computation. err = CphisMatVec( solver->Aresidual[scale], u, solver->r[scale] );CPHISCHECK(err); } CphisScalar *rData, *fData; err = CphisVecGetData(solver->r[scale], &rData);CPHISCHECK(err); err = CphisVecGetData(f, &fData);CPHISCHECK(err); CphisIndex numElements; err = CphisVecGetNumElements(f, &numElements);CPHISCHECK(err); int numLocalDOFr, numLocalDOFf; err = CphisVecGetNumLocalDOF(solver->r[scale], &numLocalDOFr);CPHISCHECK(err); err = CphisVecGetNumLocalDOF(f, &numLocalDOFf);CPHISCHECK(err); #pragma omp parallel for for (CphisIndex k = 0; k < numElements; k++) { for (int l = 0; l < numLocalDOFr; l++) { rData[k*numLocalDOFr + l] = fData[k*numLocalDOFf + l] - rData[k*numLocalDOFr + l]; } } #ifdef _OPENMP const double tEnd = omp_get_wtime(); solver->timers[CPHIS_TIMER_RESIDUAL] += tEnd - tStart; #endif return CPHIS_SUCCESS; } static CphisError CphisSolverProlongate( const CphisSolver solver, CphisVec u, int scale ) { CphisError err; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Prolongation\n", scale); } #ifdef _OPENMP const double tStart = omp_get_wtime(); #endif CphisScalar *eData, *uData; err = CphisVecGetData(solver->e[scale], &eData);CPHISCHECK(err); err = CphisVecGetData(u, &uData);CPHISCHECK(err); CphisIndex numElements; err = CphisVecGetNumElements(u, &numElements);CPHISCHECK(err); int numLocalDOFe, numLocalDOFu; err = CphisVecGetNumLocalDOF(solver->e[scale], &numLocalDOFe);CPHISCHECK(err); err = CphisVecGetNumLocalDOF(u, &numLocalDOFu);CPHISCHECK(err); #pragma omp parallel for for (CphisIndex k = 0; k < numElements; k++) { for (int l = 0; l < numLocalDOFe; l++) { uData[k*numLocalDOFu + l] += eData[k*numLocalDOFe + l]; } } #ifdef _OPENMP const double tEnd = omp_get_wtime(); solver->timers[CPHIS_TIMER_PROLONGATION] += tEnd - tStart; #endif return CPHIS_SUCCESS; } static CphisError CphisSolverPostsmooth( const CphisSolver solver, const CphisVec f, CphisVec u, int scale ) { CphisError err; if (solver->conf->nu2 == 0) return CPHIS_SUCCESS; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Postsmoothing\n", scale); } #ifdef _OPENMP const double tStart = omp_get_wtime(); #endif // Prepare smoother. err = CphisScaleSolverSetMaxIter( solver->conf->solvers[scale], solver->conf->nu2 );CPHISCHECK(err); const int isHSSType = solver->conf->scales[2*scale] != 0; if (isHSSType) { err = CphisSolverSmoothHSS(solver, f, u, scale, 0);CPHISCHECK(err); } else { // On standard p-multigrid scales, all we have to do is smooth call the // smoother. err = CphisScaleSolverSolve( solver->conf->solvers[scale], f, u, NULL, NULL, NULL );CPHISCHECK(err); } #ifdef _OPENMP const double tEnd = omp_get_wtime(); solver->timers[CPHIS_TIMER_POSTSMOOTH] += tEnd - tStart; #endif return CPHIS_SUCCESS; } static CphisError CphisSolverCycleV( const CphisSolver solver, const CphisVec f, CphisVec u, int scale ) { CphisError err; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Entering\n", scale); } if (scale == 0) { err = CphisSolverSolveCoarseScale(solver, f, u);CPHISCHECK(err); if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#0: Leaving\n"); } return CPHIS_SUCCESS; } err = CphisSolverPresmooth(solver, f, u, scale);CPHISCHECK(err); err = CphisSolverComputeRestrictedResidual( solver, f, u, scale );CPHISCHECK(err); // A V-cycle is just a simple recursion. err = CphisVecSetAll(solver->e[scale], 0.0);CPHISCHECK(err); err = CphisSolverCycleV( solver, solver->r[scale], solver->e[scale], scale - 1 );CPHISCHECK(err); err = CphisSolverProlongate(solver, u, scale);CPHISCHECK(err); err = CphisSolverPostsmooth(solver, f, u, scale);CPHISCHECK(err); if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Leaving\n", scale); } return CPHIS_SUCCESS; } static CphisError CphisSolverCycleW( const CphisSolver solver, const CphisVec f, CphisVec u, int scale ) { CphisError err; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Entering\n", scale); } if (scale == 0) { err = CphisSolverSolveCoarseScale(solver, f, u);CPHISCHECK(err); if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#0: Leaving\n"); } return CPHIS_SUCCESS; } err = CphisSolverPresmooth(solver, f, u, scale);CPHISCHECK(err); err = CphisSolverComputeRestrictedResidual( solver, f, u, scale );CPHISCHECK(err); // A W-cycle recurses twice. err = CphisVecSetAll(solver->e[scale], 0.0);CPHISCHECK(err); err = CphisSolverCycleW( solver, solver->r[scale], solver->e[scale], scale - 1 );CPHISCHECK(err); err = CphisSolverCycleW( solver, solver->r[scale], solver->e[scale], scale - 1 );CPHISCHECK(err); err = CphisSolverProlongate(solver, u, scale);CPHISCHECK(err); err = CphisSolverPostsmooth(solver, f, u, scale);CPHISCHECK(err); if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Leaving\n", scale); } return CPHIS_SUCCESS; } static CphisError CphisSolverCycleF( const CphisSolver solver, const CphisVec f, CphisVec u, int scale ) { CphisError err; if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Entering\n", scale); } if (scale == 0) { err = CphisSolverSolveCoarseScale(solver, f, u);CPHISCHECK(err); if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#0: Leaving\n"); } return CPHIS_SUCCESS; } err = CphisSolverPresmooth(solver, f, u, scale);CPHISCHECK(err); err = CphisSolverComputeRestrictedResidual( solver, f, u, scale );CPHISCHECK(err); // Like the W-cycle, the F-cycle recurses twice. // However, the second recursion is a simple V-cycle. err = CphisVecSetAll(solver->e[scale], 0.0);CPHISCHECK(err); err = CphisSolverCycleF( solver, solver->r[scale], solver->e[scale], scale - 1 );CPHISCHECK(err); err = CphisSolverCycleV( solver, solver->r[scale], solver->e[scale], scale - 1 );CPHISCHECK(err); err = CphisSolverProlongate(solver, u, scale);CPHISCHECK(err); err = CphisSolverPostsmooth(solver, f, u, scale);CPHISCHECK(err); if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { CphisPrintf("#%d: Leaving\n", scale); } return CPHIS_SUCCESS; } static CphisError CphisSolverCycle( const CphisSolver solver, const CphisVec f, CphisVec u ) { CphisError err; // Enter recursion based on cycle type. switch (solver->conf->cycle) { case CPHIS_CYCLE_V: err = CphisSolverCycleV( solver, f, u, solver->conf->numScales - 1 );CPHISCHECK(err); break; case CPHIS_CYCLE_W: err = CphisSolverCycleW( solver, f, u, solver->conf->numScales - 1 );CPHISCHECK(err); break; case CPHIS_CYCLE_F: err = CphisSolverCycleF( solver, f, u, solver->conf->numScales - 1 );CPHISCHECK(err); break; default: CPHISCHECK(CPHIS_UNKNOWN_TYPE); break; } return CPHIS_SUCCESS; } static CphisError CphisSolverPrintTimers(const CphisSolver solver) { CphisPrintf("CPHIS Timers:\n"); #ifdef _OPENMP CphisPrintf( " Setup: %.3f s\n", solver->timers[CPHIS_TIMER_SETUP] ); CphisPrintf( " Solve: %.3f s\n", solver->timers[CPHIS_TIMER_SOLVER] ); CphisPrintf( " Presmooth: %.3f s\n", solver->timers[CPHIS_TIMER_PRESMOOTH] ); CphisPrintf( " Postsmooth: %.3f s\n", solver->timers[CPHIS_TIMER_POSTSMOOTH] ); CphisPrintf( " Coarse scale solves: %.3f s\n", solver->timers[CPHIS_TIMER_COARSE_SOLVE] ); CphisPrintf( " Multigrid residual & restriction: %.3f s\n", solver->timers[CPHIS_TIMER_RESIDUAL] ); CphisPrintf( " Prolongation: %.3f s\n", solver->timers[CPHIS_TIMER_PROLONGATION] ); CphisPrintf( " System residual check: %.3f s\n", solver->timers[CPHIS_TIMER_SYSTEM_RESIDUAL] ); // Compute and print time delta, i.e., the difference between the total solver // time and the sum of the individual timers. This time difference is caused // by terminal output etc. double tDelta = 0.0; for (int i = 0; i < CPHIS_NUM_TIMERS; i++) { if (i == CPHIS_TIMER_SETUP || i == CPHIS_TIMER_SOLVER) continue; tDelta += solver->timers[i]; } tDelta = solver->timers[CPHIS_TIMER_SOLVER] - tDelta; CphisPrintf(" Time delta: %.3f s\n", tDelta); const double wtick = omp_get_wtick(); CphisPrintf(" Timer resolution: %.3e s\n", wtick); #else CphisPrintf(" Timers require OpenMP to be enabled!\n"); #endif return CPHIS_SUCCESS; } CphisError CphisSolverSolve( const CphisSolver solver, const CphisVec b, CphisVec x, CphisConvergenceFlag *flag, CphisReal *residual, int *iter ) { CphisError err; int k = 0; CphisReal rNorm, r0Norm; #ifdef _OPENMP const double tStart = omp_get_wtime(); #endif // Reset number of coarse scale solver iterations. solver->iterCoarseScale = 0; // Compute initial residual norm (only if used as a stopping criterion). const int computeResidual = solver->conf->rtol > 0.0 || solver->conf->atol > 0.0; if (computeResidual) { err = CphisMatVec(solver->A, x, solver->rfull);CPHISCHECK(err); err = CphisVecAXPY(-1.0, b, solver->rfull);CPHISCHECK(err); err = CphisVecNorm2(solver->rfull, &r0Norm);CPHISCHECK(err); } rNorm = r0Norm; #ifdef _OPENMP solver->timers[CPHIS_TIMER_SYSTEM_RESIDUAL] += omp_get_wtime() - tStart; #endif if (solver->conf->verbosity >= CPHIS_VERBOSITY_SUMMARY) { CphisPrintHline(1); CphisPrintf("CPHIS: Beginning solve\n"); CphisPrintHline(1); } while (1) { // Check relative residual norm. if (solver->conf->rtol > 0.0 && rNorm/r0Norm < solver->conf->rtol) { if (flag) *flag = CPHIS_CONVERGED; break; } // Check absolute residual norm. if (solver->conf->atol > 0.0 && rNorm < solver->conf->atol) { if (flag) *flag = CPHIS_CONVERGED; break; } // Check for maximum number of iterations. if (k >= solver->conf->maxIter) { if (flag) *flag = CPHIS_MAX_ITER; break; } if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { if (k > 0) CphisPrintHline(0); CphisPrintf("Beginning iteration #%d\n", k + 1); } // Perform one full cycle. err = CphisSolverCycle(solver, b, x);CPHISCHECK(err); // Compute residual norm (only if used as a stopping criterion. #ifdef _OPENMP const double tStartResidual = omp_get_wtime(); #endif if (computeResidual) { err = CphisMatVec(solver->A, x, solver->rfull);CPHISCHECK(err); err = CphisVecAXPY(-1.0, b, solver->rfull);CPHISCHECK(err); err = CphisVecNorm2(solver->rfull, &rNorm);CPHISCHECK(err); } #ifdef _OPENMP const double tEndResidual = omp_get_wtime(); solver->timers[CPHIS_TIMER_SYSTEM_RESIDUAL] += tEndResidual - tStartResidual; #endif if (solver->conf->verbosity >= CPHIS_VERBOSITY_DETAILED) { if (computeResidual) { CphisPrintf( "End of iteration #%d (residual = %e)\n", k + 1, rNorm/r0Norm ); } else { CphisPrintf("End of iteration #%d (residual not computed)\n", k + 1); } } k++; } #ifdef _OPENMP const double tEnd = omp_get_wtime(); solver->timers[CPHIS_TIMER_SOLVER] += tEnd - tStart; #endif if (solver->conf->verbosity >= CPHIS_VERBOSITY_SUMMARY) { CphisPrintHline(1); } if (solver->conf->verbosity >= CPHIS_VERBOSITY_SUMMARY) { if (computeResidual && rNorm/r0Norm < solver->conf->rtol) { CphisPrintf( "CPHIS: Solver converged to desired rel. tolerance of %.3e!\n", solver->conf->rtol ); } if (computeResidual && rNorm < solver->conf->atol) { CphisPrintf( "CPHIS: Solver converged to desired abs. tolerance of %.3e!\n", solver->conf->atol ); } if (k >= solver->conf->maxIter) { CphisPrintf("CPHIS: Solver reached the maximum number of iterations!\n"); } if (computeResidual) { CphisPrintf( " Rel. residual: %e\n", rNorm/r0Norm ); } else { CphisPrintf(" Rel. residual: not computed\n"); } CphisPrintf(" #Iterations: %d\n", k); CphisPrintf( " #Iterations (coarse scale solver): %d\n", solver->iterCoarseScale ); CphisPrintf( " #Iterations (smoothers): %d\n", k*(solver->conf->numScales - 1)*(solver->conf->nu1 + solver->conf->nu2) ); CphisPrintHline(0); err = CphisSolverPrintTimers(solver);CPHISCHECK(err); } if (solver->conf->verbosity >= CPHIS_VERBOSITY_SUMMARY) { CphisPrintHline(1); } if (computeResidual && residual) *residual = rNorm/r0Norm; if (iter) *iter = k; return CPHIS_SUCCESS; }
convolution_1x1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 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_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; const int size = w * h; Mat bottom_im2col = bottom_blob; bottom_im2col.w = size; bottom_im2col.h = 1; im2col_sgemm_neon(bottom_im2col, top_blob, kernel, _bias, opt); } static void conv1x1s2_sgemm_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; const int tailstep = w - 2 * outw + w; Mat bottom_blob_shrinked; bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < channels; p++) { const float* r0 = bottom_blob.channel(p); float* outptr = bottom_blob_shrinked.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { outptr[0] = r0[0]; r0 += 2; outptr += 1; } r0 += tailstep; } } conv1x1s1_sgemm_neon(bottom_blob_shrinked, top_blob, kernel, _bias, opt); } static void conv1x1s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ 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; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); Mat out4 = top_blob.channel(p + 4); Mat out5 = top_blob.channel(p + 5); Mat out6 = top_blob.channel(p + 6); Mat out7 = top_blob.channel(p + 7); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; const float bias4 = bias ? bias[p + 4] : 0.f; const float bias5 = bias ? bias[p + 5] : 0.f; const float bias6 = bias ? bias[p + 6] : 0.f; const float bias7 = bias ? bias[p + 7] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); out4.fill(bias4); out5.fill(bias5); out6.fill(bias6); out7.fill(bias7); int q = 0; for (; q + 7 < inch; q += 8) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; float* outptr6 = out6; float* outptr7 = out7; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* img4 = bottom_blob.channel(q + 4); const float* img5 = bottom_blob.channel(q + 5); const float* img6 = bottom_blob.channel(q + 6); const float* img7 = bottom_blob.channel(q + 7); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float* kernel6 = kernel + (p + 6) * inch + q; const float* kernel7 = kernel + (p + 7) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; const float* r4 = img4; const float* r5 = img5; const float* r6 = img6; const float* r7 = img7; int size = outw * outh; int nn = size >> 2; int remain = size & 3; float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); float32x4_t _k4 = vld1q_f32(kernel4); float32x4_t _k5 = vld1q_f32(kernel5); float32x4_t _k6 = vld1q_f32(kernel6); float32x4_t _k7 = vld1q_f32(kernel7); float32x4_t _k0n = vld1q_f32(kernel0 + 4); float32x4_t _k1n = vld1q_f32(kernel1 + 4); float32x4_t _k2n = vld1q_f32(kernel2 + 4); float32x4_t _k3n = vld1q_f32(kernel3 + 4); float32x4_t _k4n = vld1q_f32(kernel4 + 4); float32x4_t _k5n = vld1q_f32(kernel5 + 4); float32x4_t _k6n = vld1q_f32(kernel6 + 4); float32x4_t _k7n = vld1q_f32(kernel7 + 4); #ifdef __clang__ // gcc reject over 30 oprands :( if (nn > 0) { asm volatile( "prfm pldl1keep, [%9, #128] \n" "ld1 {v17.4s}, [%9], #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "0: \n" "fmla v18.4s, v17.4s, %34.s[0] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v20.4s}, [%3] \n" "fmla v19.4s, v17.4s, %35.s[0] \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v21.4s}, [%4] \n" "fmla v20.4s, v17.4s, %36.s[0] \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v22.4s}, [%5] \n" "fmla v21.4s, v17.4s, %37.s[0] \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v23.4s}, [%6] \n" "fmla v22.4s, v17.4s, %38.s[0] \n" "prfm pldl1keep, [%10, #128] \n" "ld1 {v16.4s}, [%10], #16 \n" "fmla v23.4s, v17.4s, %39.s[0] \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v24.4s}, [%7] \n" "fmla v18.4s, v16.4s, %34.s[1] \n" "fmla v19.4s, v16.4s, %35.s[1] \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v25.4s}, [%8] \n" "fmla v24.4s, v17.4s, %40.s[0] \n" "fmla v25.4s, v17.4s, %41.s[0] \n" "fmla v20.4s, v16.4s, %36.s[1] \n" "fmla v21.4s, v16.4s, %37.s[1] \n" "prfm pldl1keep, [%11, #128] \n" "ld1 {v17.4s}, [%11], #16 \n" "fmla v22.4s, v16.4s, %38.s[1] \n" "fmla v23.4s, v16.4s, %39.s[1] \n" "fmla v18.4s, v17.4s, %34.s[2] \n" "fmla v19.4s, v17.4s, %35.s[2] \n" "fmla v24.4s, v16.4s, %40.s[1] \n" "fmla v25.4s, v16.4s, %41.s[1] \n" "fmla v20.4s, v17.4s, %36.s[2] \n" "fmla v21.4s, v17.4s, %37.s[2] \n" "prfm pldl1keep, [%12, #128] \n" "ld1 {v16.4s}, [%12], #16 \n" "fmla v22.4s, v17.4s, %38.s[2] \n" "fmla v23.4s, v17.4s, %39.s[2] \n" "fmla v18.4s, v16.4s, %34.s[3] \n" "fmla v19.4s, v16.4s, %35.s[3] \n" "fmla v24.4s, v17.4s, %40.s[2] \n" "fmla v25.4s, v17.4s, %41.s[2] \n" "fmla v20.4s, v16.4s, %36.s[3] \n" "fmla v21.4s, v16.4s, %37.s[3] \n" "prfm pldl1keep, [%13, #128] \n" "ld1 {v17.4s}, [%13], #16 \n" "fmla v22.4s, v16.4s, %38.s[3] \n" "fmla v23.4s, v16.4s, %39.s[3] \n" "fmla v18.4s, v17.4s, %42.s[0] \n" "fmla v19.4s, v17.4s, %43.s[0] \n" "fmla v24.4s, v16.4s, %40.s[3] \n" "fmla v25.4s, v16.4s, %41.s[3] \n" "fmla v20.4s, v17.4s, %44.s[0] \n" "fmla v21.4s, v17.4s, %45.s[0] \n" "prfm pldl1keep, [%14, #128] \n" "ld1 {v16.4s}, [%14], #16 \n" "fmla v22.4s, v17.4s, %46.s[0] \n" "fmla v23.4s, v17.4s, %47.s[0] \n" "fmla v18.4s, v16.4s, %42.s[1] \n" "fmla v19.4s, v16.4s, %43.s[1] \n" "fmla v24.4s, v17.4s, %48.s[0] \n" "fmla v25.4s, v17.4s, %49.s[0] \n" "fmla v20.4s, v16.4s, %44.s[1] \n" "fmla v21.4s, v16.4s, %45.s[1] \n" "prfm pldl1keep, [%15, #128] \n" "ld1 {v17.4s}, [%15], #16 \n" "fmla v22.4s, v16.4s, %46.s[1] \n" "fmla v23.4s, v16.4s, %47.s[1] \n" "fmla v18.4s, v17.4s, %42.s[2] \n" "fmla v19.4s, v17.4s, %43.s[2] \n" "fmla v24.4s, v16.4s, %48.s[1] \n" "fmla v25.4s, v16.4s, %49.s[1] \n" "fmla v20.4s, v17.4s, %44.s[2] \n" "fmla v21.4s, v17.4s, %45.s[2] \n" "prfm pldl1keep, [%16, #128] \n" "ld1 {v16.4s}, [%16], #16 \n" "fmla v22.4s, v17.4s, %46.s[2] \n" "fmla v23.4s, v17.4s, %47.s[2] \n" "fmla v18.4s, v16.4s, %42.s[3] \n" "fmla v19.4s, v16.4s, %43.s[3] \n" "fmla v24.4s, v17.4s, %48.s[2] \n" "fmla v25.4s, v17.4s, %49.s[2] \n" "fmla v20.4s, v16.4s, %44.s[3] \n" "fmla v21.4s, v16.4s, %45.s[3] \n" "st1 {v18.4s}, [%1], #16 \n" "fmla v22.4s, v16.4s, %46.s[3] \n" "st1 {v19.4s}, [%2], #16 \n" "fmla v23.4s, v16.4s, %47.s[3] \n" "st1 {v20.4s}, [%3], #16 \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v17.4s}, [%9], #16 \n" "fmla v24.4s, v16.4s, %48.s[3] \n" "st1 {v21.4s}, [%4], #16 \n" "fmla v25.4s, v16.4s, %49.s[3] \n" "st1 {v22.4s}, [%5], #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "st1 {v23.4s}, [%6], #16 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "st1 {v24.4s}, [%7], #16 \n" "subs %w0, %w0, #1 \n" "st1 {v25.4s}, [%8], #16 \n" "bne 0b \n" "sub %9, %9, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(outptr6), // %7 "=r"(outptr7), // %8 "=r"(r0), // %9 "=r"(r1), // %10 "=r"(r2), // %11 "=r"(r3), // %12 "=r"(r4), // %13 "=r"(r5), // %14 "=r"(r6), // %15 "=r"(r7) // %16 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(outptr6), "8"(outptr7), "9"(r0), "10"(r1), "11"(r2), "12"(r3), "13"(r4), "14"(r5), "15"(r6), "16"(r7), "w"(_k0), // %34 "w"(_k1), // %35 "w"(_k2), // %36 "w"(_k3), // %37 "w"(_k4), // %38 "w"(_k5), // %39 "w"(_k6), // %40 "w"(_k7), // %41 "w"(_k0n), // %42 "w"(_k1n), // %43 "w"(_k2n), // %44 "w"(_k3n), // %45 "w"(_k4n), // %46 "w"(_k5n), // %47 "w"(_k6n), // %48 "w"(_k7n) // %49 : "cc", "memory", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25" //, "v26", "v27", "v28", "v29", "v30", "v31" ); } #else for (; nn > 0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _out0p = vld1q_f32(outptr0); float32x4_t _out1p = vld1q_f32(outptr1); float32x4_t _out2p = vld1q_f32(outptr2); float32x4_t _out3p = vld1q_f32(outptr3); float32x4_t _out4p = vld1q_f32(outptr4); float32x4_t _out5p = vld1q_f32(outptr5); float32x4_t _out6p = vld1q_f32(outptr6); float32x4_t _out7p = vld1q_f32(outptr7); _out0p = vfmaq_laneq_f32(_out0p, _p, _k0, 0); _out1p = vfmaq_laneq_f32(_out1p, _p, _k1, 0); _out2p = vfmaq_laneq_f32(_out2p, _p, _k2, 0); _out3p = vfmaq_laneq_f32(_out3p, _p, _k3, 0); _out4p = vfmaq_laneq_f32(_out4p, _p, _k4, 0); _out5p = vfmaq_laneq_f32(_out5p, _p, _k5, 0); _out6p = vfmaq_laneq_f32(_out6p, _p, _k6, 0); _out7p = vfmaq_laneq_f32(_out7p, _p, _k7, 0); float32x4_t _p1 = vld1q_f32(r1); _out0p = vfmaq_laneq_f32(_out0p, _p1, _k0, 1); _out1p = vfmaq_laneq_f32(_out1p, _p1, _k1, 1); _out2p = vfmaq_laneq_f32(_out2p, _p1, _k2, 1); _out3p = vfmaq_laneq_f32(_out3p, _p1, _k3, 1); _out4p = vfmaq_laneq_f32(_out4p, _p1, _k4, 1); _out5p = vfmaq_laneq_f32(_out5p, _p1, _k5, 1); _out6p = vfmaq_laneq_f32(_out6p, _p1, _k6, 1); _out7p = vfmaq_laneq_f32(_out7p, _p1, _k7, 1); float32x4_t _p2 = vld1q_f32(r2); _out0p = vfmaq_laneq_f32(_out0p, _p2, _k0, 2); _out1p = vfmaq_laneq_f32(_out1p, _p2, _k1, 2); _out2p = vfmaq_laneq_f32(_out2p, _p2, _k2, 2); _out3p = vfmaq_laneq_f32(_out3p, _p2, _k3, 2); _out4p = vfmaq_laneq_f32(_out4p, _p2, _k4, 2); _out5p = vfmaq_laneq_f32(_out5p, _p2, _k5, 2); _out6p = vfmaq_laneq_f32(_out6p, _p2, _k6, 2); _out7p = vfmaq_laneq_f32(_out7p, _p2, _k7, 2); float32x4_t _p3 = vld1q_f32(r3); _out0p = vfmaq_laneq_f32(_out0p, _p3, _k0, 3); _out1p = vfmaq_laneq_f32(_out1p, _p3, _k1, 3); _out2p = vfmaq_laneq_f32(_out2p, _p3, _k2, 3); _out3p = vfmaq_laneq_f32(_out3p, _p3, _k3, 3); _out4p = vfmaq_laneq_f32(_out4p, _p3, _k4, 3); _out5p = vfmaq_laneq_f32(_out5p, _p3, _k5, 3); _out6p = vfmaq_laneq_f32(_out6p, _p3, _k6, 3); _out7p = vfmaq_laneq_f32(_out7p, _p3, _k7, 3); float32x4_t _p4 = vld1q_f32(r4); _out0p = vfmaq_laneq_f32(_out0p, _p4, _k0n, 0); _out1p = vfmaq_laneq_f32(_out1p, _p4, _k1n, 0); _out2p = vfmaq_laneq_f32(_out2p, _p4, _k2n, 0); _out3p = vfmaq_laneq_f32(_out3p, _p4, _k3n, 0); _out4p = vfmaq_laneq_f32(_out4p, _p4, _k4n, 0); _out5p = vfmaq_laneq_f32(_out5p, _p4, _k5n, 0); _out6p = vfmaq_laneq_f32(_out6p, _p4, _k6n, 0); _out7p = vfmaq_laneq_f32(_out7p, _p4, _k7n, 0); float32x4_t _p5 = vld1q_f32(r5); _out0p = vfmaq_laneq_f32(_out0p, _p5, _k0n, 1); _out1p = vfmaq_laneq_f32(_out1p, _p5, _k1n, 1); _out2p = vfmaq_laneq_f32(_out2p, _p5, _k2n, 1); _out3p = vfmaq_laneq_f32(_out3p, _p5, _k3n, 1); _out4p = vfmaq_laneq_f32(_out4p, _p5, _k4n, 1); _out5p = vfmaq_laneq_f32(_out5p, _p5, _k5n, 1); _out6p = vfmaq_laneq_f32(_out6p, _p5, _k6n, 1); _out7p = vfmaq_laneq_f32(_out7p, _p5, _k7n, 1); float32x4_t _p6 = vld1q_f32(r6); _out0p = vfmaq_laneq_f32(_out0p, _p6, _k0n, 2); _out1p = vfmaq_laneq_f32(_out1p, _p6, _k1n, 2); _out2p = vfmaq_laneq_f32(_out2p, _p6, _k2n, 2); _out3p = vfmaq_laneq_f32(_out3p, _p6, _k3n, 2); _out4p = vfmaq_laneq_f32(_out4p, _p6, _k4n, 2); _out5p = vfmaq_laneq_f32(_out5p, _p6, _k5n, 2); _out6p = vfmaq_laneq_f32(_out6p, _p6, _k6n, 2); _out7p = vfmaq_laneq_f32(_out7p, _p6, _k7n, 2); float32x4_t _p7 = vld1q_f32(r7); _out0p = vfmaq_laneq_f32(_out0p, _p7, _k0n, 3); _out1p = vfmaq_laneq_f32(_out1p, _p7, _k1n, 3); _out2p = vfmaq_laneq_f32(_out2p, _p7, _k2n, 3); _out3p = vfmaq_laneq_f32(_out3p, _p7, _k3n, 3); _out4p = vfmaq_laneq_f32(_out4p, _p7, _k4n, 3); _out5p = vfmaq_laneq_f32(_out5p, _p7, _k5n, 3); _out6p = vfmaq_laneq_f32(_out6p, _p7, _k6n, 3); _out7p = vfmaq_laneq_f32(_out7p, _p7, _k7n, 3); vst1q_f32(outptr0, _out0p); vst1q_f32(outptr1, _out1p); vst1q_f32(outptr2, _out2p); vst1q_f32(outptr3, _out3p); vst1q_f32(outptr4, _out4p); vst1q_f32(outptr5, _out5p); vst1q_f32(outptr6, _out6p); vst1q_f32(outptr7, _out7p); r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; r6 += 4; r7 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; outptr4 += 4; outptr5 += 4; outptr6 += 4; outptr7 += 4; } #endif for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3] + *r4 * kernel0[4] + *r5 * kernel0[5] + *r6 * kernel0[6] + *r7 * kernel0[7]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3] + *r4 * kernel1[4] + *r5 * kernel1[5] + *r6 * kernel1[6] + *r7 * kernel1[7]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3] + *r4 * kernel2[4] + *r5 * kernel2[5] + *r6 * kernel2[6] + *r7 * kernel2[7]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3] + *r4 * kernel3[4] + *r5 * kernel3[5] + *r6 * kernel3[6] + *r7 * kernel3[7]; float sum4 = *r0 * kernel4[0] + *r1 * kernel4[1] + *r2 * kernel4[2] + *r3 * kernel4[3] + *r4 * kernel4[4] + *r5 * kernel4[5] + *r6 * kernel4[6] + *r7 * kernel4[7]; float sum5 = *r0 * kernel5[0] + *r1 * kernel5[1] + *r2 * kernel5[2] + *r3 * kernel5[3] + *r4 * kernel5[4] + *r5 * kernel5[5] + *r6 * kernel5[6] + *r7 * kernel5[7]; float sum6 = *r0 * kernel6[0] + *r1 * kernel6[1] + *r2 * kernel6[2] + *r3 * kernel6[3] + *r4 * kernel6[4] + *r5 * kernel6[5] + *r6 * kernel6[6] + *r7 * kernel6[7]; float sum7 = *r0 * kernel7[0] + *r1 * kernel7[1] + *r2 * kernel7[2] + *r3 * kernel7[3] + *r4 * kernel7[4] + *r5 * kernel7[5] + *r6 * kernel7[6] + *r7 * kernel7[7]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; *outptr6 += sum6; *outptr7 += sum7; r0++; r1++; r2++; r3++; r4++; r5++; r6++; r7++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; float* outptr6 = out6; float* outptr7 = out7; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float* kernel6 = kernel + (p + 6) * inch + q; const float* kernel7 = kernel + (p + 7) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float k4 = kernel4[0]; const float k5 = kernel5[0]; const float k6 = kernel6[0]; const float k7 = kernel7[0]; const float* r0 = img0; int size = outw * outh; int nn = size >> 2; int remain = size & 3; float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); float32x4_t _k4 = vdupq_n_f32(k4); float32x4_t _k5 = vdupq_n_f32(k5); float32x4_t _k6 = vdupq_n_f32(k6); float32x4_t _k7 = vdupq_n_f32(k7); for (; nn > 0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _out0p = vld1q_f32(outptr0); float32x4_t _out1p = vld1q_f32(outptr1); float32x4_t _out2p = vld1q_f32(outptr2); float32x4_t _out3p = vld1q_f32(outptr3); float32x4_t _out4p = vld1q_f32(outptr4); float32x4_t _out5p = vld1q_f32(outptr5); float32x4_t _out6p = vld1q_f32(outptr6); float32x4_t _out7p = vld1q_f32(outptr7); _out0p = vfmaq_f32(_out0p, _p, _k0); _out1p = vfmaq_f32(_out1p, _p, _k1); _out2p = vfmaq_f32(_out2p, _p, _k2); _out3p = vfmaq_f32(_out3p, _p, _k3); _out4p = vfmaq_f32(_out4p, _p, _k4); _out5p = vfmaq_f32(_out5p, _p, _k5); _out6p = vfmaq_f32(_out6p, _p, _k6); _out7p = vfmaq_f32(_out7p, _p, _k7); vst1q_f32(outptr0, _out0p); vst1q_f32(outptr1, _out1p); vst1q_f32(outptr2, _out2p); vst1q_f32(outptr3, _out3p); vst1q_f32(outptr4, _out4p); vst1q_f32(outptr5, _out5p); vst1q_f32(outptr6, _out6p); vst1q_f32(outptr7, _out7p); r0 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; outptr4 += 4; outptr5 += 4; outptr6 += 4; outptr7 += 4; } for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; float sum4 = *r0 * k4; float sum5 = *r0 * k5; float sum6 = *r0 * k6; float sum7 = *r0 * k7; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; *outptr6 += sum6; *outptr7 += sum7; r0++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } } #else nn_outch = outch / 6; remain_outch_start = nn_outch * 6; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 6; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); Mat out4 = top_blob.channel(p + 4); Mat out5 = top_blob.channel(p + 5); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; const float bias4 = bias ? bias[p + 4] : 0.f; const float bias5 = bias ? bias[p + 5] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); out4.fill(bias4); out5.fill(bias5); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 2; int remain = size & 3; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); float32x4_t _k4 = vld1q_f32(kernel4); float32x4_t _k5 = vld1q_f32(kernel5); if (nn > 0) { asm volatile( "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n" // q7 = outptr1 "vmla.f32 q6, q12, %e22[0] \n" "0: \n" "pld [%3, #128] \n" "vld1.f32 {d16-d17}, [%3 :128] \n" // q8 = outptr2 "vmla.f32 q7, q12, %e23[0] \n" "pld [%4, #128] \n" "vld1.f32 {d18-d19}, [%4 :128] \n" // q9 = outptr3 "vmla.f32 q8, q12, %e24[0] \n" "pld [%8, #128] \n" "vld1.f32 {d26-d27}, [%8 :128]! \n" // q13 = r1 "vmla.f32 q9, q12, %e25[0] \n" "pld [%5, #128] \n" "vld1.f32 {d20-d21}, [%5 :128] \n" // q10 = outptr4 "vmla.f32 q6, q13, %e22[1] \n" "vmla.f32 q7, q13, %e23[1] \n" "pld [%6, #128] \n" "vld1.f32 {d22-d23}, [%6 :128] \n" // q11 = outptr5 "vmla.f32 q10, q12, %e26[0] \n" "vmla.f32 q11, q12, %e27[0] \n" "vmla.f32 q8, q13, %e24[1] \n" "vmla.f32 q9, q13, %e25[1] \n" "pld [%9, #128] \n" "vld1.f32 {d28-d29}, [%9 :128]! \n" // q14 = r2 "vmla.f32 q10, q13, %e26[1] \n" "vmla.f32 q11, q13, %e27[1] \n" "vmla.f32 q6, q14, %f22[0] \n" "vmla.f32 q7, q14, %f23[0] \n" "vmla.f32 q8, q14, %f24[0] \n" "vmla.f32 q9, q14, %f25[0] \n" "pld [%10, #128] \n" "vld1.f32 {d30-d31}, [%10 :128]! \n" // q15 = r3 "vmla.f32 q10, q14, %f26[0] \n" "vmla.f32 q11, q14, %f27[0] \n" "vmla.f32 q6, q15, %f22[1] \n" "vmla.f32 q7, q15, %f23[1] \n" "vmla.f32 q8, q15, %f24[1] \n" "vmla.f32 q9, q15, %f25[1] \n" "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "vmla.f32 q10, q15, %f26[1] \n" "vmla.f32 q11, q15, %f27[1] \n" "vst1.f32 {d12-d13}, [%1 :128]! \n" "vst1.f32 {d14-d15}, [%2 :128]! \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "vst1.f32 {d16-d17}, [%3 :128]! \n" "vst1.f32 {d18-d19}, [%4 :128]! \n" "vmla.f32 q6, q12, %e22[0] \n" "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n" // q7 = outptr1 "subs %0, #1 \n" "vst1.f32 {d20-d21}, [%5 :128]! \n" "vst1.f32 {d22-d23}, [%6 :128]! \n" "bne 0b \n" "sub %7, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(r0), // %7 "=r"(r1), // %8 "=r"(r2), // %9 "=r"(r3) // %10 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(r0), "8"(r1), "9"(r2), "10"(r3), "w"(_k0), // %22 "w"(_k1), // %23 "w"(_k2), // %24 "w"(_k3), // %25 "w"(_k4), // %26 "w"(_k5) // %27 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; float sum4 = *r0 * kernel4[0] + *r1 * kernel4[1] + *r2 * kernel4[2] + *r3 * kernel4[3]; float sum5 = *r0 * kernel5[0] + *r1 * kernel5[1] + *r2 * kernel5[2] + *r3 * kernel5[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float k4 = kernel4[0]; const float k5 = kernel5[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 2; int remain = size & 3; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); float32x4_t _k4 = vdupq_n_f32(k4); float32x4_t _k5 = vdupq_n_f32(k5); if (nn > 0) { asm volatile( "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "0: \n" "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n" // q7 = outptr1 "vmla.f32 q6, q12, %q16 \n" "pld [%3, #128] \n" "vld1.f32 {d16-d17}, [%3 :128] \n" // q8 = outptr2 "vmla.f32 q7, q12, %q17 \n" "pld [%4, #128] \n" "vld1.f32 {d18-d19}, [%4 :128] \n" // q9 = outptr3 "vmla.f32 q8, q12, %q18 \n" "pld [%5, #128] \n" "vld1.f32 {d20-d21}, [%5 :128] \n" // q10 = outptr4 "vmla.f32 q9, q12, %q19 \n" "pld [%6, #128] \n" "vld1.f32 {d22-d23}, [%6 :128] \n" // q11 = outptr5 "vmla.f32 q10, q12, %q20 \n" "vmla.f32 q11, q12, %q21 \n" "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "vst1.f32 {d12-d13}, [%1 :128]! \n" "vst1.f32 {d14-d15}, [%2 :128]! \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "vst1.f32 {d16-d17}, [%3 :128]! \n" "vst1.f32 {d18-d19}, [%4 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d20-d21}, [%5 :128]! \n" "vst1.f32 {d22-d23}, [%6 :128]! \n" "bne 0b \n" "sub %7, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(r0) // %7 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(r0), "w"(_k0), // %16 "w"(_k1), // %17 "w"(_k2), // %18 "w"(_k3), // %19 "w"(_k4), // %20 "w"(_k5) // %21 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12"); } #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; float sum4 = *r0 * k4; float sum5 = *r0 * k5; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; r0++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; } } } #endif // __ARM_NEON && __aarch64__ nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "0: \n" "fmla v8.4s, v6.4s, %18.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v9.4s, v7.4s, %18.s[0] \n" "fmla v10.4s, v6.4s, %19.s[0] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v11.4s, v7.4s, %19.s[0] \n" "fmla v12.4s, v6.4s, %20.s[0] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "fmla v13.4s, v7.4s, %20.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v4.4s, v5.4s}, [%6], #32 \n" "fmla v14.4s, v6.4s, %21.s[0] \n" "fmla v15.4s, v7.4s, %21.s[0] \n" "fmla v8.4s, v4.4s, %18.s[1] \n" "fmla v9.4s, v5.4s, %18.s[1] \n" "fmla v10.4s, v4.4s, %19.s[1] \n" "fmla v11.4s, v5.4s, %19.s[1] \n" "fmla v12.4s, v4.4s, %20.s[1] \n" "fmla v13.4s, v5.4s, %20.s[1] \n" "prfm pldl1keep, [%7, #256] \n" "ld1 {v6.4s, v7.4s}, [%7], #32 \n" "fmla v14.4s, v4.4s, %21.s[1] \n" "fmla v15.4s, v5.4s, %21.s[1] \n" "fmla v8.4s, v6.4s, %18.s[2] \n" "fmla v9.4s, v7.4s, %18.s[2] \n" "fmla v10.4s, v6.4s, %19.s[2] \n" "fmla v11.4s, v7.4s, %19.s[2] \n" "fmla v12.4s, v6.4s, %20.s[2] \n" "fmla v13.4s, v7.4s, %20.s[2] \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {v4.4s, v5.4s}, [%8], #32 \n" "fmla v14.4s, v6.4s, %21.s[2] \n" "fmla v15.4s, v7.4s, %21.s[2] \n" "fmla v8.4s, v4.4s, %18.s[3] \n" "fmla v9.4s, v5.4s, %18.s[3] \n" "fmla v10.4s, v4.4s, %19.s[3] \n" "fmla v11.4s, v5.4s, %19.s[3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v4.4s, %20.s[3] \n" "fmla v13.4s, v5.4s, %20.s[3] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "fmla v14.4s, v4.4s, %21.s[3] \n" "fmla v15.4s, v5.4s, %21.s[3] \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" "sub %5, %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "0: \n" "vmla.f32 q8, q6, %e18[0] \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n" "vmla.f32 q9, q7, %e18[0] \n" "vmla.f32 q10, q6, %e19[0] \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128] \n" "vmla.f32 q11, q7, %e19[0] \n" "vmla.f32 q12, q6, %e20[0] \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128] \n" "vmla.f32 q13, q7, %e20[0] \n" "pld [%6, #256] \n" "vld1.f32 {d8-d11}, [%6 :128]! \n" "vmla.f32 q14, q6, %e21[0] \n" "vmla.f32 q15, q7, %e21[0] \n" "vmla.f32 q8, q4, %e18[1] \n" "vmla.f32 q9, q5, %e18[1] \n" "vmla.f32 q10, q4, %e19[1] \n" "vmla.f32 q11, q5, %e19[1] \n" "vmla.f32 q12, q4, %e20[1] \n" "vmla.f32 q13, q5, %e20[1] \n" "pld [%7, #256] \n" "vld1.f32 {d12-d15}, [%7 :128]! \n" "vmla.f32 q14, q4, %e21[1] \n" "vmla.f32 q15, q5, %e21[1] \n" "vmla.f32 q8, q6, %f18[0] \n" "vmla.f32 q9, q7, %f18[0] \n" "vmla.f32 q10, q6, %f19[0] \n" "vmla.f32 q11, q7, %f19[0] \n" "vmla.f32 q12, q6, %f20[0] \n" "vmla.f32 q13, q7, %f20[0] \n" "pld [%8, #256] \n" "vld1.f32 {d8-d11}, [%8 :128]! \n" "vmla.f32 q14, q6, %f21[0] \n" "vmla.f32 q15, q7, %f21[0] \n" "vmla.f32 q8, q4, %f18[1] \n" "vmla.f32 q9, q5, %f18[1] \n" "vmla.f32 q10, q4, %f19[1] \n" "vmla.f32 q11, q5, %f19[1] \n" "vmla.f32 q12, q4, %f20[1] \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "vmla.f32 q13, q5, %f20[1] \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "vmla.f32 q14, q4, %f21[1] \n" "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "vmla.f32 q15, q5, %f21[1] \n" "vst1.f32 {d24-d27}, [%3 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4 :128]! \n" "bne 0b \n" "sub %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr2++; outptr3++; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v6.4s, %12.4s \n" "fmla v9.4s, v7.4s, %12.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v6.4s, %13.4s \n" "fmla v11.4s, v7.4s, %13.4s \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v12.4s, v6.4s, %14.4s \n" "fmla v13.4s, v7.4s, %14.4s \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "fmla v14.4s, v6.4s, %15.4s \n" "fmla v15.4s, v7.4s, %15.4s \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" "sub %5, %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "vmla.f32 q8, q6, %q12 \n" "vmla.f32 q9, q7, %q12 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n" "vmla.f32 q10, q6, %q13 \n" "vmla.f32 q11, q7, %q13 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128] \n" "vmla.f32 q12, q6, %q14 \n" "vmla.f32 q13, q7, %q14 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128] \n" "vmla.f32 q14, q6, %q15 \n" "vmla.f32 q15, q7, %q15 \n" "vst1.f32 {d24-d27}, [%3 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4 :128]! \n" "bne 0b \n" "sub %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0++; outptr0++; outptr1++; outptr2++; outptr3++; } } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %12.4s \n" "fmla v1.4s, v3.4s, %12.4s \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v2.4s, v3.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %13.4s \n" "fmla v1.4s, v3.4s, %13.4s \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v2.4s, v3.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %14.4s \n" "fmla v1.4s, v3.4s, %14.4s \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v2.4s, v3.4s}, [%5], #32 \n" "fmla v0.4s, v2.4s, %15.4s \n" "fmla v1.4s, v3.4s, %15.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v0", "v1", "v2", "v3"); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q3, %q12 \n" "pld [%3, #256] \n" "vld1.f32 {d4-d7}, [%3 :128]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q3, %q13 \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4 :128]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q3, %q14 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q3, %q15 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0++; r1++; r2++; r3++; outptr++; } } for (; q < inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %6.4s \n" "fmla v1.4s, v3.4s, %6.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "v0", "v1", "v2", "v3"); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q3, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; *outptr += sum; r0++; outptr++; } } } } static void conv1x1s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { int size = outw; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v4.4s, v5.4s}, [%5], #32 \n" "ld2 {v6.4s, v7.4s}, [%5], #32 \n" "and v5.16b, v6.16b, v6.16b \n" // v4 v5 "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v4.4s, %18.s[0] \n" "fmla v9.4s, v5.4s, %18.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v4.4s, %19.s[0] \n" "fmla v11.4s, v5.4s, %19.s[0] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v12.4s, v4.4s, %20.s[0] \n" "fmla v13.4s, v5.4s, %20.s[0] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "prfm pldl1keep, [%6, #512] \n" "ld2 {v6.4s, v7.4s}, [%6], #32 \n" "fmla v14.4s, v4.4s, %21.s[0] \n" "fmla v15.4s, v5.4s, %21.s[0] \n" "ld2 {v4.4s, v5.4s}, [%6], #32 \n" "and v7.16b, v4.16b, v4.16b \n" // v6 v7 "fmla v8.4s, v6.4s, %18.s[1] \n" "fmla v9.4s, v7.4s, %18.s[1] \n" "fmla v10.4s, v6.4s, %19.s[1] \n" "fmla v11.4s, v7.4s, %19.s[1] \n" "fmla v12.4s, v6.4s, %20.s[1] \n" "fmla v13.4s, v7.4s, %20.s[1] \n" "prfm pldl1keep, [%7, #512] \n" "ld2 {v4.4s, v5.4s}, [%7], #32 \n" "fmla v14.4s, v6.4s, %21.s[1] \n" "fmla v15.4s, v7.4s, %21.s[1] \n" "ld2 {v6.4s, v7.4s}, [%7], #32 \n" "and v5.16b, v6.16b, v6.16b \n" // v4 v5 "fmla v8.4s, v4.4s, %18.s[2] \n" "fmla v9.4s, v5.4s, %18.s[2] \n" "fmla v10.4s, v4.4s, %19.s[2] \n" "fmla v11.4s, v5.4s, %19.s[2] \n" "fmla v12.4s, v4.4s, %20.s[2] \n" "fmla v13.4s, v5.4s, %20.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld2 {v6.4s, v7.4s}, [%8], #32 \n" "fmla v14.4s, v4.4s, %21.s[2] \n" "fmla v15.4s, v5.4s, %21.s[2] \n" "ld2 {v4.4s, v5.4s}, [%8], #32 \n" "and v7.16b, v4.16b, v4.16b \n" // v6 v7 "fmla v8.4s, v6.4s, %18.s[3] \n" "fmla v9.4s, v7.4s, %18.s[3] \n" "fmla v10.4s, v6.4s, %19.s[3] \n" "fmla v11.4s, v7.4s, %19.s[3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v6.4s, %20.s[3] \n" "fmla v13.4s, v7.4s, %20.s[3] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "fmla v14.4s, v6.4s, %21.s[3] \n" "fmla v15.4s, v7.4s, %21.s[3] \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%5, #512] \n" "vld2.f32 {d8-d11}, [%5]! \n" "vld2.f32 {d12-d15}, [%5]! \n" "vand q5, q6, q6 \n" // q4 q5 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1] \n" "vmla.f32 q8, q4, %e18[0] \n" "vmla.f32 q9, q5, %e18[0] \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2] \n" "vmla.f32 q10, q4, %e19[0] \n" "vmla.f32 q11, q5, %e19[0] \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3] \n" "vmla.f32 q12, q4, %e20[0] \n" "vmla.f32 q13, q5, %e20[0] \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4] \n" "pld [%6, #512] \n" "vld2.f32 {d12-d15}, [%6]! \n" "vmla.f32 q14, q4, %e21[0] \n" "vmla.f32 q15, q5, %e21[0] \n" "vld2.f32 {d8-d11}, [%6]! \n" "vand q7, q4, q4 \n" // q6 q7 "vmla.f32 q8, q6, %e18[1] \n" "vmla.f32 q9, q7, %e18[1] \n" "vmla.f32 q10, q6, %e19[1] \n" "vmla.f32 q11, q7, %e19[1] \n" "vmla.f32 q12, q6, %e20[1] \n" "vmla.f32 q13, q7, %e20[1] \n" "pld [%7, #512] \n" "vld2.f32 {d8-d11}, [%7]! \n" "vmla.f32 q14, q6, %e21[1] \n" "vmla.f32 q15, q7, %e21[1] \n" "vld2.f32 {d12-d15}, [%7]! \n" "vand q5, q6, q6 \n" // q4 q5 "vmla.f32 q8, q4, %f18[0] \n" "vmla.f32 q9, q5, %f18[0] \n" "vmla.f32 q10, q4, %f19[0] \n" "vmla.f32 q11, q5, %f19[0] \n" "vmla.f32 q12, q4, %f20[0] \n" "vmla.f32 q13, q5, %f20[0] \n" "pld [%8, #512] \n" "vld2.f32 {d12-d15}, [%8]! \n" "vmla.f32 q14, q4, %f21[0] \n" "vmla.f32 q15, q5, %f21[0] \n" "vld2.f32 {d8-d11}, [%8]! \n" "vand q7, q4, q4 \n" // q6 q7 "vmla.f32 q8, q6, %f18[1] \n" "vmla.f32 q9, q7, %f18[1] \n" "vmla.f32 q10, q6, %f19[1] \n" "vmla.f32 q11, q7, %f19[1] \n" "vst1.f32 {d16-d19}, [%1]! \n" "vmla.f32 q12, q6, %f20[1] \n" "vmla.f32 q13, q7, %f20[1] \n" "vst1.f32 {d20-d23}, [%2]! \n" "vmla.f32 q14, q6, %f21[1] \n" "vmla.f32 q15, q7, %f21[1] \n" "vst1.f32 {d24-d27}, [%3]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr0++; outptr1++; outptr2++; outptr3++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { int size = outw; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v4.4s, v5.4s}, [%5], #32 \n" "ld2 {v6.4s, v7.4s}, [%5], #32 \n" "and v5.16b, v6.16b, v6.16b \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v4.4s, %12.4s \n" "fmla v9.4s, v5.4s, %12.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v4.4s, %13.4s \n" "fmla v11.4s, v5.4s, %13.4s \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v4.4s, %14.4s \n" "fmla v13.4s, v5.4s, %14.4s \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "fmla v14.4s, v4.4s, %15.4s \n" "fmla v15.4s, v5.4s, %15.4s \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%5, #512] \n" "vld2.f32 {d8-d11}, [%5]! \n" "vld2.f32 {d12-d15}, [%5]! \n" "vand q5, q6, q6 \n" // q4 q5 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1] \n" "vmla.f32 q8, q4, %q12 \n" "vmla.f32 q9, q5, %q12 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2] \n" "vmla.f32 q10, q4, %q13 \n" "vmla.f32 q11, q5, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3] \n" "vst1.f32 {d16-d19}, [%1]! \n" "vmla.f32 q12, q4, %q14 \n" "vmla.f32 q13, q5, %q14 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4] \n" "vst1.f32 {d20-d23}, [%2]! \n" "vmla.f32 q14, q4, %q15 \n" "vmla.f32 q15, q5, %q15 \n" "vst1.f32 {d24-d27}, [%3]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0 += 2; outptr0++; outptr1++; outptr2++; outptr3++; } r0 += tailstep; } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %12.4s \n" "fmla v1.4s, v8.4s, %12.4s \n" "prfm pldl1keep, [%3, #512] \n" "ld2 {v2.4s, v3.4s}, [%3], #32 \n" "ld2 {v8.4s, v9.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %13.4s \n" "fmla v1.4s, v8.4s, %13.4s \n" "prfm pldl1keep, [%4, #512] \n" "ld2 {v2.4s, v3.4s}, [%4], #32 \n" "ld2 {v8.4s, v9.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %14.4s \n" "fmla v1.4s, v8.4s, %14.4s \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v2.4s, v3.4s}, [%5], #32 \n" "ld2 {v8.4s, v9.4s}, [%5], #32 \n" "fmla v0.4s, v2.4s, %15.4s \n" "fmla v1.4s, v8.4s, %15.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9"); } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q8, %q12 \n" "pld [%3, #512] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vld2.f32 {d16-d19}, [%3]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q8, %q13 \n" "pld [%4, #512] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vld2.f32 {d16-d19}, [%4]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q8, %q14 \n" "pld [%5, #512] \n" "vld2.f32 {d4-d7}, [%5]! \n" "vld2.f32 {d16-d19}, [%5]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q8, %q15 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q < inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %6.4s \n" "fmla v1.4s, v8.4s, %6.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9"); } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q8, %q6 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } }
GB_unaryop__identity_bool_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_bool_int16 // op(A') function: GB_tran__identity_bool_int16 // C type: bool // A type: int16_t // cast: bool cij = (bool) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ bool z = (bool) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_bool_int16 ( bool *restrict Cx, const int16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_bool_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
newtonforwardinterpolation.c
#include<stdio.h> #define MAXN 100 #define ORDER 4 int main() { float ax[MAXN+1], ay [MAXN+1], diff[MAXN+1][ORDER+1], nr[ORDER+1], dr[ORDER+1],x,p,h,yp; int n,i,j,k; printf("\nEnter the value of n:\n"); scanf("%d",&n); printf("\nEnter the values in form x,y:\n"); for (i=0;i<=n;i++) scanf("%f %f",&ax[i],&ay[i]); printf("\nEnter the value of x for which the value of y is wanted: \n"); scanf("%f",&x); h=ax[1]-ax[0]; //now making the difference table //calculating the 1st order of differences #pragma omp parallel for private(i) shared(diff) for (i=0;i<=n-1;i++) diff[i][1] = ay[i+1]-ay[i]; //now calculating the second and higher order differences #pragma omp parallel for private(i,j) shared(diff) for (j=2;j<=ORDER;j++) for(i=0;i<=n-j;i++) diff[i][j] = diff[i+1][j-1] - diff[i][j-1]; //now finding x0 i=0; while (!(ax[i]>x)) i++; //now ax[i] is x0 and ay[i] is y0 i--; p = (x-ax[i])/h; yp = ay[i]; //now carrying out interpolation nr[0] = 1.0; dr[0] = 1.0; for (k=1;k<=ORDER;k++) { nr[k]=nr[k-1]*(p-k+1); dr[k]=dr[k-1]*k; } #pragma omp parallel for private(k) reduction(+:yp) for (k=1;k<=ORDER;k++) { yp +=(nr[k]/dr[k])*diff[i][k]; } printf("\nWhen x = %6.1f, corresponding y = %6.2f\n",x,yp); return 0; }
ops.h
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ #pragma once #ifndef OPS_H_ #define OPS_H_ #include <op_boilerplate.h> #include <array/DataTypeUtils.h> #include <helpers/shape.h> #include <vector> #include <Environment.h> #include <loops/summarystatsreduce.h> #include <loops/ReduceType.h> #define MIN_V 1e-12 #define MAX_FLOAT 1e37 #define MIN_FLOAT 1e-37 #define MAX_INT 2147483647 #define MIN_CUTFOFF -3.79297773665f #define FLOAT_MIN_NORMAL 1.17549435e-38 #define EPS 1e-5 #define AFFINITY close #define DOUBLE_PI_T T(2.0 * 3.14159265358979323846) #define DOUBLE_PI_X X(2.0 * 3.14159265358979323846) #define no_op_exec_special_any static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, Z *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_long static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_same static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #ifdef __CUDACC__ #define no_op_exec_special_any_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, X *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer,Z *result, Nd4jLong *resultShapeBuffer,Z *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_same_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, X *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_long_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #else // hacky fix for isnan/being being out of scope //#ifdef IOS //#define isinf(x) 0 // this isn't right. But std::isinf fails //#define isnan(x) 0 //#else //#define isnan std::isnan //#define isinf std::isinf //#endif #define no_op_exec_special_cuda #define no_op_exec_special_accumulation_cuda #define no_op_exec_special_accumulation_same_cuda #define no_op_exec_special_accumulation_long_cuda #define no_op_exec_special_any_cuda #define no_op_exec_special_bool_cuda #define no_op_exec_special_same_cuda #define no_op_exec_special_accumulation_same_cuda #endif #define SELU_ALPHA 1.6732632423543772848170429916717 #define SELU_LAMBDA 1.0507009873554804934193349852946 namespace functions { namespace indexreduce { template <typename T> struct IndexValue { T value; Nd4jLong index; _CUDA_HD IndexValue() = default; _CUDA_HD IndexValue(const T val, const Nd4jLong ind): index(ind), value(val) {} }; } namespace summarystats { template <typename T> class SummaryStatsData; } } namespace simdOps { template <typename X, typename Y, typename Z> class Add { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 + params[0]); } op_def static X startingValue() { return static_cast<X>(0.f); } }; template <typename X, typename Y> class NewAdd { public: op_def static X op(X d1, Y d2, X *params) { return d1 + d2; } }; template <typename X, typename Y, typename Z> class Subtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 - params[0]); } }; template <typename X, typename Y, typename Z> class SquaredSubtract { public: op_def static Z op(X d1, Y d2) { auto d = static_cast<Z>(d1 - d2); return d * d; } op_def static Z op(X d1, Y d2, Z *params) { auto d = static_cast<Z>(d1 - d2); return d * d; } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto d = static_cast<Z>(d1 - params[0]); return d * d; } }; template <typename X, typename Y, typename Z> class SquaredReverseSubtract { public: op_def static Z op(X d1, Y d2) { auto d = static_cast<Z>(d2 - d1); return d * d; } op_def static Z op(X d1, Y d2, Z *params) { auto d = static_cast<Z>(d2 - d1); return d * d; } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto d = static_cast<Z>(params[0] - d1); return d * d; } }; template <typename X, typename Y, typename Z> class ReverseSubtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] - d1); } }; template <typename X, typename Y, typename Z> class LogPoissonLossFull { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z) { auto zz = static_cast<Z>(z); return (zz * nd4j::math::nd4j_log<Y, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)); } // op for MetaOps op_def static X op(X z, Y *params) { return (nd4j::math::nd4j_exp<X, X>(params[0]) - z * params[0] + (z * nd4j::math::nd4j_log<X, Z>(z) - z + static_cast<X>(0.5f) * nd4j::math::nd4j_log<X, Z>(DOUBLE_PI_X * z))); } }; template <typename X, typename Y, typename Z> class LogPoissonLoss { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z) { return static_cast<Z>(z); } // op for MetaOps op_def static Z op(X z, Y *params) { return (nd4j::math::nd4j_exp<Y, Z>(params[0]) - static_cast<Z>(z) * static_cast<Z>(params[0])); } }; template <typename X, typename Y, typename Z> class Multiply { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 * params[0]); } op_def static X startingValue() { return static_cast<X>(1.f); } }; template <typename X, typename Y, typename Z> class Divide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 / params[0]); } op_def static X startingValue() { return static_cast<X>(1); } }; template <typename X, typename Y, typename Z> class DivideNoNan { public: op_def static Z op(X d1, Y d2) { if (d2 == (Y)0) return (Z)0; return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { if (d2 == (Y)0) return (Z)0; return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { if (params[0] == (Y)0) return (Z)0; return static_cast<Z>(d1 / params[0]); } op_def static X startingValue() { return static_cast<X>(1); } }; template <typename X, typename Y, typename Z> class SafeDivide { public: op_def static Z op(X d1, Y d2) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { if(params[0] == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / params[0]); } }; template <typename X, typename Y, typename Z> class FloorDiv { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1)); } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / params[0])); } }; template <typename X, typename Y, typename Z> class TruncateDiv { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 / i2); } }; template <typename X, typename Y, typename Z> class TruncateMod { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 % i2); } }; template<typename X, typename Y, typename Z> class Remainder { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FMod { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FloorMod { public: op_def static Z op(X d1, Y d2) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1, Y d2, Z *params) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0.0f)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseDivide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] / d1); } }; template <typename X, typename Y, typename Z> class CopyPws { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X> class Copy { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X, typename Y, typename Z> class Copy2 { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X, typename Y, typename Z> class Axpy { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 + d1); } op_def static Z op(X d1, Y d2, Z *params) { auto alpha = params[0]; return alpha * static_cast<Z>(d1) + static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class Assign { public: no_op_exec_special_any no_op_exec_special_any_cuda op_def static Z op(X d1, X *params) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class And { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp && d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (b1 && b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X> class IntOr { public: op_def static X op(X d1, X d2) { return d2 | d1; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class IntAnd { public: op_def static X op(X d1, X d2) { return d2 & d1; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class IntXor { public: op_def static X op(X d1, X d2) { return d2 ^ d1; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class ShiftLeft { public: op_def static X op(X d1, X d2) { return d1 << d2; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class ShiftRight { public: op_def static X op(X d1, X d2) { return d1 >> d2; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class CyclicShiftLeft { public: op_def static X op(X d1, X d2) { return nd4j::math::nd4j_rotl<X>(d1, d2); } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class CyclicShiftRight { public: op_def static X op(X d1, X d2) { return nd4j::math::nd4j_rotr<X>(d1, d2); } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X, typename Z> class Or { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp || d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return b1 || b2 ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X, typename Z> class Xor { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return ((d1 == comp && d2 != comp) || (d1 != comp && d2 == comp)) ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (!b1 && b2 )||(b1 && !b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Z> class Not { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return d1 != d2 ? static_cast<Z>(1) : static_cast<Z>(0); } // this transform op should run only on boolean input op_def static Z op(X d1, X *params) { auto b1 = static_cast<bool>(d1); return !b1; } }; template <typename X, typename Y, typename Z> class LogicalNot { public: op_def static Z op(X d1, Y d2) { return !((int) d1 && (int) d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<X>(!(static_cast<int>(d1) && static_cast<int>(d2))); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class LogicalXor { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return (i1 | i2) &~ (i1 & i2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalAnd { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) & static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(Y d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalOr { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) | static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class Mod { public: /* // just a optional note, feel free to remove later op_def static half op(half d1, half d2, half *params) { return __float2half(simdOps::Mod<float>::op(__half2float(d1), __half2float(d2), nullptr)); } */ op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) % static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseMod { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d2) % static_cast<int>(d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; /** * Whether 2 elements in an array * are epsilion equal */ template <typename X, typename Z> class Epsilon { public: op_def static Z op(X d1, X d2) { X diff = d1 - d2; X absDiff = nd4j::math::nd4j_abs<X>(diff); if (absDiff <= static_cast<X>(MIN_V)) return static_cast<Z>(1); return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class EqualTo { public: op_def static Z op(X d1, X d2) { return d1 == d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class NotEqualTo { public: op_def static Z op(X d1, X d2) { return d1 != d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 >= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThan { public: op_def static Z op(X d1, X d2) { return d1 > d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThan { public: op_def static Z op(X d1, X d2) { return d1 < d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 <= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X> class Abs { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_abs<X>(d1); } }; template <typename X> class Ceiling { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_ceil<X,X>(d1); } }; template <typename X> class Cosine { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cos<X,X>(d1); } }; template <typename X> class Exp { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X> class HardTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return ((d1 >= static_cast<X>(-1.f) && d1 <= static_cast<X>(1.f)) ? static_cast<X>(1.f) : static_cast<X>(0.f)); } }; template <typename X> class HardTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 < static_cast<X>(-1)) return static_cast<X>(-1); else if (d1 > static_cast<X>(1)) return static_cast<X>(1); else return d1; } }; template <typename X> class Floor { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_floor<X,X>(d1); } }; template <typename X> class Log { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(d1); } }; template <typename X> class Log1p { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(1 + d1); } }; template <typename X, typename Y, typename Z> class LogX { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_log<X, Z>(d1) / nd4j::math::nd4j_log<Y, Z>(d2) ; } }; template <typename X> class StabilizeFP16 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return static_cast<X>(nd4j::DataTypeUtils::min<float16>()); else return d1; } }; template <typename X> class StabilizeX { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return nd4j::DataTypeUtils::min<X>(); else return d1; } }; template <typename X> class SpecialDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1.f) - d1); } }; template <typename X> class Neg { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return -d1; } }; template <typename X> class Erf { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erf<X,X>(d1); } }; template <typename X> class Erfc { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erfc<X,X>(d1); } }; template <typename X> class Reciprocal { public: no_op_exec_special_same no_op_exec_special_same_cuda // op_def static T op(T d1) { // return (T(1.0f) / d1); // } // op for MetaOps op_def static X op(X d1, X *params) { return (static_cast<X>(1) / d1); } }; template <typename X, typename Z> class Sqr { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } }; template <typename X, typename Y, typename Z> class RelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_re<X>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X threshold = params[0]; return nd4j::math::nd4j_re<X>(d1, d2) > threshold ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryMinimumAbsoluteRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, X *params) { X d2 = params[0]; X thresholdRelative = params[1]; X thresholdAbsolute = params[2]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1, Y d2, Z *params) { X thresholdRelative = params[0]; X thresholdAbsolute = params[1]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class ReversePow { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(params[0], d1); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class Pow { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, params[0]); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class PowDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return params[0] * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(params[0]) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class IGamma { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_igamma<X, X, Z>(d1, params[0]); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_igamma<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_igamma<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class IGammac { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_igammac<X, X, Z>(d1, params[0]); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_igammac<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_igammac<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } }; template <typename X> class Round { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_round<X,X>(d1); } }; template <typename X, typename Z> class IsNan { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<X>(1) : static_cast<X>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class Expm1 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(1); } }; template <typename X, typename Z> class IsPositive { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return d1 > (X)0.f; } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsNegative { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return d1 < (X)0.f; } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInf { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isinf<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInfOrNan{ public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) && old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) && old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction != static_cast<X>(0); } }; template <typename X, typename Z> class IsFinite { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) || old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) || old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction != static_cast<X>(0); } }; template <typename X> class ClipByValue { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 > params[1]) return params[1]; if (d1 < params[0]) return params[0]; return d1; } }; template <typename X, typename Y, typename Z> class LstmClip { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X _v = (X) d2; if (d1 > _v) return _v; else if (d1 < -_v) return -_v; else return d1; } }; template <typename X> class Swish { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_sigmoid<X,X>(d1); } }; template <typename X> class Mish { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_tanh<X,X>(nd4j::math::nd4j_softplus<X,X>(d1)); } }; template <typename X> class MishDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto ex = nd4j::math::nd4j_exp<X,X>(d1); auto e2x = ex * ex; auto e3x = ex * ex * ex; return (ex * (4 * (d1 + 1) + 4 * e2x + e3x + ex *(4 * d1 + 6))) / nd4j::math::nd4j_pow<X, X, X>((2 * ex + e2x + 2), (X) 2.f); } }; template <typename X> class GELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_sigmoid<X,X>(static_cast<X>(1.702f) * d1); } }; template <typename X> class PreciseGELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto sp = nd4j::math::nd4j_sqrt<X, X>(static_cast<X>(2) / static_cast<X>(M_PI)); auto xp = d1 + nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(0.044715) * d1, static_cast<X>(3)); return (d1 / static_cast<X>(2)) * (static_cast<X>(1) + nd4j::math::nd4j_tanh<X, X>(sp * xp)); } }; template <typename X> class GELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto x17 = static_cast<X>(1.702f) * d1; auto ep = nd4j::math::nd4j_pow<X,X,X>(static_cast<X>(M_E), x17); // (E^(1.702 x) (1. + E^(1.702 x) + 1.702 x))/(1. + E^(1.702 x))^2 return (ep * (static_cast<X>(1.f) + ep + x17)) / nd4j::math::nd4j_pow<X, int, X>((static_cast<X>(1.f) + ep), 2); } }; template <typename X> class PreciseGELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto x79 = static_cast<X>(0.797885) * d1; auto x03 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0356774) * d1, 3); auto x39 = static_cast<X>(0.398942) * d1; auto x05 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0535161) * d1, 3); auto scz = nd4j::math::nd4j_sech<X, X>(x79 + x03); // 0.5 + (0.398942 x + 0.0535161 x^3) Sech[0.797885 x + 0.0356774 x^3]^2 + 0.5 Tanh[0.797885 x + 0.0356774 x^3] return static_cast<X>(0.5) + (x39 + x05) * (scz * scz) + static_cast<X>(0.5) * nd4j::math::nd4j_tanh<X, X>(x79 + x03); } }; template <typename X> class SwishDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(M_E), d1); return (ex * (d1 + ex + static_cast<X>(1.f))) / nd4j::math::nd4j_pow<X, X, X>((ex + static_cast<X>(1.f)) , static_cast<X>(2.f)); } }; template <typename X> class LogSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(nd4j::math::nd4j_sigmoid<X, X>(d1)); } }; template <typename X> class LogSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(M_E, d1); return static_cast<X>(1.f) / (ex + static_cast<X>(1.f)); } }; template <typename X> class Sigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoid<X, X>(d1); } }; template <typename X> class Affine { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return params[0] * d1 + params[1]; } }; template <typename X> class SigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoidderivative<X, X>(d1); } }; template <typename X> class HardSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_min<X>(static_cast<X>(1), nd4j::math::nd4j_max<X>(static_cast<X>(0), (static_cast<X>(0.2f)) * d1 + static_cast<X>(0.5f))); } }; template <typename X> class HardSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 < static_cast<X>(-2.5f) || d1 > static_cast<X>(2.5f) ? static_cast<X>(0.f) : static_cast<X>(0.2f); } }; /** * Scale to be between a min and max */ template <typename X> class SetRange { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto min = params[0]; auto max = params[1]; if (static_cast<X>(d1) >= min && static_cast<X>(d1) <= max) return d1; if (min == static_cast<X>(0) && max == static_cast<X>(1)) { auto val = static_cast<X>(1) / (static_cast<X>(1) + nd4j::math::nd4j_exp<X, X>(-d1)); return (nd4j::math::nd4j_floor<X,X>(val * (max - min)) + min); } return (nd4j::math::nd4j_floor<X,X>(d1 * (max - min)) + min); } }; template <typename X> class Sin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sin<X,X>(d1); } }; template <typename X> class Square { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1; } }; template <typename X, typename Z> class Sqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X, typename Z> class RSqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return static_cast<Z>(1) / nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X> class Rint { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_rint<X,X>(d1); } }; template <typename X> class SoftPlus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softplus<X, X>(d1); } }; template <typename X> class Sign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return (d1 > static_cast<X>(0)) - (d1 < static_cast<X>(0)); } }; template <typename X> class TimesOneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1) - d1); } }; template <typename X> class RationalTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { // keep 2/3 as runtime variable, to match precision auto dis = (static_cast<X>(2) / static_cast<X>(3)) * d1; auto tanh = nd4j::math::nd4j_sgn<X,X>(dis) * (static_cast<X>(1) - (static_cast<X>(1) / (static_cast<X>(1) + static_cast<X>(nd4j::math::nd4j_abs<X>(dis)) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)) ))); return static_cast<X>(1.7159f) * tanh; } }; template <typename X> class RationalTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto dis = (static_cast<X>(2.f) / static_cast<X>(3.f)) * d1; auto a = static_cast<X>(1.f) + nd4j::math::nd4j_abs<X>(dis) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2.f)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)); auto tDeriv = (static_cast<X>(1.f) + nd4j::math::nd4j_sign<X,X>(dis) * (static_cast<X>(2.f) * dis + static_cast<X>(4.f) * static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(3)))) / (a * a); return static_cast<X>(1.7159f) * (static_cast<X>(2.f) / static_cast<X>(3.f)) * tDeriv; } }; template <typename X> class Tanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanh<X, X>(d1); } }; template <typename X> class ScaledTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return params[0] * nd4j::math::nd4j_tanh<X, X>(params[1] * d1); } }; template <typename X> class RectifiedTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_max<X>(static_cast<X>(0), nd4j::math::nd4j_tanh<X,X>(d1)); } }; template <typename X> class RectifiedTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? nd4j::math::nd4j_tanhderivative<X,X>(d1) : static_cast<X>(0.f); } }; template <typename X> class ATanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atanh<X,X>(d1); } }; template <typename X> class TanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanhderivative<X,X>(d1); } }; template <typename X> class Cube { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1 * d1; } }; template <typename X> class CubeDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(3) * d1 * d1; } }; template <typename X> class ACos { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acos<X, X>(d1); } }; template <typename X> class ASinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asinh<X, X>(d1); } }; template <typename X> class ASinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(nd4j::math::nd4j_pow<X, X, X>(d1, static_cast<X>(2.f)) + static_cast<X>(1.f))); } }; template <typename X> class ACosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acosh<X, X>(d1); } }; template <typename X> class ACoshDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(d1 - static_cast<X>(1.f)) * nd4j::math::nd4j_sqrt<X, X>(d1 + static_cast<X>(1.f))); } }; template <typename X> class Ones { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.0f); } }; template <typename X> class SoftSign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsign<X, X>(d1); } }; template <typename X> class SoftSignDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsignderivative<X,X>(d1); } }; template <typename X, typename Z> class MatchConditionBool { public: no_op_exec_special_bool no_op_exec_special_bool_cuda // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); //nd4j_printf("value: %f; comp: %f; eps: %f; mode: %i;\n", d1, compare, eps, mode); switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? true : false; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? true : false; case 2: // less_than return d1 < compare ? true : false; case 3: // greater_than return d1 > compare ? true : false; case 4: // less_or_equals_than return d1 <= compare ? true : false; case 5: // greater_or_equals_than return d1 >= compare ? true : false; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? true : false; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? true : false; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? true : false; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? true : false; case 10: return (d1 == compare) ? true : false; case 11: return (d1 != compare) ? true : false; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? true : false; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? true : false; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)); case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1); default: printf("Undefined match condition: [%i]\n", mode); } return d1; } }; template <typename X, typename Z> class MatchCondition { public: no_op_exec_special no_op_exec_special_cuda no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return old + opOutput; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return old + opOutput; } op_def static Z op(X d1, X compare, X eps, int mode) { switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? 1 : 0; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? 1 : 0; case 2: // less_than return d1 < compare ? 1 : 0; case 3: // greater_than return d1 > compare ? 1 : 0; case 4: // less_or_equals_than return d1 <= compare ? 1 : 0; case 5: // greater_or_equals_than return d1 >= compare ? 1 : 0; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? 1 : 0; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? 1 : 0; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? 1 : 0; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? 1 : 0; case 10: return (d1 == compare) ? 1 : 0; case 11: return (d1 != compare) ? 1 : 0; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? 1 : 0; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? 1 : 0; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)) ? 1 : 0; case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1) ? 1 : 0; default: printf("Undefined match condition: [%i]\n", mode); } return d1; } // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X compare, X *extraParams) { X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[0]); return op(d1, compare, eps, mode); } // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); return op(d1, compare, eps, mode); } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Y, typename Z> class ELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_elu<X,Z>(d1, static_cast<X>(d2)); } }; template <typename X, typename Y, typename Z> class ELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_eluderivative<X,Z>(d1, static_cast<X>(d2)); } }; template <typename X, typename Y, typename Z> class RELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto xt = static_cast<Z>(d1); auto xf = static_cast<Z>(d2); return xt < xf ? xf : xt; } }; template <typename X, typename Y, typename Z> class SXELogitsSmoother { public: op_def static Z op(X d1, Y d2, Z *params) { return d1 * ((X)1.f - (X) d2) + (X)(0.5f) * (X) d2; } }; template <typename X, typename Y, typename Z> class RELU6 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto relu = simdOps::RELU<X,Y,Z>::op(d1, d2, params); return relu < static_cast<Z>(6) ? relu : static_cast<Z>(6); } }; template <typename X, typename Y, typename Z> class LeakyRELU { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { auto val = static_cast<Z>(d1); auto alpha = static_cast<Z>(d2); return val < 0.0f ? alpha * val : val; } }; template <typename X> class SELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.0f) ? static_cast<X>(SELU_LAMBDA) * static_cast<X>(d1) : static_cast<X>(SELU_LAMBDA) * (static_cast<X>(SELU_ALPHA) * nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(SELU_ALPHA)); } }; template <typename X> class SELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? static_cast<X>(SELU_LAMBDA) : static_cast<X>(SELU_ALPHA) * static_cast<X>(SELU_LAMBDA) * nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X, typename Y, typename Z> class LeakyRELUDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { if (d1 >= static_cast<X>(0)) return static_cast<Z>(1); else return static_cast<Z>(d2); } }; template <typename X> class ASin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asin<X,X>(d1); } }; template <typename X> class Sinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sinh<X,X>(d1); } }; template <typename X> class SinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X, X>(d1); } }; template <typename X> class Cosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X,X>(d1); } }; template <typename X> class Tan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tan<X,X>(d1); } }; template <typename X> class TanDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / nd4j::math::nd4j_pow<X, X, X>(nd4j::math::nd4j_cos<X, X>(d1), static_cast<X>(2.0f)); } }; template <typename X> class ATan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atan<X, X>(d1); } }; template <typename X, typename Y, typename Z> class Atan2 { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_atan2<X, Z>(d2, d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X> class Identity { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X> class Stabilize { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X k = params[0]; if (d1 * k > static_cast<X>(- MIN_CUTFOFF)) return static_cast<X>(- MIN_CUTFOFF) / k; else if (d1 * k < static_cast<X>(MIN_CUTFOFF)) return static_cast<X>(MIN_CUTFOFF) / k; return d1; } }; template <typename X, typename Y, typename Z> class Step { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return (d1 > static_cast<X>(d2) ? static_cast<Z>(1) : static_cast<Z>(0)); } }; template <typename X> class OneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1) - d1; } }; template <typename X> class Sum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class ReduceSameBenchmarkOp { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X op(X d1, X *extraParams) { auto f1 = static_cast<float>(d1); return static_cast<X>(nd4j::math::nd4j_pow<float,float,float>(f1, 3) + nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1) / nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1) * nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1) - nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1)); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class ShannonEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { auto p = d1 * d1; return static_cast<Z>(p) * nd4j::math::nd4j_log<X, Z>(p); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return -reduction; } }; template <typename X, typename Z> class LogEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { //entropy is -sum(p(x) * log(p(x))); log entropy is log of this return nd4j::math::nd4j_log<Z, Z>(-reduction); } }; template <typename X, typename Z> class Entropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return static_cast<Z>(-reduction); //entropy is -sum(p(x) * log(p(x))) } }; template <typename X> class ASum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::ASUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X, typename Z> class CountNonZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::ASUM; op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0.0f) ? static_cast<Z>(0.0f) : static_cast<Z>(1.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class CountZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static Z startingValue(const X *input) { return static_cast<Z>(0.0f); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0) ? static_cast<X>(1) : static_cast<X>(0); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return static_cast<Z>(reduction); } }; template <typename X> class Prod { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT; op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Any { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0) ; } }; template <typename X, typename Z> class All { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT; op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0); } }; template <typename X, typename Z> class Mean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return d1; } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction / (Z) n; } }; template <typename X, typename Z> class ReduceFloatBenchmarkOp { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { auto f1 = static_cast<float>(d1); return static_cast<Z>(nd4j::math::nd4j_pow<float,float,float>(f1, 3) + nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1) / nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1) * nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1) - nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1)); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return (Z) reduction / (Z) n; } }; template <typename X, typename Z> class AMean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_abs<Z>(reduction) / static_cast<Z>(n); } }; template <typename X> class Max { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::MAX; op_def static X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Y, typename Z> class AMaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) > nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class AMinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) < nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class MaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X, typename Y, typename Z> class MinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X> class AMax { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::AMAX; op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_abs<X>(d1) > nd4j::math::nd4j_abs<X>(d2) ? d1 : d2; } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class AMin { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::AMIN; op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class Min { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::MIN; op_def static X startingValue(const X *input) { return nd4j::DataTypeUtils::infOrMax<X>(); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Norm1 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(nd4j::math::nd4j_abs<X>(d1)); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction; } }; template <typename X, typename Z> class Norm2 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<Z, Z>(reduction); } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } }; template <typename X, typename Z> class SquaredNorm { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction; } }; template <typename X, typename Z> class NormFrobenius { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { X v = nd4j::math::nd4j_abs<X>(d1); return static_cast<Z>(v * v); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<Z, Z>(reduction); } }; template <typename X, typename Z> class NormP { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_pow<X, Z, Z>(nd4j::math::nd4j_abs<X>(d1), extraParams[0]); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_pow<Z, Z, Z>(reduction, static_cast<Z>(1.0f) / extraParams[0]); } }; template <typename X, typename Z> class NormMax { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(old), nd4j::math::nd4j_abs<Z>(opOutput)); } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(reduction), nd4j::math::nd4j_abs<Z>(reduction)); } }; template <typename X, typename Z> class Variance { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static X op(X d1, Z *extraParams) { X mean = static_cast<X>(extraParams[0]); X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { // T bias = extraParams[1]; // return (reduction - (nd4j::math::nd4j_pow<T>(bias, static_cast<T>(2.0f)) / static_cast<T>(n))) / (n - 1) return static_cast<Z>(reduction) / static_cast<Z>(n - 1); } }; /** * Standard deviation of a buffer */ template <typename X, typename Z> class StandardDeviation { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z op(X d1, Z *extraParams) { X mean = extraParams[0]; X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { Z ret = Variance<X,Z>::postProcess(reduction, n, extraParams); Z sqrtRet = nd4j::math::nd4j_sqrt<X, Z>(ret); return sqrtRet; } }; template <typename X, typename Y> class CosineSimilarity { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1])); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(d1 * d1); extraParams[1] += static_cast<Y>(d2 * d2); return static_cast<Y>(d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],static_cast<Y>(d1 * d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1],static_cast<Y>(d2 * d2)); return static_cast<Y>(d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class JaccardDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { // num / denom return (static_cast<Y>(1.0f)) - (extraParams[0] / extraParams[1]); } op_def static Y num(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static Y denom(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(num(d1, d2)); extraParams[1] += static_cast<Y>(denom(d1, d2)); return static_cast<Y>(0.0f); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],num(d1, d2)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], denom(d1, d2)); return static_cast<Y>(0.0f); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class SimpleHammingDistance { public: static const int extraParamsLen = 0; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return static_cast<Y>(reduction / n); } op_def static Y op(X d1, X d2, Y *extraParams) { return (d1 == d2) ? static_cast<Y>(0.0f) : static_cast<Y>(1.0f); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { return op(d1, d2, extraParams); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class CosineDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return (static_cast<Y>(1.0f)) - (reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1]))); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d1) * nd4j::math::nd4j_abs<X>(d1)); extraParams[1] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d2) * nd4j::math::nd4j_abs<X>(d2)); return (d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0], nd4j::math::nd4j_abs<Y>(d1) * nd4j::math::nd4j_abs<Y>(d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], nd4j::math::nd4j_abs<Y>(d2) * nd4j::math::nd4j_abs<Y>(d2)); return (d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; /** * Dot product between 2 arrays */ template <typename X, typename Y> class Dot { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op //delete[] * extraParamsRef; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return static_cast<Y>(d1 * d2); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; /** * Op to check equality within arrays */ template <typename X, typename Z> class EqualsWithEps { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Z startingValue(const X *input) { return static_cast<Z>(0.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParamsRef) { return reduction; } op_def static Z op(X d1, X d2, Z *extraParamsRef) { double eps = nd4j::math::nd4j_abs<double>(extraParamsRef[2]); return static_cast<Z>(!nd4j::math::nd4j_eq<X>(d1, d2, eps)); } #ifdef __CUDACC__ __device__ static inline Z opAtomic(X d1, X d2, Z *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Z update(Z old, Z opOutput, Z *extraParamsRef) { return opOutput + old; } op_def static Z merge(X old, Z opOutput, Z *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Z *extraParamsTotal, Z *extraParamsLocal) {} }; template <typename X, typename Y> class EuclideanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return nd4j::math::nd4j_sqrt<Y, Y>(reduction); } op_def static Y op(X d1, X d2, Y *extraParamsRef) { X ret = d1 - d2; return static_cast<Y>(ret * ret); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; template <typename X, typename Y> class ManhattanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return nd4j::math::nd4j_abs<X>(d1 - d2); } op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return old + opOutput; } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif #ifndef __clang__ #pragma omp declare simd uniform(extraParamsRef) #endif op_def static Y merge(X old, X opOutput, X *extraParamsRef) { return update(old, opOutput, extraParamsRef); } }; template <typename X, typename Z> class IndexAbsoluteMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return nd4j::math::nd4j_abs<X>(val); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value > old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) > nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(const X *input) { return 0; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class FirstIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); //printf("res: %f; oldIdx: %i; newIdx: %i\n", res, old.index, opOutput.index); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index > opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index > f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X, typename Z> class LastIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index < opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index < f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X, typename Z> class IndexMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value > old.value) { return opOutput; } #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value > f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class IndexAbsoluteMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(const X *input) { return nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) < nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class IndexMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(const X *input) { return nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value < f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsVariance { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { Z ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return static_cast<Z>(val.variance()); return ret; } return static_cast<Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsStandardDeviation { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { auto ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); else return nd4j::math::nd4j_sqrt<double, Z>(ret); } return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X> class DropOut { public: no_op_exec_special_same no_op_exec_special_same_cuda inline _CUDA_D static X op(X d1, X *params) { X prob = params[0]; #ifdef __CUDACC__ X length = params[1]; X tid = blockIdx.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= prob ? static_cast<X>(0.0f) : d1; } }; template <typename X, typename Y, typename Z> class DropOutInverted { public: no_op_exec_special no_op_exec_special_cuda #ifdef __CUDACC__ __device__ #endif inline static Z op(X d1, Y d2, Z *params) { Y prob = d2; #ifdef __CUDACC__ X length = params[1]; X tid = blockIdx.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= static_cast<X>(prob) ? static_cast<Z>(0.0f) : reinterpret_cast<Z>(d1 / static_cast<X>(prob)); } }; template <typename X, typename Y, typename Z> class ReplaceNans { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<Z>(d2) : static_cast<Z>(d1) ; } }; // this op is used for conditional pairwise transforms only template <typename X, typename Y, typename Z> class CompareAndReplace{ public: // op definition for PairWise Transform op_def static Z op(X d1, Y d2, Z *params) { auto zd1 = static_cast<Z>(d1); auto zd2 = static_cast<Z>(d2); auto compare = params[0]; auto eps = params[2]; int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(zd1 - compare) <= eps) return zd2; else return zd1; else if (mode == 1) // not equals eps if (nd4j::math::nd4j_abs<Z>(zd1 - compare) > eps) return zd2; else return zd1; else if (mode == 2) // less_than eps if (zd1 < compare) return zd2; else return zd1; else if (mode ==3) // greater_than if (zd1 > compare) return zd2; else return zd1; else if (mode == 4) // less_or_equals_than if (zd1 <= compare) return zd2; else return zd1; else if (mode == 5) // greater_or_equals_than if (zd1 >= compare) return zd2; else return zd1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(zd1) < compare) return zd2; else return zd1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(zd1) > compare) return zd2; else return zd1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(zd1)) return zd2; else return zd1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(zd1)) return zd2; else return zd1; else if (mode == 10) if (zd1 == compare) return zd2; else return zd1; else if (mode == 11) if (zd1 != compare) return zd2; else return zd1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) >= compare) return zd2; else return zd1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) <= compare) return zd2; else return zd1; else printf("Undefined boolean operation: [%i]\n", mode); return zd1; } }; template <typename X, typename Y, typename Z> class CompareAndSet { public: // op definition for PairWise Transform op_def static Z op(X dX, Y dY, Z *params) { auto d1 = static_cast<Z>(dX); auto d2 = static_cast<Z>(dY); auto compare = params[0]; auto eps = params[2]; auto mode = static_cast<int>(params[3]); if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) <= eps) return d2; else return d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) > eps) return d2; else return d1; else if (mode == 2) // less_than if (d2 < compare) return d2; else return d1; else if (mode ==3) // greater_than if (d2 > compare) return d2; else return d1; else if (mode == 4) // less_or_equals_than if (d2 <= compare) return d2; else return d1; else if (mode == 5) // greater_or_equals_than if (d2 >= compare) return d2; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(d2) < compare) return d2; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(d2) > compare) return d2; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d2)) return d2; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d2)) return d2; else return d1; else if (mode == 10) if (d2 == compare) return d2; else return d1; else if (mode == 11) if (d2 != compare) return d2; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) >= compare) return d2; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) <= compare) return d2; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; template <typename X> class CompareAndSetTransform { public: no_op_exec_special_same no_op_exec_special_same_cuda // op definition for Transform op_def static X op(X d1, X *params) { auto compare = params[0]; auto set = params[1]; auto eps = params[2]; // with mode == 0 we do set if d1 equals to compare, and with mode == 1 - we go otherwise int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<X>(d1 - compare) <= eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? set : d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<X>(d1 - compare) > eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? set : d1; else if (mode == 2) // less_than if (d1 < compare) return set; else return d1; else if (mode ==3) // greater_than if (d1 > compare) return set; else return d1; else if (mode == 4) // less_or_equals_than if (d1 <= compare) return set; else return d1; else if (mode == 5) // greater_or_equals_than if (d1 >= compare) return set; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<X>(d1) < compare) return set; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<X>(d1) > compare) return set; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d1)) return set; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d1)) return set; else return d1; else if (mode == 10) if (d1 == compare) return set; else return d1; else if (mode == 11) if (d1 != compare) return set; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) >= compare) return set; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) <= compare) return set; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; } #endif
GraphReconstructor.h
// // Copyright (C) 2015-2020 Yahoo Japan Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <unordered_map> #include <unordered_set> #include <list> #include "defines.h" #ifdef _OPENMP #include <omp.h> #else #warning "*** OMP is *NOT* available! ***" #endif namespace NGT { class GraphReconstructor { public: static void extractGraph(std::vector<NGT::ObjectDistances> &graph, NGT::GraphIndex &graphIndex) { graph.reserve(graphIndex.repository.size()); for (size_t id = 1; id < graphIndex.repository.size(); id++) { if (id % 1000000 == 0) { if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor::extractGraph: Processed " + std::to_string(id) + " objects."); // std::cerr << "GraphReconstructor::extractGraph: Processed " << id << " objects." << std::endl; } try { NGT::GraphNode &node = *graphIndex.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::ObjectDistances nd; nd.reserve(node.size()); for (auto n = node.begin(graphIndex.repository.allocator); n != node.end(graphIndex.repository.allocator); ++n) { nd.push_back(ObjectDistance((*n).id, (*n).distance)); } graph.push_back(nd); #else graph.push_back(node); #endif if (graph.back().size() != graph.back().capacity()) { if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor::extractGraph: Warning! The graph size must be the same as the capacity. " + std::to_string(id)); // std::cerr << "GraphReconstructor::extractGraph: Warning! The graph size must be the same as the capacity. " << id << std::endl; } } catch(NGT::Exception &err) { graph.push_back(NGT::ObjectDistances()); continue; } } } static void adjustPaths(NGT::Index &outIndex) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("construct index is not implemented."); // std::cerr << "construct index is not implemented." << std::endl; exit(1); #else NGT::GraphIndex &outGraph = dynamic_cast<NGT::GraphIndex&>(outIndex.getIndex()); size_t rStartRank = 0; std::list<std::pair<size_t, NGT::GraphNode> > tmpGraph; for (size_t id = 1; id < outGraph.repository.size(); id++) { NGT::GraphNode &node = *outGraph.getNode(id); tmpGraph.push_back(std::pair<size_t, NGT::GraphNode>(id, node)); if (node.size() > rStartRank) { node.resize(rStartRank); } } size_t removeCount = 0; for (size_t rank = rStartRank; ; rank++) { bool edge = false; Timer timer; for (auto it = tmpGraph.begin(); it != tmpGraph.end();) { size_t id = (*it).first; try { NGT::GraphNode &node = (*it).second; if (rank >= node.size()) { it = tmpGraph.erase(it); continue; } edge = true; if (rank >= 1 && node[rank - 1].distance > node[rank].distance) { // std::cerr << "distance order is wrong!" << std::endl; // std::cerr << id << ":" << rank << ":" << node[rank - 1].id << ":" << node[rank].id << std::endl; if (NGT_LOG_DEBUG_) { (*NGT_LOG_DEBUG_)("distance order is wrong!"); (*NGT_LOG_DEBUG_)(std::to_string(id) + ":" + std::to_string(rank) + ":" + std::to_string(node[rank - 1].id) + ":" + std::to_string(node[rank].id)); } } NGT::GraphNode &tn = *outGraph.getNode(id); volatile bool found = false; if (rank < 1000) { for (size_t tni = 0; tni < tn.size() && !found; tni++) { if (tn[tni].id == node[rank].id) { continue; } NGT::GraphNode &dstNode = *outGraph.getNode(tn[tni].id); for (size_t dni = 0; dni < dstNode.size(); dni++) { if ((dstNode[dni].id == node[rank].id) && (dstNode[dni].distance < node[rank].distance)) { found = true; break; } } } } else { #ifdef _OPENMP #pragma omp parallel for num_threads(10) #endif for (size_t tni = 0; tni < tn.size(); tni++) { if (found) { continue; } if (tn[tni].id == node[rank].id) { continue; } NGT::GraphNode &dstNode = *outGraph.getNode(tn[tni].id); for (size_t dni = 0; dni < dstNode.size(); dni++) { if ((dstNode[dni].id == node[rank].id) && (dstNode[dni].distance < node[rank].distance)) { found = true; } } } } if (!found) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) outGraph.addEdge(id, node.at(i, outGraph.repository.allocator).id, node.at(i, outGraph.repository.allocator).distance, true); #else tn.push_back(NGT::ObjectDistance(node[rank].id, node[rank].distance)); #endif } else { removeCount++; } } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); it++; continue; } it++; } if (edge == false) { break; } } #endif // NGT_SHARED_MEMORY_ALLOCATOR } static void adjustPathsEffectively(NGT::Index &outIndex) { NGT::GraphIndex &outGraph = dynamic_cast<NGT::GraphIndex&>(outIndex.getIndex()); adjustPathsEffectively(outGraph); } static bool edgeComp(NGT::ObjectDistance a, NGT::ObjectDistance b) { return a.id < b.id; } #if defined(NGT_SHARED_MEMORY_ALLOCATOR) static void insert(NGT::GraphNode &node, size_t edgeID, NGT::Distance edgeDistance, NGT::GraphIndex &graph) { NGT::ObjectDistance edge(edgeID, edgeDistance); GraphNode::iterator ni = std::lower_bound(node.begin(graph.repository.allocator), node.end(graph.repository.allocator), edge, edgeComp); node.insert(ni, edge, graph.repository.allocator); } static bool hasEdge(NGT::GraphIndex &graph, size_t srcNodeID, size_t dstNodeID) { NGT::GraphNode &srcNode = *graph.getNode(srcNodeID); GraphNode::iterator ni = std::lower_bound(srcNode.begin(graph.repository.allocator), srcNode.end(graph.repository.allocator), ObjectDistance(dstNodeID, 0.0), edgeComp); return (ni != srcNode.end(graph.repository.allocator)) && ((*ni).id == dstNodeID); } #else static void insert(NGT::GraphNode &node, size_t edgeID, NGT::Distance edgeDistance) { NGT::ObjectDistance edge(edgeID, edgeDistance); GraphNode::iterator ni = std::lower_bound(node.begin(), node.end(), edge, edgeComp); node.insert(ni, edge); } static bool hasEdge(NGT::GraphIndex &graph, size_t srcNodeID, size_t dstNodeID) { NGT::GraphNode &srcNode = *graph.getNode(srcNodeID); GraphNode::iterator ni = std::lower_bound(srcNode.begin(), srcNode.end(), ObjectDistance(dstNodeID, 0.0), edgeComp); return (ni != srcNode.end()) && ((*ni).id == dstNodeID); } #endif static void adjustPathsEffectively(NGT::GraphIndex &outGraph) { Timer timer; timer.start(); std::vector<NGT::GraphNode> tmpGraph; for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &node = *outGraph.getNode(id); tmpGraph.push_back(node); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.clear(outGraph.repository.allocator); #else node.clear(); #endif } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) tmpGraph.push_back(NGT::GraphNode(outGraph.repository.allocator)); #else tmpGraph.push_back(NGT::GraphNode()); #endif } } if (outGraph.repository.size() != tmpGraph.size() + 1) { std::stringstream msg; msg << "GraphReconstructor: Fatal inner error. " << outGraph.repository.size() << ":" << tmpGraph.size(); NGTThrowException(msg); } timer.stop(); // std::cerr << "GraphReconstructor::adjustPaths: graph preparing time=" << timer << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor::adjustPaths: graph preparing time=" + std::to_string(timer.time)); timer.reset(); timer.start(); std::vector<std::vector<std::pair<uint32_t, uint32_t> > > removeCandidates(tmpGraph.size()); int removeCandidateCount = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (size_t idx = 0; idx < tmpGraph.size(); ++idx) { auto it = tmpGraph.begin() + idx; size_t id = idx + 1; try { NGT::GraphNode &srcNode = *it; std::unordered_map<uint32_t, std::pair<size_t, double> > neighbors; for (size_t sni = 0; sni < srcNode.size(); ++sni) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) neighbors[srcNode.at(sni, outGraph.repository.allocator).id] = std::pair<size_t, double>(sni, srcNode.at(sni, outGraph.repository.allocator).distance); #else neighbors[srcNode[sni].id] = std::pair<size_t, double>(sni, srcNode[sni].distance); #endif } std::vector<std::pair<int, std::pair<uint32_t, uint32_t> > > candidates; for (size_t sni = 0; sni < srcNode.size(); sni++) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::GraphNode &pathNode = tmpGraph[srcNode.at(sni, outGraph.repository.allocator).id - 1]; #else NGT::GraphNode &pathNode = tmpGraph[srcNode[sni].id - 1]; #endif for (size_t pni = 0; pni < pathNode.size(); pni++) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) auto dstNodeID = pathNode.at(pni, outGraph.repository.allocator).id; #else auto dstNodeID = pathNode[pni].id; #endif auto dstNode = neighbors.find(dstNodeID); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) if (dstNode != neighbors.end() && srcNode.at(sni, outGraph.repository.allocator).distance < (*dstNode).second.second && pathNode.at(pni, outGraph.repository.allocator).distance < (*dstNode).second.second ) { #else if (dstNode != neighbors.end() && srcNode[sni].distance < (*dstNode).second.second && pathNode[pni].distance < (*dstNode).second.second ) { #endif #if defined(NGT_SHARED_MEMORY_ALLOCATOR) candidates.push_back(std::pair<int, std::pair<uint32_t, uint32_t> >((*dstNode).second.first, std::pair<uint32_t, uint32_t>(srcNode.at(sni, outGraph.repository.allocator).id, dstNodeID))); #else candidates.push_back(std::pair<int, std::pair<uint32_t, uint32_t> >((*dstNode).second.first, std::pair<uint32_t, uint32_t>(srcNode[sni].id, dstNodeID))); #endif removeCandidateCount++; } } } sort(candidates.begin(), candidates.end(), std::greater<std::pair<int, std::pair<uint32_t, uint32_t>>>()); removeCandidates[id - 1].reserve(candidates.size()); for (size_t i = 0; i < candidates.size(); i++) { removeCandidates[id - 1].push_back(candidates[i].second); } } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } timer.stop(); // std::cerr << "GraphReconstructor::adjustPaths: extracting removed edge candidates time=" << timer << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor::adjustPaths: extracting removed edge candidates time=" + std::to_string(timer.time)); timer.reset(); timer.start(); std::list<size_t> ids; for (size_t idx = 0; idx < tmpGraph.size(); ++idx) { ids.push_back(idx + 1); } int removeCount = 0; removeCandidateCount = 0; for (size_t rank = 0; ids.size() != 0; rank++) { for (auto it = ids.begin(); it != ids.end(); ) { size_t id = *it; size_t idx = id - 1; try { NGT::GraphNode &srcNode = tmpGraph[idx]; if (rank >= srcNode.size()) { if (!removeCandidates[idx].empty()) { // std::cerr << "Something wrong! ID=" << id << " # of remaining candidates=" << removeCandidates[idx].size() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Something wrong! ID=" + std::to_string(id) + " # of remaining candidates=" + std::to_string(removeCandidates[idx].size())); abort(); } #if !defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::GraphNode empty; tmpGraph[idx] = empty; #endif it = ids.erase(it); continue; } if (removeCandidates[idx].size() > 0) { removeCandidateCount++; bool pathExist = false; #if defined(NGT_SHARED_MEMORY_ALLOCATOR) while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode.at(rank, outGraph.repository.allocator).id)) { #else while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode[rank].id)) { #endif size_t path = removeCandidates[idx].back().first; size_t dst = removeCandidates[idx].back().second; removeCandidates[idx].pop_back(); if (removeCandidates[idx].empty()) { std::vector<std::pair<uint32_t, uint32_t>> empty; removeCandidates[idx] = empty; } if ((hasEdge(outGraph, id, path)) && (hasEdge(outGraph, path, dst))) { pathExist = true; #if defined(NGT_SHARED_MEMORY_ALLOCATOR) while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode.at(rank, outGraph.repository.allocator).id)) { #else while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode[rank].id)) { #endif removeCandidates[idx].pop_back(); if (removeCandidates[idx].empty()) { std::vector<std::pair<uint32_t, uint32_t>> empty; removeCandidates[idx] = empty; } } break; } } if (pathExist) { removeCount++; it++; continue; } } NGT::GraphNode &outSrcNode = *outGraph.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) insert(outSrcNode, srcNode.at(rank, outGraph.repository.allocator).id, srcNode.at(rank, outGraph.repository.allocator).distance, outGraph); #else insert(outSrcNode, srcNode[rank].id, srcNode[rank].distance); #endif } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); it++; continue; } it++; } } for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &node = *outGraph.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::sort(node.begin(outGraph.repository.allocator), node.end(outGraph.repository.allocator)); #else std::sort(node.begin(), node.end()); #endif } catch(...) {} } } static void convertToANNG(std::vector<NGT::ObjectDistances> &graph) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("convertToANNG is not implemented for shared memory."); // std::cerr << "convertToANNG is not implemented for shared memory." << std::endl; return; #else // std::cerr << "convertToANNG begin" << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("convertToANNG begin"); for (size_t idx = 0; idx < graph.size(); idx++) { NGT::GraphNode &node = graph[idx]; for (auto ni = node.begin(); ni != node.end(); ++ni) { graph[(*ni).id - 1].push_back(NGT::ObjectDistance(idx + 1, (*ni).distance)); } } for (size_t idx = 0; idx < graph.size(); idx++) { NGT::GraphNode &node = graph[idx]; if (node.size() == 0) { continue; } std::sort(node.begin(), node.end()); NGT::ObjectID prev = 0; for (auto it = node.begin(); it != node.end();) { if (prev == (*it).id) { it = node.erase(it); continue; } prev = (*it).id; it++; } NGT::GraphNode tmp = node; node.swap(tmp); } if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("convertToANNG end"); // std::cerr << "convertToANNG end" << std::endl; #endif } static void reconstructGraph(std::vector<NGT::ObjectDistances> &graph, NGT::GraphIndex &outGraph, size_t originalEdgeSize, size_t reverseEdgeSize) { if (reverseEdgeSize > 10000) { // std::cerr << "something wrong. Edge size=" << reverseEdgeSize << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("something wrong. Edge size=" + std::to_string(reverseEdgeSize)); exit(1); } NGT::Timer originalEdgeTimer, reverseEdgeTimer, normalizeEdgeTimer; originalEdgeTimer.start(); for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &node = *outGraph.getNode(id); if (originalEdgeSize == 0) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.clear(outGraph.repository.allocator); #else NGT::GraphNode empty; node.swap(empty); #endif } else { NGT::ObjectDistances n = graph[id - 1]; if (n.size() < originalEdgeSize) { // std::cerr << "GraphReconstructor: Warning. The edges are too few. " << n.size() << ":" << originalEdgeSize << " for " << id << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. The edges are too few. " + std::to_string(n.size()) + ":" + std::to_string(originalEdgeSize) + " for " + std::to_string(id)); continue; } n.resize(originalEdgeSize); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.copy(n, outGraph.repository.allocator); #else node.swap(n); #endif } } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } originalEdgeTimer.stop(); reverseEdgeTimer.start(); int insufficientNodeCount = 0; for (size_t id = 1; id <= graph.size(); ++id) { try { NGT::ObjectDistances &node = graph[id - 1]; size_t rsize = reverseEdgeSize; if (rsize > node.size()) { insufficientNodeCount++; rsize = node.size(); } for (size_t i = 0; i < rsize; ++i) { NGT::Distance distance = node[i].distance; size_t nodeID = node[i].id; try { NGT::GraphNode &n = *outGraph.getNode(nodeID); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) n.push_back(NGT::ObjectDistance(id, distance), outGraph.repository.allocator); #else n.push_back(NGT::ObjectDistance(id, distance)); #endif } catch(...) {} } } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } reverseEdgeTimer.stop(); if (insufficientNodeCount != 0) { // std::cerr << "# of the nodes edges of which are in short = " << insufficientNodeCount << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("# of the nodes edges of which are in short = " + std::to_string(insufficientNodeCount)); } normalizeEdgeTimer.start(); for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &n = *outGraph.getNode(id); if (id % 100000 == 0) { // std::cerr << "Processed " << id << " nodes" << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Processed " + std::to_string(id) + " nodes"); } #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::sort(n.begin(outGraph.repository.allocator), n.end(outGraph.repository.allocator)); #else std::sort(n.begin(), n.end()); #endif NGT::ObjectID prev = 0; #if defined(NGT_SHARED_MEMORY_ALLOCATOR) for (auto it = n.begin(outGraph.repository.allocator); it != n.end(outGraph.repository.allocator);) { #else for (auto it = n.begin(); it != n.end();) { #endif if (prev == (*it).id) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) it = n.erase(it, outGraph.repository.allocator); #else it = n.erase(it); #endif continue; } prev = (*it).id; it++; } #if !defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::GraphNode tmp = n; n.swap(tmp); #endif } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } normalizeEdgeTimer.stop(); // std::cerr << "Reconstruction time=" << originalEdgeTimer.time << ":" << reverseEdgeTimer.time // << ":" << normalizeEdgeTimer.time << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Reconstruction time=" + std::to_string(originalEdgeTimer.time) + ":" + std::to_string(reverseEdgeTimer.time) + ":" + std::to_string(normalizeEdgeTimer.time)); NGT::Property prop; outGraph.getProperty().get(prop); prop.graphType = NGT::NeighborhoodGraph::GraphTypeONNG; outGraph.getProperty().set(prop); } static void reconstructGraphWithConstraint(std::vector<NGT::ObjectDistances> &graph, NGT::GraphIndex &outGraph, size_t originalEdgeSize, size_t reverseEdgeSize, char mode = 'a') { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("reconstructGraphWithConstraint is not implemented."); // std::cerr << "reconstructGraphWithConstraint is not implemented." << std::endl; abort(); #else NGT::Timer originalEdgeTimer, reverseEdgeTimer, normalizeEdgeTimer; if (reverseEdgeSize > 10000) { // std::cerr << "something wrong. Edge size=" << reverseEdgeSize << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("something wrong. Edge size=" + std::to_string(reverseEdgeSize)); exit(1); } for (size_t id = 1; id < outGraph.repository.size(); id++) { if (id % 1000000 == 0) { // std::cerr << "Processed " << id << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Processed " + std::to_string(id)); } try { NGT::GraphNode &node = *outGraph.getNode(id); if (node.size() == 0) { continue; } node.clear(); NGT::GraphNode empty; node.swap(empty); } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } NGT::GraphIndex::showStatisticsOfGraph(outGraph); std::vector<ObjectDistances> reverse(graph.size() + 1); for (size_t id = 1; id <= graph.size(); ++id) { try { NGT::GraphNode &node = graph[id - 1]; if (id % 100000 == 0) { // std::cerr << "Processed (summing up) " << id << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Processed (summing up) " + std::to_string(id)); } for (size_t rank = 0; rank < node.size(); rank++) { reverse[node[rank].id].push_back(ObjectDistance(id, node[rank].distance)); } } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } std::vector<std::pair<size_t, size_t> > reverseSize(graph.size() + 1); reverseSize[0] = std::pair<size_t, size_t>(0, 0); for (size_t rid = 1; rid <= graph.size(); ++rid) { reverseSize[rid] = std::pair<size_t, size_t>(reverse[rid].size(), rid); } std::sort(reverseSize.begin(), reverseSize.end()); std::vector<uint32_t> indegreeCount(graph.size(), 0); size_t zeroCount = 0; for (size_t sizerank = 0; sizerank <= reverseSize.size(); sizerank++) { if (reverseSize[sizerank].first == 0) { zeroCount++; continue; } size_t rid = reverseSize[sizerank].second; ObjectDistances &rnode = reverse[rid]; for (auto rni = rnode.begin(); rni != rnode.end(); ++rni) { if (indegreeCount[(*rni).id] >= reverseEdgeSize) { continue; } NGT::GraphNode &node = *outGraph.getNode(rid); if (indegreeCount[(*rni).id] > 0 && node.size() >= originalEdgeSize) { continue; } node.push_back(NGT::ObjectDistance((*rni).id, (*rni).distance)); indegreeCount[(*rni).id]++; } } reverseEdgeTimer.stop(); // std::cerr << "The number of nodes with zero outdegree by reverse edges=" << zeroCount << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("The number of nodes with zero outdegree by reverse edges=" + std::to_string(zeroCount)); NGT::GraphIndex::showStatisticsOfGraph(outGraph); normalizeEdgeTimer.start(); for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &n = *outGraph.getNode(id); if (id % 100000 == 0) { // std::cerr << "Processed " << id << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Processed " + std::to_string(id)); } std::sort(n.begin(), n.end()); NGT::ObjectID prev = 0; for (auto it = n.begin(); it != n.end();) { if (prev == (*it).id) { it = n.erase(it); continue; } prev = (*it).id; it++; } NGT::GraphNode tmp = n; n.swap(tmp); } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } normalizeEdgeTimer.stop(); NGT::GraphIndex::showStatisticsOfGraph(outGraph); originalEdgeTimer.start(); for (size_t id = 1; id < outGraph.repository.size(); id++) { if (id % 1000000 == 0) { // std::cerr << "Processed " << id << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Processed " + std::to_string(id)); } NGT::GraphNode &node = graph[id - 1]; try { NGT::GraphNode &onode = *outGraph.getNode(id); bool stop = false; for (size_t rank = 0; (rank < node.size() && rank < originalEdgeSize) && stop == false; rank++) { switch (mode) { case 'a': if (onode.size() >= originalEdgeSize) { stop = true; continue; } break; case 'c': break; } NGT::Distance distance = node[rank].distance; size_t nodeID = node[rank].id; outGraph.addEdge(id, nodeID, distance, false); } } catch(NGT::Exception &err) { // std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("GraphReconstructor: Warning. Cannot get the node. ID=" + std::to_string(id) + ":" + err.what()); continue; } } originalEdgeTimer.stop(); NGT::GraphIndex::showStatisticsOfGraph(outGraph); // std::cerr << "Reconstruction time=" << originalEdgeTimer.time << ":" << reverseEdgeTimer.time // << ":" << normalizeEdgeTimer.time << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Reconstruction time=" + std::to_string(originalEdgeTimer.time) + ":" + std::to_string(reverseEdgeTimer.time) + ":" + std::to_string(normalizeEdgeTimer.time)); #endif } // reconstruct a pseudo ANNG with a fewer edges from an actual ANNG with more edges. // graph is a source ANNG // index is an index with a reconstructed ANNG static void reconstructANNGFromANNG(std::vector<NGT::ObjectDistances> &graph, NGT::Index &index, size_t edgeSize) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("reconstructANNGFromANNG is not implemented."); // std::cerr << "reconstructANNGFromANNG is not implemented." << std::endl; abort(); #else NGT::GraphIndex &outGraph = dynamic_cast<NGT::GraphIndex&>(index.getIndex()); // remove all edges in the index. for (size_t id = 1; id < outGraph.repository.size(); id++) { if (id % 1000000 == 0) { // std::cerr << "Processed " << id << " nodes." << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("Processed " + std::to_string(id) + " nodes."); } try { NGT::GraphNode &node = *outGraph.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.clear(outGraph.repository.allocator); #else NGT::GraphNode empty; node.swap(empty); #endif } catch(NGT::Exception &err) { } } for (size_t id = 1; id <= graph.size(); ++id) { size_t edgeCount = 0; try { NGT::ObjectDistances &node = graph[id - 1]; NGT::GraphNode &n = *outGraph.getNode(id); NGT::Distance prevDistance = 0.0; assert(n.size() == 0); for (size_t i = 0; i < node.size(); ++i) { NGT::Distance distance = node[i].distance; if (prevDistance > distance) { NGTThrowException("Edge distance order is invalid"); } prevDistance = distance; size_t nodeID = node[i].id; if (node[i].id < id) { try { NGT::GraphNode &dn = *outGraph.getNode(nodeID); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) n.push_back(NGT::ObjectDistance(nodeID, distance), outGraph.repository.allocator); dn.push_back(NGT::ObjectDistance(id, distance), outGraph.repository.allocator); #else n.push_back(NGT::ObjectDistance(nodeID, distance)); dn.push_back(NGT::ObjectDistance(id, distance)); #endif } catch(...) {} edgeCount++; } if (edgeCount >= edgeSize) { break; } } } catch(NGT::Exception &err) { } } for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &n = *outGraph.getNode(id); std::sort(n.begin(), n.end()); NGT::ObjectID prev = 0; for (auto it = n.begin(); it != n.end();) { if (prev == (*it).id) { it = n.erase(it); continue; } prev = (*it).id; it++; } NGT::GraphNode tmp = n; n.swap(tmp); } catch (...) { } } #endif } static void refineANNG(NGT::Index &index, bool unlog, float epsilon = 0.1, float accuracy = 0.0, int noOfEdges = 0, int exploreEdgeSize = INT_MIN, size_t batchSize = 10000) { NGT::StdOstreamRedirector redirector(unlog); redirector.begin(); try { refineANNG(index, epsilon, accuracy, noOfEdges, exploreEdgeSize, batchSize); } catch (NGT::Exception &err) { redirector.end(); throw(err); } } static void refineANNG(NGT::Index &index, float epsilon = 0.1, float accuracy = 0.0, int noOfEdges = 0, int exploreEdgeSize = INT_MIN, size_t batchSize = 10000) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) NGTThrowException("GraphReconstructor::refineANNG: Not implemented for the shared memory option."); #else auto prop = static_cast<GraphIndex&>(index.getIndex()).getGraphProperty(); NGT::ObjectRepository &objectRepository = index.getObjectSpace().getRepository(); NGT::GraphIndex &graphIndex = static_cast<GraphIndex&>(index.getIndex()); size_t nOfObjects = objectRepository.size(); bool error = false; std::string errorMessage; for (size_t bid = 1; bid < nOfObjects; bid += batchSize) { NGT::ObjectDistances results[batchSize]; // search #pragma omp parallel for for (size_t idx = 0; idx < batchSize; idx++) { size_t id = bid + idx; if (id % 100000 == 0) { // std::cerr << "# of processed objects=" << id << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("# of processed objects=" + std::to_string(id)); } if (objectRepository.isEmpty(id)) { continue; } NGT::SearchContainer searchContainer(*objectRepository.get(id)); searchContainer.setResults(&results[idx]); assert(prop.edgeSizeForCreation > 0); searchContainer.setSize(noOfEdges > prop.edgeSizeForCreation ? noOfEdges : prop.edgeSizeForCreation); if (accuracy > 0.0) { searchContainer.setExpectedAccuracy(accuracy); } else { searchContainer.setEpsilon(epsilon); } if (exploreEdgeSize != INT_MIN) { searchContainer.setEdgeSize(exploreEdgeSize); } if (!error) { try { index.search(searchContainer); } catch (NGT::Exception &err) { #pragma omp critical { error = true; errorMessage = err.what(); } } } } if (error) { std::stringstream msg; msg << "GraphReconstructor::refineANNG: " << errorMessage; NGTThrowException(msg); } // outgoing edges #pragma omp parallel for for (size_t idx = 0; idx < batchSize; idx++) { size_t id = bid + idx; if (objectRepository.isEmpty(id)) { continue; } NGT::GraphNode &node = *graphIndex.getNode(id); for (auto i = results[idx].begin(); i != results[idx].end(); ++i) { if ((*i).id != id) { node.push_back(*i); } } std::sort(node.begin(), node.end()); // dedupe ObjectID prev = 0; for (GraphNode::iterator ni = node.begin(); ni != node.end();) { if (prev == (*ni).id) { ni = node.erase(ni); continue; } prev = (*ni).id; ni++; } } // incomming edges if (noOfEdges != 0) { continue; } for (size_t idx = 0; idx < batchSize; idx++) { size_t id = bid + idx; if (id % 10000 == 0) { // std::cerr << "# of processed objects=" << id << std::endl; if (NGT_LOG_DEBUG_) (*NGT_LOG_DEBUG_)("# of processed objects=" + std::to_string(id)); } for (auto i = results[idx].begin(); i != results[idx].end(); ++i) { if ((*i).id != id) { NGT::GraphNode &node = *graphIndex.getNode((*i).id); graphIndex.addEdge(node, id, (*i).distance, false); } } } } if (noOfEdges != 0) { // prune to build knng size_t nedges = noOfEdges < 0 ? -noOfEdges : noOfEdges; #pragma omp parallel for for (ObjectID id = 1; id < nOfObjects; ++id) { if (objectRepository.isEmpty(id)) { continue; } NGT::GraphNode &node = *graphIndex.getNode(id); if (node.size() > nedges) { node.resize(nedges); } } } #endif // defined(NGT_SHARED_MEMORY_ALLOCATOR) } }; }; // NGT
GridInit.c
#include "XSbench_header.h" SimulationData grid_init_do_not_profile( Inputs in, int mype ) { // Structure to hold all allocated simuluation data arrays SimulationData SD; // Keep track of how much data we're allocating size_t nbytes = 0; // Set the initial seed value uint64_t seed = 42; //////////////////////////////////////////////////////////////////// // Initialize Nuclide Grids //////////////////////////////////////////////////////////////////// if(mype == 0) printf("Intializing nuclide grids...\n"); // First, we need to initialize our nuclide grid. This comes in the form // of a flattened 2D array that hold all the information we need to define // the cross sections for all isotopes in the simulation. // The grid is composed of "NuclideGridPoint" structures, which hold the // energy level of the grid point and all associated XS data at that level. // An array of structures (AOS) is used instead of // a structure of arrays, as the grid points themselves are accessed in // a random order, but all cross section interaction channels and the // energy level are read whenever the gridpoint is accessed, meaning the // AOS is more cache efficient. // Initialize Nuclide Grid SD.length_nuclide_grid = in.n_isotopes * in.n_gridpoints; SD.nuclide_grid = (NuclideGridPoint *) malloc( SD.length_nuclide_grid * sizeof(NuclideGridPoint)); assert(SD.nuclide_grid != NULL); nbytes += SD.length_nuclide_grid * sizeof(NuclideGridPoint); for( int i = 0; i < SD.length_nuclide_grid; i++ ) { SD.nuclide_grid[i].energy = LCG_random_double(&seed); SD.nuclide_grid[i].total_xs = LCG_random_double(&seed); SD.nuclide_grid[i].elastic_xs = LCG_random_double(&seed); SD.nuclide_grid[i].absorbtion_xs = LCG_random_double(&seed); SD.nuclide_grid[i].fission_xs = LCG_random_double(&seed); SD.nuclide_grid[i].nu_fission_xs = LCG_random_double(&seed); } // Sort so that each nuclide has data stored in ascending energy order. for( int i = 0; i < in.n_isotopes; i++ ) qsort( &SD.nuclide_grid[i*in.n_gridpoints], in.n_gridpoints, sizeof(NuclideGridPoint), NGP_compare); // error debug check /* for( int i = 0; i < in.n_isotopes; i++ ) { printf("NUCLIDE %d ==============================\n", i); for( int j = 0; j < in.n_gridpoints; j++ ) printf("E%d = %lf\n", j, SD.nuclide_grid[i * in.n_gridpoints + j].energy); } */ //////////////////////////////////////////////////////////////////// // Initialize Acceleration Structure //////////////////////////////////////////////////////////////////// if( in.grid_type == NUCLIDE ) { SD.length_unionized_energy_array = 0; SD.length_index_grid = 0; } if( in.grid_type == UNIONIZED ) { if(mype == 0) printf("Intializing unionized grid...\n"); // Allocate space to hold the union of all nuclide energy data SD.length_unionized_energy_array = in.n_isotopes * in.n_gridpoints; SD.unionized_energy_array = (double *) malloc( SD.length_unionized_energy_array * sizeof(double)); assert(SD.unionized_energy_array != NULL ); nbytes += SD.length_unionized_energy_array * sizeof(double); // Copy energy data over from the nuclide energy grid for( int i = 0; i < SD.length_unionized_energy_array; i++ ) SD.unionized_energy_array[i] = SD.nuclide_grid[i].energy; // Sort unionized energy array qsort( SD.unionized_energy_array, SD.length_unionized_energy_array, sizeof(double), double_compare); // Allocate space to hold the acceleration grid indices SD.length_index_grid = SD.length_unionized_energy_array * in.n_isotopes; SD.index_grid = (int *) malloc( SD.length_index_grid * sizeof(int)); assert(SD.index_grid != NULL); nbytes += SD.length_index_grid * sizeof(int); // Generates the double indexing grid int * idx_low = (int *) calloc( in.n_isotopes, sizeof(int)); assert(idx_low != NULL ); double * energy_high = (double *) malloc( in.n_isotopes * sizeof(double)); assert(energy_high != NULL ); for( int i = 0; i < in.n_isotopes; i++ ) energy_high[i] = SD.nuclide_grid[i * in.n_gridpoints + 1].energy; for( long e = 0; e < SD.length_unionized_energy_array; e++ ) { double unionized_energy = SD.unionized_energy_array[e]; for( long i = 0; i < in.n_isotopes; i++ ) { if( unionized_energy < energy_high[i] ) SD.index_grid[e * in.n_isotopes + i] = idx_low[i]; else if( idx_low[i] == in.n_gridpoints - 2 ) SD.index_grid[e * in.n_isotopes + i] = idx_low[i]; else { idx_low[i]++; SD.index_grid[e * in.n_isotopes + i] = idx_low[i]; energy_high[i] = SD.nuclide_grid[i * in.n_gridpoints + idx_low[i] + 1].energy; } } } free(idx_low); free(energy_high); } if( in.grid_type == HASH ) { if(mype == 0) printf("Intializing hash grid...\n"); SD.length_unionized_energy_array = 0; SD.length_index_grid = in.hash_bins * in.n_isotopes; SD.index_grid = (int *) malloc( SD.length_index_grid * sizeof(int)); assert(SD.index_grid != NULL); nbytes += SD.length_index_grid * sizeof(int); double du = 1.0 / in.hash_bins; // For each energy level in the hash table #pragma omp parallel for for( long e = 0; e < in.hash_bins; e++ ) { double energy = e * du; // We need to determine the bounding energy levels for all isotopes for( long i = 0; i < in.n_isotopes; i++ ) { SD.index_grid[e * in.n_isotopes + i] = grid_search_nuclide( in.n_gridpoints, energy, SD.nuclide_grid + i * in.n_gridpoints, 0, in.n_gridpoints-1); } } } //////////////////////////////////////////////////////////////////// // Initialize Materials and Concentrations //////////////////////////////////////////////////////////////////// if(mype == 0) printf("Intializing material data...\n"); // Set the number of nuclides in each material SD.num_nucs = load_num_nucs(in.n_isotopes); SD.length_num_nucs = 12; // There are always 12 materials in XSBench // Intialize the flattened 2D grid of material data. The grid holds // a list of nuclide indices for each of the 12 material types. The // grid is allocated as a full square grid, even though not all // materials have the same number of nuclides. SD.mats = load_mats(SD.num_nucs, in.n_isotopes, &SD.max_num_nucs); SD.length_mats = SD.length_num_nucs * SD.max_num_nucs; // Intialize the flattened 2D grid of nuclide concentration data. The grid holds // a list of nuclide concentrations for each of the 12 material types. The // grid is allocated as a full square grid, even though not all // materials have the same number of nuclides. SD.concs = load_concs(SD.num_nucs, SD.max_num_nucs); SD.length_concs = SD.length_mats; // Allocate and initialize replicas #ifdef AML // num_nucs aml_replicaset_hwloc_create(&(SD.num_nucs_replica), SD.length_num_nucs * sizeof(*(SD.num_nucs)), HWLOC_OBJ_CORE, HWLOC_DISTANCES_KIND_FROM_OS | HWLOC_DISTANCES_KIND_MEANS_LATENCY); nbytes += (SD.num_nucs_replica)->n * (SD.num_nucs_replica)->size; aml_replicaset_init(SD.num_nucs_replica, SD.num_nucs); // concs aml_replicaset_hwloc_create(&(SD.concs_replica), SD.length_concs * sizeof(*(SD.concs)), HWLOC_OBJ_CORE, HWLOC_DISTANCES_KIND_FROM_OS | HWLOC_DISTANCES_KIND_MEANS_LATENCY); nbytes += (SD.concs_replica)->n * (SD.concs_replica)->size; aml_replicaset_init(SD.concs_replica, SD.concs); // unionized_energy_array if( in.grid_type == UNIONIZED ){ aml_replicaset_hwloc_create(&(SD.unionized_energy_array_replica), SD.length_unionized_energy_array * sizeof(*(SD.unionized_energy_array)), HWLOC_OBJ_CORE, HWLOC_DISTANCES_KIND_FROM_OS | HWLOC_DISTANCES_KIND_MEANS_LATENCY); nbytes += (SD.unionized_energy_array_replica)->n * (SD.unionized_energy_array_replica)->size; aml_replicaset_init(SD.unionized_energy_array_replica, SD.unionized_energy_array); } // index grid if( in.grid_type == UNIONIZED || in.grid_type == HASH ){ aml_replicaset_hwloc_create(&(SD.index_grid_replica), SD.length_index_grid * sizeof(*(SD.index_grid)), HWLOC_OBJ_CORE, HWLOC_DISTANCES_KIND_FROM_OS | HWLOC_DISTANCES_KIND_MEANS_LATENCY); nbytes += (SD.index_grid_replica)->n * (SD.index_grid_replica)->size; aml_replicaset_init(SD.index_grid_replica, SD.index_grid); } // nuclide grid aml_replicaset_hwloc_create(&(SD.nuclide_grid_replica), SD.length_nuclide_grid * sizeof(*(SD.nuclide_grid)), HWLOC_OBJ_CORE, HWLOC_DISTANCES_KIND_FROM_OS | HWLOC_DISTANCES_KIND_MEANS_LATENCY); nbytes += (SD.nuclide_grid_replica)->n * (SD.nuclide_grid_replica)->size; aml_replicaset_init(SD.nuclide_grid_replica, SD.nuclide_grid); #endif if(mype == 0) printf("Intialization complete. Allocated %.0lf MB of data.\n", nbytes/1024.0/1024.0 ); return SD; }