source
stringlengths
3
92
c
stringlengths
26
2.25M
boxloop_cuda.h
/****************************************************************************** * 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) ******************************************************************************/ /****************************************************************************** * * Header info for the BoxLoop * *****************************************************************************/ /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #ifndef HYPRE_BOXLOOP_CUDA_HEADER #define HYPRE_BOXLOOP_CUDA_HEADER #define HYPRE_LAMBDA [=] __host__ __device__ /* TODO: RL: support 4-D */ typedef struct hypre_Boxloop_struct { HYPRE_Int lsize0, lsize1, lsize2; HYPRE_Int strides0, strides1, strides2; HYPRE_Int bstart0, bstart1, bstart2; HYPRE_Int bsize0, bsize1, bsize2; } hypre_Boxloop; #ifdef __cplusplus extern "C++" { #endif /* ------------------------- * parfor-loop * ------------------------*/ template <typename LOOP_BODY> __global__ void forall_kernel( LOOP_BODY loop_body, HYPRE_Int length ) { const HYPRE_Int idx = hypre_cuda_get_grid_thread_id<1,1>(); /* const HYPRE_Int number_threads = hypre_cuda_get_grid_num_threads<1,1>(); */ if (idx < length) { loop_body(idx); } } template<typename LOOP_BODY> void BoxLoopforall( HYPRE_Int length, LOOP_BODY loop_body ) { HYPRE_ExecutionPolicy exec_policy = hypre_HandleStructExecPolicy(hypre_handle()); if (exec_policy == HYPRE_EXEC_HOST) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (HYPRE_Int idx = 0; idx < length; idx++) { loop_body(idx); } } else if (exec_policy == HYPRE_EXEC_DEVICE) { const dim3 bDim = hypre_GetDefaultCUDABlockDimension(); const dim3 gDim = hypre_GetDefaultCUDAGridDimension(length, "thread", bDim); HYPRE_CUDA_LAUNCH( forall_kernel, gDim, bDim, loop_body, length ); } } /* ------------------------------ * parforreduction-loop * -----------------------------*/ template <typename LOOP_BODY, typename REDUCER> __global__ void reductionforall_kernel( HYPRE_Int length, REDUCER reducer, LOOP_BODY loop_body ) { const HYPRE_Int thread_id = hypre_cuda_get_grid_thread_id<1,1>(); const HYPRE_Int n_threads = hypre_cuda_get_grid_num_threads<1,1>(); for (HYPRE_Int idx = thread_id; idx < length; idx += n_threads) { loop_body(idx, reducer); } /* reduction in block-level and the save the results in reducer */ reducer.BlockReduce(); } template<typename LOOP_BODY, typename REDUCER> void ReductionBoxLoopforall( HYPRE_Int length, REDUCER &reducer, LOOP_BODY loop_body ) { if (length <= 0) { return; } HYPRE_ExecutionPolicy exec_policy = hypre_HandleStructExecPolicy(hypre_handle()); if (exec_policy == HYPRE_EXEC_HOST) { for (HYPRE_Int idx = 0; idx < length; idx++) { loop_body(idx, reducer); } } else if (exec_policy == HYPRE_EXEC_DEVICE) { const dim3 bDim = hypre_GetDefaultCUDABlockDimension(); dim3 gDim = hypre_GetDefaultCUDAGridDimension(length, "thread", bDim); /* Note: we assume gDim cannot exceed 1024 * and bDim < WARP * WARP */ gDim.x = hypre_min(gDim.x, 1024); reducer.nblocks = gDim.x; /* hypre_printf("length= %d, blocksize = %d, gridsize = %d\n", length, bDim.x, gDim.x); */ HYPRE_CUDA_LAUNCH( reductionforall_kernel, gDim, bDim, length, reducer, loop_body ); } } #ifdef __cplusplus } #endif /* Get 1-D length of the loop, in hypre__tot */ #define hypre_newBoxLoopInit(ndim, loop_size) \ HYPRE_Int hypre__tot = 1; \ for (HYPRE_Int hypre_d = 0; hypre_d < ndim; hypre_d ++) \ { \ hypre__tot *= loop_size[hypre_d]; \ } /* Initialize struct for box-k */ #define hypre_BoxLoopDataDeclareK(k, ndim, loop_size, dbox, start, stride) \ hypre_Boxloop databox##k; \ /* dim 0 */ \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = start[0] - dbox->imin[0]; \ databox##k.bsize0 = dbox->imax[0] - dbox->imin[0]; \ /* dim 1 */ \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = start[1] - dbox->imin[1]; \ databox##k.bsize1 = dbox->imax[1] - dbox->imin[1]; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ /* dim 2 */ \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = start[2] - dbox->imin[2]; \ databox##k.bsize2 = dbox->imax[2] - dbox->imin[2]; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define zypre_BasicBoxLoopDataDeclareK(k,ndim,loop_size,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = 0; \ databox##k.bsize0 = 0; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } /* RL: TODO loop_size out of box struct, bsize +1 */ /* Given input 1-D 'idx' in box, get 3-D 'local_idx' in loop_size */ #define hypre_newBoxLoopDeclare(box) \ hypre_Index local_idx; \ HYPRE_Int idx_local = idx; \ hypre_IndexD(local_idx, 0) = idx_local % box.lsize0; \ idx_local = idx_local / box.lsize0; \ hypre_IndexD(local_idx, 1) = idx_local % box.lsize1; \ idx_local = idx_local / box.lsize1; \ hypre_IndexD(local_idx, 2) = idx_local % box.lsize2; \ /* Given input 3-D 'local_idx', get 1-D 'hypre__i' in 'box' */ #define hypre_BoxLoopIncK(k, box, hypre__i) \ HYPRE_Int hypre_boxD##k = 1; \ HYPRE_Int hypre__i = 0; \ hypre__i += (hypre_IndexD(local_idx, 0) * box.strides0 + box.bstart0) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize0 + 1); \ hypre__i += (hypre_IndexD(local_idx, 1) * box.strides1 + box.bstart1) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize1 + 1); \ hypre__i += (hypre_IndexD(local_idx, 2) * box.strides2 + box.bstart2) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize2 + 1); /* get 3-D local_idx into 'index' */ #define hypre_BoxLoopGetIndex(index) \ index[0] = hypre_IndexD(local_idx, 0); \ index[1] = hypre_IndexD(local_idx, 1); \ index[2] = hypre_IndexD(local_idx, 2); /* BoxLoop 0 */ #define hypre_newBoxLoop0Begin(ndim, loop_size) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ BoxLoopforall(hypre__tot, HYPRE_LAMBDA (HYPRE_Int idx) \ { #define hypre_newBoxLoop0End() \ }); \ } /* BoxLoop 1 */ #define hypre_newBoxLoop1Begin(ndim, loop_size, dbox1, start1, stride1, i1) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ hypre_BoxLoopDataDeclareK(1, ndim, loop_size, dbox1, start1, stride1); \ BoxLoopforall(hypre__tot, HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); #define hypre_newBoxLoop1End(i1) \ }); \ } /* BoxLoop 2 */ #define hypre_newBoxLoop2Begin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ hypre_BoxLoopDataDeclareK(1, ndim, loop_size, dbox1, start1, stride1); \ hypre_BoxLoopDataDeclareK(2, ndim, loop_size, dbox2, start2, stride2); \ BoxLoopforall(hypre__tot, HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); \ hypre_BoxLoopIncK(2, databox2, i2); #define hypre_newBoxLoop2End(i1, i2) \ }); \ } /* BoxLoop 3 */ #define hypre_newBoxLoop3Begin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ hypre_BoxLoopDataDeclareK(1, ndim,loop_size, dbox1, start1, stride1); \ hypre_BoxLoopDataDeclareK(2, ndim,loop_size, dbox2, start2, stride2); \ hypre_BoxLoopDataDeclareK(3, ndim,loop_size, dbox3, start3, stride3); \ BoxLoopforall(hypre__tot, HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); \ hypre_BoxLoopIncK(2, databox2, i2); \ hypre_BoxLoopIncK(3, databox3, i3); #define hypre_newBoxLoop3End(i1, i2, i3) \ }); \ } /* BoxLoop 4 */ #define hypre_newBoxLoop4Begin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3, \ dbox4, start4, stride4, i4) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ hypre_BoxLoopDataDeclareK(1, ndim, loop_size, dbox1, start1, stride1); \ hypre_BoxLoopDataDeclareK(2, ndim, loop_size, dbox2, start2, stride2); \ hypre_BoxLoopDataDeclareK(3, ndim, loop_size, dbox3, start3, stride3); \ hypre_BoxLoopDataDeclareK(4, ndim, loop_size, dbox4, start4, stride4); \ BoxLoopforall(hypre__tot, HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); \ hypre_BoxLoopIncK(2, databox2, i2); \ hypre_BoxLoopIncK(3, databox3, i3); \ hypre_BoxLoopIncK(4, databox4, i4); #define hypre_newBoxLoop4End(i1, i2, i3, i4) \ }); \ } /* Basic BoxLoops have no boxes */ /* BoxLoop 1 */ #define zypre_newBasicBoxLoop1Begin(ndim, loop_size, stride1, i1) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ zypre_BasicBoxLoopDataDeclareK(1, ndim, loop_size, stride1); \ BoxLoopforall(hypre__tot, HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); /* BoxLoop 2 */ #define zypre_newBasicBoxLoop2Begin(ndim, loop_size, stride1, i1, stride2, i2) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ zypre_BasicBoxLoopDataDeclareK(1, ndim, loop_size, stride1); \ zypre_BasicBoxLoopDataDeclareK(2, ndim, loop_size, stride2); \ BoxLoopforall(hypre__tot, HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); \ hypre_BoxLoopIncK(2, databox2, i2); \ /* TODO: RL just parallel-for, it should not be here, better in utilities */ #define hypre_LoopBegin(size, idx) \ { \ BoxLoopforall(size, HYPRE_LAMBDA (HYPRE_Int idx) \ { #define hypre_LoopEnd() \ }); \ } /* Reduction BoxLoop1 */ #define hypre_BoxLoop1ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, reducesum) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ hypre_BoxLoopDataDeclareK(1, ndim, loop_size, dbox1, start1, stride1); \ ReductionBoxLoopforall(hypre__tot, reducesum, HYPRE_LAMBDA (HYPRE_Int idx, decltype(reducesum) &reducesum) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); #define hypre_BoxLoop1ReductionEnd(i1, reducesum) \ }); \ } /* Reduction BoxLoop2 */ #define hypre_BoxLoop2ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, reducesum) \ { \ hypre_newBoxLoopInit(ndim, loop_size); \ hypre_BoxLoopDataDeclareK(1, ndim, loop_size, dbox1, start1, stride1); \ hypre_BoxLoopDataDeclareK(2, ndim, loop_size, dbox2, start2, stride2); \ ReductionBoxLoopforall(hypre__tot, reducesum, HYPRE_LAMBDA (HYPRE_Int idx, decltype(reducesum) &reducesum) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1, databox1, i1); \ hypre_BoxLoopIncK(2, databox2, i2); #define hypre_BoxLoop2ReductionEnd(i1, i2, reducesum) \ }); \ } /* Renamings */ #define hypre_BoxLoopBlock() 0 #define hypre_BoxLoop0Begin hypre_newBoxLoop0Begin #define hypre_BoxLoop0For hypre_newBoxLoop0For #define hypre_BoxLoop0End hypre_newBoxLoop0End #define hypre_BoxLoop1Begin hypre_newBoxLoop1Begin #define hypre_BoxLoop1For hypre_newBoxLoop1For #define hypre_BoxLoop1End hypre_newBoxLoop1End #define hypre_BoxLoop2Begin hypre_newBoxLoop2Begin #define hypre_BoxLoop2For hypre_newBoxLoop2For #define hypre_BoxLoop2End hypre_newBoxLoop2End #define hypre_BoxLoop3Begin hypre_newBoxLoop3Begin #define hypre_BoxLoop3For hypre_newBoxLoop3For #define hypre_BoxLoop3End hypre_newBoxLoop3End #define hypre_BoxLoop4Begin hypre_newBoxLoop4Begin #define hypre_BoxLoop4For hypre_newBoxLoop4For #define hypre_BoxLoop4End hypre_newBoxLoop4End #define hypre_BasicBoxLoop1Begin zypre_newBasicBoxLoop1Begin #define hypre_BasicBoxLoop2Begin zypre_newBasicBoxLoop2Begin #endif /* #ifndef HYPRE_BOXLOOP_CUDA_HEADER */
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] = 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<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; }
SwathFileConsumer.h
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <boost/cast.hpp> // Datastructures #include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> // Consumers #include <OpenMS/FORMAT/DATAACCESS/MSDataCachedConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h> // Helpers #include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h> #include <OpenMS/KERNEL/StandardTypes.h> #ifdef _OPENMP #include <omp.h> #endif namespace OpenMS { /** * @brief Abstract base class which can consume spectra coming from SWATH experiment stored in a single file. * * The class consumes spectra which are coming from a complete SWATH * experiment. It will group MS2 spectra by their precursor m/z, assuming * that they correspond to the same SWATH window. For example, the spectra * could be arranged in the following fashion: * * - MS1 Spectrum (no precursor) * - MS2 Spectrum (precursor = [400,425]) * - MS2 Spectrum (precursor = [425,450]) * - [...] * - MS2 Spectrum (precursor = [1175,1200]) * - MS1 Spectrum (no precursor) * - MS2 Spectrum (precursor = [400,425]) * - MS2 Spectrum (precursor = [425,450]) * - [...] * * Base classes are expected to implement functions consuming a spectrum coming * from a specific SWATH or an MS1 spectrum and a final function * ensureMapsAreFilled_ after which the swath_maps_ vector needs to contain * valid pointers to MSExperiment. * * In addition it is possible to provide the swath boundaries and the read in * spectra will be matched by their precursor m/z to the "center" attribute * of the provided Swath maps. * * Usage: * * @code * FullSwathFileConsumer * dataConsumer; * // assign dataConsumer to an implementation of FullSwathFileConsumer * MzMLFile().transform(file, dataConsumer); * dataConsumer->retrieveSwathMaps(maps); * @endcode * */ class OPENMS_DLLAPI FullSwathFileConsumer : public Interfaces::IMSDataConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; FullSwathFileConsumer() : ms1_map_(), // initialize to null consuming_possible_(true), use_external_boundaries_(false), correct_window_counter_(0) { use_external_boundaries_ = !swath_map_boundaries_.empty(); } /** * @brief Constructor * * @param swath_boundaries A vector of SwathMaps of which only the center, * lower and upper attributes will be used to infer the expected Swath maps. * */ FullSwathFileConsumer(std::vector<OpenSwath::SwathMap> swath_boundaries) : swath_map_boundaries_(swath_boundaries), ms1_map_(), // initialize to null consuming_possible_(true), use_external_boundaries_(false), correct_window_counter_(0) { use_external_boundaries_ = !swath_map_boundaries_.empty(); } ~FullSwathFileConsumer() override {} void setExpectedSize(Size, Size) override {} void setExperimentalSettings(const ExperimentalSettings& exp) override {settings_ = exp; } /** * @brief Populate the vector of swath maps after consuming all spectra. * * Will populate the input vector with SwathMap objects which correspond to * the MS1 map (if present) and the MS2 maps (SWATH maps). This should be * called after all spectra are consumed. * * @note It is not possible to consume any more spectra after calling this * function (it contains finalization code and may close file streams). * */ void retrieveSwathMaps(std::vector<OpenSwath::SwathMap>& maps) { consuming_possible_ = false; // make consumption of further spectra / chromatograms impossible ensureMapsAreFilled_(); if (ms1_map_) { OpenSwath::SwathMap map; map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(ms1_map_); map.lower = -1; map.upper = -1; map.center = -1; map.ms1 = true; maps.push_back(map); } // Print warning if the lower/upper window could not be determined and we // required manual determination of the boundaries. if (!use_external_boundaries_ && correct_window_counter_ != swath_maps_.size()) { std::cout << "WARNING: Could not correctly read the upper/lower limits of the SWATH windows from your input file. Read " << correct_window_counter_ << " correct (non-zero) window limits (expected " << swath_maps_.size() << " windows)." << std::endl; } size_t nonempty_maps = 0; for (Size i = 0; i < swath_maps_.size(); i++) { OpenSwath::SwathMap map; map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_maps_[i]); map.lower = swath_map_boundaries_[i].lower; map.upper = swath_map_boundaries_[i].upper; map.center = swath_map_boundaries_[i].center; map.ms1 = false; maps.push_back(map); if (map.sptr->getNrSpectra() > 0) {nonempty_maps++;} } if (nonempty_maps != swath_map_boundaries_.size()) { std::cout << "WARNING: The number nonempty maps found in the input file (" << nonempty_maps << ") is not equal to the number of provided swath window boundaries (" << swath_map_boundaries_.size() << "). Please check your input." << std::endl; } } /// Consume a chromatogram -> should not happen when dealing with SWATH maps void consumeChromatogram(MapType::ChromatogramType&) override { std::cerr << "Read chromatogram while reading SWATH files, did not expect that!" << std::endl; } /** * @brief * Consume a spectrum which may belong either to an MS1 scan or * one of n MS2 (SWATH) scans * */ void consumeSpectrum(MapType::SpectrumType& s) override { if (!consuming_possible_) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "FullSwathFileConsumer cannot consume any more spectra after retrieveSwathMaps has been called already"); } if (s.getMSLevel() == 1) { consumeMS1Spectrum_(s); } else { if (s.getPrecursors().empty()) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Swath scan does not provide a precursor."); } const std::vector<Precursor> prec = s.getPrecursors(); double center = prec[0].getMZ(); double lower = prec[0].getMZ() - prec[0].getIsolationWindowLowerOffset(); double upper = prec[0].getMZ() + prec[0].getIsolationWindowUpperOffset(); bool found = false; // Check if enough information is present to infer the swath if (center <= 0.0) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Swath scan does not provide any precursor isolation information."); } // try to match the current scan to one of the already known windows for (Size i = 0; i < swath_map_boundaries_.size(); i++) { // We group by the precursor mz (center of the window) since this // should be present in all SWATH scans. if (std::fabs(center - swath_map_boundaries_[i].center) < 1e-6) { found = true; consumeSwathSpectrum_(s, i); break; } } if (!found) { if (use_external_boundaries_) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Encountered SWATH scan with boundary ") + center + " m/z which was not present in the provided windows."); } else { consumeSwathSpectrum_(s, swath_map_boundaries_.size()); // we found a new SWATH window if (lower > 0.0 && upper > 0.0) {correct_window_counter_++;} OpenSwath::SwathMap boundary; boundary.lower = lower; boundary.upper = upper; boundary.center = center; swath_map_boundaries_.push_back(boundary); OPENMS_LOG_DEBUG << "Adding Swath centered at " << center << " m/z with an isolation window of " << lower << " to " << upper << " m/z." << std::endl; } } } } protected: /** * @brief Consume an MS2 spectrum belonging to SWATH "swath_nr" * * This function should handle a spectrum belonging to a specific SWATH * (indicated by swath_nr). * */ virtual void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) = 0; /** * @brief Consume an MS1 spectrum * * This function should handle an MS1 spectrum. * */ virtual void consumeMS1Spectrum_(MapType::SpectrumType& s) = 0; /** * @brief Callback function after the reading is complete * * Has to ensure that swath_maps_ and ms1_map_ are correctly populated. */ virtual void ensureMapsAreFilled_() = 0; /// A list of Swath map identifiers (lower/upper boundary and center) std::vector<OpenSwath::SwathMap> swath_map_boundaries_; /// A list of SWATH maps and the MS1 map std::vector<boost::shared_ptr<PeakMap > > swath_maps_; boost::shared_ptr<PeakMap > ms1_map_; /// The Experimental settings // (MSExperiment has no constructor using ExperimentalSettings) PeakMap settings_; /// Whether further spectra can still be consumed bool consuming_possible_; /// Whether to use external input for SWATH boundaries bool use_external_boundaries_; /// How many windows were correctly annotated (non-zero window limits) size_t correct_window_counter_; }; /** * @brief In-memory implementation of FullSwathFileConsumer * * Keeps all the spectra in memory by just appending them to an MSExperiment. * */ class OPENMS_DLLAPI RegularSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; RegularSwathFileConsumer() {} RegularSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries) : FullSwathFileConsumer(known_window_boundaries) {} protected: void addNewSwathMap_() { boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); swath_maps_.push_back(exp); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { while (swath_maps_.size() <= swath_nr) { addNewSwathMap_(); } swath_maps_[swath_nr]->addSpectrum(s); } void addMS1Map_() { boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); ms1_map_ = exp; } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (!ms1_map_) { addMS1Map_(); } ms1_map_->addSpectrum(s); } void ensureMapsAreFilled_() override {} }; /** * @brief On-disk cached implementation of FullSwathFileConsumer * * Writes all spectra immediately to disk in a user-specified caching * location using the MSDataCachedConsumer. Internally, it handles * n+1 (n SWATH + 1 MS1 map) objects of MSDataCachedConsumer which can consume the * spectra and write them to disk immediately. * */ class OPENMS_DLLAPI CachedSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; CachedSwathFileConsumer(String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) : ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} CachedSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries, String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) : FullSwathFileConsumer(known_window_boundaries), ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} ~CachedSwathFileConsumer() override { // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } } protected: void addNewSwathMap_() { String meta_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML"; String cached_file = meta_file + ".cached"; MSDataCachedConsumer* consumer = new MSDataCachedConsumer(cached_file, true); consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0); swath_consumers_.push_back(consumer); // maps for meta data boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); swath_maps_.push_back(exp); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { while (swath_maps_.size() <= swath_nr) { addNewSwathMap_(); } swath_consumers_[swath_nr]->consumeSpectrum(s); // write data to cached file; clear data from spectrum s swath_maps_[swath_nr]->addSpectrum(s); // append for the metadata (actual data was deleted) } void addMS1Map_() { String meta_file = cachedir_ + basename_ + "_ms1.mzML"; String cached_file = meta_file + ".cached"; ms1_consumer_ = new MSDataCachedConsumer(cached_file, true); ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0); boost::shared_ptr<PeakMap > exp(new PeakMap(settings_)); ms1_map_ = exp; } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (ms1_consumer_ == nullptr) { addMS1Map_(); } ms1_consumer_->consumeSpectrum(s); ms1_map_->addSpectrum(s); // append for the metadata (actual data is deleted) } void ensureMapsAreFilled_() override { size_t swath_consumers_size = swath_consumers_.size(); bool have_ms1 = (ms1_consumer_ != nullptr); // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream // The file streams to the cached data on disc can and should be closed // here safely. Since ensureMapsAreFilled_ is called after consuming all // the spectra, there will be no more spectra to append but the client // might already want to read after this call, so all data needs to be // present on disc and the file streams closed. // // TODO merge with destructor code into own function! while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } if (have_ms1) { boost::shared_ptr<PeakMap > exp(new PeakMap); String meta_file = cachedir_ + basename_ + "_ms1.mzML"; // write metadata to disk and store the correct data processing tag Internal::CachedMzMLHandler().writeMetadata(*ms1_map_, meta_file, true); MzMLFile().load(meta_file, *exp.get()); ms1_map_ = exp; } #ifdef _OPENMP #pragma omp parallel for #endif for (SignedSize i = 0; i < boost::numeric_cast<SignedSize>(swath_consumers_size); i++) { boost::shared_ptr<PeakMap > exp(new PeakMap); String meta_file = cachedir_ + basename_ + "_" + String(i) + ".mzML"; // write metadata to disk and store the correct data processing tag Internal::CachedMzMLHandler().writeMetadata(*swath_maps_[i], meta_file, true); MzMLFile().load(meta_file, *exp.get()); swath_maps_[i] = exp; } } MSDataCachedConsumer* ms1_consumer_; std::vector<MSDataCachedConsumer*> swath_consumers_; String cachedir_; String basename_; int nr_ms1_spectra_; std::vector<int> nr_ms2_spectra_; }; /** * @brief On-disk mzML implementation of FullSwathFileConsumer * * Writes all spectra immediately to disk to an mzML file location using the * PlainMSDataWritingConsumer. Internally, it handles n+1 (n SWATH + 1 MS1 * map) objects of MSDataCachedConsumer which can consume the spectra and * write them to disk immediately. * * Warning: no swathmaps (MS1 nor MS2) will be available when calling retrieveSwathMaps() * for downstream use. * */ class OPENMS_DLLAPI MzMLSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; MzMLSwathFileConsumer(const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) : ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} MzMLSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries, const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) : FullSwathFileConsumer(known_window_boundaries), ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} ~MzMLSwathFileConsumer() override { deleteSetNull_(); } protected: void deleteSetNull_() { // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } } void addNewSwathMap_() { String mzml_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML"; PlainMSDataWritingConsumer* consumer = new PlainMSDataWritingConsumer(mzml_file); consumer->getOptions().setCompression(true); consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0); swath_consumers_.push_back(consumer); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { // only use swath_consumers_ to count how many we have already added while (swath_consumers_.size() <= swath_nr) { addNewSwathMap_(); } swath_consumers_[swath_nr]->consumeSpectrum(s); s.clear(false); } void addMS1Map_() { String mzml_file = cachedir_ + basename_ + "_ms1.mzML"; ms1_consumer_ = new PlainMSDataWritingConsumer(mzml_file); ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0); ms1_consumer_->getOptions().setCompression(true); } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (ms1_consumer_ == nullptr) { addMS1Map_(); } ms1_consumer_->consumeSpectrum(s); } void ensureMapsAreFilled_() override { deleteSetNull_(); } PlainMSDataWritingConsumer* ms1_consumer_; std::vector<PlainMSDataWritingConsumer*> swath_consumers_; String cachedir_; String basename_; int nr_ms1_spectra_; std::vector<int> nr_ms2_spectra_; }; }
2048-ai.c
#if defined(__linux__) || defined(linux) || defined(__unix__) || defined(unix) || defined(__CYGWIN__) || defined(__MACH__) #define UNIX_LIKE 1 #endif #if defined(__MSDOS__) || defined(_MSDOS) || defined(__DOS__) #ifndef MSDOS #define MSDOS 1 #endif #endif #if defined(_M_I86) #define FASTMODE 0 #define __16BIT__ 1 #endif #if !defined(FASTMODE) || (defined(FASTMODE) && FASTMODE != 0) #define FASTMODE 1 #endif typedef unsigned short row_t; #ifdef __16BIT__ typedef unsigned long score_t; #else typedef unsigned int score_t; #endif #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__WATCOMC__) typedef unsigned __int64 board_t; #define W64LIT(x) x##ui64 #else typedef unsigned long long board_t; #define W64LIT(x) x##ULL #endif typedef float score_heur_t; #if defined(__TINYC__) #define NOT_USE_WIN32_SDK 1 #endif #if defined(_WIN32) && !defined(NOT_USE_WIN32_SDK) #define WIN32_LEAN_AND_MEAN #include <windows.h> #elif defined(__WATCOMC__) #include <graph.h> #elif defined(__BORLANDC__) || defined (__TURBOC__) || defined(__DJGPP__) #include <conio.h> #endif static const board_t ROW_MASK = W64LIT(0xFFFF); static const board_t COL_MASK = W64LIT(0x000F000F000F000F); enum { UP = 0, DOWN, LEFT, RIGHT, }; #if defined(OPENMP_THREAD) #include <omp.h> #endif typedef int (*get_move_func_t)(board_t); #if defined(_MSC_VER) && _MSC_VER >= 1500 && defined(POPCNT) #include <intrin.h> #define __builtin_popcount __popcnt #define __POPCNT__ 1 #endif #if defined(__MINGW64__) || defined(__MINGW32__) #undef __USE_MINGW_ANSI_STDIO #define __USE_MINGW_ANSI_STDIO 0 #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #define _max(a,b) ( ((a)>(b)) ? (a):(b) ) #define _min(a,b) ( ((a)>(b)) ? (b):(a) ) static void clear_screen(void) { #if defined(_WIN32) && !defined(NOT_USE_WIN32_SDK) HANDLE hStdOut; DWORD count; DWORD cellCount; COORD homeCoords = { 0, 0 }; static CONSOLE_SCREEN_BUFFER_INFO csbi; static int full_clear = 1; hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (hStdOut == INVALID_HANDLE_VALUE) return; if (full_clear == 1) { if (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return; cellCount = csbi.dwSize.X * csbi.dwSize.Y; if (cellCount >= 8192) full_clear = 0; } else { cellCount = 8192; } if (!FillConsoleOutputCharacter(hStdOut, (TCHAR)' ', cellCount, homeCoords, &count)) return; if (full_clear && !FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, cellCount, homeCoords, &count)) return; SetConsoleCursorPosition(hStdOut, homeCoords); #elif defined(UNIX_LIKE) printf("\033[2J\033[H"); #elif defined(__WATCOMC__) _clearscreen(_GCLEARSCREEN); #elif defined(__BORLANDC__) || defined (__TURBOC__) || defined(__DJGPP__) clrscr(); #elif (defined(_WIN32) && defined(NOT_USE_WIN32_SDK)) || defined(MSDOS) system("cls"); #endif } const score_heur_t SCORE_LOST_PENALTY = 200000.0f; const score_heur_t SCORE_MONOTONICITY_POWER = 4.0f; const score_heur_t SCORE_MONOTONICITY_WEIGHT = 47.0f; const score_heur_t SCORE_SUM_POWER = 3.5f; const score_heur_t SCORE_SUM_WEIGHT = 11.0f; const score_heur_t SCORE_MERGES_WEIGHT = 700.0f; const score_heur_t SCORE_EMPTY_WEIGHT = 270.0f; const score_heur_t CPROB_THRESH_BASE = 0.0001f; typedef struct { int maxdepth; int curdepth; long nomoves; long tablehits; long cachehits; long moves_evaled; int depth_limit; } eval_state; #if FASTMODE != 0 #define TABLESIZE 65536 row_t *row_left_table; row_t *row_right_table; score_t *score_table; score_heur_t *score_heur_table; #else #define TABLESIZE 8192 row_t *row_table[8]; score_heur_t *score_heur_table[8]; #endif static unsigned int unif_random(unsigned int n) { static unsigned int seeded = 0; if (!seeded) { srand((unsigned int)time(NULL)); seeded = 1; } return rand() % n; } static board_t unpack_col(row_t row) { board_t tmp = row; return (tmp | (tmp << 12) | (tmp << 24) | (tmp << 36)) & COL_MASK; } static row_t reverse_row(row_t row) { return (row >> 12) | ((row >> 4) & 0x00F0) | ((row << 4) & 0x0F00) | (row << 12); } static void print_board(board_t board) { int i = 0, j = 0; printf("-----------------------------\n"); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { unsigned int power_val = (unsigned int)(board & 0xf); if (power_val == 0) { printf("|%6c", ' '); } else { printf("|%6u", 1 << power_val); } board >>= 4; } printf("|\n"); } printf("-----------------------------\n"); } static board_t transpose(board_t x) { board_t a1 = x & W64LIT(0xF0F00F0FF0F00F0F); board_t a2 = x & W64LIT(0x0000F0F00000F0F0); board_t a3 = x & W64LIT(0x0F0F00000F0F0000); board_t a = a1 | (a2 << 12) | (a3 >> 12); board_t b1 = a & W64LIT(0xFF00FF0000FF00FF); board_t b2 = a & W64LIT(0x00FF00FF00000000); board_t b3 = a & W64LIT(0x00000000FF00FF00); return b1 | (b2 >> 24) | (b3 << 24); } static int count_empty(board_t x) { x |= (x >> 2) & W64LIT(0x3333333333333333); x |= (x >> 1); x = ~x & W64LIT(0x1111111111111111); x += x >> 32; x += x >> 16; x += x >> 8; x += x >> 4; return (int)(x & 0xf); } static void init_tables(void) { row_t row = 0, result = 0; #if FASTMODE != 0 row_t rev_row = 0, rev_result = 0; #endif do { int i = 0, j = 0; row_t line[4] = { 0 }; score_t score = 0, rank = 0; score_heur_t sum = 0.0f; score_t empty = 0; score_t merges = 0; score_t prev = 0; score_t counter = 0; score_heur_t monotonicity_left = 0.0f; score_heur_t monotonicity_right = 0.0f; line[0] = row & 0xf; line[1] = (row >> 4) & 0xf; line[2] = (row >> 8) & 0xf; line[3] = (row >> 12) & 0xf; #if FASTMODE != 0 for (i = 0; i < 4; ++i) { rank = line[i]; if (rank >= 2) { score += (rank - 1) * (1 << rank); } } score_table[row] = score; #endif for (i = 0; i < 4; ++i) { score_t rank = line[i]; sum += (score_heur_t)pow((score_heur_t)rank, SCORE_SUM_POWER); if (rank == 0) { empty++; } else { if (prev == rank) { counter++; } else if (counter > 0) { merges += 1 + counter; counter = 0; } prev = rank; } } if (counter > 0) { merges += 1 + counter; } for (i = 1; i < 4; ++i) { if (line[i - 1] > line[i]) { monotonicity_left += (score_heur_t)(pow((score_heur_t)line[i - 1], SCORE_MONOTONICITY_POWER) - pow((score_heur_t)line[i], SCORE_MONOTONICITY_POWER)); } else { monotonicity_right += (score_heur_t)(pow((score_heur_t)line[i], SCORE_MONOTONICITY_POWER) - pow((score_heur_t)line[i - 1], SCORE_MONOTONICITY_POWER)); } } #if FASTMODE != 0 score_heur_table[row] = (score_heur_t)(SCORE_LOST_PENALTY + SCORE_EMPTY_WEIGHT * empty + SCORE_MERGES_WEIGHT * merges - SCORE_MONOTONICITY_WEIGHT * _min(monotonicity_left, monotonicity_right) - SCORE_SUM_WEIGHT * sum); #else score_heur_table[row / TABLESIZE][row % TABLESIZE] = (score_heur_t)(SCORE_LOST_PENALTY + SCORE_EMPTY_WEIGHT * empty + SCORE_MERGES_WEIGHT * merges - SCORE_MONOTONICITY_WEIGHT * _min(monotonicity_left, monotonicity_right) - SCORE_SUM_WEIGHT * sum); #endif for (i = 0; i < 3; ++i) { for (j = i + 1; j < 4; ++j) { if (line[j] != 0) break; } if (j == 4) break; if (line[i] == 0) { line[i] = line[j]; line[j] = 0; i--; } else if (line[i] == line[j]) { if (line[i] != 0xf) { line[i]++; } line[j] = 0; } } result = line[0] | (line[1] << 4) | (line[2] << 8) | (line[3] << 12); #if FASTMODE != 0 rev_row = reverse_row(row); rev_result = reverse_row(result); row_left_table[row] = row ^ result; row_right_table[rev_row] = rev_row ^ rev_result; #else row_table[row / TABLESIZE][row % TABLESIZE] = row ^ result; #endif } while (row++ != 0xFFFF); } #if FASTMODE != 0 static void alloc_tables(void) { row_left_table = (row_t *)malloc(sizeof(row_t) * TABLESIZE); row_right_table = (row_t *)malloc(sizeof(row_t) * TABLESIZE); score_table = (score_t *)malloc(sizeof(score_t) * TABLESIZE); score_heur_table = (score_heur_t *)malloc(sizeof(score_heur_t) * TABLESIZE); if (!row_left_table || !row_right_table || !score_table || !score_heur_table) { fprintf(stderr, "Not enough memory."); fflush(stderr); abort(); } } static void free_tables(void) { free(row_left_table); free(row_right_table); free(score_table); free(score_heur_table); } static board_t execute_move(board_t board, int move) { board_t ret = board; if (move == UP) { board = transpose(board); ret ^= unpack_col(row_left_table[board & ROW_MASK]); ret ^= unpack_col(row_left_table[(board >> 16) & ROW_MASK]) << 4; ret ^= unpack_col(row_left_table[(board >> 32) & ROW_MASK]) << 8; ret ^= unpack_col(row_left_table[(board >> 48) & ROW_MASK]) << 12; } else if (move == DOWN) { board = transpose(board); ret ^= unpack_col(row_right_table[board & ROW_MASK]); ret ^= unpack_col(row_right_table[(board >> 16) & ROW_MASK]) << 4; ret ^= unpack_col(row_right_table[(board >> 32) & ROW_MASK]) << 8; ret ^= unpack_col(row_right_table[(board >> 48) & ROW_MASK]) << 12; } else if (move == LEFT) { ret ^= (board_t)(row_left_table[board & ROW_MASK]); ret ^= (board_t)(row_left_table[(board >> 16) & ROW_MASK]) << 16; ret ^= (board_t)(row_left_table[(board >> 32) & ROW_MASK]) << 32; ret ^= (board_t)(row_left_table[(board >> 48) & ROW_MASK]) << 48; } else if (move == RIGHT) { ret ^= (board_t)(row_right_table[board & ROW_MASK]); ret ^= (board_t)(row_right_table[(board >> 16) & ROW_MASK]) << 16; ret ^= (board_t)(row_right_table[(board >> 32) & ROW_MASK]) << 32; ret ^= (board_t)(row_right_table[(board >> 48) & ROW_MASK]) << 48; } return ret; } static score_t score_helper(board_t board) { return score_table[board & ROW_MASK] + score_table[(board >> 16) & ROW_MASK] + score_table[(board >> 32) & ROW_MASK] + score_table[(board >> 48) & ROW_MASK]; } static score_heur_t score_heur_helper(board_t board) { return score_heur_table[board & ROW_MASK] + score_heur_table[(board >> 16) & ROW_MASK] + score_heur_table[(board >> 32) & ROW_MASK] + score_heur_table[(board >> 48) & ROW_MASK]; } #else static void alloc_tables(void) { int i = 0; memset(row_table, 0x00, sizeof(row_table)); memset(score_heur_table, 0x00, sizeof(score_heur_table)); for (i = 0; i < 8; ++i) { row_table[i] = (row_t *)malloc(sizeof(row_t) * TABLESIZE); score_heur_table[i] = (score_heur_t *)malloc(sizeof(score_heur_t) * TABLESIZE); if (!row_table[i] || !score_heur_table[i]) { fprintf(stderr, "Not enough memory."); fflush(stderr); abort(); } } } static void free_tables(void) { int i = 0; for (i = 0; i < 8; ++i) { free(row_table[i]); free(score_heur_table[i]); } } static board_t execute_move(board_t board, int move) { board_t ret = board; row_t row = 0; int i = 0; if (move == UP) { board = transpose(board); for (i = 0; i < 4; ++i) { row = (board >> (i << 4)) & ROW_MASK; ret ^= unpack_col(row_table[row / TABLESIZE][row % TABLESIZE]) << (i << 2); } } else if (move == DOWN) { board = transpose(board); for (i = 0; i < 4; ++i) { row = reverse_row((board >> (i << 4)) & ROW_MASK); ret ^= unpack_col(reverse_row(row_table[row / TABLESIZE][row % TABLESIZE])) << (i << 2); } } else if (move == LEFT) { for (i = 0; i < 4; ++i) { row = (board >> (i << 4)) & ROW_MASK; ret ^= (board_t)(row_table[row / TABLESIZE][row % TABLESIZE]) << (i << 4); } } else if (move == RIGHT) { for (i = 0; i < 4; ++i) { row = reverse_row((board >> (i << 4)) & ROW_MASK); ret ^= (board_t)(reverse_row(row_table[row / TABLESIZE][row % TABLESIZE])) << (i << 4); } } return ret; } static score_t score_helper(board_t board) { score_t score = 0, rank = 0; row_t row = 0; int i = 0, j = 0; for (j = 0; j < 4; ++j) { row = (row_t)((board >> (j << 4)) & ROW_MASK); for (i = 0; i < 4; ++i) { rank = (row >> (i << 2)) & 0xf; if (rank >= 2) { score += (rank - 1) * (1 << rank); } } } return score; } static score_heur_t score_heur_helper(board_t board) { score_heur_t score_heur = 0.0f; row_t row = 0; int i = 0; for (i = 0; i < 4; ++i) { row = (board >> (i << 4)) & ROW_MASK; score_heur += score_heur_table[row / TABLESIZE][row % TABLESIZE]; } return score_heur; } #endif static score_t score_board(board_t board) { return score_helper(board); } static score_heur_t score_heur_board(board_t board) { return score_heur_helper(board) + score_heur_helper(transpose(board)); } static row_t draw_tile(void) { return (unif_random(10) < 9) ? 1 : 2; } static board_t insert_tile_rand(board_t board, board_t tile) { int index = unif_random(count_empty(board)); board_t tmp = board; while (1) { while ((tmp & 0xf) != 0) { tmp >>= 4; tile <<= 4; } if (index == 0) break; --index; tmp >>= 4; tile <<= 4; } return board | tile; } static board_t initial_board(void) { board_t board = (board_t)(draw_tile()) << (unif_random(16) << 2); return insert_tile_rand(board, draw_tile()); } #if FASTMODE != 0 static int get_depth_limit(board_t board) { row_t bitset = 0, max_limit = 0; int count = 0; while (board) { bitset |= 1 << (board & 0xf); board >>= 4; } if (bitset <= 128) { return 1; } else if (bitset <= 512) { return 2; } else if (bitset <= 2048) { return 3; } else if (bitset <= 2048 + 1024) { max_limit = 4; } else { max_limit = 5; } bitset >>= 1; #ifdef __POPCNT__ count = (int)(__builtin_popcount(bitset)) - 2; #else while (bitset) { bitset &= bitset - 1; count++; } count -= 2; #endif count = _max(count, 3); count = _min(count, max_limit); return count; } #else static int get_depth_limit(board_t board) { row_t bitset = 0; while (board) { bitset |= 1 << (board & 0xf); board >>= 4; } if (bitset <= 128) { return 1; } else if (bitset <= 512) { return 2; } return 3; } #endif static score_heur_t score_move_node(eval_state *state, board_t board, score_heur_t cprob); static score_heur_t score_tilechoose_node(eval_state *state, board_t board, score_heur_t cprob) { int num_open = 0; score_heur_t res = 0.0f; board_t tmp = board; board_t tile_2 = 1; if (cprob < CPROB_THRESH_BASE || state->curdepth >= state->depth_limit) { state->maxdepth = _max(state->curdepth, state->maxdepth); state->tablehits++; return score_heur_board(board); } num_open = count_empty(board); cprob /= num_open; while (tile_2) { if ((tmp & 0xf) == 0) { res += score_move_node(state, board | tile_2, cprob * 0.9f) * 0.9f; res += score_move_node(state, board | (tile_2 << 1), cprob * 0.1f) * 0.1f; } tmp >>= 4; tile_2 <<= 4; } res = res / num_open; return res; } static score_heur_t score_move_node(eval_state *state, board_t board, score_heur_t cprob) { score_heur_t best = 0.0f; int move = 0; state->curdepth++; for (move = 0; move < 4; ++move) { board_t newboard = execute_move(board, move); state->moves_evaled++; if (board != newboard) { score_heur_t tmp = score_tilechoose_node(state, newboard, cprob); if (best < tmp) { best = tmp; } } else { state->nomoves++; } } state->curdepth--; return best; } static score_heur_t _score_toplevel_move(eval_state *state, board_t board, int move) { board_t newboard = execute_move(board, move); if (board == newboard) return 0.0f; return score_tilechoose_node(state, newboard, 1.0f) + 1e-6f; } static score_heur_t score_toplevel_move(board_t board, int move) { eval_state state; score_heur_t res = 0.0f; memset(&state, 0x00, sizeof(eval_state)); state.depth_limit = get_depth_limit(board); res = _score_toplevel_move(&state, board, move); printf ("Move %d: result %f: eval'd %ld moves (%ld no moves, %ld table hits, %ld cache hits, %ld cache size) (maxdepth=%d)\n", move, res, state.moves_evaled, state.nomoves, state.tablehits, state.cachehits, 0L, state.maxdepth); return res; } int find_best_move(board_t board) { int move = 0; score_heur_t best = 0.0f; int bestmove = -1; score_heur_t res[4] = { 0.0f }; print_board(board); printf("Current scores: heur %ld, actual %ld\n", (long)score_heur_board(board), (long)score_board(board)); #if defined(OPENMP_THREAD) #pragma omp parallel for #endif for (move = 0; move < 4; move++) { res[move] = score_toplevel_move(board, move); } for (move = 0; move < 4; move++) { if (res[move] > best) { best = res[move]; bestmove = move; } } printf("Selected bestmove: %d, result: %f\n", bestmove, best); return bestmove; } void play_game(get_move_func_t get_move) { board_t board = initial_board(); int scorepenalty = 0; long last_score = 0, current_score = 0, moveno = 0; init_tables(); while (1) { int move; row_t tile; board_t newboard; clear_screen(); for (move = 0; move < 4; move++) { if (execute_move(board, move) != board) break; } if (move == 4) break; current_score = score_board(board) - scorepenalty; printf("Move #%ld, current score=%ld(+%ld)\n", ++moveno, current_score, current_score - last_score); last_score = current_score; move = get_move(board); if (move < 0) break; newboard = execute_move(board, move); if (newboard == board) { moveno--; continue; } tile = draw_tile(); if (tile == 2) scorepenalty += 4; board = insert_tile_rand(newboard, tile); } print_board(board); printf("Game over. Your score is %ld.\n", current_score); } int main() { alloc_tables(); play_game(find_best_move); free_tables(); return 0; }
ccl_tracers.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include "ccl.h" ccl_cl_tracer_collection_t *ccl_cl_tracer_collection_t_new(int *status) { ccl_cl_tracer_collection_t *trc = NULL; trc = malloc(sizeof(ccl_cl_tracer_collection_t)); if (trc == NULL) *status = CCL_ERROR_MEMORY; if (*status == 0) { trc->n_tracers = 0; // Currently CCL_MAX_TRACERS_PER_COLLECTION is hard-coded to 100. // It should be enough for any practical application with minimal memory overhead trc->ts = malloc(CCL_MAX_TRACERS_PER_COLLECTION*sizeof(ccl_cl_tracer_t *)); if (trc->ts == NULL) { *status = CCL_ERROR_MEMORY; free(trc); trc = NULL; } } return trc; } void ccl_cl_tracer_collection_t_free(ccl_cl_tracer_collection_t *trc) { if (trc != NULL) { if (trc->ts != NULL) free(trc->ts); free(trc); } } void ccl_add_cl_tracer_to_collection(ccl_cl_tracer_collection_t *trc, ccl_cl_tracer_t *tr, int *status) { if (trc->n_tracers >= CCL_MAX_TRACERS_PER_COLLECTION) { *status = CCL_ERROR_MEMORY; return; } trc->ts[trc->n_tracers] = tr; trc->n_tracers++; } //Integrand for N(z) integrator static double nz_integrand(double z, void *pars) { ccl_f1d_t *nz_f = (ccl_f1d_t *)pars; return ccl_f1d_t_eval(nz_f,z); } // Gets area of N(z) curve static double get_nz_norm(ccl_cosmology *cosmo, ccl_f1d_t *nz_f, double z0, double zf, int *status) { double nz_norm = -1, nz_enorm; // Get N(z) norm gsl_function F; gsl_integration_workspace *w = NULL; F.function = &nz_integrand; F.params = nz_f; w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_tracers.c: get_nz_norm(): out of memory"); } else { int gslstatus = gsl_integration_qag( &F, z0, zf, 0, cosmo->gsl_params.INTEGRATION_EPSREL, cosmo->gsl_params.N_ITERATION, cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS, w, &nz_norm, &nz_enorm); if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_tracers.c: get_nz_norm():"); *status = CCL_ERROR_INTEG; ccl_cosmology_set_status_message( cosmo, "ccl_tracers.c: get_nz_norm(): " "integration error when normalizing N(z)\n"); } } gsl_integration_workspace_free(w); return nz_norm; } void ccl_get_number_counts_kernel(ccl_cosmology *cosmo, int nz, double *z_arr, double *nz_arr, int normalize_nz, double *pchi_arr, int *status) { // Returns dn/dchi normalized to unit area from an unnormalized dn/dz. // Prepare N(z) spline ccl_f1d_t *nz_f = NULL; nz_f = ccl_f1d_t_new(nz, z_arr, nz_arr, 0, 0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (nz_f == NULL) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_tracers.c: ccl_get_number_counts_kernel(): " "error initializing spline\n"); } // Get N(z) normalization double i_nz_norm = -1; if (*status == 0) { if (normalize_nz) i_nz_norm = 1./get_nz_norm(cosmo, nz_f, z_arr[0], z_arr[nz-1], status); else i_nz_norm = 1; } if (*status == 0) { // Populate arrays for(int ichi=0; ichi < nz; ichi++) { double a = 1./(1+z_arr[ichi]); double h = cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/ccl_constants.CLIGHT_HMPC; // H(z) * dN/dz * 1/Ngal pchi_arr[ichi] = h*nz_arr[ichi]*i_nz_norm; } } ccl_f1d_t_free(nz_f); } //3 H0^2 Omega_M / 2 static double get_lensing_prefactor(ccl_cosmology *cosmo,int *status) { double hub = cosmo->params.h/ccl_constants.CLIGHT_HMPC; return 1.5*hub*hub*cosmo->params.Omega_m; } typedef struct { ccl_cosmology *cosmo; double z_max; double z_end; double chi_end; double i_nz_norm; ccl_f1d_t *nz_f; ccl_f1d_t *sz_f; int *status; } integ_lensing_pars; // Integrand for lensing kernel. // Returns N(z) * (1 - 5*s(z)/2) * (chi(z)-chi) / chi(z) static double lensing_kernel_integrand(double z, void *pars) { integ_lensing_pars *p = (integ_lensing_pars *)pars; double pz = ccl_f1d_t_eval(p->nz_f, z); double qz; if (p->sz_f == NULL) // No magnification factor qz = 1; else // With magnification factor qz = (1 - 2.5*ccl_f1d_t_eval(p->sz_f, z)); if (z == 0) return pz * qz; else { double chi = ccl_comoving_radial_distance(p->cosmo, 1./(1+z), p->status); return ( pz * qz * ccl_sinn(p->cosmo, chi-p->chi_end, p->status) / ccl_sinn(p->cosmo, chi, p->status)); } } // Returns // Integral[ p(z) * (1-5s(z)/2) * chi_end * (chi(z)-chi_end)/chi(z) , {z',z_end,z_max} ] static double lensing_kernel_integrate(ccl_cosmology *cosmo, integ_lensing_pars *pars, gsl_integration_workspace *w) { int gslstatus = 0; double result, eresult; gsl_function F; F.function = &lensing_kernel_integrand; F.params = pars; gslstatus = gsl_integration_qag( &F, pars->z_end, pars->z_max, 0, cosmo->gsl_params.INTEGRATION_EPSREL, cosmo->gsl_params.N_ITERATION, cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS, w, &result, &eresult); if ((gslstatus != GSL_SUCCESS) || (*(pars->status))) { ccl_raise_gsl_warning(gslstatus, "ccl_tracers.c: lensing_kernel_integrate():"); return -1; } return result * pars->i_nz_norm * pars->chi_end; } //Returns number of divisions on which //the lensing kernel should be calculated int ccl_get_nchi_lensing_kernel(int nz, double *z_arr, int *status) { double dz = -1; //Compute redshift step dz = (z_arr[nz-1]-z_arr[0])/(nz-1); //How many steps to z=0? return (int)(z_arr[nz-1]/dz+0.5); } //Return array with the values of chi at //the which the lensing kernel will be //calculated. void ccl_get_chis_lensing_kernel(ccl_cosmology *cosmo, int nchi, double z_max, double *chis, int *status) { double dz = z_max/nchi; for(int ichi=0; ichi < nchi; ichi++) { double z = dz*ichi+1E-15; double a = 1./(1+z); chis[ichi] = ccl_comoving_radial_distance(cosmo, a, status); } } //Returns array with lensing kernel: //3 * H0^2 * Omega_M / 2 / a * // Integral[ p(z) * (1-5s(z)/2) * chi_end * (chi(z)-chi_end)/chi(z) , // {z',z_end,z_max} ] void ccl_get_lensing_mag_kernel(ccl_cosmology *cosmo, int nz, double *z_arr, double *nz_arr, int normalize_nz, double z_max, int nz_s, double *zs_arr, double *sz_arr, int nchi, double *chi_arr, double *wL_arr, int *status) { ccl_f1d_t *nz_f = NULL; ccl_f1d_t *sz_f = NULL; // Prepare N(z) spline nz_f = ccl_f1d_t_new(nz, z_arr, nz_arr, 0, 0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (nz_f == NULL) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_tracers.c: get_lensing_mag_kernel(): error initializing spline\n"); } // Get N(z) normalization double i_nz_norm = -1; if (*status == 0) { if (normalize_nz) i_nz_norm = 1./get_nz_norm(cosmo, nz_f, z_arr[0], z_arr[nz-1], status); else i_nz_norm = 1.; } // Prepare magnification bias spline if needed if (*status == 0) { if ((nz_s > 0) && (zs_arr != NULL) && (sz_arr != NULL)) { sz_f = ccl_f1d_t_new(nz_s, zs_arr, sz_arr, sz_arr[0], sz_arr[nz_s-1], ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (sz_f == NULL) { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message( cosmo, "ccl_tracers.c: get_lensing_mag_kernel(): error initializing spline\n"); } } } if(*status==0) { #pragma omp parallel default(none) \ shared(cosmo, z_max, i_nz_norm, sz_f, nz_f, \ nchi, chi_arr, wL_arr, status) { double chi, a, z, mgfac, lens_prefac; int ichi, local_status; integ_lensing_pars *ipar = NULL; gsl_integration_workspace *w = NULL; local_status = *status; lens_prefac = get_lensing_prefactor(cosmo, &local_status); if (local_status == 0) { ipar = malloc(sizeof(integ_lensing_pars)); w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION); if ((ipar == NULL) || (w == NULL)) { local_status = CCL_ERROR_MEMORY; } } if (local_status == 0) { ipar->cosmo = cosmo; ipar->z_max = z_max; ipar->i_nz_norm = i_nz_norm; ipar->sz_f = sz_f; ipar->nz_f = nz_f; ipar->status = &local_status; } //Populate arrays #pragma omp for for (ichi=0; ichi < nchi; ichi++) { if (local_status == 0) { chi = chi_arr[ichi]; a = ccl_scale_factor_of_chi(cosmo, chi, &local_status); z = 1./a-1; // Add MG correction if needed mgfac = 1.0; if (fabs(cosmo->params.sigma_0)) mgfac += ccl_Sig_MG(cosmo, a, &local_status); ipar->z_end = z; ipar->chi_end = chi; wL_arr[ichi] = lensing_kernel_integrate(cosmo, ipar, w)*(1+z)*lens_prefac*mgfac; } else { wL_arr[ichi] = NAN; } } //end omp for gsl_integration_workspace_free(w); free(ipar); if (local_status) { #pragma omp atomic write *status = CCL_ERROR_INTEG; } } //end omp parallel } ccl_f1d_t_free(nz_f); ccl_f1d_t_free(sz_f); } // Returns kernel for CMB lensing // 3H0^2Om/2 * chi * (chi_s - chi) / chi_s / a void ccl_get_kappa_kernel(ccl_cosmology *cosmo, double chi_source, int nchi, double *chi_arr, double *wchi, int *status) { double lens_prefac = get_lensing_prefactor(cosmo, status) / ccl_sinn(cosmo, chi_source, status); for (int ichi=0; ichi < nchi; ichi++) { double chi = chi_arr[ichi]; double a = ccl_scale_factor_of_chi(cosmo, chi, status); double mgfac = 1; // Add MG correction if needed if (fabs(cosmo->params.sigma_0)) mgfac += ccl_Sig_MG(cosmo, a, status); wchi[ichi] = lens_prefac*(ccl_sinn(cosmo,chi_source-chi,status))*chi*mgfac/a; } } ccl_cl_tracer_t *ccl_cl_tracer_t_new(ccl_cosmology *cosmo, int der_bessel, int der_angles, int n_w, double *chi_w, double *w_w, int na_ka, double *a_ka, int nk_ka, double *lk_ka, double *fka_arr, double *fk_arr, double *fa_arr, int is_fka_log, int is_factorizable, int extrap_order_lok, int extrap_order_hik, int *status) { ccl_cl_tracer_t *tr = NULL; // Check der_bessel and der_angles are sensible if ((der_angles < 0) || (der_angles > 2)) { *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message( cosmo, "ccl_tracers.c: ccl_cl_tracer_new(): der_angles must be between 0 and 2\n"); } if ((der_bessel < -1) || (der_bessel > 2)) { *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message( cosmo, "ccl_tracers.c: ccl_cl_tracer_new(): der_bessel must be between -1 and 2\n"); } if (*status == 0) { tr = malloc(sizeof(ccl_cl_tracer_t)); if (tr == NULL) *status = CCL_ERROR_MEMORY; } // Initialize everythin if (*status == 0) { tr->der_angles = der_angles; tr->der_bessel = der_bessel; tr->kernel = NULL; // Initialize these to NULL tr->transfer = NULL; // Initialize these to NULL tr->chi_min = 0; tr->chi_max = 1E15; } if (*status == 0) { // Initialize radial kernel if ((n_w > 0) && (chi_w != NULL) && (w_w != NULL)) { tr->kernel = ccl_f1d_t_new(n_w,chi_w,w_w,0,0, ccl_f1d_extrap_const, ccl_f1d_extrap_const, status); if (tr->kernel == NULL) *status=CCL_ERROR_MEMORY; } } // Find kernel edges if (*status == 0) { // If no radial kernel, set limits to zero and maximum distance if (tr->kernel == NULL) { tr->chi_min = 0; tr->chi_max = ccl_comoving_radial_distance(cosmo, cosmo->spline_params.A_SPLINE_MIN, status); } else { int ichi; double w_max = fabs(w_w[0]); // Find maximum of radial kernel for (ichi=0; ichi < n_w; ichi++) { if (fabs(w_w[ichi]) >= w_max) w_max = fabs(w_w[ichi]); } // Multiply by fraction w_max *= CCL_FRAC_RELEVANT; // Initialize as the original edges in case we don't find an interval tr->chi_min = chi_w[0]; tr->chi_max = chi_w[n_w-1]; // Find minimum for (ichi=0; ichi < n_w; ichi++) { if (fabs(w_w[ichi]) >= w_max) { tr->chi_min = chi_w[ichi]; break; } } // Find maximum for (ichi=n_w-1; ichi >= 0; ichi--) { if (fabs(w_w[ichi]) >= w_max) { tr->chi_max = chi_w[ichi]; break; } } } } if (*status == 0) { if ((fka_arr != NULL) || (fk_arr != NULL) || (fa_arr != NULL)) { tr->transfer = ccl_f2d_t_new( na_ka,a_ka, // na, a_arr nk_ka,lk_ka, // nk, lk_arr fka_arr, // fka_arr fk_arr, // fk_arr fa_arr, // fa_arr is_factorizable, // is factorizable extrap_order_lok, // extrap_order_lok extrap_order_hik, // extrap_order_hik ccl_f2d_constantgrowth, // extrap_linear_growth is_fka_log, // is_fka_log NULL, // growth (function) 1, // growth_factor_0 -> will assume constant transfer function 0, // growth_exponent ccl_f2d_3, // interp_type status); if (tr->transfer == NULL) *status=CCL_ERROR_MEMORY; } } return tr; } void ccl_cl_tracer_t_free(ccl_cl_tracer_t *tr) { if (tr != NULL) { if (tr->transfer != NULL) ccl_f2d_t_free(tr->transfer); if (tr->kernel != NULL) ccl_f1d_t_free(tr->kernel); free(tr); } } double ccl_cl_tracer_t_get_f_ell(ccl_cl_tracer_t *tr, double ell, int *status) { if (tr != NULL) { if (tr->der_angles == 1) return ell*(ell+1.); else if (tr->der_angles == 2) { if (ell <= 1) // This is identically 0 return 0; else if (ell <= 10) // Use full expression in this case return sqrt((ell+2)*(ell+1)*ell*(ell-1)); else { double lp1h = ell+0.5; double lp1h2 = lp1h*lp1h; if (ell <= 1000) // This is accurate to 5E-5 for l>10 return lp1h2*(1-1.25/lp1h2); else // This is accurate to 1E-6 for l>1000 return lp1h2; } } else return 1; } else return 1; } double ccl_cl_tracer_t_get_kernel(ccl_cl_tracer_t *tr, double chi, int *status) { if (tr != NULL) { if (tr->kernel != NULL) return ccl_f1d_t_eval(tr->kernel, chi); else return 1; } else return 1; } double ccl_cl_tracer_t_get_transfer(ccl_cl_tracer_t *tr, double lk, double a, int *status) { if (tr != NULL) { if (tr->transfer != NULL) return ccl_f2d_t_eval(tr->transfer, lk, a, NULL, status); else return 1; } else return 1; }
GB_AxB_dot3_template.c
//------------------------------------------------------------------------------ // GB_AxB_dot3_template: C<M>=A'*B via dot products //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ #ifndef GB_DOT3 #define GB_DOT3 #endif { //-------------------------------------------------------------------------- // get M, A, B, and C //-------------------------------------------------------------------------- const int64_t *GB_RESTRICT Cp = C->p ; const int64_t *GB_RESTRICT Ch = C->h ; int64_t *GB_RESTRICT Ci = C->i ; GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ; const int64_t *GB_RESTRICT Bp = B->p ; const int64_t *GB_RESTRICT Bh = B->h ; const int64_t *GB_RESTRICT Bi = B->i ; const GB_BTYPE *GB_RESTRICT Bx = (GB_BTYPE *) (B_is_pattern ? NULL : B->x) ; const int64_t bvlen = B->vlen ; const int64_t bnvec = B->nvec ; const bool B_is_hyper = B->is_hyper ; const int64_t *GB_RESTRICT Mi = M->i ; const GB_void *GB_RESTRICT Mx = (GB_void *) (Mask_struct ? NULL : (M->x)) ; const size_t msize = M->type->size ; const int64_t *GB_RESTRICT Ah = A->h ; const int64_t *GB_RESTRICT Ap = A->p ; const int64_t *GB_RESTRICT Ai = A->i ; const int64_t anvec = A->nvec ; const bool A_is_hyper = GB_IS_HYPER (A) ; const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) (A_is_pattern ? NULL : A->x) ; //-------------------------------------------------------------------------- // C<M> = A'*B //-------------------------------------------------------------------------- // C and M have the same pattern, except some entries of C may become // zombies. int64_t nzombies = 0 ; int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- int64_t kfirst = TaskList [taskid].kfirst ; int64_t klast = TaskList [taskid].klast ; int64_t pC_first = TaskList [taskid].pC ; int64_t pC_last = TaskList [taskid].pC_end ; int64_t task_nzombies = 0 ; int64_t bpleft = 0 ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get C(:,k) and M(:k) //------------------------------------------------------------------ int64_t j = (Ch == NULL) ? k : Ch [k] ; int64_t pC_start, pC_end ; if (k == kfirst) { // First vector for task; may only be partially owned. pC_start = pC_first ; pC_end = GB_IMIN (Cp [k+1], pC_last) ; } else if (k == klast) { // Last vector for task; may only be partially owned. pC_start = Cp [k] ; pC_end = pC_last ; } else { // task fully owns this vector C(:,k). pC_start = Cp [k] ; pC_end = Cp [k+1] ; } //------------------------------------------------------------------ // get B(:,j) //------------------------------------------------------------------ int64_t pB_start, pB_end ; GB_lookup (B_is_hyper, Bh, Bp, &bpleft, bnvec-1, j, &pB_start, &pB_end) ; int64_t bjnz = pB_end - pB_start ; //------------------------------------------------------------------ // C(:,j)<M(:,j)> = A(:,i)'*B(:,j) //------------------------------------------------------------------ if (bjnz == 0) { //-------------------------------------------------------------- // C(:,j) is empty if B(:,j) is empty //-------------------------------------------------------------- task_nzombies += (pC_end - pC_start) ; for (int64_t pC = pC_start ; pC < pC_end ; pC++) { // C(i,j) is a zombie Ci [pC] = GB_FLIP (Mi [pC]) ; } } else { //-------------------------------------------------------------- // B(:,j) not empty //-------------------------------------------------------------- int64_t ib_first = Bi [pB_start] ; int64_t ib_last = Bi [pB_end-1] ; int64_t apleft = 0 ; for (int64_t pC = pC_start ; pC < pC_end ; pC++) { //---------------------------------------------------------- // compute C(i,j) //---------------------------------------------------------- // get the value of M(i,j) int64_t i = Mi [pC] ; if (GB_mcast (Mx, pC, msize)) // note: Mx [pC], same as Cx { //------------------------------------------------------ // M(i,j) is true, so compute C(i,j) //------------------------------------------------------ // get A(:,i), if it exists int64_t pA, pA_end ; GB_lookup (A_is_hyper, Ah, Ap, &apleft, anvec-1, i, &pA, &pA_end) ; // C(i,j) = A(:,i)'*B(:,j) #include "GB_AxB_dot_cij.c" } else { //------------------------------------------------------ // M(i,j) is false, so C(i,j) is a zombie //------------------------------------------------------ task_nzombies++ ; Ci [pC] = GB_FLIP (i) ; } } } } //---------------------------------------------------------------------- // sum up the zombies found by this task //---------------------------------------------------------------------- nzombies += task_nzombies ; } //-------------------------------------------------------------------------- // finalize the zombie count for C //-------------------------------------------------------------------------- C->nzombies = nzombies ; } #undef GB_DOT3
block_coloring.c
/* ============================================================================ Name : coloring.c Author : qwinpin Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <time.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> void test(); void print_graph(int **a, int size){ printf("\nGraph\n"); for (int i = 0; i < size && i < 5; i++){ for (int j = 0; j < size && j < 5; j++){ printf("%d ", a[i][j]); } printf("\n"); } } void print_color(int *vert, int size){ printf("Graph color\n"); for (int i = 0; i < size && i < 10; i++){ printf("%d, ", vert[i]); } printf("\n"); } void color_single(int **a, int *vert, int end){ vert[end] = 1; for (int i = 0; i < end; i++){ if (a[i][end] != 0 && vert[end] == vert[i]){ vert[end] = vert[i] + 1; } } } void color(int **a, int *vert, int k){ for (int i = 0; i < k; i++){ if (a[i][k] != 0 && vert[k] == vert[i]){ vert[k] = vert[i] + 1; } } } void coloring(int **a, int *vert, int size, int th){ int i, j; int step = size / th; int *tmp = (int*) malloc(size * sizeof(int)); #pragma omp parallel for num_threads(th) for (i = 0; i < size; i++){ tmp[i] = 0; } int **pool = (int**) malloc(size * sizeof(int*)); // #pragma omp parallel num_threads(th) { #pragma omp parallel for num_threads(th) for (i = 0; i < size; i++){ pool[i] = (int*) malloc(size * sizeof(int)); } } // #pragma omp parallel num_threads(th) { #pragma omp parallel for num_threads(th) for (int i = 0; i < size; i++){ pool[i][i] = 0; #pragma omp parallel for num_threads(th) for (j = i + 1; j < size; j++){ pool[i][j] = 0; pool[j][i] = 0; } } } // #pragma omp parallel num_threads(th) { #pragma omp parallel for num_threads(th) for (i = 0; i < th; i++){ for (j = i * step; j < (i + 1) * step; j++){ color_single(a, vert, j); } } } for (i = 0; i < size; i++){ for (j = 0; j < tmp[i]; j++){ color(a, vert, pool[i][j]); } } #pragma omp parallel for num_threads(th) for (i = 0; i < size; i++){ free(pool[i]); } free(pool); } int main() { int evaluate; printf("Evaluate test or not? 1/0\n"); scanf("%d", &evaluate); if (evaluate){ test(); return 0; } int size; int tmp; printf("Enter graph size\n"); scanf("%d", &size); int th; printf("Threads number\n"); scanf("%d", &th); if (th == 0){ printf("Bye"); } int *vert = (int*) malloc(size * sizeof(int)); int **a = (int**) malloc(size * sizeof(int*)); for (int i = 0; i < size; i++){ a[i] = (int*) malloc(size * sizeof(int)); } srand(time(NULL)); printf("Start coloring"); // #pragma omp parallel num_threads(th) { #pragma omp parallel for num_threads(th) for (int i = 0; i < size; i++){ a[i][i] = 0; #pragma omp parallel for num_threads(th) for (int j = i + 1; j < size; j++){ tmp = rand() % 2; a[i][j] = tmp; a[j][i] = tmp; } } } #pragma omp parallel for num_threads(th) for (int i = 0; i < size; i++){ vert[i] = 0; } clock_t start = clock(), diff; coloring(a, vert, size, th); diff = clock() - start; print_graph(a, size); print_color(vert, size); for (int i = 0; i < size; i++){ free(a[i]); } free(a); printf("It took %li sec %li milisec", diff / CLOCKS_PER_SEC, diff * 1000 / CLOCKS_PER_SEC % 1000); return 0; } void test(){ int size = 1000; int threads = 100; int size_step = 1000; int size_max = 15000; int tmp; srand(time(NULL)); FILE *f = fopen("color_parallel_process.txt", "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } int *vert = (int*) malloc(size_max * sizeof(int)); int **a = (int**) malloc(size_max * sizeof(int*)); for (int i = 0; i < size_max; i++){ a[i] = (int*) malloc(size_max * sizeof(int)); } srand(time(NULL)); printf("Start coloring"); for (int i = 0; i < size_max; i++){ a[i][i] = 0; for (int j = i + 1; j < size_max; j++){ tmp = rand() % 2; a[i][j] = tmp; a[j][i] = tmp; } } for (int i = 0; i < size_max; i++){ vert[i] = 0; } for (int th = 1; th < threads; th++){ printf("Threads num %d\n", th); fprintf(f, "\nThreads_num: %d\n ", th); size = 1000; while (size <= size_max){ for (int i = 0; i < size_max; i++){ vert[i] = 0; } printf("Size %d\n", size); clock_t start = clock(), diff; coloring(a, vert, size, th); diff = clock() - start; fprintf(f, "%f, ", (double)diff / CLOCKS_PER_SEC * 1000); size = size + size_step; } th = th + 4; } for (int i = 0; i < size_max; i++){ free(a[i]); } free(a); }
clean.h
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * 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 (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #ifndef __VCGLIB_CLEAN #define __VCGLIB_CLEAN // VCG headers #include <vcg/complex/complex.h> #include <vcg/simplex/face/pos.h> #include <vcg/simplex/face/topology.h> #include <vcg/simplex/edge/topology.h> #include <vcg/complex/algorithms/closest.h> #include <vcg/space/index/grid_static_ptr.h> #include <vcg/space/index/spatial_hashing.h> #include <vcg/complex/algorithms/update/selection.h> #include <vcg/complex/algorithms/update/flag.h> #include <vcg/complex/algorithms/update/normal.h> #include <vcg/complex/algorithms/update/topology.h> #include <vcg/space/triangle3.h> namespace vcg { namespace tri{ template <class ConnectedMeshType> class ConnectedComponentIterator { public: typedef ConnectedMeshType MeshType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::VertexPointer VertexPointer; typedef typename MeshType::VertexIterator VertexIterator; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::FacePointer FacePointer; typedef typename MeshType::FaceIterator FaceIterator; typedef typename MeshType::ConstFaceIterator ConstFaceIterator; typedef typename MeshType::FaceContainer FaceContainer; public: void operator ++() { FacePointer fpt=sf.top(); sf.pop(); for(int j=0;j<3;++j) if( !face::IsBorder(*fpt,j) ) { FacePointer l=fpt->FFp(j); if( !tri::IsMarked(*mp,l) ) { tri::Mark(*mp,l); sf.push(l); } } } void start(MeshType &m, FacePointer p) { tri::RequirePerFaceMark(m); mp=&m; while(!sf.empty()) sf.pop(); UnMarkAll(m); assert(p); assert(!p->IsD()); tri::Mark(m,p); sf.push(p); } bool completed() { return sf.empty(); } FacePointer operator *() { return sf.top(); } private: std::stack<FacePointer> sf; MeshType *mp; }; /// /** \addtogroup trimesh */ /*@{*/ /// Class of static functions to clean//restore meshs. template <class CleanMeshType> class Clean { public: typedef CleanMeshType MeshType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::VertexPointer VertexPointer; typedef typename MeshType::VertexIterator VertexIterator; typedef typename MeshType::ConstVertexIterator ConstVertexIterator; typedef typename MeshType::EdgeIterator EdgeIterator; typedef typename MeshType::EdgePointer EdgePointer; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::FacePointer FacePointer; typedef typename MeshType::FaceIterator FaceIterator; typedef typename MeshType::ConstFaceIterator ConstFaceIterator; typedef typename MeshType::FaceContainer FaceContainer; typedef typename vcg::Box3<ScalarType> Box3Type; typedef GridStaticPtr<FaceType, ScalarType > TriMeshGrid; /* classe di confronto per l'algoritmo di eliminazione vertici duplicati*/ class RemoveDuplicateVert_Compare{ public: inline bool operator()(VertexPointer const &a, VertexPointer const &b) { return ((*a).cP() == (*b).cP()) ? (a<b): ((*a).cP() < (*b).cP()); } }; /** This function removes all duplicate vertices of the mesh by looking only at their spatial positions. * Note that it does not update any topology relation that could be affected by this like the VT or TT relation. * the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateVertex( MeshType & m, bool RemoveDegenerateFlag=true) // V1.0 { if(m.vert.size()==0 || m.vn==0) return 0; std::map<VertexPointer, VertexPointer> mp; size_t i,j; VertexIterator vi; int deleted=0; int k=0; size_t num_vert = m.vert.size(); std::vector<VertexPointer> perm(num_vert); for(vi=m.vert.begin(); vi!=m.vert.end(); ++vi, ++k) perm[k] = &(*vi); RemoveDuplicateVert_Compare c_obj; std::sort(perm.begin(),perm.end(),c_obj); j = 0; i = j; mp[perm[i]] = perm[j]; ++i; for(;i!=num_vert;) { if( (! (*perm[i]).IsD()) && (! (*perm[j]).IsD()) && (*perm[i]).P() == (*perm[j]).cP() ) { VertexPointer t = perm[i]; mp[perm[i]] = perm[j]; ++i; Allocator<MeshType>::DeleteVertex(m,*t); deleted++; } else { j = i; ++i; } } for(FaceIterator fi = m.face.begin(); fi!=m.face.end(); ++fi) if( !(*fi).IsD() ) for(k = 0; k < (*fi).VN(); ++k) if( mp.find( (typename MeshType::VertexPointer)(*fi).V(k) ) != mp.end() ) { (*fi).V(k) = &*mp[ (*fi).V(k) ]; } for(EdgeIterator ei = m.edge.begin(); ei!=m.edge.end(); ++ei) if( !(*ei).IsD() ) for(k = 0; k < 2; ++k) if( mp.find( (typename MeshType::VertexPointer)(*ei).V(k) ) != mp.end() ) { (*ei).V(k) = &*mp[ (*ei).V(k) ]; } if(RemoveDegenerateFlag) RemoveDegenerateFace(m); if(RemoveDegenerateFlag && m.en>0) { RemoveDegenerateEdge(m); RemoveDuplicateEdge(m); } return deleted; } class SortedPair { public: SortedPair() {} SortedPair(unsigned int v0, unsigned int v1, EdgePointer _fp) { v[0]=v0;v[1]=v1; fp=_fp; if(v[0]>v[1]) std::swap(v[0],v[1]); } bool operator < (const SortedPair &p) const { return (v[1]!=p.v[1])?(v[1]<p.v[1]): (v[0]<p.v[0]); } bool operator == (const SortedPair &s) const { if( (v[0]==s.v[0]) && (v[1]==s.v[1]) ) return true; return false; } unsigned int v[2]; EdgePointer fp; }; class SortedTriple { public: SortedTriple() {} SortedTriple(unsigned int v0, unsigned int v1, unsigned int v2,FacePointer _fp) { v[0]=v0;v[1]=v1;v[2]=v2; fp=_fp; std::sort(v,v+3); } bool operator < (const SortedTriple &p) const { return (v[2]!=p.v[2])?(v[2]<p.v[2]): (v[1]!=p.v[1])?(v[1]<p.v[1]): (v[0]<p.v[0]); } bool operator == (const SortedTriple &s) const { if( (v[0]==s.v[0]) && (v[1]==s.v[1]) && (v[2]==s.v[2]) ) return true; return false; } unsigned int v[3]; FacePointer fp; }; /** This function removes all duplicate faces of the mesh by looking only at their vertex reference. So it should be called after unification of vertices. Note that it does not update any topology relation that could be affected by this like the VT or TT relation. the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateFace( MeshType & m) // V1.0 { std::vector<SortedTriple> fvec; for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { fvec.push_back(SortedTriple( tri::Index(m,(*fi).V(0)), tri::Index(m,(*fi).V(1)), tri::Index(m,(*fi).V(2)), &*fi)); } assert (size_t(m.fn) == fvec.size()); std::sort(fvec.begin(),fvec.end()); int total=0; for(int i=0;i<int(fvec.size())-1;++i) { if(fvec[i]==fvec[i+1]) { total++; tri::Allocator<MeshType>::DeleteFace(m, *(fvec[i].fp) ); } } return total; } /** This function removes all duplicate faces of the mesh by looking only at their vertex reference. So it should be called after unification of vertices. Note that it does not update any topology relation that could be affected by this like the VT or TT relation. the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateEdge( MeshType & m) // V1.0 { if (m.en==0) return 0; std::vector<SortedPair> eVec; for(EdgeIterator ei=m.edge.begin();ei!=m.edge.end();++ei) if(!(*ei).IsD()) { eVec.push_back(SortedPair( tri::Index(m,(*ei).V(0)), tri::Index(m,(*ei).V(1)), &*ei)); } assert (size_t(m.en) == eVec.size()); //for(int i=0;i<fvec.size();++i) qDebug("fvec[%i] = (%i %i %i)(%i)",i,fvec[i].v[0],fvec[i].v[1],fvec[i].v[2],tri::Index(m,fvec[i].fp)); std::sort(eVec.begin(),eVec.end()); int total=0; for(int i=0;i<int(eVec.size())-1;++i) { if(eVec[i]==eVec[i+1]) { total++; tri::Allocator<MeshType>::DeleteEdge(m, *(eVec[i].fp) ); //qDebug("deleting face %i (pos in fvec %i)",tri::Index(m,fvec[i].fp) ,i); } } return total; } static int CountUnreferencedVertex( MeshType& m) { return RemoveUnreferencedVertex(m,false); } /** This function removes that are not referenced by any face. The function updates the vn counter. @param m The mesh @return The number of removed vertices */ static int RemoveUnreferencedVertex( MeshType& m, bool DeleteVertexFlag=true) // V1.0 { FaceIterator fi; EdgeIterator ei; VertexIterator vi; int referredBit = VertexType::NewBitFlag(); int j; int deleted = 0; for(vi=m.vert.begin();vi!=m.vert.end();++vi) (*vi).ClearUserBit(referredBit); for(fi=m.face.begin();fi!=m.face.end();++fi) if( !(*fi).IsD() ) for(j=0;j<(*fi).VN();++j) (*fi).V(j)->SetUserBit(referredBit); for(ei=m.edge.begin();ei!=m.edge.end();++ei) if( !(*ei).IsD() ){ (*ei).V(0)->SetUserBit(referredBit); (*ei).V(1)->SetUserBit(referredBit); } for(vi=m.vert.begin();vi!=m.vert.end();++vi) if( (!(*vi).IsD()) && (!(*vi).IsUserBit(referredBit))) { if(DeleteVertexFlag) Allocator<MeshType>::DeleteVertex(m,*vi); ++deleted; } VertexType::DeleteBitFlag(referredBit); return deleted; } /** Degenerate vertices are vertices that have coords with invalid floating point values, All the faces incident on deleted vertices are also deleted */ static int RemoveDegenerateVertex(MeshType& m) { VertexIterator vi; int count_vd = 0; for(vi=m.vert.begin(); vi!=m.vert.end();++vi) if(math::IsNAN( (*vi).P()[0]) || math::IsNAN( (*vi).P()[1]) || math::IsNAN( (*vi).P()[2]) ) { count_vd++; Allocator<MeshType>::DeleteVertex(m,*vi); } FaceIterator fi; int count_fd = 0; for(fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) if( (*fi).V(0)->IsD() || (*fi).V(1)->IsD() || (*fi).V(2)->IsD() ) { count_fd++; Allocator<MeshType>::DeleteFace(m,*fi); } return count_vd; } /** Degenerate faces are faces that are Topologically degenerate, i.e. have two or more vertex reference that link the same vertex (and not only two vertexes with the same coordinates). All Degenerate faces are zero area faces BUT not all zero area faces are degenerate. We do not take care of topology because when we have degenerate faces the topology calculation functions crash. */ static int RemoveDegenerateFace(MeshType& m) { int count_fd = 0; for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) { if((*fi).V(0) == (*fi).V(1) || (*fi).V(0) == (*fi).V(2) || (*fi).V(1) == (*fi).V(2) ) { count_fd++; Allocator<MeshType>::DeleteFace(m,*fi); } } return count_fd; } static int RemoveDegenerateEdge(MeshType& m) { int count_ed = 0; for(EdgeIterator ei=m.edge.begin(); ei!=m.edge.end();++ei) if(!(*ei).IsD()) { if((*ei).V(0) == (*ei).V(1) ) { count_ed++; Allocator<MeshType>::DeleteEdge(m,*ei); } } return count_ed; } static int RemoveNonManifoldVertex(MeshType& m) { CountNonManifoldVertexFF(m,true); tri::UpdateSelection<MeshType>::FaceFromVertexLoose(m); int count_removed = 0; FaceIterator fi; for(fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD() && (*fi).IsS()) Allocator<MeshType>::DeleteFace(m,*fi); VertexIterator vi; for(vi=m.vert.begin(); vi!=m.vert.end();++vi) if(!(*vi).IsD() && (*vi).IsS()) { ++count_removed; Allocator<MeshType>::DeleteVertex(m,*vi); } return count_removed; } static int SplitSelectedVertexOnEdgeMesh(MeshType& m) { tri::RequireCompactness(m); tri::UpdateFlags<MeshType>::VertexClearV(m); for(size_t i=0;i<m.edge.size();++i) { for(int j=0;j<2;++j) { VertexPointer vp = m.edge[i].V(j); if(vp->IsS()) { if(!vp->IsV()) m.edge[i].V(j) = &*(tri::Allocator<MeshType>::AddVertex(m,vp->P())); else vp->SetV(); } } } } static void SelectNonManifoldVertexOnEdgeMesh(MeshType &m) { tri::RequireCompactness(m); tri::UpdateSelection<MeshType>::VertexClear(m); std::vector<int> cnt(m.vn,0); for(size_t i=0;i<m.edge.size();++i) { cnt[tri::Index(m,m.edge[i].V(0))]++; cnt[tri::Index(m,m.edge[i].V(1))]++; } for(size_t i=0;i<m.vert.size();++i) if(cnt[i]>2) m.vert[i].SetS(); } static void SelectCreaseVertexOnEdgeMesh(MeshType &m, ScalarType AngleRadThr) { tri::RequireCompactness(m); tri::RequireVEAdjacency(m); tri::UpdateTopology<MeshType>::VertexEdge(m); for(size_t i=0;i<m.vert.size();++i) { std::vector<VertexPointer> VVStarVec; edge::VVStarVE<typename MeshType::EdgeType>(&(m.vert[i]),VVStarVec); if(VVStarVec.size()==2) { CoordType v0 = m.vert[i].P() - VVStarVec[0]->P(); CoordType v1 = m.vert[i].P() - VVStarVec[1]->P(); float angle = M_PI-vcg::Angle(v0,v1); if(angle > AngleRadThr) m.vert[i].SetS(); } } } /// Removal of faces that were incident on a non manifold edge. // Given a mesh with FF adjacency // it search for non manifold vertices and duplicate them. // Duplicated vertices are moved apart according to the move threshold param. // that is a percentage of the average vector from the non manifold vertex to the barycenter of the incident faces. static int SplitNonManifoldVertex(MeshType& m, ScalarType moveThreshold) { RequireFFAdjacency(m); typedef std::pair<FacePointer,int> FaceInt; // a face and the index of the vertex that we have to change // std::vector<std::pair<VertexPointer, std::vector<FaceInt> > >ToSplitVec; SelectionStack<MeshType> ss(m); ss.push(); CountNonManifoldVertexFF(m,true); UpdateFlags<MeshType>::VertexClearV(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;i++) if((*fi).V(i)->IsS() && !(*fi).V(i)->IsV()) { (*fi).V(i)->SetV(); face::Pos<FaceType> startPos(&*fi,i); face::Pos<FaceType> curPos = startPos; std::set<FaceInt> faceSet; do { faceSet.insert(std::make_pair(curPos.F(),curPos.VInd())); curPos.NextE(); } while (curPos != startPos); ToSplitVec.push_back(make_pair((*fi).V(i),std::vector<FaceInt>())); typename std::set<FaceInt>::const_iterator iii; for(iii=faceSet.begin();iii!=faceSet.end();++iii) ToSplitVec.back().second.push_back(*iii); } } ss.pop(); // Second step actually add new vertices and split them. typename tri::Allocator<MeshType>::template PointerUpdater<VertexPointer> pu; VertexIterator firstVp = tri::Allocator<MeshType>::AddVertices(m,ToSplitVec.size(),pu); for(size_t i =0;i<ToSplitVec.size();++i) { // qDebug("Splitting Vertex %i",ToSplitVec[i].first-&*m.vert.begin()); VertexPointer np=ToSplitVec[i].first; pu.Update(np); firstVp->ImportData(*np); // loop on the face to be changed, and also compute the movement vector; CoordType delta(0,0,0); for(size_t j=0;j<ToSplitVec[i].second.size();++j) { FaceInt ff=ToSplitVec[i].second[j]; ff.first->V(ff.second)=&*firstVp; delta+=Barycenter(*(ff.first))-np->cP(); } delta /= ToSplitVec[i].second.size(); firstVp->P() = firstVp->P() + delta * moveThreshold; firstVp++; } return ToSplitVec.size(); } // Auxiliary function for sorting the non manifold faces according to their area. Used in RemoveNonManifoldFace struct CompareAreaFP { bool operator ()(FacePointer const& f1, FacePointer const& f2) const { return DoubleArea(*f1) < DoubleArea(*f2); } }; /// Removal of faces that were incident on a non manifold edge. static int RemoveNonManifoldFace(MeshType& m) { FaceIterator fi; int count_fd = 0; std::vector<FacePointer> ToDelVec; for(fi=m.face.begin(); fi!=m.face.end();++fi) if (!fi->IsD()) { if ((!IsManifold(*fi,0))|| (!IsManifold(*fi,1))|| (!IsManifold(*fi,2))) ToDelVec.push_back(&*fi); } std::sort(ToDelVec.begin(),ToDelVec.end(),CompareAreaFP()); for(size_t i=0;i<ToDelVec.size();++i) { if(!ToDelVec[i]->IsD()) { FaceType &ff= *ToDelVec[i]; if ((!IsManifold(ff,0))|| (!IsManifold(ff,1))|| (!IsManifold(ff,2))) { for(int j=0;j<3;++j) if(!face::IsBorder<FaceType>(ff,j)) vcg::face::FFDetach<FaceType>(ff,j); Allocator<MeshType>::DeleteFace(m,ff); count_fd++; } } } return count_fd; } /* The following functions remove faces that are geometrically "bad" according to edges and area criteria. They remove the faces that are out of a given range of area or edges (e.g. faces too large or too small, or with edges too short or too long) but that could be topologically correct. These functions can optionally take into account only the selected faces. */ template<bool Selected> static int RemoveFaceOutOfRangeAreaSel(MeshType& m, ScalarType MinAreaThr=0, ScalarType MaxAreaThr=(std::numeric_limits<ScalarType>::max)()) { FaceIterator fi; int count_fd = 0; MinAreaThr*=2; MaxAreaThr*=2; for(fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) if(!Selected || (*fi).IsS()) { const ScalarType doubleArea=DoubleArea<FaceType>(*fi); if((doubleArea<=MinAreaThr) || (doubleArea>=MaxAreaThr) ) { Allocator<MeshType>::DeleteFace(m,*fi); count_fd++; } } return count_fd; } // alias for the old style. Kept for backward compatibility static int RemoveZeroAreaFace(MeshType& m) { return RemoveFaceOutOfRangeArea(m);} // Aliases for the functions that do not look at selection static int RemoveFaceOutOfRangeArea(MeshType& m, ScalarType MinAreaThr=0, ScalarType MaxAreaThr=(std::numeric_limits<ScalarType>::max)()) { return RemoveFaceOutOfRangeAreaSel<false>(m,MinAreaThr,MaxAreaThr); } /** * Is the mesh only composed by quadrilaterals? */ static bool IsBitQuadOnly(const MeshType &m) { typedef typename MeshType::FaceType F; tri::RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->Flags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp != F::FAUX0 && tmp != F::FAUX1 && tmp != F::FAUX2) return false; } return true; } static bool IsFaceFauxConsistent(MeshType &m) { RequirePerFaceFlags(m); RequireFFAdjacency(m); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { for(int z=0;z<(*fi).VN();++z) { FacePointer fp = fi->FFp(z); int zp = fi->FFi(z); if(fi->IsF(z) != fp->IsF(zp)) return false; } } return true; } /** * Is the mesh only composed by triangles? (non polygonal faces) */ static bool IsBitTriOnly(const MeshType &m) { tri::RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if ( !fi->IsD() && fi->IsAnyF() ) return false; } return true; } static bool IsBitPolygonal(const MeshType &m){ return !IsBitTriOnly(m); } /** * Is the mesh only composed by quadrilaterals and triangles? (no pentas, etc) * It assumes that the bits are consistent. In that case there can be only a single faux edge. */ static bool IsBitTriQuadOnly(const MeshType &m) { tri::RequirePerFaceFlags(m); typedef typename MeshType::FaceType F; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp!=F::FAUX0 && tmp!=F::FAUX1 && tmp!=F::FAUX2 && tmp!=0 ) return false; } return true; } /** * How many quadrilaterals? * It assumes that the bits are consistent. In that case we count the tris with a single faux edge and divide by two. */ static int CountBitQuads(const MeshType &m) { tri::RequirePerFaceFlags(m); typedef typename MeshType::FaceType F; int count=0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp==F::FAUX0 || tmp==F::FAUX1 || tmp==F::FAUX2) count++; } return count / 2; } /** * How many triangles? (non polygonal faces) */ static int CountBitTris(const MeshType &m) { tri::RequirePerFaceFlags(m); int count=0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { if (!(fi->IsAnyF())) count++; } return count; } /** * How many polygons of any kind? (including triangles) * it assumes that there are no faux vertexes (e.g vertices completely surrounded by faux edges) */ static int CountBitPolygons(const MeshType &m) { tri::RequirePerFaceFlags(m); int count = 0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { if (fi->IsF(0)) count++; if (fi->IsF(1)) count++; if (fi->IsF(2)) count++; } return m.fn - count/2; } /** * The number of polygonal faces is * FN - EN_f (each faux edge hides exactly one triangular face or in other words a polygon of n edges has n-3 faux edges.) * In the general case where a The number of polygonal faces is * FN - EN_f + VN_f * where: * EN_f is the number of faux edges. * VN_f is the number of faux vertices (e.g vertices completely surrounded by faux edges) * as a intuitive proof think to a internal vertex that is collapsed onto a border of a polygon: * it deletes 2 faces, 1 faux edges and 1 vertex so to keep the balance you have to add back the removed vertex. */ static int CountBitLargePolygons(MeshType &m) { tri::RequirePerFaceFlags(m); UpdateFlags<MeshType>::VertexSetV(m); // First loop Clear all referenced vertices for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) for(int i=0;i<3;++i) fi->V(i)->ClearV(); // Second Loop, count (twice) faux edges and mark all vertices touched by non faux edges // (e.g vertexes on the boundary of a polygon) int countE = 0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;++i) { if (fi->IsF(i)) countE++; else { fi->V0(i)->SetV(); fi->V1(i)->SetV(); } } } // Third Loop, count the number of referenced vertexes that are completely surrounded by faux edges. int countV = 0; for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD() && !vi->IsV()) countV++; return m.fn - countE/2 + countV ; } /** * Checks that the mesh has consistent per-face faux edges * (the ones that merges triangles into larger polygons). * A border edge should never be faux, and faux edges should always be * reciprocated by another faux edges. * It requires FF adjacency. */ static bool HasConsistentPerFaceFauxFlag(const MeshType &m) { RequireFFAdjacency(m); RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) for (int k=0; k<3; k++) if( ( fi->IsF(k) != fi->cFFp(k)->IsF(fi->cFFi(k)) ) || ( fi->IsF(k) && face::IsBorder(*fi,k)) ) { return false; } return true; } /** * Count the number of non manifold edges in a polylinemesh, e.g. the edges where there are more than 2 incident faces. * */ static int CountNonManifoldEdgeEE( MeshType & m, bool SelectFlag=false) { assert(m.fn == 0 && m.en >0); // just to be sure we are using an edge mesh... RequireEEAdjacency(m); tri::UpdateTopology<MeshType>::EdgeEdge(m); if(SelectFlag) UpdateSelection<MeshType>::VertexClear(m); int nonManifoldCnt=0; SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0); // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter. EdgeIterator ei; for (ei = m.edge.begin(); ei != m.edge.end(); ++ei) if (!ei->IsD()) { TD[(*ei).V(0)]++; TD[(*ei).V(1)]++; } tri::UpdateFlags<MeshType>::VertexClearV(m); // Second Loop, Check that each vertex have been seen 1 or 2 times. for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD()) { if( TD[vi] >2 ) { if(SelectFlag) (*vi).SetS(); nonManifoldCnt++; } } return nonManifoldCnt; } /** * Count the number of non manifold edges in a mesh, e.g. the edges where there are more than 2 incident faces. * * Note that this test is not enough to say that a mesh is two manifold, * you have to count also the non manifold vertexes. */ static int CountNonManifoldEdgeFF( MeshType & m, bool SelectFlag=false) { RequireFFAdjacency(m); int nmfBit[3]; nmfBit[0]= FaceType::NewBitFlag(); nmfBit[1]= FaceType::NewBitFlag(); nmfBit[2]= FaceType::NewBitFlag(); UpdateFlags<MeshType>::FaceClear(m,nmfBit[0]+nmfBit[1]+nmfBit[2]); if(SelectFlag){ UpdateSelection<MeshType>::VertexClear(m); UpdateSelection<MeshType>::FaceClear(m); } int edgeCnt = 0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if (!fi->IsD()) { for(int i=0;i<3;++i) if(!IsManifold(*fi,i)) { if(!(*fi).IsUserBit(nmfBit[i])) { ++edgeCnt; if(SelectFlag) { (*fi).V0(i)->SetS(); (*fi).V1(i)->SetS(); } // follow the ring of faces incident on edge i; face::Pos<FaceType> nmf(&*fi,i); do { if(SelectFlag) nmf.F()->SetS(); nmf.F()->SetUserBit(nmfBit[nmf.E()]); nmf.NextF(); } while(nmf.f != &*fi); } } } } return edgeCnt; } /** Count (and eventually select) non 2-Manifold vertexes of a mesh * e.g. the vertices with a non 2-manif. neighbourhood but that do not belong to not 2-manif edges. * typical situation two cones connected by one vertex. */ static int CountNonManifoldVertexFF( MeshType & m, bool selectVert = true ) { RequireFFAdjacency(m); if(selectVert) UpdateSelection<MeshType>::VertexClear(m); int nonManifoldCnt=0; SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0); // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter. FaceIterator fi; for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { TD[(*fi).V(0)]++; TD[(*fi).V(1)]++; TD[(*fi).V(2)]++; } tri::UpdateFlags<MeshType>::VertexClearV(m); // Second Loop. // mark out of the game the vertexes that are incident on non manifold edges. for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;++i) if (!IsManifold(*fi,i)) { (*fi).V0(i)->SetV(); (*fi).V1(i)->SetV(); } } // Third Loop, for safe vertexes, check that the number of faces that you can reach starting // from it and using FF is the same of the previously counted. for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;i++) if(!(*fi).V(i)->IsV()){ (*fi).V(i)->SetV(); face::Pos<FaceType> pos(&(*fi),i); int starSizeFF = pos.NumberOfIncidentFaces(); if (starSizeFF != TD[(*fi).V(i)]) { if(selectVert) (*fi).V(i)->SetS(); nonManifoldCnt++; } } } return nonManifoldCnt; } /// Very simple test of water tightness. No boundary and no non manifold edges. /// Assume that it is orientable. /// It could be debated if a closed non orientable surface is watertight or not. /// /// The rationale of not testing orientability here is that /// it requires FFAdj while this test do not require any adjacency. /// static bool IsWaterTight(MeshType & m) { int edgeNum=0,edgeBorderNum=0,edgeNonManifNum=0; CountEdgeNum(m, edgeNum, edgeBorderNum,edgeNonManifNum); return (edgeBorderNum==0) && (edgeNonManifNum==0); } static void CountEdgeNum( MeshType & m, int &total_e, int &boundary_e, int &non_manif_e ) { std::vector< typename tri::UpdateTopology<MeshType>::PEdge > edgeVec; tri::UpdateTopology<MeshType>::FillEdgeVector(m,edgeVec,true); sort(edgeVec.begin(), edgeVec.end()); // Lo ordino per vertici total_e=0; boundary_e=0; non_manif_e=0; size_t f_on_cur_edge =1; for(size_t i=0;i<edgeVec.size();++i) { if(( (i+1) == edgeVec.size()) || !(edgeVec[i] == edgeVec[i+1])) { ++total_e; if(f_on_cur_edge==1) ++boundary_e; if(f_on_cur_edge>2) ++non_manif_e; f_on_cur_edge=1; } else { ++f_on_cur_edge; } } // end for } static int CountHoles( MeshType & m) { int numholev=0; FaceIterator fi; FaceIterator gi; vcg::face::Pos<FaceType> he; vcg::face::Pos<FaceType> hei; std::vector< std::vector<CoordType> > holes; //indices of vertices vcg::tri::UpdateFlags<MeshType>::VertexClearS(m); gi=m.face.begin(); fi=gi; for(fi=m.face.begin();fi!=m.face.end();fi++)//for all faces do { for(int j=0;j<3;j++)//for all edges { if(fi->V(j)->IsS()) continue; if(face::IsBorder(*fi,j))//found an unvisited border edge { he.Set(&(*fi),j,fi->V(j)); //set the face-face iterator to the current face, edge and vertex std::vector<CoordType> hole; //start of a new hole hole.push_back(fi->P(j)); // including the first vertex numholev++; he.v->SetS(); //set the current vertex as selected he.NextB(); //go to the next boundary edge while(fi->V(j) != he.v)//will we do not encounter the first boundary edge. { CoordType newpoint = he.v->P(); //select its vertex. if(he.v->IsS())//check if this vertex was selected already, because then we have an additional hole. { //cut and paste the additional hole. std::vector<CoordType> hole2; int index = static_cast<int>(find(hole.begin(),hole.end(),newpoint) - hole.begin()); for(unsigned int i=index; i<hole.size(); i++) hole2.push_back(hole[i]); hole.resize(index); if(hole2.size()!=0) //annoying in degenerate cases holes.push_back(hole2); } hole.push_back(newpoint); numholev++; he.v->SetS(); //set the current vertex as selected he.NextB(); //go to the next boundary edge } holes.push_back(hole); } } } return static_cast<int>(holes.size()); } /* Compute the set of connected components of a given mesh it fills a vector of pair < int , faceptr > with, for each connecteed component its size and a represnant */ static int CountConnectedComponents(MeshType &m) { std::vector< std::pair<int,FacePointer> > CCV; return ConnectedComponents(m,CCV); } static int ConnectedComponents(MeshType &m, std::vector< std::pair<int,FacePointer> > &CCV) { tri::RequireFFAdjacency(m); CCV.clear(); tri::UpdateSelection<MeshType>::FaceClear(m); std::stack<FacePointer> sf; FacePointer fpt=&*(m.face.begin()); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) { if(!((*fi).IsD()) && !(*fi).IsS()) { (*fi).SetS(); CCV.push_back(std::make_pair(0,&*fi)); sf.push(&*fi); while (!sf.empty()) { fpt=sf.top(); ++CCV.back().first; sf.pop(); for(int j=0;j<3;++j) { if( !face::IsBorder(*fpt,j) ) { FacePointer l = fpt->FFp(j); if( !(*l).IsS() ) { (*l).SetS(); sf.push(l); } } } } } } return int(CCV.size()); } static void ComputeValence( MeshType &m, typename MeshType::PerVertexIntHandle &h) { for(VertexIterator vi=m.vert.begin(); vi!= m.vert.end();++vi) h[vi]=0; for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) { if(!((*fi).IsD())) for(int j=0;j<fi->VN();j++) ++h[tri::Index(m,fi->V(j))]; } } /** GENUS. A topologically invariant property of a surface defined as the largest number of non-intersecting simple closed curves that can be drawn on the surface without separating it. Roughly speaking, it is the number of holes in a surface. The genus g of a closed surface, also called the geometric genus, is related to the Euler characteristic by the relation $chi$ by $chi==2-2g$. The genus of a connected, orientable surface is an integer representing the maximum number of cuttings along closed simple curves without rendering the resultant manifold disconnected. It is equal to the number of handles on it. For general polyhedra the <em>Euler Formula</em> is: V - E + F = 2 - 2G - B where V is the number of vertices, F is the number of faces, E is the number of edges, G is the genus and B is the number of <em>boundary polygons</em>. The above formula is valid for a mesh with one single connected component. By considering multiple connected components the formula becomes: V - E + F = 2C - 2Gs - B -> 2Gs = - ( V-E+F +B -2C) where C is the number of connected components and Gs is the sum of the genus of all connected components. Note that in the case of a mesh with boundaries the intuitive meaning of Genus is less intuitive that it could seem. A closed sphere, a sphere with one hole (e.g. a disk) and a sphere with two holes (e.g. a tube) all of them have Genus == 0 */ static int MeshGenus(int nvert,int nedges,int nfaces, int numholes, int numcomponents) { return -((nvert + nfaces - nedges + numholes - 2 * numcomponents) / 2); } static int MeshGenus(MeshType &m) { int nvert=m.vn; int nfaces=m.fn; int boundary_e,total_e,nonmanif_e; CountEdgeNum(m,total_e,boundary_e,nonmanif_e); int numholes=CountHoles(m); int numcomponents=CountConnectedComponents(m); int G=MeshGenus(nvert,total_e,nfaces,numholes,numcomponents); return G; } /** * Check if the given mesh is regular, semi-regular or irregular. * * Each vertex of a \em regular mesh has valence 6 except for border vertices * which have valence 4. * * A \em semi-regular mesh is derived from an irregular one applying * 1-to-4 subdivision recursively. (not checked for now) * * All other meshes are \em irregular. */ static void IsRegularMesh(MeshType &m, bool &Regular, bool &Semiregular) { RequireVFAdjacency(m); Regular = true; VertexIterator vi; // for each vertex the number of edges are count for (vi = m.vert.begin(); vi != m.vert.end(); ++vi) { if (!vi->IsD()) { face::Pos<FaceType> he((*vi).VFp(), &*vi); face::Pos<FaceType> ht = he; int n=0; bool border=false; do { ++n; ht.NextE(); if (ht.IsBorder()) border=true; } while (ht != he); if (border) n = n/2; if ((n != 6)&&(!border && n != 4)) { Regular = false; break; } } } if (!Regular) Semiregular = false; else { // For now we do not account for semi-regularity Semiregular = false; } } static bool IsCoherentlyOrientedMesh(MeshType &m) { for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) for(int i=0;i<3;++i) if(!face::CheckOrientation(*fi,i)) return false; return true; } static void OrientCoherentlyMesh(MeshType &m, bool &Oriented, bool &Orientable) { RequireFFAdjacency(m); assert(&Oriented != &Orientable); assert(m.face.back().FFp(0)); // This algorithms require FF topology initialized Orientable = true; Oriented = true; tri::UpdateSelection<MeshType>::FaceClear(m); std::stack<FacePointer> faces; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if (!fi->IsD() && !fi->IsS()) { // each face put in the stack is selected (and oriented) fi->SetS(); faces.push(&(*fi)); // empty the stack while (!faces.empty()) { FacePointer fp = faces.top(); faces.pop(); // make consistently oriented the adjacent faces for (int j = 0; j < 3; j++) { // get one of the adjacent face FacePointer fpaux = fp->FFp(j); int iaux = fp->FFi(j); if (!fpaux->IsD() && fpaux != fp && face::IsManifold<FaceType>(*fp, j)) { if (!CheckOrientation(*fpaux, iaux)) { Oriented = false; if (!fpaux->IsS()) { face::SwapEdge<FaceType,true>(*fpaux, iaux); assert(CheckOrientation(*fpaux, iaux)); } else { Orientable = false; break; } } // put the oriented face into the stack if (!fpaux->IsS()) { fpaux->SetS(); faces.push(fpaux); } } } } } if (!Orientable) break; } } /// Flip the orientation of the whole mesh flipping all the faces (by swapping the first two vertices) static void FlipMesh(MeshType &m, bool selected=false) { for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) if(!selected || (*fi).IsS()) { face::SwapEdge<FaceType,false>((*fi), 0); if (HasPerWedgeTexCoord(m)) std::swap((*fi).WT(0),(*fi).WT(1)); } } /// Flip a mesh so that its normals are orented outside. /// Just for safety it uses a voting scheme. /// It assumes that /// mesh has already has coherent normals. /// mesh is watertight and signle component. static bool FlipNormalOutside(MeshType &m) { if(m.vert.empty()) return false; tri::UpdateNormal<MeshType>::PerVertexAngleWeighted(m); tri::UpdateNormal<MeshType>::NormalizePerVertex(m); std::vector< VertexPointer > minVertVec; std::vector< VertexPointer > maxVertVec; // The set of directions to be choosen std::vector< CoordType > dirVec; dirVec.push_back(CoordType(1,0,0)); dirVec.push_back(CoordType(0,1,0)); dirVec.push_back(CoordType(0,0,1)); dirVec.push_back(CoordType( 1, 1,1)); dirVec.push_back(CoordType(-1, 1,1)); dirVec.push_back(CoordType(-1,-1,1)); dirVec.push_back(CoordType( 1,-1,1)); for(size_t i=0;i<dirVec.size();++i) { Normalize(dirVec[i]); minVertVec.push_back(&*m.vert.begin()); maxVertVec.push_back(&*m.vert.begin()); } for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if(!(*vi).IsD()) { for(size_t i=0;i<dirVec.size();++i) { if( (*vi).cP().dot(dirVec[i]) < minVertVec[i]->P().dot(dirVec[i])) minVertVec[i] = &*vi; if( (*vi).cP().dot(dirVec[i]) > maxVertVec[i]->P().dot(dirVec[i])) maxVertVec[i] = &*vi; } } int voteCount=0; ScalarType angleThreshold = cos(math::ToRad(85.0)); for(size_t i=0;i<dirVec.size();++i) { // qDebug("Min vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],minVertVec[i]->P()[0],minVertVec[i]->P()[1],minVertVec[i]->P()[2]); // qDebug("Max vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],maxVertVec[i]->P()[0],maxVertVec[i]->P()[1],maxVertVec[i]->P()[2]); if(minVertVec[i]->N().dot(dirVec[i]) > angleThreshold ) voteCount++; if(maxVertVec[i]->N().dot(dirVec[i]) < -angleThreshold ) voteCount++; } // qDebug("votecount = %i",voteCount); if(voteCount < int(dirVec.size())/2) return false; FlipMesh(m); return true; } // Search and remove small single triangle folds // - a face has normal opposite to all other faces // - choose the edge that brings to the face f1 containing the vertex opposite to that edge. static int RemoveFaceFoldByFlip(MeshType &m, float normalThresholdDeg=175, bool repeat=true) { RequireFFAdjacency(m); RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UpdateTopology<MeshType>::FaceFace(m); tri::UnMarkAll(m); count = 0; ScalarType NormalThrRad = math::ToRad(normalThresholdDeg); ScalarType eps = 0.0001; // this epsilon value is in absolute value. It is a distance from edge in baricentric coords. //detection stage for(FaceIterator fi=m.face.begin();fi!= m.face.end();++fi ) if(!(*fi).IsV()) { Point3<ScalarType> NN = vcg::TriangleNormal((*fi)).Normalize(); if( vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(0)).Normalize()) > NormalThrRad && vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(1)).Normalize()) > NormalThrRad && vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(2)).Normalize()) > NormalThrRad ) { (*fi).SetS(); //(*fi).C()=Color4b(Color4b::Red); // now search the best edge to flip for(int i=0;i<3;i++) { Point3<ScalarType> &p=(*fi).P2(i); Point3<ScalarType> L; bool ret = vcg::InterpolationParameters((*(*fi).FFp(i)),TriangleNormal(*(*fi).FFp(i)),p,L); if(ret && L[0]>eps && L[1]>eps && L[2]>eps) { (*fi).FFp(i)->SetS(); (*fi).FFp(i)->SetV(); //(*fi).FFp(i)->C()=Color4b(Color4b::Green); if(face::CheckFlipEdge<FaceType>( *fi, i )) { face::FlipEdge<FaceType>( *fi, i ); ++count; ++total; } } } } } // tri::UpdateNormal<MeshType>::PerFace(m); } while( repeat && count ); return total; } static int RemoveTVertexByFlip(MeshType &m, float threshold=40, bool repeat=true) { RequireFFAdjacency(m); RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UpdateTopology<MeshType>::FaceFace(m); tri::UnMarkAll(m); count = 0; //detection stage for(unsigned int index = 0 ; index < m.face.size(); ++index ) { FacePointer f = &(m.face[index]); float sides[3]; CoordType dummy; sides[0] = Distance(f->P(0), f->P(1)); sides[1] = Distance(f->P(1), f->P(2)); sides[2] = Distance(f->P(2), f->P(0)); // Find largest triangle side int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides); if( tri::IsMarked(m,f->V2(i) )) continue; if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] ) { tri::Mark(m,f->V2(i)); if(face::CheckFlipEdge<FaceType>( *f, i )) { // Check if EdgeFlipping improves quality FacePointer g = f->FFp(i); int k = f->FFi(i); Triangle3<ScalarType> t1(f->P(i), f->P1(i), f->P2(i)), t2(g->P(k), g->P1(k), g->P2(k)), t3(f->P(i), g->P2(k), f->P2(i)), t4(g->P(k), f->P2(i), g->P2(k)); if ( std::min( QualityFace(t1), QualityFace(t2) ) < std::min( QualityFace(t3), QualityFace(t4) )) { face::FlipEdge<FaceType>( *f, i ); ++count; ++total; } } } } // tri::UpdateNormal<MeshType>::PerFace(m); } while( repeat && count ); return total; } static int RemoveTVertexByCollapse(MeshType &m, float threshold=40, bool repeat=true) { RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UnMarkAll(m); count = 0; //detection stage for(unsigned int index = 0 ; index < m.face.size(); ++index ) { FacePointer f = &(m.face[index]); float sides[3]; CoordType dummy; sides[0] = Distance(f->P(0), f->P(1)); sides[1] = Distance(f->P(1), f->P(2)); sides[2] = Distance(f->P(2), f->P(0)); int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides); if( tri::IsMarked(m,f->V2(i) )) continue; if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] ) { tri::Mark(m,f->V2(i)); int j = Distance(dummy,f->P(i))<Distance(dummy,f->P1(i))?i:(i+1)%3; f->P2(i) = f->P(j); tri::Mark(m,f->V(j)); ++count; ++total; } } tri::Clean<MeshType>::RemoveDuplicateVertex(m); tri::Allocator<MeshType>::CompactFaceVector(m); tri::Allocator<MeshType>::CompactVertexVector(m); } while( repeat && count ); return total; } static bool SelfIntersections(MeshType &m, std::vector<FaceType*> &ret) { RequirePerFaceMark(m); ret.clear(); int referredBit = FaceType::NewBitFlag(); tri::UpdateFlags<MeshType>::FaceClear(m,referredBit); TriMeshGrid gM; gM.Set(m.face.begin(),m.face.end()); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { (*fi).SetUserBit(referredBit); Box3< ScalarType> bbox; (*fi).GetBBox(bbox); std::vector<FaceType*> inBox; vcg::tri::GetInBoxFace(m, gM, bbox,inBox); bool Intersected=false; typename std::vector<FaceType*>::iterator fib; for(fib=inBox.begin();fib!=inBox.end();++fib) { if(!(*fib)->IsUserBit(referredBit) && (*fib != &*fi) ) if(Clean<MeshType>::TestFaceFaceIntersection(&*fi,*fib)){ ret.push_back(*fib); if(!Intersected) { ret.push_back(&*fi); Intersected=true; } } } inBox.clear(); } FaceType::DeleteBitFlag(referredBit); return (ret.size()>0); } /** This function simply test that the vn and fn counters be consistent with the size of the containers and the number of deleted simplexes. */ static bool IsSizeConsistent(MeshType &m) { int DeletedVertNum=0; for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if((*vi).IsD()) DeletedVertNum++; int DeletedEdgeNum=0; for (EdgeIterator ei = m.edge.begin(); ei != m.edge.end(); ++ei) if((*ei).IsD()) DeletedEdgeNum++; int DeletedFaceNum=0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if((*fi).IsD()) DeletedFaceNum++; if(size_t(m.vn+DeletedVertNum) != m.vert.size()) return false; if(size_t(m.en+DeletedEdgeNum) != m.edge.size()) return false; if(size_t(m.fn+DeletedFaceNum) != m.face.size()) return false; return true; } /** This function simply test that all the faces have a consistent face-face topology relation. useful for checking that a topology modifying algorithm does not mess something. */ static bool IsFFAdjacencyConsistent(MeshType &m) { RequireFFAdjacency(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { for(int i=0;i<3;++i) if(!FFCorrectness(*fi, i)) return false; } return true; } /** This function simply test that a mesh has some reasonable tex coord. */ static bool HasConsistentPerWedgeTexCoord(MeshType &m) { tri::RequirePerFaceWedgeTexCoord(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { FaceType &f=(*fi); if( ! ( (f.WT(0).N() == f.WT(1).N()) && (f.WT(0).N() == (*fi).WT(2).N()) ) ) return false; // all the vertices must have the same index. if((*fi).WT(0).N() <0) return false; // no undefined texture should be allowed } return true; } /** Simple check that there are no face with all collapsed tex coords. */ static bool HasZeroTexCoordFace(MeshType &m) { tri::RequirePerFaceWedgeTexCoord(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { if( (*fi).WT(0).P() == (*fi).WT(1).P() && (*fi).WT(0).P() == (*fi).WT(2).P() ) return false; } return true; } /** This function test if two triangular faces of a mesh intersect. It assumes that the faces (as storage) are different (e.g different address) If the two faces are different but coincident (same set of vertexes) return true. if the faces share an edge no test is done. if the faces share only a vertex, the opposite edge is tested against the face */ static bool TestFaceFaceIntersection(FaceType *f0,FaceType *f1) { assert(f0!=f1); int sv = face::CountSharedVertex(f0,f1); if(sv==3) return true; if(sv==0) return (vcg::IntersectionTriangleTriangle<FaceType>((*f0),(*f1))); // if the faces share only a vertex, the opposite edge (as a segment) is tested against the face // to avoid degenerate cases where the two triangles have the opposite edge on a common plane // we offset the segment to test toward the shared vertex if(sv==1) { int i0,i1; ScalarType a,b; face::FindSharedVertex(f0,f1,i0,i1); CoordType shP = f0->V(i0)->P()*0.5; if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f0).V1(i0)->P()*0.5+shP,(*f0).V2(i0)->P()*0.5+shP), *f1, a, b) ) { // a,b are the param coords of the intersection point of the segment. if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false; return true; } if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f1).V1(i1)->P()*0.5+shP,(*f1).V2(i1)->P()*0.5+shP), *f0, a, b) ) { // a,b are the param coords of the intersection point of the segment. if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false; return true; } } return false; } /** This function merge all the vertices that are closer than the given radius */ static int MergeCloseVertex(MeshType &m, const ScalarType radius) { int mergedCnt=0; mergedCnt = ClusterVertex(m,radius); RemoveDuplicateVertex(m,true); return mergedCnt; } static int ClusterVertex(MeshType &m, const ScalarType radius) { if(m.vn==0) return 0; // some spatial indexing structure does not work well with deleted vertices... tri::Allocator<MeshType>::CompactVertexVector(m); typedef vcg::SpatialHashTable<VertexType, ScalarType> SampleSHT; SampleSHT sht; tri::EmptyTMark<MeshType> markerFunctor; std::vector<VertexType*> closests; int mergedCnt=0; sht.Set(m.vert.begin(), m.vert.end()); UpdateFlags<MeshType>::VertexClearV(m); for(VertexIterator viv = m.vert.begin(); viv!= m.vert.end(); ++viv) if(!(*viv).IsD() && !(*viv).IsV()) { (*viv).SetV(); Point3<ScalarType> p = viv->cP(); Box3<ScalarType> bb(p-Point3<ScalarType>(radius,radius,radius),p+Point3<ScalarType>(radius,radius,radius)); GridGetInBox(sht, markerFunctor, bb, closests); // qDebug("Vertex %i has %i closest", &*viv - &*m.vert.begin(),closests.size()); for(size_t i=0; i<closests.size(); ++i) { ScalarType dist = Distance(p,closests[i]->cP()); if(dist < radius && !closests[i]->IsV()) { // printf("%f %f \n",dist,radius); mergedCnt++; closests[i]->SetV(); closests[i]->P()=p; } } } return mergedCnt; } static std::pair<int,int> RemoveSmallConnectedComponentsSize(MeshType &m, int maxCCSize) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { std::vector<typename MeshType::FacePointer> FPV; if(CCV[i].first<maxCCSize) { DeletedCC++; for(ci.start(m,CCV[i].second);!ci.completed();++ci) FPV.push_back(*ci); typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /// Remove the connected components smaller than a given diameter // it returns a pair with the number of connected components and the number of deleted ones. static std::pair<int,int> RemoveSmallConnectedComponentsDiameter(MeshType &m, ScalarType maxDiameter) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; tri::ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { Box3<ScalarType> bb; std::vector<typename MeshType::FacePointer> FPV; for(ci.start(m,CCV[i].second);!ci.completed();++ci) { FPV.push_back(*ci); bb.Add((*ci)->P(0)); bb.Add((*ci)->P(1)); bb.Add((*ci)->P(2)); } if(bb.Diag()<maxDiameter) { DeletedCC++; typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) tri::Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /// Remove the connected components greater than a given diameter // it returns a pair with the number of connected components and the number of deleted ones. static std::pair<int,int> RemoveHugeConnectedComponentsDiameter(MeshType &m, ScalarType minDiameter) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; tri::ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { Box3f bb; std::vector<typename MeshType::FacePointer> FPV; for(ci.start(m,CCV[i].second);!ci.completed();++ci) { FPV.push_back(*ci); bb.Add((*ci)->P(0)); bb.Add((*ci)->P(1)); bb.Add((*ci)->P(2)); } if(bb.Diag()>minDiameter) { DeletedCC++; typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) tri::Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /** Select the folded faces using an angle threshold on the face normal. The face is selected if the dot product between the face normal and the normal of the plane fitted using the vertices of the one ring faces is below the cosThreshold. The cosThreshold requires a negative cosine value (a positive value is clamp to zero). */ static void SelectFoldedFaceFromOneRingFaces(MeshType &m, ScalarType cosThreshold) { tri::RequireVFAdjacency(m); tri::RequirePerFaceNormal(m); tri::RequirePerVertexNormal(m); vcg::tri::UpdateSelection<MeshType>::FaceClear(m); vcg::tri::UpdateNormal<MeshType>::PerFaceNormalized(m); vcg::tri::UpdateNormal<MeshType>::PerVertexNormalized(m); vcg::tri::UpdateTopology<MeshType>::VertexFace(m); if (cosThreshold > 0) cosThreshold = 0; #pragma omp parallel for schedule(dynamic, 10) for (int i = 0; i < m.face.size(); i++) { std::vector<typename MeshType::VertexPointer> nearVertex; std::vector<typename MeshType::CoordType> point; typename MeshType::FacePointer f = &m.face[i]; for (int j = 0; j < 3; j++) { std::vector<typename MeshType::VertexPointer> temp; vcg::face::VVStarVF<typename MeshType::FaceType>(f->V(j), temp); typename std::vector<typename MeshType::VertexPointer>::iterator iter = temp.begin(); for (; iter != temp.end(); iter++) { if ((*iter) != f->V1(j) && (*iter) != f->V2(j)) { nearVertex.push_back((*iter)); point.push_back((*iter)->P()); } } nearVertex.push_back(f->V(j)); point.push_back(f->P(j)); } if (point.size() > 3) { vcg::Plane3<typename MeshType::ScalarType> plane; vcg::FitPlaneToPointSet(point, plane); float avgDot = 0; for (int j = 0; j < nearVertex.size(); j++) avgDot += plane.Direction().dot(nearVertex[j]->N()); avgDot /= nearVertex.size(); typename MeshType::VertexType::NormalType normal; if (avgDot < 0) normal = -plane.Direction(); else normal = plane.Direction(); if (normal.dot(f->N()) < cosThreshold) f->SetS(); } } } }; // end class /*@}*/ } //End Namespace Tri } // End Namespace vcg #endif
transform_functions_fp32.h
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // 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. #ifndef CHEETAH_X86_TRANSFORM_FUNTIONS_FP32_H #define CHEETAH_X86_TRANSFORM_FUNTIONS_FP32_H #include "thread_affinity.h" template <U32 C, U32 N> inline void transformNCHWCxNx(U32 fc, U32 fh, U32 fw, U32 oc, const F32 *input, F32 *output) { F32 *dest = nullptr; const F32 *src; U32 cSize = 0, cSizePadding = 0; U32 lstep = fc * fh * fw; __m256i vindex = _mm256_set_epi32( lstep * 7, lstep * 6, lstep * 5, lstep * 4, lstep * 3, lstep * 2, lstep, 0); for (U32 c = 0; c < fc; c += cSize) { cSize = UNI_MIN(fc - c, C); cSizePadding = UNI_MIN(oc - c, C); for (U32 hw = 0; hw < fh * fw; ++hw) { for (U32 c8 = 0; c8 < cSize; ++c8) { src = input + (c + c8) * fh * fw + hw; dest = output + c * fh * fw * N + hw * cSizePadding * N + c8 * N; if (N >= 8) { _mm256_storeu_ps(dest, _mm256_i32gather_ps(src, vindex, 4)); } if (N >= 16) { _mm256_storeu_ps(dest + 8, _mm256_i32gather_ps(src + 8 * lstep, vindex, 4)); } if (N >= 24) { _mm256_storeu_ps(dest + 16, _mm256_i32gather_ps(src + 16 * lstep, vindex, 4)); } if (N == 32) { _mm256_storeu_ps(dest + 24, _mm256_i32gather_ps(src + 24 * lstep, vindex, 4)); } } UNI_MEMSET(dest + N, 0, ((cSizePadding - cSize) * N * 4)); } } } // N is 32/24 template <U32 C, U32 N> inline EE transformNCHWToNCHWCxNx( TensorDesc inputDesc, const F32 *input, TensorDesc outputDesc, F32 *output) { if (input == NULL || output == NULL) { CHECK_STATUS(NULL_POINTER); } DataType fdt, odt; DataFormat fdf, odf; U32 fn, fc, fh, fw; U32 on, oc, oh, ow; CHECK_STATUS(tensor4dGet(inputDesc, &fdt, &fdf, &fn, &fc, &fh, &fw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); U32 remain = fn % N; fn -= remain; for (U32 n = 0; n < fn; n += N) { transformNCHWCxNx<C, N>(fc, fh, fw, oc, input, output); input += fc * fh * fw * N; output += oc * fh * fw * N; } if (remain >= 24) { transformNCHWCxNx<C, 24>(fc, fh, fw, oc, input, output); input += fc * fh * fw * 24; output += oc * fh * fw * 24; remain -= 24; } if (remain >= 16) { transformNCHWCxNx<C, 16>(fc, fh, fw, oc, input, output); input += fc * fh * fw * 16; output += oc * fh * fw * 16; remain -= 16; } if (remain >= 8) { transformNCHWCxNx<C, 8>(fc, fh, fw, oc, input, output); input += fc * fh * fw * 8; output += oc * fh * fw * 8; remain -= 8; } if (remain > 0) { F32 *dest = NULL; U32 cSize = 0, cSizePadding = 0; F32 m[8] = {0.0f}; for (U32 i = 0; i < remain; ++i) { m[i] = -1.0f; } __m256 mask = _mm256_set_ps(m[7], m[6], m[5], m[4], m[3], m[2], m[1], m[0]); U32 lstep = fc * fh * fw; __m256i vindex = _mm256_set_epi32( lstep * 7, lstep * 6, lstep * 5, lstep * 4, lstep * 3, lstep * 2, lstep, 0); __m256 src256 = _mm256_setzero_ps(); for (U32 c = 0; c < fc; c += cSize) { cSize = UNI_MIN(fc - c, C); cSizePadding = UNI_MIN(oc - c, C); for (U32 hw = 0; hw < fh * fw; ++hw) { for (U32 c8 = 0; c8 < cSize; ++c8) { const F32 *src = input + (c + c8) * fh * fw + hw; dest = output + c * fh * fw * 8 + hw * cSizePadding * 8 + c8 * 8; _mm256_storeu_ps(dest, _mm256_mask_i32gather_ps(src256, src, vindex, mask, 4)); } UNI_MEMSET(dest + 8, 0, ((cSizePadding - cSize) * 32)); } } fn += remain; } return SUCCESS; } inline void PaddingNCHWC8( F32 *data, F32 *tmp, TensorDesc inputDesc, ConvolutionParamSpec convParamSpec) { // NCHWC8 DataType idt; DataFormat idf; U32 in, ic, ih, iw; CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); U32 paddingT = convParamSpec.pad_top; U32 paddingB = convParamSpec.pad_bottom; U32 paddingL = convParamSpec.pad_left; U32 paddingR = convParamSpec.pad_right; U32 padih = paddingT + paddingB + ih; U32 padiw = paddingL + paddingR + iw; CHECK_REQUIREMENT((idf == DF_NCHWC8) && (ic % 8 == 0)); ic /= 8; #ifdef _USE_OPENMP #pragma omp parallel num_threads(OMP_NUM_THREADS) { #endif #ifdef _USE_OPENMP #pragma omp for schedule(static) #endif for (U32 c = 0; c < ic; ++c) { U32 coff = c * padih * padiw * 8; UNI_MEMSET(tmp + coff, 0, padiw * paddingT * 8 * bytesOf(idt)); UNI_MEMSET( tmp + coff + (ih + paddingT) * padiw * 8, 0, padiw * paddingB * 8 * bytesOf(idt)); } #ifdef _USE_OPENMP #pragma omp for schedule(static) #endif for (U32 hc = 0; hc < ih * ic; ++hc) { U32 c = hc / ih; U32 coff = c * padih * padiw * 8; U32 h = hc % ih; U32 hoff = (h + paddingT) * padiw; UNI_MEMSET(tmp + coff + hoff * 8, 0, paddingL * 8 * bytesOf(idt)); UNI_MEMCPY(tmp + coff + (hoff + paddingL) * 8, data + c * ih * iw * 8 + h * iw * 8, iw * 8 * bytesOf(idt)); UNI_MEMSET(tmp + coff + (hoff + (paddingL + iw)) * 8, 0, paddingR * 8 * bytesOf(idt)); } #ifdef _USE_OPENMP } #endif } inline void deconvOverlapAndCrop(F32 *input, F32 *output, TensorDesc inputDesc, TensorDesc outputDesc, ConvolutionParamSpec convParamSpec) { DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); U32 fh = convParamSpec.kernel_h; U32 fw = convParamSpec.kernel_w; U32 fhfw = fh * fw; U32 strideH = convParamSpec.stride_h; U32 strideW = convParamSpec.stride_w; U32 paddingT = convParamSpec.pad_top; U32 paddingL = convParamSpec.pad_left; __m256i vindex = _mm256_set_epi32(fhfw * 7, fhfw * 6, fhfw * 5, fhfw * 4, fhfw * 3, fhfw * 2, fhfw, 0); for (U32 kn = 0; kn < in; ++kn) { for (U32 kh = 0; kh < ih; ++kh) { for (U32 kw = 0; kw < iw; ++kw) { for (U32 kc = 0; kc < oc; kc += 8) { for (U32 jh = 0; jh < fh; ++jh) { for (U32 jw = 0; jw < fw; ++jw) { U32 ohIdx = kh * strideH + jh; U32 owIdx = kw * strideW + jw; if ((ohIdx < paddingT) || (ohIdx >= oh + paddingT) || (owIdx < paddingL) || (owIdx >= ow + paddingL)) { continue; } ohIdx -= paddingT; owIdx -= paddingL; U32 oidx = (kc * oh + ohIdx * 8) * ow + owIdx * 8; U32 iidx = ((kh * iw + kw) * oc + kc) * fhfw + jh * fw + jw; __m256 x = _mm256_i32gather_ps(input + iidx, vindex, 4); x = _mm256_add_ps(x, _mm256_loadu_ps(output + oidx)); _mm256_storeu_ps(output + oidx, x); } } } } } input += oc * fh * fw * ih * iw; output += oc * oh * ow; } } inline void deconvOverlapAndCropNCHWC8(F32 *input, F32 *output, TensorDesc inputDesc, TensorDesc outputDesc, ConvolutionParamSpec convParamSpec) { DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); U32 fh = convParamSpec.kernel_h; U32 fw = convParamSpec.kernel_w; U32 fhfw = fh * fw; U32 strideH = convParamSpec.stride_h; U32 strideW = convParamSpec.stride_w; U32 paddingT = convParamSpec.pad_top; U32 paddingL = convParamSpec.pad_left; for (U32 kn = 0; kn < in; ++kn) { for (U32 kh = 0; kh < ih; ++kh) { for (U32 kw = 0; kw < iw; ++kw) { for (U32 kc = 0; kc < oc; kc += 8) { for (U32 jh = 0; jh < fh; ++jh) { for (U32 jw = 0; jw < fw; ++jw) { U32 ohIdx = kh * strideH + jh; U32 owIdx = kw * strideW + jw; if ((ohIdx < paddingT) || (ohIdx >= oh + paddingT) || (owIdx < paddingL) || (owIdx >= ow + paddingL)) { continue; } ohIdx -= paddingT; owIdx -= paddingL; U32 oidx = (kc * oh + ohIdx * 8) * ow + owIdx * 8; U32 iidx = ((jh * fw + jw) * oc + kc) * ih * iw + kh * iw * 8 + kw * 8; _mm256_storeu_ps(output + oidx, _mm256_add_ps( _mm256_loadu_ps(input + iidx), _mm256_loadu_ps(output + oidx))); } } } } } input += oc * fh * fw * ih * iw; output += oc * oh * ow; } } inline void deconvOverlapAndCropEqualNCHWC8(F32 *input, F32 *output, const F32 *bias, TensorDesc inputDesc, TensorDesc outputDesc, ConvolutionParamSpec convParamSpec) { DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); U32 fh = convParamSpec.kernel_h; U32 fw = convParamSpec.kernel_w; U32 fhfw = fh * fw; U32 strideH = convParamSpec.stride_h; U32 strideW = convParamSpec.stride_w; U32 paddingT = convParamSpec.pad_top; U32 paddingL = convParamSpec.pad_left; for (U32 kn = 0; kn < in; ++kn) { for (U32 kc = 0; kc < oc; kc += 8) { #ifdef _USE_OPENMP #pragma omp parallel for num_threads(OMP_NUM_THREADS) schedule(static) #endif for (U32 kh = 0; kh < ih; ++kh) { for (U32 kw = 0; kw < iw; ++kw) { for (U32 jh = 0; jh < fh; ++jh) { for (U32 jw = 0; jw < fw; ++jw) { U32 ohIdx = kh * strideH + jh; U32 owIdx = kw * strideW + jw; if ((ohIdx < paddingT) || (ohIdx >= oh + paddingT) || (owIdx < paddingL) || (owIdx >= ow + paddingL)) { continue; } ohIdx -= paddingT; owIdx -= paddingL; U32 oidx = (kc * oh + ohIdx * 8) * ow + owIdx * 8; U32 iidx = ((jh * fw + jw) * oc + kc) * ih * iw + kh * iw * 8 + kw * 8; _mm256_storeu_ps(output + oidx, _mm256_loadu_ps(input + iidx)); } } } } } input += oc * fh * fw * ih * iw; output += oc * oh * ow; } } #endif
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * 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] = 24; tile_size[1] = 24; tile_size[2] = 4; tile_size[3] = 2048; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. 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 ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,3);t1++) { lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6)); ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(1,ceild(24*t2-Nz+9,4)),3*t1+1),6*t1-6*t2+2);t3<=min(min(min(floord(4*Nt+Ny-9,4),floord(12*t1+Ny+15,4)),floord(24*t2+Ny+11,4)),floord(24*t1-24*t2+Nz+Ny+13,4));t3++) { for (t4=max(max(max(max(0,ceild(3*t1-3*t2-254,256)),ceild(3*t1-510,512)),ceild(24*t2-Nz-2035,2048)),ceild(4*t3-Ny-2035,2048));t4<=min(min(min(min(floord(4*Nt+Nx-9,2048),floord(12*t1+Nx+15,2048)),floord(24*t2+Nx+11,2048)),floord(4*t3+Nx-9,2048)),floord(24*t1-24*t2+Nz+Nx+13,2048));t4++) { for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(4*t3-Ny+5,4)),ceild(2048*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),Nt-1),3*t1+5),6*t2+4),t3-1),512*t4+510);t5++) { for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=4*t3;t7<=min(4*t3+3,4*t5+Ny-5);t7++) { lbv=max(2048*t4,4*t5+4); ubv=min(2048*t4+2047,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ 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; }
utility.c
#include <assert.h> #include "utility.h" #include "ptools_ppf.h" #include <string.h> //prints out a 3d matrix void printMatrix(REAL *** mat,int x,int y,int z){ int i1,i2,i3; for(i3=0;i3<z;i3++){ printf("\n z=%d", i3); for(i2=0;i2<y;i2++){ printf("\n"); for(i1=0;i1<x;i1++){ printf("%f ", mat[i3][i2][i1]); } } } } //merges striped matrices together REAL *** merge_matrices(REAL*** mat1, REAL *** mat2,int x1, int y1, int z1, int x2, int y2, int z2, bool buffer){ int start = buffer ? 1 : 0; //offfset by 1 if there is a buffer //only expands in the z dimension REAL *** result = alloc3D((x1),(y1),(z1+z2)); int i1,i2,i3; //copy matrix 1 for(i3=buffer;i3<(z1);i3++){ for(i2=buffer;i2<(y1-buffer);i2++){ for(i1=buffer;i1<(x1-buffer);i1++){ result[i3][i2][i1] = mat1[i3][i2][i1]; } } } //copy matrix 2 for(i3=z1;i3<(z1+z2-buffer);i3++){ for(i2=buffer;i2<(y1-buffer);i2++){ for(i1=buffer;i1<(x1-buffer);i1++){ result[i3][i2][i1] = mat2[i3 - z1 + buffer][i2][i1]; } } } return result; } //even processors send data first and then receive while odd ones are in the other order. REAL ** exchange_data(REAL** data,int size){ //REAL ** messages = (REAL**) malloc(sizeof(REAL**)*2); //messages[0] = (REAL*) malloc(sizeof(REAL*)*size); //messages[1] = (REAL*) malloc(sizeof(REAL*)*size); REAL **messages = alloc2D(2, size); MPI_Request lr_req = MPI_REQUEST_NULL, rr_req = MPI_REQUEST_NULL; MPI_Request ls_req = MPI_REQUEST_NULL, rs_req = MPI_REQUEST_NULL; MPI_Status status; // initiate receive from the left and send to the left if(global_params->mpi_rank != 0){ //MPI_Request lr_req, rr_req; MPI_Irecv(messages[0],size, MPI_DOUBLE, global_params->mpi_rank - global_params->neig_offset, 1,MPI_COMM_WORLD, &lr_req); MPI_Isend(data[0], size, MPI_DOUBLE, global_params->mpi_rank - global_params->neig_offset, 2, MPI_COMM_WORLD, &ls_req); } // initiate receive from the right and send to the right if(global_params->mpi_rank != global_params->mpi_size-1){ //MPI_Request ls_req, rs_req; MPI_Irecv(messages[1], size, MPI_DOUBLE, global_params->mpi_rank + global_params->neig_offset, 2,MPI_COMM_WORLD,&rr_req); MPI_Isend(data[1], size, MPI_DOUBLE, global_params->mpi_rank + global_params->neig_offset, 1, MPI_COMM_WORLD,&rs_req); } MPI_Wait(&lr_req, &status); MPI_Wait(&ls_req, &status); MPI_Wait(&rr_req, &status); MPI_Wait(&rs_req, &status); return messages; } //returns the ghost cells for a matrix (so that they can be sent to neigbor processors) //currently returns front and back planes- REAL ** getGhostCells(REAL*** mat,int x,int y, int z){ int i2,i1; int offset = (x)*(y); //plane size REAL **ghost_cells = alloc2D(2, offset); //note: the matrix is already padded with boundary data so it must be offset by 1 for(i2=0;i2<y;i2++){ for(i1=0;i1<x;i1++){ //get first plane ghost_cells[0][(i2)*(x) + i1] = mat[0+1][i2][i1]; //get last plane ghost_cells[1][(i2)*(x) + i1] = mat[z-1-1][i2][i1]; } } return ghost_cells; } // REAL ** splitMatrix //given a 3d matrix, returns the strip that a processor should have //has the option to maintain boundary points on the result matrix //TODO : current split values: 258x258x129- should this be 258x258x130?= //n1,n2,n3 are input REAL *** splitMatrix(REAL*** mat,int x,int y,int z,int processorID,int size,bool addBuffer){ int i3,i2,i1; int z_size = (z - 2) / size + 2; //130 int offset = (z_size - 2) * processorID; //128 offset per processor //allocate 3D strip matrix REAL*** strip = alloc3D(x,y,z_size); for(i3=1;i3<z_size-1;i3++){ for(i2=1;i2<y-1;i2++){ for(i1=1;i1<x-1;i1++){ strip[i3][i2][i1] = mat[i3 + offset][i2][i1]; } } } return strip; } //opposite of flatten matrix REAL *** unflattenMatrix(REAL* mat,int x,int y,int z){ REAL *** data = alloc3D(x,y,z); int i3,i2,i1; // printf(" unflat Values: %dx%dx%d\n ", x, y, z ); //map 3D matrix to 1D for(i3=0;i3<z;i3++){ for(i2=0;i2<y;i2++){ for(i1=0;i1<x;i1++){ data[i3][i2][i1] = mat[i3*x*y + i2*x + i1]; } } } return data; } /*flatten function: Given matrix pointer, x,y,z sizes, return 1D matrix */ REAL * flattenMatrix(REAL*** mat,int x,int y,int z){ REAL * data = (REAL*) malloc(sizeof(REAL)*x*y*z); // printf(" flat Values: %dx%dx%d\n ", x, y, z ); int i3,i2,i1; //map 3D matrix to 1D for(i3=0;i3<z;i3++){ for(i2=0;i2<y;i2++){ for(i1=0;i1<x;i1++){ data[i3*x*y + i2*x + i1] = mat[i3][i2][i1]; } } } return data; } double TestNorm(double r[],int n1,int n2,int n3) { double rnm2=0.0; int i1,i2,i3; for(i3=1;i3<n3-1;i3++) for(i2=1;i2<n2-1;i2++) for(i1=1;i1<n1-1;i1++) rnm2+=r[i1+n1*(i2+n2*i3)]*r[i1+n1*(i2+n2*i3)]; rnm2 = sqrt( rnm2 / ((double)n1*n2*n3)); printf("*****TestNorm %f\n", rnm2); return rnm2; } //Fill the 3-dimensional array z with zeroes void zero3(double ***z,int n1,int n2,int n3) { int i1, i2, i3; #pragma omp parallel for private(i1,i2,i3) for(i3=0;i3<n3;i3++) for(i2=0;i2<n2;i2++) for(i1=0;i1<n1;i1++) z[i3][i2][i1] = 0.; //[off+i1+n1*i2+n1*n2*i3]=0.0; } //Fill the 3-dimensional array z with zeroes void zero3old(double z[],int off,int n1,int n2,int n3) { int i1, i2, i3; #pragma omp parallel for private(i1,i2,i3) for(i3=0;i3<n3;i3++) for(i2=0;i2<n2;i2++) for(i1=0;i1<n1;i1++) z[off+i1+n1*i2+n1*n2*i3]=0.0; } //bubble does a bubble sort in direction dir void bubble(double ten[],int j1[],int j2[],int j3[],int m,int ind ) { double temp; int i, j_temp=0; if( ind == 1 ) { for(i=0;i<m-1;i++) { if( ten[i+m*ind] > ten[i+1+m*ind] ) { temp = ten[i+1+m*ind]; ten[i+1+m*ind] = ten[i+m*ind]; ten[i+m*ind] = temp; j_temp = j1[i+1+m*ind]; j1[i+1+m*ind] = j1[i+m*ind]; j1[i+m*ind] = j_temp; j_temp = j2[i+1+m*ind]; j2[i+1+m*ind] = j2[i+m*ind]; j2[i+m*ind] = j_temp; j_temp = j3[ i+1+m*ind ]; j3[i+1+m*ind] = j3[ i+m*ind ]; j3[i+m*ind] = j_temp; } else { return; } } } else { for(i=0;i<m-1;i++) { if( ten[i+m*ind] < ten[i+1+m*ind] ) { temp = ten[i+1+m*ind]; ten[i+1+m*ind] = ten[i+m*ind]; ten[i+m*ind] = temp; j_temp = j1[i+1+m*ind]; j1[i+1+m*ind] = j1[i+m*ind]; j1[i+m*ind] = j_temp; j_temp = j2[i+1+m*ind]; j2[i+1+m*ind] = j2[i+m*ind]; j2[i+m*ind] = j_temp; j_temp = j3[ i+1+m*ind ]; j3[i+1+m*ind] = j3[ i+m*ind ]; j3[i+m*ind] = j_temp; } else { return; } } } } REAL **alloc2D(int n, int m){ int i; REAL ** buffer = (REAL**) malloc(sizeof(REAL*)*n); for(i=0; i<n; i++){ buffer[i] = (REAL*) malloc(sizeof(REAL)*m); } return buffer; } void free2D(REAL** buffer, int n){ int i; for(i=0; i<n; i++){ free(buffer[i]); } free(buffer); } REAL ***alloc3D(int n, int m,int k) { REAL ***m_buffer=NULL; int nx=n, ny=m, nk = k; m_buffer = (REAL***)malloc(sizeof(REAL**)* nk); assert(m_buffer); REAL** m_tempzy = (REAL**)malloc(sizeof(REAL*)* nk * ny); REAL *m_tempzyx = (REAL*)malloc(sizeof(REAL)* nx * ny * nk ); int z,y; for ( z = 0 ; z < nk ; z++, m_tempzy += ny ) { m_buffer[z] = m_tempzy; for ( y = 0 ; y < ny ; y++, m_tempzyx += nx ) { m_buffer[z][y] = m_tempzyx; } } return m_buffer; } void free3D(REAL*** arr) { free(arr[0][0]); free(arr[0]); free(arr); } void free3D_old(REAL*** arr, int n, int m){ int i,j; for(i=0; i<n; i++){ for(j=0; j<m; j++){ free(arr[i][j]); } free(arr[i]); } free(arr); } REAL **** allocGrids(size_t depth, size_t n1, size_t n2, size_t n3, size_t pad) { size_t _n1 = n1, _n2 = n2, _n3 = n3; long total = 0; size_t indexes = 0; size_t zsize = 0, zysize = 0; long i,d,z,y; for (i = 0; i < depth; i++) { total += (_n1+pad)*(_n2+pad)*(_n3+pad); zsize += (_n1+pad); zysize += (_n1+pad)*(_n2+pad); _n1 /= 2; _n2 /= 2; _n3 /= 2; } REAL**** buffer = (REAL****) malloc(sizeof(REAL***)* depth); REAL*** tempdz = (REAL***) malloc(sizeof(REAL**) * zsize); REAL** tempdzy = (REAL**) malloc(sizeof(REAL*) * zysize); REAL* tempdzyx = (REAL*) malloc(sizeof(REAL) * total); _n1 = n1; _n2 = n2; _n3 = n3; for (d = 0; d < depth; d++) { buffer[d] = tempdz; for (z = 0; z < _n1+pad; z++, tempdzy += _n2+pad) { buffer[d][z] = tempdzy; for (y = 0; y < _n2+pad; y++, tempdzyx += _n3+pad) { buffer[d][z][y] = tempdzyx; } } tempdz += _n1+pad; _n1 /= 2; _n2 /= 2; _n3 /= 2; } return buffer; } void freeGrids(REAL**** grids) { free(grids[0][0][0]); free(grids[0][0]); free(grids[0]); free(grids); }
GB_unop__lnot_uint16_uint16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__lnot_uint16_uint16) // op(A') function: GB (_unop_tran__lnot_uint16_uint16) // C type: uint16_t // A type: uint16_t // cast: uint16_t cij = aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint16_t #define GB_CTYPE \ uint16_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 != 0) ; // casting #define GB_CAST(z, aij) \ uint16_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint16_t z = aij ; \ Cx [pC] = !(z != 0) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__lnot_uint16_uint16) ( uint16_t *Cx, // Cx and Ax may be aliased const uint16_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++) { uint16_t aij = Ax [p] ; uint16_t z = aij ; Cx [p] = !(z != 0) ; } } 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 ; uint16_t aij = Ax [p] ; uint16_t z = aij ; Cx [p] = !(z != 0) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__lnot_uint16_uint16) ( 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
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // 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/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/LocInfoType.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.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/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include <deque> #include <memory> #include <string> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; class InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class AttributeList; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; 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 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 ExternalSemaSource; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; 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 OMPClause; 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 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 CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class TemplateDeductionInfo; } // 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; /// Sema - This implements semantic analysis and AST building for C. class Sema { Sema(const Sema &) LLVM_DELETED_FUNCTION; void operator=(const Sema &) LLVM_DELETED_FUNCTION; ///\brief Source of additional semantic information. ExternalSemaSource *ExternalSource; ///\brief Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); static bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { // We are about to link these. It is now safe to compute the linkage of // the new decl. If the new decl has external linkage, we will // link it with the hidden decl (which also has external linkage) and // it will keep having external linkage. If it has internal linkage, we // will not link it. Since it has no previous decls, it will remain // with internal linkage. return !Old->isHidden() || New->isExternallyVisible(); } 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; /// \brief Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// \brief Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// \brief 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; /// PackContext - Manages the stack for \#pragma pack. An alignment /// of 0 indicates default alignment. void *PackContext; // Really a "PragmaPackStack*" bool MSStructPragmaOn; // True when \#pragma ms_struct on /// \brief Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; enum PragmaVtorDispKind { PVDK_Push, ///< #pragma vtordisp(push, mode) PVDK_Set, ///< #pragma vtordisp(mode) PVDK_Pop, ///< #pragma vtordisp(pop) PVDK_Reset ///< #pragma vtordisp() }; enum PragmaMsStackAction { PSK_Reset, // #pragma () PSK_Set, // #pragma ("name") PSK_Push, // #pragma (push[, id]) PSK_Push_Set, // #pragma (push[, id], "name") PSK_Pop, // #pragma (pop[, id]) PSK_Pop_Set, // #pragma (pop[, id], "name") }; /// \brief 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 /// /// The stack always has at least one element in it. SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack; /// \brief Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value); explicit PragmaStack(const ValueType &Value) : CurrentValue(Value) {} SmallVector<Slot, 2> Stack; 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). PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// \brief 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; /// \brief 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; /// ExprNeedsCleanups - True if the current evaluation context /// requires cleanups to be run at its conclusion. bool ExprNeedsCleanups; /// 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; /// \brief Store a list 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. llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs; /// \brief Stack containing information about each of the nested /// function, block, and method scopes that are currently active. /// /// This array is never empty. Clients should ignore the first /// element, which is used to cache a single FunctionScopeInfo /// that's used to parse every top-level function. 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<const NamedDecl*, 16> NamedDeclSetType; /// \brief Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// \brief Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; 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; /// \brief A mapping from external names to the most recent /// locally-scoped extern "C" declaration with that name. /// /// This map contains external declarations introduced in local /// scopes, e.g., /// /// \code /// extern "C" void f() { /// void foo(int, int); /// } /// \endcode /// /// Here, the name "foo" will be associated with the declaration of /// "foo" within f. This name is not visible outside of /// "f". However, we still find it in two cases: /// /// - If we are declaring another global or extern "C" entity with /// the name "foo", we can find "foo" as a previous declaration, /// so that the types of this external declaration can be checked /// for compatibility. /// /// - If we would implicitly declare "foo" (e.g., due to a call to /// "foo" in C when no prototype or definition is visible), then /// we find this declaration of "foo" and complain that it is /// not visible. llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls; /// \brief 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; /// \brief All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// \brief 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; /// \brief All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// \brief 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> DelayedExceptionSpecChecks; /// \brief All the members seen during a class definition which were both /// explicitly defaulted and had explicitly-specified exception /// specifications, along with the function type containing their /// user-specified exception specification. Those exception specifications /// were overridden with the default specifications, but we still need to /// check whether they are compatible with the default specification, and /// we can't do that until the nesting set of class definitions is complete. SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2> DelayedDefaultedMemberExceptionSpecs; typedef llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// \brief 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 { /// \brief 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(); } }; /// \brief RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); } ~SynthesizedFunctionScope() { S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::DenseMap<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; /// \brief 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; /// \brief The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// \brief The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// \brief Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// \brief The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// \brief Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// \brief The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// \brief The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// \brief Pointer to NSString type (NSString *). QualType NSStringPointer; /// \brief The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// \brief The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// \brief The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// \brief The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// \brief id<NSCopying> type. QualType QIDNSCopying; /// \brief will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// \brief counter for internal MS Asm label names. unsigned MSAsmLabelNameCounter; /// 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; /// \brief Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum ExpressionEvaluationContext { /// \brief 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, /// \brief 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, /// \brief 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, /// \brief 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, /// \brief 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 }; /// \brief Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// \brief The expression evaluation context. ExpressionEvaluationContext Context; /// \brief Whether the enclosing context needed a cleanup. bool ParentNeedsCleanups; /// \brief Whether we are in a decltype expression. bool IsDecltype; /// \brief The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// \brief The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs; /// \brief The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// \brief 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; /// \brief The context information used to mangle lambda expressions /// and block literals within this context. /// /// This mangling information is allocated lazily, since most contexts /// do not have lambda expressions or block literals. IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering; /// \brief 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; /// \brief 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; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, bool ParentNeedsCleanups, Decl *ManglingContextDecl, bool IsDecltype) : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups), IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), MangleNumbering() { } /// \brief Retrieve the mangling numbering context, used to consistently /// number constructs like lambdas for mangling. MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); bool isUnevaluated() const { return Context == Unevaluated || Context == UnevaluatedAbstract; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// \brief Compute the mangling number context for a lambda expression or /// block literal. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl /// associated with the context, if relevant. MangleNumberingContext *getCurrentMangleNumberContext( const DeclContext *DC, Decl *&ManglingContextDecl); /// 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 llvm::FastFoldingSetNode { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} 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); } }; /// \brief A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache; /// \brief 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; /// \brief The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// \brief 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::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed; /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 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::DenseMap<Selector, SourceLocation> ReferencedSelectors; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef std::pair<CXXRecordDecl*, 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::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; void ReadMethodPool(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// \brief 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), OldFPContractState(S.FPFeatures.fp_contract) {} ~FPContractStateRAII() { S.FPFeatures.fp_contract = OldFPContractState; } private: Sema& S; bool OldFPContractState : 1; }; void addImplicitTypedef(StringRef Name, QualType T); public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// \brief 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; } ///\brief 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; /// \brief 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) { } ~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; } }; /// \brief Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// \brief Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// \brief Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// \brief 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; /// \brief Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// \brief Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; void emitAndClearUnusedLocalTypedefWarnings(); void ActOnEndOfTranslationUnit(); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// \brief 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); void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, const BlockExpr *blkExpr = nullptr); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const { if (FunctionScopes.empty()) return nullptr; for (int e = FunctionScopes.size()-1; e >= 0; --e) { if (isa<sema::BlockScopeInfo>(FunctionScopes[e])) continue; return FunctionScopes[e]; } return nullptr; } template <typename ExprT> void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) { if (!isUnevaluatedContext()) getCurFunction()->recordUseOfWeak(E, IsRead); } void PushCompoundScope(); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// \brief Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// \brief Retrieve the current lambda scope info, if any. sema::LambdaScopeInfo *getCurLambda(); /// \brief Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// \brief 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 BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// \brief 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); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, TypeSourceInfo *ReturnTypeInfo); /// \brief 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, const 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 *MissingExceptionSpecification = nullptr, bool *MissingEmptyExceptionSpecification = nullptr, bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false); bool CheckExceptionSpecSubset( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// \brief The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// \brief Abstract class used to diagnose incomplete types. struct TypeDiagnoser { bool Suppressed; TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { } 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(Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template<typename T1> class BoundTypeDiagnoser1 : public TypeDiagnoser { unsigned DiagID; const T1 &Arg1; public: BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1) : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { if (Suppressed) return; S.Diag(Loc, DiagID) << getPrintable(Arg1) << T; } virtual ~BoundTypeDiagnoser1() { } }; template<typename T1, typename T2> class BoundTypeDiagnoser2 : public TypeDiagnoser { unsigned DiagID; const T1 &Arg1; const T2 &Arg2; public: BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1, const T2 &Arg2) : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), Arg2(Arg2) { } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { if (Suppressed) return; S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T; } virtual ~BoundTypeDiagnoser2() { } }; template<typename T1, typename T2, typename T3> class BoundTypeDiagnoser3 : public TypeDiagnoser { unsigned DiagID; const T1 &Arg1; const T2 &Arg2; const T3 &Arg3; public: BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), Arg2(Arg2), Arg3(Arg3) { } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { if (Suppressed) return; S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T; } virtual ~BoundTypeDiagnoser3() { } }; private: bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); public: bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID); template<typename T1> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1) { BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); return RequireCompleteType(Loc, T, Diagnoser); } template<typename T1, typename T2> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); return RequireCompleteType(Loc, T, Diagnoser); } template<typename T1, typename T2, typename T3> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); return RequireCompleteType(Loc, T, Diagnoser); } bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template<typename T1> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) { BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); return RequireCompleteExprType(E, Diagnoser); } template<typename T1, typename T2> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); return RequireCompleteExprType(E, Diagnoser); } template<typename T1, typename T2, typename T3> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); return RequireCompleteExprType(E, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template<typename T1> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1) { BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); return RequireLiteralType(Loc, T, Diagnoser); } template<typename T1, typename T2> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); return RequireLiteralType(Loc, T, Diagnoser); } template<typename T1, typename T2, typename T3> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); QualType BuildDecltypeType(Expr *E, SourceLocation Loc); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // /// List of decls defined in a function prototype. This contains EnumConstants /// that incorrectly end up in translation unit scope because there is no /// function to pin them on. ActOnFunctionDeclarator reads this list and patches /// them into the FunctionDecl. std::vector<NamedDecl*> DeclsInPrototypeScope; 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 = ParsedType(), bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, 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 AllowClassTemplates = false); /// \brief For compatibility with MSVC, we delay parsing of some default /// template type arguments until instantiation time. Emits a warning and /// returns a synthesized DependentNameType that isn't really dependent on any /// other template arguments. ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, SourceLocation NameLoc); /// \brief Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { NC_Unknown, NC_Error, NC_Keyword, NC_Type, NC_Expression, NC_NestedNameSpecifier, NC_TypeTemplate, NC_VarTemplate, NC_FunctionTemplate }; class NameClassification { NameClassificationKind Kind; ExprResult Expr; TemplateName Template; ParsedType Type; const IdentifierInfo *Keyword; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword), Keyword(Keyword) { } static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification NestedNameSpecifier() { return NameClassification(NC_NestedNameSpecifier); } 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; } NameClassificationKind getKind() const { return Kind; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } ExprResult getExpression() const { assert(Kind == NC_Expression); return Expr; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate); 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; default: llvm_unreachable("unsupported name classification."); } } }; /// \brief 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 IsAddressOfOperand True if this name is the operand of a unary /// address of ('&') expression, assuming it is classified as an /// expression. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, bool IsAddressOfOperand, std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr); 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); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); void CheckShadow(Scope *S, VarDecl *D); void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 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); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); void CheckCompleteVariableDeclaration(VarDecl *var); 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); bool CheckConstexprFunctionDecl(const FunctionDecl *FD); bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); 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 IsExplicitSpecialization); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); 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); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, bool TypeMayContainAuto); void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); void ActOnInitializerError(Decl *Dcl); 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 FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, bool TypeMayContainAuto = true); /// 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); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// \brief 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); /// \brief 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 ActOnFinishInlineMethodDef(CXXMethodDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// \brief Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, ParmVarDecl * const *End); /// \brief 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(ParmVarDecl * const *Begin, ParmVarDecl * const *End, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// \brief Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, AttributeList *AttrList, SourceLocation SemiLoc); /// \brief The parser has processed a module import declaration. /// /// \param AtLoc The location of the '@' symbol, if any. /// /// \param ImportLoc The location of the 'import' keyword. /// /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, ModuleIdPath Path); /// \brief The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// \brief 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); /// \brief Retrieve a suitable printing policy. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// \brief Retrieve a suitable printing policy. 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); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation = false); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); 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, AttributeList *Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *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, AttributeList *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); bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, bool Diagnose = false); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 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, AttributeList *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); 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, SourceLocation RBraceLoc); void ActOnObjCContainerFinishDefinition(); /// \brief 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, const EnumDecl *Prev); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, AttributeList *Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, SourceLocation RBraceLoc, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, AttributeList *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); /// \brief Make the given externally-produced declaration visible at the /// top level scope. /// /// \param D The externally-produced declaration to push. /// /// \param Name The name of the externally-produced declaration. void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); /// 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); /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool Override, unsigned AttrSpellingListIndex); TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, TypeVisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex); VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex); DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, unsigned AttrSpellingListIndex, MSInheritanceAttr::Spelling SemanticSpelling); FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, IdentifierInfo *Format, int FormatIdx, int FirstArg, unsigned AttrSpellingListIndex); SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex); /// \brief Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// \brief Don't merge availability attributes at all. AMK_None, /// \brief Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// \brief Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override }; void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(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 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); /// \brief Checks availability of the function depending on the current /// function context.Inside an unavailable function,unavailability is ignored. /// /// \returns true if \p FD is unavailable and current context is inside /// an available function, false otherwise. bool isFunctionConsideredUnavailable(FunctionDecl *FD); 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); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess); 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 IsNoReturnConversion(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 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); 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. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// \brief 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) {} /// \brief Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// \brief Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// \brief Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// \brief Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// \brief Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// \brief Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// \brief Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// \brief 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); } /// \brief 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::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = false); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false); void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false); void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet& CandidateSet, bool AllowObjCConversionOnExplicit); void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, SourceRange OpRange = SourceRange()); void AddBuiltinCandidate(QualType ResultTy, 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(FunctionDecl *Fn, QualType DestType = QualType()); // Emit as a series of 'note's all template and non-templates // identified by the expression Expr void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType()); /// 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); // [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 * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, const 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 }; // An enum to represent whether something is dealing with a call to begin() // or a call to end() in a range-based for loop. enum BeginEndFunction { BEF_begin, BEF_end }; ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, SourceLocation RangeLoc, VarDecl *Decl, BeginEndFunction BEF, 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 buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned Opc, const UnresolvedSetImpl &Fns, Expr *input); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, unsigned Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS); 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(ParmVarDecl *const *Param, ParmVarDecl *const *ParamEnd, 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. //@{ /// @brief 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, /// \brief Look up any declaration with any name. LookupAnyName }; /// \brief Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// \brief The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// \brief The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists. ForRedeclaration }; /// \brief The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// \brief The lookup resulted in an error. LOLR_Error, /// \brief The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// \brief The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// \brief 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, /// \brief 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) LLVM_NOEXCEPT; TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT; }; /// \brief The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// \brief Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC); // \brief 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; /// \brief Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// \brief 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, std::unique_ptr<CorrectionCandidateCallback> CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery, bool &IsUnqualifiedLookup); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// \brief Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// \brief 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 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); void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions, DeclAccessPair Operator, QualType T1, QualType T2); 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 isKnownName(StringRef name); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = 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, std::unique_ptr<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, std::unique_ptr<CorrectionCandidateCallback> CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); ExprResult CorrectDelayedTyposInExpr(Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr(ExprResult ER, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), 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 FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); 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); void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const AttributeList *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 AttributeList &attr, unsigned &value); bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckNoReturnAttr(const AttributeList &attr); bool checkStringLiteralArgumentAttr(const AttributeList &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); 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); // 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; /// \brief Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *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; typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; /// 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); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, ObjCInterfaceDecl *IDecl); void DefaultSynthesizeProperties(Scope *S, Decl *D); /// 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, Selector SetterSel, const bool isAssign, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, bool *isOverridingProperty, TypeSourceInfo *T, 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, Selector SetterSel, const bool isAssign, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, TypeSourceInfo *T, 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, ObjCContainerDecl* 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); /// \brief 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 warn, bool instance); public: /// \brief - Returns instance or factory methods in global method pool for /// given selector. If no such method or only one method found, function returns /// false; otherwise, it returns true bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool instance); bool AreMultipleMethodsInGlobalPool(Selector Sel, bool instance); private: /// \brief - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance); /// \brief Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true, bool IsUnqualifiedLookup = false) { if (IsUnqualifiedLookup) (void)UnqualifiedTyposCorrected[Typo]; 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, bool warn=true) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, warn, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false, bool warn=true) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, warn, /*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(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).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// \brief A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S): S(S) { S.ActOnStartOfCompoundStmt(); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, SourceLocation DotDotDotLoc, Expr *RHSVal, 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); StmtResult ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, Decl *CondVar); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, Decl *CondVar, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, FullExprArg Second, Decl *SecondVar, 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(SourceLocation ForLoc, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *BeginEndDecl, 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); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, bool AllowFunctionParameters); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, bool AllowFunctionParameters); 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, SourceLocation RParenLoc); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, llvm::InlineAsmIdentifierInfo &Info, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, 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); StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// \brief 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); 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); enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable }; void EmitAvailabilityWarning(AvailabilityDiagnostic AD, NamedDecl *D, StringRef Message, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass, const ObjCPropertyDecl *ObjCProperty, bool ObjCPropertyAccess); bool makeUnavailableInSystemHeader(SourceLocation loc, StringRef message); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D); bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false); void NoteDeletedFunction(FunctionDecl *FD); std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, bool IsDecltype = false); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, bool IsDecltype = false); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(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. void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool OdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E); void MarkMemberReferenced(MemberExpr *E); void UpdateMarkingForLValueToRValue(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// \brief 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); /// \brief Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// \brief Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// \brief 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); /// \brief Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// \brief 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); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr<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, std::unique_ptr<CorrectionCandidateCallback> CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); 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); ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, 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); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr( CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, 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::IdentType IT); 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); 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, const 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); // 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; bool HasTrailingLParen; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, 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, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 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, bool HasTrailingLParen); 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, bool IsExecConfig = false); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false); 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); /// \brief 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 ActOnDesignatedInitializer(Designation &Desig, SourceLocation Loc, 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); /// 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); // "({..})" 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, OffsetOfComponent *CompPtr, unsigned NumComponents, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, OffsetOfComponent *CompPtr, unsigned NumComponents, 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); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// \brief Describes the result of an "if-exists" condition check. enum IfExistsResult { /// \brief The symbol exists. IER_Exists, /// \brief The symbol does not exist. IER_DoesNotExist, /// \brief The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// \brief 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, AttributeList *AttrList); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); CXXRecordDecl *getStdBadAlloc() const; /// \brief 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); /// \brief 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); /// \brief Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const CXXConstructorDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, AttributeList *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, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, AttributeList *AttrList, bool IsInstantiation, bool HasTypenameKeyword, SourceLocation TypenameLoc); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, bool HasUsingKeyword, SourceLocation UsingLoc, CXXScopeSpec &SS, UnqualifiedId &Name, AttributeList *AttrList, bool HasTypenameKeyword, SourceLocation TypenameLoc); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, AttributeList *AttrList, TypeResult Type); /// 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, CXXConstructorDecl *Constructor, 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, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// 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); /// \brief 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; } /// \brief Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(ComputedEST != EST_ComputedNoexcept && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// \brief The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// \brief The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// \brief Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// \brief Integrate an invoked expression into the collected data. void CalledExpr(Expr *E); /// \brief 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_ComputedNoexcept; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// \brief Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// \brief 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); /// \brief Determine what sort of exception specification a defautled /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// \brief Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// \brief Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// \brief Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// \brief Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD); /// \brief Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, bool Diagnose = false); /// \brief 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); /// \brief 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); /// \brief 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(CXXRecordDecl *ClassDecl, CXXDestructorDecl *Destructor); /// \brief Declare all inheriting constructors for the given class. /// /// \param ClassDecl The class declaration into which the inheriting /// constructors will be added. void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl); /// \brief Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// \brief 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); /// \brief Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// \brief Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// \brief Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// \brief 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); /// \brief Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// \brief 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 getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorType(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 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); /// \brief 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); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// \brief Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// \brief 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; /// \brief 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: /// \brief 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, unsigned CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// \brief 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); /// \brief 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); /// 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); ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, bool IsThrownVarInScope); /// 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 LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc); /// 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, Expr *ArraySize, SourceRange DirectInitRange, Expr *Initializer, bool TypeMayContainAuto = true); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, bool UseGlobal, QualType AllocType, bool IsArray, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete); bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, DeclarationName Name, MultiExprArg Args, DeclContext *Ctx, bool AllowMissing, FunctionDecl *&Operator, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, QualType Param1, QualType Param2 = QualType(), bool addMallocAttr = false); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, DeclarationName Name); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, bool ConvertToBoolean); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// \brief 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 bianry 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 DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType, bool HasTrailingLParen); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName, bool HasTrailingLParen); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS, bool HasTrailingLParen); /// 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); ExprResult ActOnFinishFullExpr(Expr *Expr) { return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc() : SourceLocation()); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue = false, bool IsConstexpr = false, bool IsLambdaInitCaptureInitializer = 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); /// \brief 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); /// \brief 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); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation IdLoc, IdentifierInfo &II, ParsedType ObjectType); bool BuildCXXNestedNameSpecifier(Scope *S, IdentifierInfo &Identifier, SourceLocation IdentifierLoc, SourceLocation CCLoc, QualType ObjectType, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr); /// \brief The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param Identifier The identifier preceding the '::'. /// /// \param IdentifierLoc The location of the identifier. /// /// \param CCLoc The location of the '::'. /// /// \param ObjectType The type of the object, if we're parsing /// nested-name-specifier in a member access expression. /// /// \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 '::'. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, IdentifierInfo &Identifier, SourceLocation IdentifierLoc, SourceLocation CCLoc, ParsedType ObjectType, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, IdentifierInfo &Identifier, SourceLocation IdentifierLoc, SourceLocation ColonLoc, ParsedType ObjectType, bool EnteringContext); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// \brief Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params); /// \brief 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); /// \brief 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. QualType performLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, IdentifierInfo *Id, Expr *&Init); /// \brief 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, IdentifierInfo *Id, Expr *Init); /// \brief Build the implicit field for an init-capture. FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// \brief Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief Introduce the lambda parameters into scope. void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); /// \brief 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, bool IsInstantiation = false); /// \brief 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); /// \brief 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); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, Expr **Strings, unsigned NumStrings); 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 *" or "NSString *" depending on the type of /// ValueType, which is allowed to be a built-in numeric type or /// "char *" or "const char *". ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, ObjCDictionaryElement *Elements, unsigned NumElements); 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 // 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, AttributeList *Attrs = nullptr); 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); /// \brief 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; /// \brief The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// \brief 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; /// \brief Load any externally-stored vtable uses. void LoadExternalVTableUses(); typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDynamicClasses, 2, 2> DynamicClassesType; /// \brief A list of all of the dynamic classes in this translation /// unit. DynamicClassesType DynamicClasses; /// \brief Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// \brief 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); /// \brief 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); void CheckCompletedCXXClass(CXXRecordDecl *Record); void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList); void ActOnFinishCXXMemberDecls(); 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 CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, const FunctionProtoType *T); void CheckDelayedMemberExceptionSpecs(); //===--------------------------------------------------------------------===// // 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, CXXBaseSpecifier **Bases, unsigned NumBases); void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, unsigned NumBases); bool IsDerivedFrom(QualType Derived, QualType Base); bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool BasePathInvolvesVirtualBase(const 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); 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, const InitializedEntity &Entity, AccessSpecifier Access, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, const InitializedEntity &Entity, AccessSpecifier Access, 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 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, DeclContext *Ctx); 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); /// \brief 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 RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template<typename T1> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1) { BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); return RequireNonAbstractType(Loc, T, Diagnoser); } template<typename T1, typename T2> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); return RequireNonAbstractType(Loc, T, Diagnoser); } template<typename T1, typename T2, typename T3> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, AbstractDiagSelID SelID = AbstractNone); //===--------------------------------------------------------------------===// // 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 hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true); void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); Decl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); Decl *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, Decl **Params, unsigned NumParams, SourceLocation RAngleLoc); /// \brief 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); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid); DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false); /// \brief 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 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, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template); DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 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 CheckMemberSpecialization(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, AttributeList *Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *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); /// \brief Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// \brief The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// \brief The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// \brief 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); /// \brief 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. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted); 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 CheckTemplateArgument(TemplateTemplateParmDecl *Param, TemplateArgumentLoc &Arg, unsigned ArgumentPackIndex); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// \brief Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// \brief 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, /// \brief 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, /// \brief 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); /// \brief 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); /// \brief 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 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 ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, 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); //===--------------------------------------------------------------------===// // 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(); /// \brief 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 { /// \brief An arbitrary expression. UPPC_Expression = 0, /// \brief The base type of a class type. UPPC_BaseType, /// \brief The type of an arbitrary declaration. UPPC_DeclarationType, /// \brief The type of a data member. UPPC_DataMemberType, /// \brief The size of a bit-field. UPPC_BitFieldWidth, /// \brief The expression in a static assertion. UPPC_StaticAssertExpression, /// \brief The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// \brief The enumerator value. UPPC_EnumeratorValue, /// \brief A using declaration. UPPC_UsingDeclaration, /// \brief A friend declaration. UPPC_FriendDeclaration, /// \brief A declaration qualifier. UPPC_DeclarationQualifier, /// \brief An initializer. UPPC_Initializer, /// \brief A default argument. UPPC_DefaultArgument, /// \brief The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// \brief The type of an exception. UPPC_ExceptionType, /// \brief Partial specialization. UPPC_PartialSpecialization, /// \brief Microsoft __if_exists. UPPC_IfExists, /// \brief Microsoft __if_not_exists. UPPC_IfNotExists, /// \brief Lambda expression. UPPC_Lambda, /// \brief Block expression, UPPC_Block }; /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param SS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(CXXScopeSpec &SS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// \brief Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief 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; //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType); /// \brief 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 { /// \brief Template argument deduction was successful. TDK_Success = 0, /// \brief The declaration was invalid; do nothing. TDK_Invalid, /// \brief Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// \brief Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// \brief Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// \brief 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, /// \brief Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// \brief A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// \brief When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// \brief When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// \brief The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// \brief The arguments included an overloaded function name that could /// not be resolved to a suitable function. TDK_FailedOverloadResolution, /// \brief Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure }; 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, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) { } QualType OriginalParamType; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool InOverloadResolution = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool InOverloadResolution = false); /// \brief Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// \brief Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// \brief Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); 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); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, 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); /// \brief A template instantiation that is currently in progress. struct ActiveTemplateInstantiation { /// \brief The kind of template instantiation we are performing enum InstantiationKind { /// 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, and /// TemplateArgs/NumTemplateArguments provides the template /// arguments as specified. /// FIXME: Use a TemplateArgumentList 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 ClassTemplatePartialSpecializationDecl or /// a FunctionTemplateDecl. 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 instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation } Kind; /// \brief The point of instantiation within the source code. SourceLocation PointOfInstantiation; /// \brief The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// \brief The entity that is being instantiated. Decl *Entity; /// \brief The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; /// \brief The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// \brief The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// \brief The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; ActiveTemplateInstantiation() : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// \brief Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; friend bool operator==(const ActiveTemplateInstantiation &X, const ActiveTemplateInstantiation &Y) { if (X.Kind != Y.Kind) return false; if (X.Entity != Y.Entity) return false; switch (X.Kind) { case TemplateInstantiation: case ExceptionSpecInstantiation: return true; case PriorTemplateArgumentSubstitution: case DefaultTemplateArgumentChecking: return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs; case DefaultTemplateArgumentInstantiation: case ExplicitTemplateArgumentSubstitution: case DeducedTemplateArgumentSubstitution: case DefaultFunctionArgumentInstantiation: return X.TemplateArgs == Y.TemplateArgs; } llvm_unreachable("Invalid InstantiationKind!"); } friend bool operator!=(const ActiveTemplateInstantiation &X, const ActiveTemplateInstantiation &Y) { return !(X == Y); } }; /// \brief List of active template instantiations. /// /// This vector is treated as a stack. As one template instantiation /// requires another template instantiation, additional /// instantiations are pushed onto the stack up to a /// user-configurable limit LangOptions::InstantiationDepth. SmallVector<ActiveTemplateInstantiation, 16> ActiveTemplateInstantiations; /// \brief Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules; /// \brief 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; /// \brief 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(); /// \brief 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; /// \brief The number of ActiveTemplateInstantiation entries in /// \c ActiveTemplateInstantiations that are not actual instantiations and, /// therefore, should not be counted as part of the instantiation depth. unsigned NonInstantiationEntries; /// \brief The last template from which a template instantiation /// error or warning was produced. /// /// This value is used to suppress printing of redundant template /// instantiation backtraces when there are multiple errors in the /// same instantiation. FIXME: Does this belong in Sema? It's tough /// to implement it anywhere else. ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; /// \brief 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; /// \brief 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; /// \brief The stack of calls expression undergoing template instantiation. /// /// The top of this stack is used by a fixit instantiating unresolved /// function calls to fix the AST to match the textual change it prints. SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; /// \brief 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; /// \brief 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 { /// \brief Note that we are instantiating a class template, /// function template, or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// \brief Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, ActiveTemplateInstantiation::InstantiationKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief 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()); /// \brief 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()); InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// \brief 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); /// \brief 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); /// \brief 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); /// \brief Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// \brief Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } private: Sema &SemaRef; bool Invalid; bool SavedInNonInstantiationSFINAEContext; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); // FIXME: Replace this with a constructor once we can use delegating // constructors in llvm. void Initialize( ActiveTemplateInstantiation::InstantiationKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(), sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; InstantiatingTemplate& operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; }; void PrintInstantiationStack(); /// \brief 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; /// \brief 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(); } /// \brief 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; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; } /// \brief Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// \brief 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; } }; /// \brief The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// \brief Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// \brief The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> UnqualifiedTyposCorrectedMap; /// \brief A cache containing the results of typo correction for unqualified /// name lookup. /// /// The string is the string that we corrected to (which may be empty, if /// there was no correction), while the boolean will be true when the /// string represents a keyword. UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// \brief 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; /// \brief Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; /// \brief 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; /// \brief The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; class SavePendingInstantiationsAndVTableUsesRAII { public: SavePendingInstantiationsAndVTableUsesRAII(Sema &S): S(S) { SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } ~SavePendingInstantiationsAndVTableUsesRAII() { // 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; }; /// \brief 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 SavePendingLocalImplicitInstantiationsRAII { public: SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } ~SavePendingLocalImplicitInstantiationsRAII() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); 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, unsigned ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ParmVarDecl **Params, unsigned NumParams, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// \brief 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 NumExprs The number of expressions in \p Exprs. /// /// \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(Expr **Exprs, unsigned NumExprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, 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); 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); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = 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); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false); void InstantiateStaticDataMemberDefinition( SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs); 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; Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, Decl * const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, AttributeList *AttrList); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 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, AttributeList *AttrList); Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl * const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc); Decl *ActOnStartClassImplementation( SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, const IdentifierLocPair *IdentList, unsigned NumElts, AttributeList *attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, const IdentifierLocPair *ProtocolId, unsigned NumProtocols, SmallVectorImpl<Decl *> &Protocols); /// 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 /// \param CD The semantic container for the property /// \param redeclaredProperty Declaration for property if redeclared /// in class extension. /// \param lexicalDC Container for redeclaredProperty. void ProcessPropertyDecl(ObjCPropertyDecl *property, ObjCContainerDecl *CD, ObjCPropertyDecl *redeclaredProperty = nullptr, ObjCContainerDecl *lexicalDC = nullptr); 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, bool *OverridingProperty, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc); 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. AttributeList *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 AttributeList *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); /// \brief Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// \brief The message is sent to 'super'. ObjCSuperMessage, /// \brief The message is an instance message. ObjCInstanceMessage, /// \brief 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 CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr); bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// \brief 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); /// \brief 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 }; /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); enum PragmaPackKind { PPK_Default, // #pragma pack([n]) PPK_Show, // #pragma pack(show), only supported by MSVC. PPK_Push, // #pragma pack(push, [identifier], [n]) PPK_Pop // #pragma pack(pop, [identifier], [n]) }; enum PragmaMSStructKind { PMSST_OFF, // #pragms ms_struct off PMSST_ON // #pragms ms_struct on }; enum PragmaMSCommentKind { PCK_Unknown, PCK_Linker, // #pragma comment(linker, ...) PCK_Lib, // #pragma comment(lib, ...) PCK_Compiler, // #pragma comment(compiler, ...) PCK_ExeStr, // #pragma comment(exestr, ...) PCK_User // #pragma comment(user, ...) }; /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, Expr *Alignment, SourceLocation PragmaLoc, SourceLocation LParenLoc, SourceLocation RParenLoc); /// 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(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); /// \brief Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, 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); /// \brief 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); /// \brief Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// \brief Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(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 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); /// 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); /// \brief Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// \brief 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; } /// \brief 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); /// \brief 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(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex, bool IsPackExpansion); void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, unsigned SpellingListIndex, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, unsigned SpellingListIndex); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex); // OpenMP directives and clauses. private: void *VarDataSharingAttributesStack; /// \brief Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind); public: ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// \brief Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// \brief Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); // OpenMP directives and clauses. /// \brief Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id); /// \brief Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl( SourceLocation Loc, ArrayRef<Expr *> VarList); /// \brief Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); /// \brief Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); /// \brief 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, llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); /// \brief Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief 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, llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); /// \brief 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, llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); /// \brief 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); /// \brief Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, unsigned Argument, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ArgumentLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'ordered' clause. OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); OMPClause * ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId); /// \brief Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'reduction' clause. OMPClause * ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId); /// \brief Called on well-formed 'linear' clause. OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// \brief The kind of conversion being performed. enum CheckedConversionKind { /// \brief An implicit conversion. CCK_ImplicitConversion, /// \brief A C-style cast. CCK_CStyleCast, /// \brief A functional-style cast. CCK_FunctionalCast, /// \brief A cast other than a C-style cast. 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); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); // 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); // 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, /// IncompatiblePointer - 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, /// 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 prepare for a conversion of the /// RHS to the LHS type. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind); // CheckSingleAssignmentConstraints - Currently used by // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, // this routine performs the default function/array converions. AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false); // \brief 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); /// 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 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, unsigned 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, unsigned Opc, bool IsCompAssign = false); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, bool isRelational); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned 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 *NonStandardCompositeType = nullptr); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool *NonStandardCompositeType = nullptr) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType); 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); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool isRelational); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); 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_With_Added_Qualification - The two types are /// reference-compatible with added qualification, meaning that /// they are reference-compatible and the qualifiers on T1 (cv1) /// are greater than the qualifiers on T2 (cv2). Ref_Compatible_With_Added_Qualification, /// Ref_Compatible - The two types are reference-compatible and /// have equivalent qualifiers (cv1 == cv2). Ref_Compatible }; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// \brief Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// \brief 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); // 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, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged }; /// \brief Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds. ARCConversionResult CheckObjCARCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, 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(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); /// \brief 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(QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// \brief 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); /// \brief 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); /// 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(Expr *E, SourceLocation Loc); ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, Expr *SubExpr); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// \brief 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); /// 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); /// \brief 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); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); bool CheckCUDATarget(CUDAFunctionTarget CallerTarget, CUDAFunctionTarget CalleeTarget); bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee); /// 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); /// \name Code completion //@{ /// \brief Describes the context in which code completion occurs. enum ParserCompletionContext { /// \brief Code completion occurs at top-level or namespace context. PCC_Namespace, /// \brief Code completion occurs within a class, struct, or union. PCC_Class, /// \brief Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// \brief Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// \brief Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// \brief Code completion occurs following one or more template /// headers. PCC_Template, /// \brief Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// \brief Code completion occurs within an expression. PCC_Expression, /// \brief Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// \brief Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// \brief Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// \brief 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, /// \brief Code completion occurs where only a type is permitted. PCC_Type, /// \brief Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// \brief 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 CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool IsArrow); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteCase(Scope *S); void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args); void CodeCompleteInitializer(Scope *S, Decl *D); void CodeCompleteReturn(Scope *S); void CodeCompleteAfterIf(Scope *S); void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext); 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(IdentifierLocPair *Protocols, unsigned NumProtocols); 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, bool IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); 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 CodeCompleteNaturalLanguage(); 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; }; 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, ArrayRef<const Expr *> Args, unsigned NumParams, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(CallExpr *TheCall); bool SemaBuiltinVAStartARM(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 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 SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs); bool FormatStringHasSArg(const StringLiteral *FExpr); 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, IdentifierInfo *FnInfo); 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); void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(Expr *E); /// \brief 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); /// \brief Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); public: /// \brief 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: /// \brief A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// \brief 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 Expr * const *ExprArgs); /// \brief The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTWriter; public: /// \brief 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 incrementMSLocalManglingNumber() const { return CurScope->incrementMSLocalManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } AvailabilityResult getCurContextAvailability() const; 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; } }; /// \brief RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; public: EnterExpressionEvaluationContext(Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, bool IsDecltype = false) : Actions(Actions) { Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype); } EnterExpressionEvaluationContext(Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, bool IsDecltype = false) : Actions(Actions) { Actions.PushExpressionEvaluationContext(NewContext, Sema::ReuseLambdaContextDecl, IsDecltype); } ~EnterExpressionEvaluationContext() { Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// \brief Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// \brief The template function declaration to be late parsed. Decl *D; }; } // end namespace clang #endif
nvector_openmp.c
/* * ----------------------------------------------------------------- * $Revision: 4869 $ * $Date: 2016-08-19 10:34:20 -0700 (Fri, 19 Aug 2016) $ * ----------------------------------------------------------------- * Programmer(s): David J. Gardner and Carol S. Woodward @ LLNL * ----------------------------------------------------------------- * Acknowledgements: This NVECTOR module is based on the NVECTOR * Serial module by Scott D. Cohen, Alan C. * Hindmarsh, Radu Serban, and Aaron Collier * @ LLNL * ----------------------------------------------------------------- * LLNS Copyright Start * Copyright (c) 2014, Lawrence Livermore National Security * This work was performed under the auspices of the U.S. Department * of Energy by Lawrence Livermore National Laboratory in part under * Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344. * Produced at the Lawrence Livermore National Laboratory. * All rights reserved. * For details, see the LICENSE file. * LLNS Copyright End * ----------------------------------------------------------------- * This is the implementation file for an OpenMP implementation * of the NVECTOR module. * ----------------------------------------------------------------- */ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <nvector/nvector_openmp.h> #include <sundials/sundials_math.h> #define ZERO RCONST(0.0) #define HALF RCONST(0.5) #define ONE RCONST(1.0) #define ONEPT5 RCONST(1.5) /* Private function prototypes */ /* z=x */ static void VCopy_OpenMP(N_Vector x, N_Vector z); /* z=x+y */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x-y */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=-x */ static void VNeg_OpenMP(N_Vector x, N_Vector z); /* z=c(x+y) */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x-y) */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=ax+y */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax-y */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* y <- ax+y */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y); /* x <- ax */ static void VScaleBy_OpenMP(realtype a, N_Vector x); /* * ----------------------------------------------------------------- * exported functions * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------- * Returns vector type ID. Used to identify vector implementation * from abstract N_Vector interface. */ N_Vector_ID N_VGetVectorID_OpenMP(N_Vector v) { return SUNDIALS_NVEC_OPENMP; } /* ---------------------------------------------------------------------------- * Function to create a new empty vector */ N_Vector N_VNewEmpty_OpenMP(long int length, int num_threads) { N_Vector v; N_Vector_Ops ops; N_VectorContent_OpenMP content; /* Create vector */ v = NULL; v = (N_Vector) malloc(sizeof *v); if (v == NULL) return(NULL); /* Create vector operation structure */ ops = NULL; ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops)); if (ops == NULL) { free(v); return(NULL); } ops->nvgetvectorid = N_VGetVectorID_OpenMP; ops->nvclone = N_VClone_OpenMP; ops->nvcloneempty = N_VCloneEmpty_OpenMP; ops->nvdestroy = N_VDestroy_OpenMP; ops->nvspace = N_VSpace_OpenMP; ops->nvgetarraypointer = N_VGetArrayPointer_OpenMP; ops->nvsetarraypointer = N_VSetArrayPointer_OpenMP; ops->nvlinearsum = N_VLinearSum_OpenMP; ops->nvconst = N_VConst_OpenMP; ops->nvprod = N_VProd_OpenMP; ops->nvdiv = N_VDiv_OpenMP; ops->nvscale = N_VScale_OpenMP; ops->nvabs = N_VAbs_OpenMP; ops->nvinv = N_VInv_OpenMP; ops->nvaddconst = N_VAddConst_OpenMP; ops->nvdotprod = N_VDotProd_OpenMP; ops->nvmaxnorm = N_VMaxNorm_OpenMP; ops->nvwrmsnormmask = N_VWrmsNormMask_OpenMP; ops->nvwrmsnorm = N_VWrmsNorm_OpenMP; ops->nvmin = N_VMin_OpenMP; ops->nvwl2norm = N_VWL2Norm_OpenMP; ops->nvl1norm = N_VL1Norm_OpenMP; ops->nvcompare = N_VCompare_OpenMP; ops->nvinvtest = N_VInvTest_OpenMP; ops->nvconstrmask = N_VConstrMask_OpenMP; ops->nvminquotient = N_VMinQuotient_OpenMP; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof(struct _N_VectorContent_OpenMP)); if (content == NULL) { free(ops); free(v); return(NULL); } content->length = length; content->num_threads = num_threads; content->own_data = FALSE; content->data = NULL; /* Attach content and ops */ v->content = content; v->ops = ops; return(v); } /* ---------------------------------------------------------------------------- * Function to create a new vector */ N_Vector N_VNew_OpenMP(long int length, int num_threads) { N_Vector v; realtype *data; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = TRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create a vector with user data component */ N_Vector N_VMake_OpenMP(long int length, realtype *v_data, int num_threads) { N_Vector v; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); if (length > 0) { /* Attach data */ NV_OWN_DATA_OMP(v) = FALSE; NV_DATA_OMP(v) = v_data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors. */ N_Vector *N_VCloneVectorArray_OpenMP(int count, N_Vector w) { N_Vector *vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector *) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VClone_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors with NULL data array. */ N_Vector *N_VCloneVectorArrayEmpty_OpenMP(int count, N_Vector w) { N_Vector *vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector *) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VCloneEmpty_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to free an array created with N_VCloneVectorArray_OpenMP */ void N_VDestroyVectorArray_OpenMP(N_Vector *vs, int count) { int j; for (j = 0; j < count; j++) N_VDestroy_OpenMP(vs[j]); free(vs); vs = NULL; return; } /* ---------------------------------------------------------------------------- * Function to return number of vector elements */ long int N_VGetLength_OpenMP(N_Vector v) { return NV_LENGTH_OMP(v); } /* ---------------------------------------------------------------------------- * Function to print a vector */ void N_VPrint_OpenMP(N_Vector x) { long int i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); for (i = 0; i < N; i++) { #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%11.8Lg\n", xd[i]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%11.8g\n", xd[i]); #else printf("%11.8g\n", xd[i]); #endif } printf("\n"); return; } /* * ----------------------------------------------------------------- * implementation of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Create new vector from existing vector without attaching data */ N_Vector N_VCloneEmpty_OpenMP(N_Vector w) { N_Vector v; N_Vector_Ops ops; N_VectorContent_OpenMP content; if (w == NULL) return(NULL); /* Create vector */ v = NULL; v = (N_Vector) malloc(sizeof *v); if (v == NULL) return(NULL); /* Create vector operation structure */ ops = NULL; ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops)); if (ops == NULL) { free(v); return(NULL); } ops->nvgetvectorid = w->ops->nvgetvectorid; ops->nvclone = w->ops->nvclone; ops->nvcloneempty = w->ops->nvcloneempty; ops->nvdestroy = w->ops->nvdestroy; ops->nvspace = w->ops->nvspace; ops->nvgetarraypointer = w->ops->nvgetarraypointer; ops->nvsetarraypointer = w->ops->nvsetarraypointer; ops->nvlinearsum = w->ops->nvlinearsum; ops->nvconst = w->ops->nvconst; ops->nvprod = w->ops->nvprod; ops->nvdiv = w->ops->nvdiv; ops->nvscale = w->ops->nvscale; ops->nvabs = w->ops->nvabs; ops->nvinv = w->ops->nvinv; ops->nvaddconst = w->ops->nvaddconst; ops->nvdotprod = w->ops->nvdotprod; ops->nvmaxnorm = w->ops->nvmaxnorm; ops->nvwrmsnormmask = w->ops->nvwrmsnormmask; ops->nvwrmsnorm = w->ops->nvwrmsnorm; ops->nvmin = w->ops->nvmin; ops->nvwl2norm = w->ops->nvwl2norm; ops->nvl1norm = w->ops->nvl1norm; ops->nvcompare = w->ops->nvcompare; ops->nvinvtest = w->ops->nvinvtest; ops->nvconstrmask = w->ops->nvconstrmask; ops->nvminquotient = w->ops->nvminquotient; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof(struct _N_VectorContent_OpenMP)); if (content == NULL) { free(ops); free(v); return(NULL); } content->length = NV_LENGTH_OMP(w); content->num_threads = NV_NUM_THREADS_OMP(w); content->own_data = FALSE; content->data = NULL; /* Attach content and ops */ v->content = content; v->ops = ops; return(v); } /* ---------------------------------------------------------------------------- * Create new vector from existing vector and attach data */ N_Vector N_VClone_OpenMP(N_Vector w) { N_Vector v; realtype *data; long int length; v = NULL; v = N_VCloneEmpty_OpenMP(w); if (v == NULL) return(NULL); length = NV_LENGTH_OMP(w); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = TRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Destroy vector and free vector memory */ void N_VDestroy_OpenMP(N_Vector v) { if (NV_OWN_DATA_OMP(v) == TRUE) { free(NV_DATA_OMP(v)); NV_DATA_OMP(v) = NULL; } free(v->content); v->content = NULL; free(v->ops); v->ops = NULL; free(v); v = NULL; return; } /* ---------------------------------------------------------------------------- * Get storage requirement for N_Vector */ void N_VSpace_OpenMP(N_Vector v, long int *lrw, long int *liw) { *lrw = NV_LENGTH_OMP(v); *liw = 1; return; } /* ---------------------------------------------------------------------------- * Get vector data pointer */ realtype *N_VGetArrayPointer_OpenMP(N_Vector v) { return((realtype *) NV_DATA_OMP(v)); } /* ---------------------------------------------------------------------------- * Set vector data pointer */ void N_VSetArrayPointer_OpenMP(realtype *v_data, N_Vector v) { if (NV_LENGTH_OMP(v) > 0) NV_DATA_OMP(v) = v_data; return; } /* ---------------------------------------------------------------------------- * Compute linear combination z[i] = a*x[i]+b*y[i] */ void N_VLinearSum_OpenMP(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z) { long int i, N; realtype c, *xd, *yd, *zd; N_Vector v1, v2; booleantype test; xd = yd = zd = NULL; if ((b == ONE) && (z == y)) { /* BLAS usage: axpy y <- ax+y */ Vaxpy_OpenMP(a,x,y); return; } if ((a == ONE) && (z == x)) { /* BLAS usage: axpy x <- by+x */ Vaxpy_OpenMP(b,y,x); return; } /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) { VSum_OpenMP(x, y, z); return; } /* Cases: (1) a == 1.0, b = -1.0, (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { v1 = test ? y : x; v2 = test ? x : y; VDiff_OpenMP(v2, v1, z); return; } /* Cases: (1) a == 1.0, b == other or 0.0, (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin1_OpenMP(c, v1, v2, z); return; } /* Cases: (1) a == -1.0, b != 1.0, (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin2_OpenMP(c, v1, v2, z); return; } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) { VScaleSum_OpenMP(a, x, y, z); return; } /* Case: a == -b */ if (a == -b) { VScaleDiff_OpenMP(a, x, y, z); return; } /* Do all cases not handled above: (1) a == other, b == 0.0 - user should have called N_VScale (2) a == 0.0, b == other - user should have called N_VScale (3) a,b == other, a !=b, a != -b */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,b,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+(b*yd[i]); return; } /* ---------------------------------------------------------------------------- * Assigns constant value to all vector elements, z[i] = c */ void N_VConst_OpenMP(realtype c, N_Vector z) { long int i, N; realtype *zd; zd = NULL; N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(z)) for (i = 0; i < N; i++) zd[i] = c; return; } /* ---------------------------------------------------------------------------- * Compute componentwise product z[i] = x[i]*y[i] */ void N_VProd_OpenMP(N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]*yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise division z[i] = x[i]/y[i] */ void N_VDiv_OpenMP(N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]/yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaler multiplication z[i] = c*x[i] */ void N_VScale_OpenMP(realtype c, N_Vector x, N_Vector z) { long int i, N; realtype *xd, *zd; xd = zd = NULL; if (z == x) { /* BLAS usage: scale x <- cx */ VScaleBy_OpenMP(c, x); return; } if (c == ONE) { VCopy_OpenMP(x, z); } else if (c == -ONE) { VNeg_OpenMP(x, z); } else { N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*xd[i]; } return; } /* ---------------------------------------------------------------------------- * Compute absolute value of vector components z[i] = SUNRabs(x[i]) */ void N_VAbs_OpenMP(N_Vector x, N_Vector z) { long int i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = SUNRabs(xd[i]); return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = 1 / x[i] */ void N_VInv_OpenMP(N_Vector x, N_Vector z) { long int i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = ONE/xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise addition of a scaler to a vector z[i] = x[i] + b */ void N_VAddConst_OpenMP(N_Vector x, realtype b, N_Vector z) { long int i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,b,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+b; return; } /* ---------------------------------------------------------------------------- * Computes the dot product of two vectors, a = sum(x[i]*y[i]) */ realtype N_VDotProd_OpenMP(N_Vector x, N_Vector y) { long int i, N; realtype sum, *xd, *yd; sum = ZERO; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); #pragma omp parallel for default(none) private(i) shared(N,xd,yd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += xd[i]*yd[i]; } return(sum); } /* ---------------------------------------------------------------------------- * Computes max norm of a vector */ realtype N_VMaxNorm_OpenMP(N_Vector x) { long int i, N; realtype tmax, max, *xd; max = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel default(none) private(i,tmax) shared(N,max,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmax = ZERO; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (SUNRabs(xd[i]) > tmax) tmax = SUNRabs(xd[i]); } #pragma omp critical { if (tmax > max) max = tmax; } } return(max); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a vector */ realtype N_VWrmsNorm_OpenMP(N_Vector x, N_Vector w) { long int i, N; realtype sum, *xd, *wd; sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum/N)); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a masked vector */ realtype N_VWrmsNormMask_OpenMP(N_Vector x, N_Vector w, N_Vector id) { long int i, N; realtype sum, *xd, *wd, *idd; sum = ZERO; xd = wd = idd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); idd = NV_DATA_OMP(id); #pragma omp parallel for default(none) private(i) shared(N,xd,wd,idd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (idd[i] > ZERO) { sum += SUNSQR(xd[i]*wd[i]); } } return(SUNRsqrt(sum / N)); } /* ---------------------------------------------------------------------------- * Finds the minimun component of a vector */ realtype N_VMin_OpenMP(N_Vector x) { long int i, N; realtype min, *xd; realtype tmin; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); min = xd[0]; #pragma omp parallel default(none) private(i,tmin) shared(N,min,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmin = xd[0]; #pragma omp for schedule(static) for (i = 1; i < N; i++) { if (xd[i] < tmin) tmin = xd[i]; } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* ---------------------------------------------------------------------------- * Computes weighted L2 norm of a vector */ realtype N_VWL2Norm_OpenMP(N_Vector x, N_Vector w) { long int i, N; realtype sum, *xd, *wd; sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum)); } /* ---------------------------------------------------------------------------- * Computes L1 norm of a vector */ realtype N_VL1Norm_OpenMP(N_Vector x) { long int i, N; realtype sum, *xd; sum = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,xd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i<N; i++) sum += SUNRabs(xd[i]); return(sum); } /* ---------------------------------------------------------------------------- * Compare vector component values to a scaler */ void N_VCompare_OpenMP(realtype c, N_Vector x, N_Vector z) { long int i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { zd[i] = (SUNRabs(xd[i]) >= c) ? ONE : ZERO; } return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = ONE/x[i] and checks if x[i] == ZERO */ booleantype N_VInvTest_OpenMP(N_Vector x, N_Vector z) { long int i, N; realtype *xd, *zd, val; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); val = ZERO; #pragma omp parallel for default(none) private(i) shared(N,val,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (xd[i] == ZERO) val = ONE; else zd[i] = ONE/xd[i]; } if (val > ZERO) return (FALSE); else return (TRUE); } /* ---------------------------------------------------------------------------- * Compute constraint mask of a vector */ booleantype N_VConstrMask_OpenMP(N_Vector c, N_Vector x, N_Vector m) { long int i, N; realtype temp; realtype *cd, *xd, *md; cd = xd = md = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); cd = NV_DATA_OMP(c); md = NV_DATA_OMP(m); temp = ONE; #pragma omp parallel for default(none) private(i) shared(N,xd,cd,md,temp) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { md[i] = ZERO; if (cd[i] == ZERO) continue; if (cd[i] > ONEPT5 || cd[i] < -ONEPT5) { if ( xd[i]*cd[i] <= ZERO) { temp = ZERO; md[i] = ONE; } continue; } if ( cd[i] > HALF || cd[i] < -HALF) { if (xd[i]*cd[i] < ZERO ) { temp = ZERO; md[i] = ONE; } } } if (temp == ONE) return (TRUE); else return(FALSE); } /* ---------------------------------------------------------------------------- * Compute minimum componentwise quotient */ realtype N_VMinQuotient_OpenMP(N_Vector num, N_Vector denom) { long int i, N; realtype *nd, *dd, min, tmin, val; nd = dd = NULL; N = NV_LENGTH_OMP(num); nd = NV_DATA_OMP(num); dd = NV_DATA_OMP(denom); min = BIG_REAL; #pragma omp parallel default(none) private(i,tmin,val) shared(N,min,nd,dd) \ num_threads(NV_NUM_THREADS_OMP(num)) { tmin = BIG_REAL; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (dd[i] != ZERO) { val = nd[i]/dd[i]; if (val < tmin) tmin = val; } } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* * ----------------------------------------------------------------- * private functions * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Copy vector components into a second vector */ static void VCopy_OpenMP(N_Vector x, N_Vector z) { long int i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector sum */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute the negative of a vector */ static void VNeg_OpenMP(N_Vector x, N_Vector z) { long int i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = -xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector sum */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]+yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute scaled vector difference */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]-yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute vector sum z[i] = a*x[i]+y[i] */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference z[i] = a*x[i]-y[i] */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { long int i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute special cases of linear sum */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y) { long int i, N; realtype *xd, *yd; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); if (a == ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += xd[i]; return; } if (a == -ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] -= xd[i]; return; } #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += a*xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector x[i] = a*x[i] */ static void VScaleBy_OpenMP(realtype a, N_Vector x) { long int i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,a,xd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) xd[i] *= a; return; }
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * 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] = 4; tile_size[1] = 4; tile_size[2] = 8; tile_size[3] = 512; 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 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. 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 ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=2*Nt-2;t1++) { lbp=ceild(t1+2,2); ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1,4),ceild(4*t2-Nz+5,8));t3<=min(min(floord(4*Nt+Ny-9,8),floord(2*t1+Ny-3,8)),floord(4*t2+Ny-9,8));t3++) { for (t4=max(max(ceild(t1-252,256),ceild(4*t2-Nz-499,512)),ceild(8*t3-Ny-499,512));t4<=min(min(min(floord(4*Nt+Nx-9,512),floord(2*t1+Nx-3,512)),floord(4*t2+Nx-9,512)),floord(8*t3+Nx-5,512));t4++) { for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(512*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) { for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(512*t4,4*t5+4); ubv=min(512*t4+511,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ 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; }
rootfinder_mex.c
#include "mex.h" #include "matrix.h" #include "linequad.h" /* The gateway function */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Read input int n = mxGetNumberOfElements(prhs[0]); double* xhat = mxGetPr(prhs[0]); double* yhat = mxGetPr(prhs[1]); double* zhat = mxGetPr(prhs[2]); int N = mxGetNumberOfElements(prhs[3]); double* x0 = mxGetPr(prhs[3]); double* y0 = mxGetPr(prhs[4]); double* z0 = mxGetPr(prhs[5]); double* tinit_re_p = mxGetPr(prhs[6]); double* tinit_im_p = mxGetPi(prhs[6]); // Prepare output plhs[0] = mxCreateDoubleMatrix(N, 1, mxCOMPLEX); double* troot_re_p = mxGetPr(plhs[0]); double* troot_im_p = mxGetPi(plhs[0]); plhs[1] = mxCreateLogicalMatrix(N, 1); mxLogical* converged_p = mxGetLogicals(plhs[1]); // Call function for all inputs #pragma omp parallel for schedule(guided) for (int i=0; i<N; i++) { double complex troot = 0; int converged = 0; double complex tinit = tinit_re_p[i] + I*tinit_im_p[i]; converged = rootfinder(xhat, yhat, zhat, n, x0[i], y0[i], z0[i], tinit, &troot); troot_re_p[i] = creal(troot); troot_im_p[i] = cimag(troot); converged_p[i] = converged; } }
LAGraphX_bc_batch.c
//------------------------------------------------------------------------------ // LAGraphX_bc_batch: Brandes' algorithm for computing betweeness centrality //------------------------------------------------------------------------------ /* LAGraph: graph algorithms based on GraphBLAS Copyright 2019 LAGraph Contributors. (see Contributors.txt for a full list of Contributors; see ContributionInstructions.txt for information on how you can Contribute to this project). All Rights Reserved. NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. Released under a BSD license, please see the LICENSE file distributed with this Software or contact permission@sei.cmu.edu for full terms. Created, in part, with funding and support from the United States Government. (see Acknowledgments.txt file). This program includes and/or can make use of certain third party source code, object code, documentation and other files ("Third Party Software"). See LICENSE file for more details. */ //------------------------------------------------------------------------------ // LAGraph_bc_batch: Batch algorithm for computing betweeness centrality. // Contributed by Scott Kolodziej and Tim Davis, Texas A&M University. // Adapted from GraphBLAS C API Spec, Appendix B.4. // LAGraph_bc_batch computes an approximation of the betweenness centrality of // all nodes in a graph using a batched version of Brandes' algorithm. // ____ // \ sigma(s,t | i) // Betweenness centrality = \ ---------------- // of node i / sigma(s,t) // /___ // s ≠ i ≠ t // // Where sigma(s,t) is the total number of shortest paths from node s to // node t, and sigma(s,t | i) is the total number of shortest paths from // node s to node t that pass through node i. // // Note that the true betweenness centrality requires computing shortest paths // from all nodes s to all nodes t (or all-pairs shortest paths), which can be // expensive to compute. By using a reasonably sized subset of source nodes, an // approximation can be made. // // LAGraph_bc_batch performs simultaneous breadth-first searches of the entire // graph starting at a given set of source nodes. This pass discovers all // shortest paths from the source nodes to all other nodes in the graph. After // the BFS is complete, the number of shortest paths that pass through a given // node is tallied by reversing the traversal. From this, the (approximate) // betweenness centrality is computed. // A_matrix represents the graph. It must be square, and can be unsymmetric. // Self-edges are OK. //------------------------------------------------------------------------------ #include "LAGraph_internal.h" #define LAGRAPH_FREE_WORK \ { \ GrB_free(&frontier); \ GrB_free(&paths); \ LAGraph_free(paths_dense); \ LAGraph_free(bc_update_dense); \ GrB_free(&t1); \ GrB_free(&t2); \ GrB_free(&desc_tsr); \ GrB_free(&replace); \ if (S_array != NULL) \ { \ for (int64_t d = 0; d < depth; d++) \ { \ GrB_free(&(S_array[d])); \ } \ free (S_array); \ } \ } #define LAGRAPH_FREE_ALL \ { \ LAGRAPH_FREE_WORK; \ GrB_free (centrality); \ } GrB_Info LAGraphX_bc_batch // betweeness centrality, batch algorithm ( GrB_Vector *centrality, // centrality(i) is the betweeness centrality of node i const GrB_Matrix A_matrix, // input graph, treated as if boolean in semiring const GrB_Index *sources, // source vertices from which to compute shortest paths int32_t num_sources // number of source vertices (length of s) ) { double tic [2]; LAGraph_tic (tic); (*centrality) = NULL; GrB_Index n; // Number of nodes in the graph int nthreads ; GxB_get (GxB_NTHREADS, &nthreads) ; // Array of BFS search matrices // S_array[i] is a matrix that stores the depth at which each vertex is // first seen thus far in each BFS at the current depth i. Each column // corresponds to a BFS traversal starting from a source node. GrB_Matrix *S_array = NULL; // Frontier matrix // Stores # of shortest paths to vertices at current BFS depth GrB_Matrix frontier = NULL; // Paths matrix holds the number of shortest paths for each node and // starting node discovered so far. Starts out sparse and becomes denser. GrB_Matrix paths = NULL; int64_t* paths_dense = NULL; // Update matrix for betweenness centrality, values for each node for // each starting node. Treated as dense for efficiency. double* bc_update_dense = NULL; GrB_Descriptor desc_tsr = NULL; GrB_Descriptor replace = NULL; GrB_Index* Sp = NULL; GrB_Index* Si = NULL; void* Sx = NULL; GrB_Index* Tp = NULL; GrB_Index* Ti = NULL; void* Tx = NULL; GrB_Index num_rows; GrB_Index num_cols; GrB_Index nnz; int64_t num_nonempty; GrB_Type type; GrB_Matrix t1 = NULL; GrB_Matrix t2 = NULL; int64_t depth = 0; // Initial BFS depth LAGr_Matrix_nrows(&n, A_matrix); // Get dimensions const GrB_Index nnz_dense = n * num_sources; // Create a new descriptor that represents the following traits: // - Tranpose the first input matrix // - Replace the output // - Use the structural complement of the mask LAGr_Descriptor_new(&desc_tsr); LAGr_Descriptor_set(desc_tsr, GrB_INP0, GrB_TRAN); LAGr_Descriptor_set(desc_tsr, GrB_OUTP, GrB_REPLACE); LAGr_Descriptor_set(desc_tsr, GrB_MASK, GrB_SCMP); // This is also: LAGraph_desc_tocr : A', compl mask, replace // Initialize paths to source vertices with ones // paths[s[i],i]=1 for i=[0, ..., num_sources) if (sources == GrB_ALL) { num_sources = n; } LAGr_Matrix_new(&paths, GrB_INT64, n, num_sources); GxB_set(paths, GxB_FORMAT, GxB_BY_COL); // make paths dense LAGr_assign(paths, NULL, NULL, 0, GrB_ALL, n, GrB_ALL, num_sources, NULL); // Force resolution of pending tuples GrB_Index ignore; GrB_Matrix_nvals(&ignore, paths); if (sources == GrB_ALL) { for (GrB_Index i = 0; i < num_sources; ++i) { // paths [i,i] = 1 LAGr_Matrix_setElement(paths, (int64_t) 1, i, i); } } else { for (GrB_Index i = 0; i < num_sources; ++i) { // paths [s[i],i] = 1 LAGr_Matrix_setElement(paths, (int64_t) 1, sources[i], i); } } // Create frontier matrix and initialize to outgoing nodes from // all source nodes LAGr_Matrix_new(&frontier, GrB_INT64, n, num_sources); GxB_set(frontier, GxB_FORMAT, GxB_BY_COL); // AT = A' // frontier <!paths> = AT (:,sources) LAGr_extract(frontier, paths, GrB_NULL, A_matrix, GrB_ALL, n, sources, num_sources, desc_tsr); // Allocate memory for the array of S matrices S_array = (GrB_Matrix*) LAGraph_calloc (n, sizeof(GrB_Matrix)); if (S_array == NULL) { // out of memory LAGRAPH_FREE_ALL; return (GrB_OUT_OF_MEMORY); } //=== Breadth-first search stage =========================================== GrB_Index sum = 0; // Sum of shortest paths to vertices at current depth // Equal to sum(frontier). Continue BFS until new paths // are no shorter than any existing paths. double time_1 = LAGraph_toc (tic) ; printf ("Xbc setup %g sec\n", time_1) ; double time_2 = 0 ; do { LAGraph_tic (tic); // Create the current search matrix - one column for each source/BFS LAGr_Matrix_new(&(S_array[depth]), GrB_BOOL, n, num_sources); GxB_set(S_array[depth], GxB_FORMAT, GxB_BY_COL); // Copy the current frontier to S LAGr_apply(S_array[depth], GrB_NULL, GrB_NULL, GrB_IDENTITY_BOOL, frontier, GrB_NULL); //=== Accumulate path counts: paths += frontier ======================== // Export paths GxB_Matrix_export_CSC(&paths, &type, &num_rows, &num_cols, &nnz, &num_nonempty, &Sp, &Si, &Sx, GrB_NULL); // Export frontier GxB_Matrix_export_CSC(&frontier, &type, &num_rows, &num_cols, &nnz, &num_nonempty, &Tp, &Ti, &Tx, GrB_NULL); // Use frontier pattern to update dense paths #pragma omp parallel for num_threads(nthreads) for (int64_t col = 0; col < num_sources; col++) { for (GrB_Index p = Tp[col]; p < Tp[col+1]; p++) { GrB_Index row = Ti[p]; ((int64_t*)Sx)[col * n + row] += ((int64_t*)Tx)[p]; } } // Import frontier GxB_Matrix_import_CSC(&frontier, GrB_INT64, n, num_sources, nnz, num_nonempty, &Tp, &Ti, (void**) &Tx, GrB_NULL); // Import paths GxB_Matrix_import_CSC(&paths, GrB_INT64, n, num_sources, nnz_dense, n, &Sp, &Si, (void**) &Sx, GrB_NULL); double time_2a = LAGraph_toc (tic) ; time_2 += time_2a ; // printf (" %16"PRId64" accum: %16.8g ", depth, time_2a) ; LAGraph_tic (tic); //=== Update frontier: frontier<!paths>=A’ +.∗ frontier ================ LAGr_mxm(frontier, paths, GrB_NULL, GxB_PLUS_TIMES_INT64, A_matrix, frontier, desc_tsr); //=== Sum up the number of BFS paths still being explored ============== LAGr_Matrix_nvals(&sum, frontier); depth = depth + 1; double time_2b = LAGraph_toc (tic) ; // printf (" mxm: %16.8g\n", time_2b) ; time_2 += time_2b ; } while (sum); // Repeat until no more shortest paths being discovered printf ("Xbc bfs phase: %g\n", time_2) ; LAGraph_tic (tic); //=== Betweenness centrality computation phase ============================= // Create the dense update matrix and initialize it to 1 // We will store it column-wise (col * p + row) bc_update_dense = LAGraph_malloc(nnz_dense, sizeof(double)); #pragma omp parallel for num_threads(nthreads) for (GrB_Index nz = 0; nz < nnz_dense; nz++) { bc_update_dense[nz] = 1.0; } // By this point, paths is (mostly) dense. // Create a dense version of the GraphBLAS paths matrix GxB_Matrix_export_CSC(&paths, &type, &num_rows, &num_cols, &nnz, &num_nonempty, &Sp, &Si, &Sx, GrB_NULL); paths_dense = (int64_t*) Sx; // Throw away the "sparse" version of paths LAGraph_free(Sp); LAGraph_free(Si); // Create temporary workspace matrix LAGr_Matrix_new(&t2, GrB_FP64, n, num_sources); double time_3 = LAGraph_toc (tic) ; printf ("Xbc: setup for backtrack %16.8g\n", time_3) ; double time_4 = 0 ; // Backtrack through the BFS and compute centrality updates for each vertex for (int64_t i = depth - 1; i > 0; i--) { // Add contributions by successors and mask with that BFS level’s frontier LAGraph_tic (tic); //=== temp<S_array[i]> = bc_update ./ paths ============================ // Export the pattern of S_array[i] GxB_Matrix_export_CSC(&(S_array[i]), &type, &num_rows, &num_cols, &nnz, &num_nonempty, &Sp, &Si, &Sx, GrB_NULL); // Compute Tx = bc_update ./ paths_dense for all elements of S_array // Build the Tp and Ti vectors, too. Tp = LAGraph_malloc(num_sources+1, sizeof(GrB_Index)); Ti = LAGraph_malloc(nnz, sizeof(GrB_Index)); Tx = LAGraph_malloc(nnz, sizeof(double)); #pragma omp parallel for num_threads(nthreads) for (int64_t col = 0; col < num_sources; col++) { Tp[col] = Sp[col]; for (GrB_Index p = Sp[col]; p < Sp[col+1]; p++) { // Compute Tx by eWiseMult of dense matrices GrB_Index row = Ti[p] = Si[p]; ((double*)Tx)[p] = bc_update_dense[col * n + row] / ((double) paths_dense[col * n + row]); } } Tp[num_sources] = Sp[num_sources]; // Restore S_array[i] by importing it GxB_Matrix_import_CSC(&(S_array[i]), GrB_BOOL, num_rows, num_cols, nnz, num_nonempty, &Sp, &Si, &Sx, GrB_NULL); // Create a GraphBLAS matrix t1 from Tp, Ti, Tx // The row/column indices are the pattern r/c from S_array[i] GxB_Matrix_import_CSC(&t1, GrB_FP64, n, num_sources, nnz, num_nonempty, &Tp, &Ti, (void**) &Tx, GrB_NULL); double time_4a = LAGraph_toc (tic) ; time_4 += time_4a ; // printf (" %16"PRId64" contr: %16.8g ", i, time_4a) ; LAGraph_tic (tic); //=== t2<S_array[i−1]> = (A * t1) ====================================== LAGr_mxm(t2, S_array[i-1], GrB_NULL, GxB_PLUS_TIMES_FP64, A_matrix, t1, LAGraph_desc_ooor); GrB_free(&t1); //=== bc_update += t2 .* paths ========================================= GxB_Matrix_export_CSC(&t2, &type, &num_rows, &num_cols, &nnz, &num_nonempty, &Tp, &Ti, &Tx, GrB_NULL); #pragma omp parallel for num_threads(nthreads) for (int64_t col = 0; col < num_sources; col++) { for (GrB_Index p = Tp[col]; p < Tp[col+1]; p++) { GrB_Index row = Ti[p]; bc_update_dense[col * n + row] += ((double*)Tx)[p] * ((double) paths_dense[col * n + row]); } } // Re-import t2 GxB_Matrix_import_CSC(&t2, GrB_FP64, num_rows, num_cols, nnz, num_nonempty, &Tp, &Ti, &Tx, GrB_NULL); double time_4b = LAGraph_toc (tic) ; time_4 += time_4b ; // printf (" mxm: %16.8g\n", time_4b) ; } printf ("Xbx 2nd phase: %g\n", time_4) ; LAGraph_tic (tic); //=== Initialize the centrality array with -(num_sources) to avoid counting // zero length paths ==================================================== double* centrality_dense = LAGraph_malloc(n, sizeof(double)); #pragma omp parallel for num_threads(nthreads) for (GrB_Index i = 0; i < n; i++) { centrality_dense[i] = -num_sources; } //=== centrality[i] += bc_update[i,:] ====================================== // Both are dense. We can also take care of the reduction. #pragma omp parallel for schedule(static) num_threads(nthreads) for (GrB_Index j = 0; j < n; j++) { for (int64_t i = 0; i < num_sources; i++) { centrality_dense[j] += bc_update_dense[n * i + j]; } } // Build the index vector. GrB_Index* I = LAGraph_malloc(n, sizeof(GrB_Index)); #pragma omp parallel for num_threads(nthreads) for (GrB_Index j = 0; j < n; j++) { I[j] = j; } // Import the dense vector into GraphBLAS and return it. GxB_Vector_import(centrality, GrB_FP64, n, n, &I, (void**) &centrality_dense, GrB_NULL); LAGRAPH_FREE_WORK; double time_5 = LAGraph_toc (tic) ; printf ("Xbc wrapup: %g\n", time_5) ; printf ("Xbc total: %g\n", time_1 + time_2 + time_3 + time_4 + time_5) ; return GrB_SUCCESS; }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_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/LoopHint.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; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class VersionTuple; 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 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; unsigned short ParenCount, BracketCount, BraceCount; /// 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. mutable IdentifierInfo *Ident_instancetype; /// \brief Identifier for "introduced". IdentifierInfo *Ident_introduced; /// \brief Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// \brief Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// \brief Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// \brief Identifier for "message". IdentifierInfo *Ident_message; /// \brief Identifier for "strict". IdentifierInfo *Ident_strict; /// \brief Identifier for "replacement". IdentifierInfo *Ident_replacement; /// C++0x contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_override; // 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> 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> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; 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; /// \brief 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; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// \brief 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; } unsigned getDepth() const { return Depth; } }; /// Factory object for creating AttributeList objects. AttributeFactory AttrFactory; /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; /// \brief Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; 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; bool SkipFunctionBodies; 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(); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result); 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 /// 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; } /// 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.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren; } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square; } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.getKind() == tok::l_brace || Tok.getKind() == 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); } /// \brief Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// \brief 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); PP.Lex(Tok); PP.EnterToken(Next); } /// 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(); return ConsumeToken(); } /// 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) --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) --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) --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; } /// \brief 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(); /// \brief 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); } /// \brief 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; } /// \brief Initialize all pragma handlers. void initializePragmaHandlers(); /// \brief Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// \brief Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// \brief Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// \brief Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// \brief Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// \brief 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); /// \brief Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// \brief Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// \brief Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// \brief Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// \brief Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// \brief Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// \brief Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// \brief Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// \brief Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); /// 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(Token &Tok) { return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, ParsedType T) { Tok.setAnnotationValue(T.getAsOpaquePtr()); } /// \brief Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// \brief 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 EnteringContext = false, bool NeedType = false); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext, bool NeedType, CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); 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(bool IsAddressOfOperand, std::unique_ptr<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().ObjC1); 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); /// \brief 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; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { 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.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!"); } }; 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 = ""); /// \brief 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); /// \brief The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// \brief Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified); 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: /// \brief 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: /// \brief Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// \brief Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend LLVM_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(); 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(); }; /// 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; 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; 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); } }; // 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; /// \brief 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, CachedTokens *Toks = nullptr) : Param(P), Toks(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. 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; /// \brief Whether this member function had an associated template /// scope. When true, D is a template declaration. /// othewise, 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; /// \brief 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; /// \brief 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) { } /// \brief Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// \brief Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// othewise, it is a tag declaration. bool TemplateScope : 1; /// \brief Whether this class is an __interface. bool IsInterface : 1; /// \brief 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; }; /// \brief 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(); } /// \brief 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)) { } /// \brief 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); } }; /// \brief 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){ } /// \brief The kind of template we are parsing. enum { /// \brief We are not parsing a template at all. NonTemplate = 0, /// \brief We are parsing a template declaration. Template, /// \brief We are parsing an explicit specialization. ExplicitSpecialization, /// \brief We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// \brief The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// \brief The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// \brief The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// \brief 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, AttributeList *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); 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) {} 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, if non-NULL, is filled with the location of the last token of // the simple-asm. ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr); ExprResult ParseAsmStringLiteral(); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(); 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); 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, Declarator::TheContext 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 ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstraintExpression(); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, void *Info, bool IsUnevaluated); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast); /// 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); } 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, std::function<void()> Completer = nullptr); /// 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 ')' 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); void CheckForLParenAfterColonColon(); //===--------------------------------------------------------------------===// // C++0x 5.1.2: Lambda expressions // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro, bool *SkippedInits = nullptr); bool TryParseLambdaIntroducer(LambdaIntroducer &Intro); ExprResult ParseLambdaExpressionAfterIntroducer( LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); //===--------------------------------------------------------------------===// // 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); //===--------------------------------------------------------------------===// // 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 condition expression. bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult, SourceLocation Loc, bool ConvertToBoolean); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // 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, bool AllowOpenMPStandalone = false); enum AllowedContsructsKind { /// \brief Allow any declarations, statements, OpenMP directives. ACK_Any, /// \brief Allow only statements and non-standalone OpenMP directives. ACK_StatementsOpenMPNonStandalone, /// \brief Allow statements and all executable OpenMP directives ACK_StatementsOpenMPAnyExecutable }; StmtResult ParseStatementOrDeclaration(StmtVector &Stmts, AllowedContsructsKind Allowed, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, AllowedContsructsKind Allowed, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs); StmtResult ParseCaseStatement(bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(ExprResult &ExprResult, Decl *&DeclResult, SourceLocation Loc, bool ConvertToBoolean); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, AllowedContsructsKind Allowed, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// \brief Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// \brief Parse the block; this code is always used. IEB_Parse, /// \brief Skip the block entirely; this code is never used. IEB_Skip, /// \brief Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// \brief Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// \brief The location of the initial keyword. SourceLocation KeywordLoc; /// \brief Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// \brief Nested-name-specifier preceding the name. CXXScopeSpec SS; /// \brief The name we're looking for. UnqualifiedId Name; /// \brief 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, 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); 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 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_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 DSC_normal: case DSC_class: case DSC_top_level: case DSC_objc_method_result: case DSC_condition: return false; case DSC_template_type_arg: case DSC_type_specifier: case DSC_trailing: case DSC_alias_declaration: return true; } 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(); } }; DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr); bool MightBeDeclarator(unsigned Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned 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); /// \brief 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(unsigned Context); void ParseDeclarationSpecifiers(DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = 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 = DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, Declarator::TheContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, unsigned 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; /// \brief 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().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// \brief Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// \brief Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// \brief 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); /// \brief 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); } /// \brief 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); /// isCXXConditionDeclaration - Disambiguates between a declaration or an /// expression for a condition of a if/switch/while/for statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXConditionDeclaration(); 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 }; /// \brief 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 *HasMissingTypename = 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(); /// \brief 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); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, Declarator::TheContext Context = Declarator::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); // Check for the start of a C++11 attribute-specifier-seq in a context where // an attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!getLangOpts().CPlusPlus11) 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 handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); void ProhibitAttributes(ParsedAttributesWithRange &attrs) { if (!attrs.Range.isValid()) return; DiagnoseProhibitedAttributes(attrs); attrs.clear(); } void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs); // Forbid C++11 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); /// \brief Skip C++11 attributes and return the end location of the last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// \brief Diagnose and skip C++11 attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// \brief 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, AttributeList::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, AttributeList::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); void MaybeParseCXX11Attributes(Declarator &D) { if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// \brief Parses a C++-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 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); /// \brief 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; } /// \brief 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, AttributeList::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::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); void ParseDirectDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( Declarator &D, 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(unsigned Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc, std::vector<IdentifierInfo*>& Ident, std::vector<SourceLocation>& NamespaceLoc, unsigned int index, SourceLocation& InlineLoc, ParsedAttributes& attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context); Decl *ParseUsingDirectiveOrDeclaration(unsigned Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, Decl **OwnedType = nullptr); Decl *ParseUsingDirective(unsigned Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); Decl *ParseUsingDeclaration(unsigned Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none, 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, AttributeList *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); /// \brief Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// \brief Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// \brief 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); /// \brief Parses declarative or executable directive. /// /// \param Allowed ACK_Any, if any directives are allowed, /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone /// executable directives are allowed. /// StmtResult ParseOpenMPDeclarativeOrExecutableDirective(AllowedContsructsKind Allowed); /// \brief 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); /// \brief Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind); /// \brief Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind); /// \brief Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind); /// \brief Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind); /// \brief Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind); 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); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *TailExpr = nullptr; SourceLocation ColonLoc; CXXScopeSpec ReductionIdScopeSpec; DeclarationNameInfo ReductionId; OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val; OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown; OpenMPMapClauseKind MapType = OMPC_MAP_unknown; bool IsMapTypeImplicit = false; SourceLocation DepLinMapLoc; }; /// 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, ParsedType ObjectType, SourceLocation& TemplateKWLoc, UnqualifiedId &Result); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none, AttributeList *AccessAttrs = nullptr); Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS, AttributeList *AccessAttrs); Decl *ParseSingleDeclarationAfterTemplate( unsigned Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, AccessSpecifier AS=AS_none, AttributeList *AccessAttrs = nullptr); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<Decl*> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<Decl*> &TemplateParams); bool isStartOfTemplateTypeParameter(); Decl *ParseTemplateParameter(unsigned Depth, unsigned Position); Decl *ParseTypeParameter(unsigned Depth, unsigned Position); Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); Decl *ParseNonTypeTemplateParameter(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(TemplateTy Template, SourceLocation TemplateNameLoc, const CXXScopeSpec &SS, bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true); void AnnotateTemplateIdTokenAsType(); bool IsTemplateArgumentList(unsigned Skip = 0); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(unsigned Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy 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; } //===--------------------------------------------------------------------===// // 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 CodeCompleteNaturalLanguage() override; }; } // end namespace clang #endif
randomgridsearch.h
// // Created by Xinyu Zhang on 4/4/21. // #ifndef COSAN_RANDOMGRIDSEARCH_H #define COSAN_RANDOMGRIDSEARCH_H #include<cosan/selection/crossvalidation.h> #include<cosan/selection/selection.h> namespace Cosan{ template<typename NumericType, Derived<CosanModel> Model, Derived<CosanMetric<NumericType>> Metric, Derived<Splitter> Split, typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type> class RandomGridSearch: public Search{ public: RandomGridSearch() = delete; RandomGridSearch(CosanData<NumericType> &CRD, Model & estimator, Metric & metric, Split & split, const std::vector<NumericType> & paramGrid,long unsigned int nsamples= 100): Search() { NumericType minError = std::numeric_limits<NumericType>::infinity(); NumericType currError; std::vector<NumericType> RandomChoice; std::sample(paramGrid.begin(), paramGrid.end(), std::back_inserter(RandomChoice), std::min({paramGrid.size(),nsamples}), std::mt19937{std::random_device{}()}); decltype(bestParam) currParam; for (gsl::index i = 0; i < RandomChoice.size(); ++i){ currParam = paramGrid[i]; estimator.SetParams(paramGrid[i]); currError = crossValidation(CRD, estimator, metric, split); if (currError < minError) { minError = currError; bestParam = currParam; } } } auto GetBestParams(){return bestParam;} private: NumericType bestParam;}; template<typename NumericType, Derived<CosanModel> Model, Derived<CosanMetric<NumericType>> Metric, Derived<Splitter> Split, typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type> class RandomGridSearchParallel: public Search{ public: RandomGridSearchParallel() = delete; RandomGridSearchParallel(CosanData<NumericType> &CRD, Model & estimator, Metric & metric, Split & split, const std::vector<NumericType> & paramGrid,long unsigned int nsamples = 100,int nthreads = -1): Search() { NumericType minError = std::numeric_limits<NumericType>::infinity(); NumericType currError; std::vector<NumericType> RandomChoice; std::sample(paramGrid.begin(), paramGrid.end(), std::back_inserter(RandomChoice), std::min({paramGrid.size(),nsamples}), std::mt19937{std::random_device{}()}); std::vector<NumericType> allError(RandomChoice.size()); if (nthreads == -1){ omp_set_num_threads(omp_get_max_threads()); } else{ omp_set_num_threads(nthreads); } #pragma omp parallel for for (gsl::index i = 0; i < RandomChoice.size(); ++i){ estimator.SetParams(RandomChoice[i]); allError[i] = crossValidation(CRD, estimator, metric, split); } bestParam =RandomChoice[std::distance(allError.begin(), std::min_element(allError.begin(), allError.end()))]; } auto GetBestParams(){return bestParam;} private: NumericType bestParam;}; template<typename NumericType, Derived<CosanModel> Model, Derived<CosanMetric<NumericType>> Metric, Derived<Splitter> Split, typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type> class RandomGridSearchMulti: public Search{ public: RandomGridSearchMulti() = delete; RandomGridSearchMulti( CosanData<NumericType> &CRD, Model & estimator, Metric & metric, Split & split, const std::vector<std::vector<NumericType>> & paramGrid, long unsigned int nsamples = 100): Search() { NumericType minError = std::numeric_limits<NumericType>::infinity(); NumericType currError; std::vector<std::vector<NumericType>> RandomChoice; std::sample(paramGrid.begin(), paramGrid.end(), std::back_inserter(RandomChoice), std::min({paramGrid.size(),nsamples}), std::mt19937{std::random_device{}()}); decltype(bestParam) currParam; for (gsl::index i = 0; i < RandomChoice.size(); ++i){ currParam = paramGrid[i]; estimator.SetParams(paramGrid[i]); currError = crossValidation(CRD, estimator, metric, split); if (currError < minError) { minError = currError; bestParam = currParam; } } } auto GetBestParams(){return bestParam;} private: std::vector<NumericType> bestParam;}; template<typename NumericType, Derived<CosanModel> Model, Derived<CosanMetric<NumericType>> Metric, Derived<Splitter> Split, typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type> class RandomGridSearchMultiParallel: public Search{ public: RandomGridSearchMultiParallel() = delete; RandomGridSearchMultiParallel( CosanData<NumericType> &CRD, Model & estimator, Metric & metric, Split & split, const std::vector<std::vector<NumericType>> & paramGrid, long unsigned int nsamples = 100,int nthreads = -1): Search() { NumericType minError = std::numeric_limits<NumericType>::infinity(); NumericType currError; std::vector<NumericType> RandomChoice; std::sample(paramGrid.begin(), paramGrid.end(), std::back_inserter(RandomChoice), std::min({paramGrid.size(),nsamples}), std::mt19937{std::random_device{}()}); std::vector<std::vector<NumericType>> allError(paramGrid.size()); if (nthreads == -1){ omp_set_num_threads(omp_get_max_threads()); } else{ omp_set_num_threads(nthreads); } #pragma omp parallel for for (gsl::index i = 0; i < paramGrid.size(); ++i){ estimator.SetParams(paramGrid[i]); allError[i] = crossValidation(CRD, estimator, metric, split); } bestParam =paramGrid[std::distance(allError.begin(), std::min_element(allError.begin(), allError.end()))]; } auto GetBestParams(){return bestParam;} private: std::vector<NumericType> bestParam;}; } #endif //COSAN_RANDOMGRIDSEARCH_H
core_cttqrt.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_zttqrt.c, normal z -> c, Fri Sep 28 17:38:25 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" #include <omp.h> // This will be swapped during the automatic code generation. #undef REAL #define COMPLEX /***************************************************************************//** * * @ingroup core_ttqrt * * Computes a QR factorization of a rectangular matrix * formed by coupling an n-by-n upper triangular tile A1 * on top of an m-by-n upper triangular tile A2: * * | A1 | = Q * R * | A2 | * ******************************************************************************* * * @param[in] m * The number of columns of the tile A2. m >= 0. * * @param[in] n * The number of rows of the tile A1. * The number of columns of the tiles A1 and A2. n >= 0. * * @param[in] ib * The inner-blocking size. ib >= 0. * * @param[in,out] A1 * On entry, the n-by-n tile A1. * On exit, the elements on and above the diagonal of the array * contain the n-by-n upper trapezoidal tile R; * the elements below the diagonal are not referenced. * * @param[in] lda1 * The leading dimension of the array A1. lda1 >= max(1,n). * * @param[in,out] A2 * On entry, the m-by-n upper triangular tile A2. * On exit, the elements on and above the diagonal of the array * with the matrix T represent * the unitary tile Q as a product of elementary reflectors * * @param[in] lda2 * The leading dimension of the tile A2. lda2 >= max(1,m). * * @param[out] T * The ib-by-n triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] ldt * The leading dimension of the array T. ldt >= ib. * * @param tau * Auxiliary workspace array of length n. * * @param work * Auxiliary workspace array of length ib*n. * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************/ __attribute__((weak)) int plasma_core_cttqrt(int m, int n, int ib, plasma_complex32_t *A1, int lda1, plasma_complex32_t *A2, int lda2, plasma_complex32_t *T, int ldt, plasma_complex32_t *tau, plasma_complex32_t *work) { // Check input arguments. if (m < 0) { plasma_coreblas_error("illegal value of m"); return -1; } if (n < 0) { plasma_coreblas_error("illegal value of n"); return -2; } if (ib < 0) { plasma_coreblas_error("illegal value of ib"); return -3; } if (A1 == NULL) { plasma_coreblas_error("NULL A1"); return -4; } if (lda1 < imax(1, m) && m > 0) { plasma_coreblas_error("illegal value of lda1"); return -5; } if (A2 == NULL) { plasma_coreblas_error("NULL A2"); return -6; } if (lda2 < imax(1, m) && m > 0) { plasma_coreblas_error("illegal value of lda2"); return -7; } if (T == NULL) { plasma_coreblas_error("NULL T"); return -8; } if (ldt < imax(1, ib) && ib > 0) { plasma_coreblas_error("illegal value of ldt"); return -9; } if (tau == NULL) { plasma_coreblas_error("NULL tau"); return -10; } if (work == NULL) { plasma_coreblas_error("NULL work"); return -11; } // quick return if ((m == 0) || (n == 0) || (ib == 0)) return PlasmaSuccess; // TODO: Need to check why some cases require this to avoid // uninitialized values //core_claset(PlasmaGeneral, ib, n, 0.0, 0.0, T, ldt); for (int ii = 0; ii < n; ii += ib) { int sb = imin(n-ii, ib); for (int i = 0; i < sb; i++) { int j = ii + i; int mi = imin(j+1, m); int ni = sb-i-1; // Generate elementary reflector H(j) to annihilate A2(1:mi, j). LAPACKE_clarfg_work( mi+1, &A1[lda1*j+j], &A2[lda2*j], 1, &tau[j]); if (ni > 0) { // Apply H(j-1) to A(j:m, j+1:ii+ib) from the left. cblas_ccopy( ni, &A1[lda1*(j+1)+j], lda1, work, 1); #ifdef COMPLEX LAPACKE_clacgv_work(ni, work, 1); #endif plasma_complex32_t zone = 1.0; cblas_cgemv( CblasColMajor, (CBLAS_TRANSPOSE)Plasma_ConjTrans, mi, ni, CBLAS_SADDR(zone), &A2[lda2*(j+1)], lda2, &A2[lda2*j], 1, CBLAS_SADDR(zone), work, 1); #ifdef COMPLEX LAPACKE_clacgv_work(ni, work, 1); #endif plasma_complex32_t alpha = -conjf(tau[j]); cblas_caxpy( ni, CBLAS_SADDR(alpha), work, 1, &A1[lda1*(j+1)+j], lda1); #ifdef COMPLEX LAPACKE_clacgv_work(ni, work, 1); #endif cblas_cgerc( CblasColMajor, mi, ni, CBLAS_SADDR(alpha), &A2[lda2*j], 1, work, 1, &A2[lda2*(j+1)], lda2); } // Calculate T. // T(0:i-1, j) = alpha * A2(0:m-1, ii:j-1)^H * A2(0:m-1, j) if (i > 0) { int l = imin(i, imax(0, m-ii)); plasma_complex32_t alpha = -(tau[j]); plasma_core_cpemv( Plasma_ConjTrans, PlasmaColumnwise, imin(j, m), i, l, alpha, &A2[lda2*ii], lda2, &A2[lda2*j], 1, 0.0, &T[ldt*j], 1, work); // T(0:i-1, j) = T(0:i-1, ii:j-1) * T(0:i-1, j) cblas_ctrmv( CblasColMajor, (CBLAS_UPLO)PlasmaUpper, (CBLAS_TRANSPOSE)PlasmaNoTrans, (CBLAS_DIAG)PlasmaNonUnit, i, &T[ldt*ii], ldt, &T[ldt*j], 1); } T[ldt*j+i] = tau[j]; } // Apply Q^H to the rest of the matrix from the left. if (n > ii+sb) { int mi = imin(ii+sb, m); int ni = n-(ii+sb); int l = imin(sb, imax(0, mi-ii)); plasma_core_cparfb( PlasmaLeft, Plasma_ConjTrans, PlasmaForward, PlasmaColumnwise, ib, ni, mi, ni, sb, l, //replaced sb by ib &A1[lda1*(ii+sb)+ii], lda1, &A2[lda2*(ii+sb)], lda2, &A2[lda2*ii], lda2, &T[ldt*ii], ldt, work, sb); } } return PlasmaSuccess; } /******************************************************************************/ void plasma_core_omp_cttqrt(int m, int n, int ib, plasma_complex32_t *A1, int lda1, plasma_complex32_t *A2, int lda2, plasma_complex32_t *T, int ldt, plasma_workspace_t work, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A1[0:lda1*n]) \ depend(inout:A2[0:lda2*n]) \ depend(out:T[0:ib*n]) { if (sequence->status == PlasmaSuccess) { // Prepare workspaces. int tid = omp_get_thread_num(); plasma_complex32_t *tau = ((plasma_complex32_t*)work.spaces[tid]); // Call the kernel. int info = plasma_core_cttqrt(m, n, ib, A1, lda1, A2, lda2, T, ldt, tau, tau+n); if (info != PlasmaSuccess) { plasma_error("core_cttqrt() failed"); plasma_request_fail(sequence, request, PlasmaErrorInternal); } } } }
acado_solver.c
/* * This file was auto-generated using the ACADO Toolkit. * * While ACADO Toolkit is free software released under the terms of * the GNU Lesser General Public License (LGPL), the generated code * as such remains the property of the user who used ACADO Toolkit * to generate this code. In particular, user dependent data of the code * do not inherit the GNU LGPL license. On the other hand, parts of the * generated code that are a direct copy of source code from the * ACADO Toolkit or the software tools it is based on, remain, as derived * work, automatically covered by the LGPL license. * * ACADO Toolkit 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. * */ #include "acado_common.h" /******************************************************************************/ /* */ /* ACADO code generation */ /* */ /******************************************************************************/ /** Row vector of size: 129 */ real_t state[ 129 ]; int acado_modelSimulation( ) { int ret; int lRun1; ret = 0; #pragma omp parallel for private(lRun1, state) shared(acadoWorkspace, acadoVariables) for (lRun1 = 0; lRun1 < 20; ++lRun1) { state[0] = acadoVariables.x[lRun1 * 9]; state[1] = acadoVariables.x[lRun1 * 9 + 1]; state[2] = acadoVariables.x[lRun1 * 9 + 2]; state[3] = acadoVariables.x[lRun1 * 9 + 3]; state[4] = acadoVariables.x[lRun1 * 9 + 4]; state[5] = acadoVariables.x[lRun1 * 9 + 5]; state[6] = acadoVariables.x[lRun1 * 9 + 6]; state[7] = acadoVariables.x[lRun1 * 9 + 7]; state[8] = acadoVariables.x[lRun1 * 9 + 8]; state[117] = acadoVariables.u[lRun1 * 3]; state[118] = acadoVariables.u[lRun1 * 3 + 1]; state[119] = acadoVariables.u[lRun1 * 3 + 2]; state[120] = acadoVariables.od[lRun1 * 9]; state[121] = acadoVariables.od[lRun1 * 9 + 1]; state[122] = acadoVariables.od[lRun1 * 9 + 2]; state[123] = acadoVariables.od[lRun1 * 9 + 3]; state[124] = acadoVariables.od[lRun1 * 9 + 4]; state[125] = acadoVariables.od[lRun1 * 9 + 5]; state[126] = acadoVariables.od[lRun1 * 9 + 6]; state[127] = acadoVariables.od[lRun1 * 9 + 7]; state[128] = acadoVariables.od[lRun1 * 9 + 8]; ret = acado_integrate(state, 1); acadoWorkspace.d[lRun1 * 9] = state[0] - acadoVariables.x[lRun1 * 9 + 9]; acadoWorkspace.d[lRun1 * 9 + 1] = state[1] - acadoVariables.x[lRun1 * 9 + 10]; acadoWorkspace.d[lRun1 * 9 + 2] = state[2] - acadoVariables.x[lRun1 * 9 + 11]; acadoWorkspace.d[lRun1 * 9 + 3] = state[3] - acadoVariables.x[lRun1 * 9 + 12]; acadoWorkspace.d[lRun1 * 9 + 4] = state[4] - acadoVariables.x[lRun1 * 9 + 13]; acadoWorkspace.d[lRun1 * 9 + 5] = state[5] - acadoVariables.x[lRun1 * 9 + 14]; acadoWorkspace.d[lRun1 * 9 + 6] = state[6] - acadoVariables.x[lRun1 * 9 + 15]; acadoWorkspace.d[lRun1 * 9 + 7] = state[7] - acadoVariables.x[lRun1 * 9 + 16]; acadoWorkspace.d[lRun1 * 9 + 8] = state[8] - acadoVariables.x[lRun1 * 9 + 17]; acadoWorkspace.evGx[lRun1 * 81] = state[9]; acadoWorkspace.evGx[lRun1 * 81 + 1] = state[10]; acadoWorkspace.evGx[lRun1 * 81 + 2] = state[11]; acadoWorkspace.evGx[lRun1 * 81 + 3] = state[12]; acadoWorkspace.evGx[lRun1 * 81 + 4] = state[13]; acadoWorkspace.evGx[lRun1 * 81 + 5] = state[14]; acadoWorkspace.evGx[lRun1 * 81 + 6] = state[15]; acadoWorkspace.evGx[lRun1 * 81 + 7] = state[16]; acadoWorkspace.evGx[lRun1 * 81 + 8] = state[17]; acadoWorkspace.evGx[lRun1 * 81 + 9] = state[18]; acadoWorkspace.evGx[lRun1 * 81 + 10] = state[19]; acadoWorkspace.evGx[lRun1 * 81 + 11] = state[20]; acadoWorkspace.evGx[lRun1 * 81 + 12] = state[21]; acadoWorkspace.evGx[lRun1 * 81 + 13] = state[22]; acadoWorkspace.evGx[lRun1 * 81 + 14] = state[23]; acadoWorkspace.evGx[lRun1 * 81 + 15] = state[24]; acadoWorkspace.evGx[lRun1 * 81 + 16] = state[25]; acadoWorkspace.evGx[lRun1 * 81 + 17] = state[26]; acadoWorkspace.evGx[lRun1 * 81 + 18] = state[27]; acadoWorkspace.evGx[lRun1 * 81 + 19] = state[28]; acadoWorkspace.evGx[lRun1 * 81 + 20] = state[29]; acadoWorkspace.evGx[lRun1 * 81 + 21] = state[30]; acadoWorkspace.evGx[lRun1 * 81 + 22] = state[31]; acadoWorkspace.evGx[lRun1 * 81 + 23] = state[32]; acadoWorkspace.evGx[lRun1 * 81 + 24] = state[33]; acadoWorkspace.evGx[lRun1 * 81 + 25] = state[34]; acadoWorkspace.evGx[lRun1 * 81 + 26] = state[35]; acadoWorkspace.evGx[lRun1 * 81 + 27] = state[36]; acadoWorkspace.evGx[lRun1 * 81 + 28] = state[37]; acadoWorkspace.evGx[lRun1 * 81 + 29] = state[38]; acadoWorkspace.evGx[lRun1 * 81 + 30] = state[39]; acadoWorkspace.evGx[lRun1 * 81 + 31] = state[40]; acadoWorkspace.evGx[lRun1 * 81 + 32] = state[41]; acadoWorkspace.evGx[lRun1 * 81 + 33] = state[42]; acadoWorkspace.evGx[lRun1 * 81 + 34] = state[43]; acadoWorkspace.evGx[lRun1 * 81 + 35] = state[44]; acadoWorkspace.evGx[lRun1 * 81 + 36] = state[45]; acadoWorkspace.evGx[lRun1 * 81 + 37] = state[46]; acadoWorkspace.evGx[lRun1 * 81 + 38] = state[47]; acadoWorkspace.evGx[lRun1 * 81 + 39] = state[48]; acadoWorkspace.evGx[lRun1 * 81 + 40] = state[49]; acadoWorkspace.evGx[lRun1 * 81 + 41] = state[50]; acadoWorkspace.evGx[lRun1 * 81 + 42] = state[51]; acadoWorkspace.evGx[lRun1 * 81 + 43] = state[52]; acadoWorkspace.evGx[lRun1 * 81 + 44] = state[53]; acadoWorkspace.evGx[lRun1 * 81 + 45] = state[54]; acadoWorkspace.evGx[lRun1 * 81 + 46] = state[55]; acadoWorkspace.evGx[lRun1 * 81 + 47] = state[56]; acadoWorkspace.evGx[lRun1 * 81 + 48] = state[57]; acadoWorkspace.evGx[lRun1 * 81 + 49] = state[58]; acadoWorkspace.evGx[lRun1 * 81 + 50] = state[59]; acadoWorkspace.evGx[lRun1 * 81 + 51] = state[60]; acadoWorkspace.evGx[lRun1 * 81 + 52] = state[61]; acadoWorkspace.evGx[lRun1 * 81 + 53] = state[62]; acadoWorkspace.evGx[lRun1 * 81 + 54] = state[63]; acadoWorkspace.evGx[lRun1 * 81 + 55] = state[64]; acadoWorkspace.evGx[lRun1 * 81 + 56] = state[65]; acadoWorkspace.evGx[lRun1 * 81 + 57] = state[66]; acadoWorkspace.evGx[lRun1 * 81 + 58] = state[67]; acadoWorkspace.evGx[lRun1 * 81 + 59] = state[68]; acadoWorkspace.evGx[lRun1 * 81 + 60] = state[69]; acadoWorkspace.evGx[lRun1 * 81 + 61] = state[70]; acadoWorkspace.evGx[lRun1 * 81 + 62] = state[71]; acadoWorkspace.evGx[lRun1 * 81 + 63] = state[72]; acadoWorkspace.evGx[lRun1 * 81 + 64] = state[73]; acadoWorkspace.evGx[lRun1 * 81 + 65] = state[74]; acadoWorkspace.evGx[lRun1 * 81 + 66] = state[75]; acadoWorkspace.evGx[lRun1 * 81 + 67] = state[76]; acadoWorkspace.evGx[lRun1 * 81 + 68] = state[77]; acadoWorkspace.evGx[lRun1 * 81 + 69] = state[78]; acadoWorkspace.evGx[lRun1 * 81 + 70] = state[79]; acadoWorkspace.evGx[lRun1 * 81 + 71] = state[80]; acadoWorkspace.evGx[lRun1 * 81 + 72] = state[81]; acadoWorkspace.evGx[lRun1 * 81 + 73] = state[82]; acadoWorkspace.evGx[lRun1 * 81 + 74] = state[83]; acadoWorkspace.evGx[lRun1 * 81 + 75] = state[84]; acadoWorkspace.evGx[lRun1 * 81 + 76] = state[85]; acadoWorkspace.evGx[lRun1 * 81 + 77] = state[86]; acadoWorkspace.evGx[lRun1 * 81 + 78] = state[87]; acadoWorkspace.evGx[lRun1 * 81 + 79] = state[88]; acadoWorkspace.evGx[lRun1 * 81 + 80] = state[89]; acadoWorkspace.evGu[lRun1 * 27] = state[90]; acadoWorkspace.evGu[lRun1 * 27 + 1] = state[91]; acadoWorkspace.evGu[lRun1 * 27 + 2] = state[92]; acadoWorkspace.evGu[lRun1 * 27 + 3] = state[93]; acadoWorkspace.evGu[lRun1 * 27 + 4] = state[94]; acadoWorkspace.evGu[lRun1 * 27 + 5] = state[95]; acadoWorkspace.evGu[lRun1 * 27 + 6] = state[96]; acadoWorkspace.evGu[lRun1 * 27 + 7] = state[97]; acadoWorkspace.evGu[lRun1 * 27 + 8] = state[98]; acadoWorkspace.evGu[lRun1 * 27 + 9] = state[99]; acadoWorkspace.evGu[lRun1 * 27 + 10] = state[100]; acadoWorkspace.evGu[lRun1 * 27 + 11] = state[101]; acadoWorkspace.evGu[lRun1 * 27 + 12] = state[102]; acadoWorkspace.evGu[lRun1 * 27 + 13] = state[103]; acadoWorkspace.evGu[lRun1 * 27 + 14] = state[104]; acadoWorkspace.evGu[lRun1 * 27 + 15] = state[105]; acadoWorkspace.evGu[lRun1 * 27 + 16] = state[106]; acadoWorkspace.evGu[lRun1 * 27 + 17] = state[107]; acadoWorkspace.evGu[lRun1 * 27 + 18] = state[108]; acadoWorkspace.evGu[lRun1 * 27 + 19] = state[109]; acadoWorkspace.evGu[lRun1 * 27 + 20] = state[110]; acadoWorkspace.evGu[lRun1 * 27 + 21] = state[111]; acadoWorkspace.evGu[lRun1 * 27 + 22] = state[112]; acadoWorkspace.evGu[lRun1 * 27 + 23] = state[113]; acadoWorkspace.evGu[lRun1 * 27 + 24] = state[114]; acadoWorkspace.evGu[lRun1 * 27 + 25] = state[115]; acadoWorkspace.evGu[lRun1 * 27 + 26] = state[116]; } return ret; } void acado_evaluateLSQ(const real_t* in, real_t* out) { const real_t* xd = in; const real_t* u = in + 9; /* Vector of auxiliary variables; number of elements: 4. */ real_t* a = acadoWorkspace.objAuxVar; /* Compute intermediate quantities: */ a[0] = (cos(xd[4])); a[1] = (cos(xd[3])); a[2] = ((real_t)(-1.0000000000000000e+00)*(sin(xd[3]))); a[3] = ((real_t)(-1.0000000000000000e+00)*(sin(xd[4]))); /* Compute outputs: */ out[0] = xd[6]; out[1] = xd[7]; out[2] = xd[8]; out[3] = xd[0]; out[4] = xd[1]; out[5] = xd[2]; out[6] = xd[3]; out[7] = xd[4]; out[8] = u[0]; out[9] = u[1]; out[10] = (((a[0]*a[1])*u[2])-(real_t)(9.8065999999999995e+00)); out[11] = (real_t)(0.0000000000000000e+00); out[12] = (real_t)(0.0000000000000000e+00); out[13] = (real_t)(0.0000000000000000e+00); out[14] = (real_t)(0.0000000000000000e+00); out[15] = (real_t)(0.0000000000000000e+00); out[16] = (real_t)(0.0000000000000000e+00); out[17] = (real_t)(1.0000000000000000e+00); out[18] = (real_t)(0.0000000000000000e+00); out[19] = (real_t)(0.0000000000000000e+00); out[20] = (real_t)(0.0000000000000000e+00); out[21] = (real_t)(0.0000000000000000e+00); out[22] = (real_t)(0.0000000000000000e+00); out[23] = (real_t)(0.0000000000000000e+00); out[24] = (real_t)(0.0000000000000000e+00); out[25] = (real_t)(0.0000000000000000e+00); out[26] = (real_t)(0.0000000000000000e+00); out[27] = (real_t)(1.0000000000000000e+00); out[28] = (real_t)(0.0000000000000000e+00); out[29] = (real_t)(0.0000000000000000e+00); out[30] = (real_t)(0.0000000000000000e+00); out[31] = (real_t)(0.0000000000000000e+00); out[32] = (real_t)(0.0000000000000000e+00); out[33] = (real_t)(0.0000000000000000e+00); out[34] = (real_t)(0.0000000000000000e+00); out[35] = (real_t)(0.0000000000000000e+00); out[36] = (real_t)(0.0000000000000000e+00); out[37] = (real_t)(1.0000000000000000e+00); out[38] = (real_t)(1.0000000000000000e+00); out[39] = (real_t)(0.0000000000000000e+00); out[40] = (real_t)(0.0000000000000000e+00); out[41] = (real_t)(0.0000000000000000e+00); out[42] = (real_t)(0.0000000000000000e+00); out[43] = (real_t)(0.0000000000000000e+00); out[44] = (real_t)(0.0000000000000000e+00); out[45] = (real_t)(0.0000000000000000e+00); out[46] = (real_t)(0.0000000000000000e+00); out[47] = (real_t)(0.0000000000000000e+00); out[48] = (real_t)(1.0000000000000000e+00); out[49] = (real_t)(0.0000000000000000e+00); out[50] = (real_t)(0.0000000000000000e+00); out[51] = (real_t)(0.0000000000000000e+00); out[52] = (real_t)(0.0000000000000000e+00); out[53] = (real_t)(0.0000000000000000e+00); out[54] = (real_t)(0.0000000000000000e+00); out[55] = (real_t)(0.0000000000000000e+00); out[56] = (real_t)(0.0000000000000000e+00); out[57] = (real_t)(0.0000000000000000e+00); out[58] = (real_t)(1.0000000000000000e+00); out[59] = (real_t)(0.0000000000000000e+00); out[60] = (real_t)(0.0000000000000000e+00); out[61] = (real_t)(0.0000000000000000e+00); out[62] = (real_t)(0.0000000000000000e+00); out[63] = (real_t)(0.0000000000000000e+00); out[64] = (real_t)(0.0000000000000000e+00); out[65] = (real_t)(0.0000000000000000e+00); out[66] = (real_t)(0.0000000000000000e+00); out[67] = (real_t)(0.0000000000000000e+00); out[68] = (real_t)(1.0000000000000000e+00); out[69] = (real_t)(0.0000000000000000e+00); out[70] = (real_t)(0.0000000000000000e+00); out[71] = (real_t)(0.0000000000000000e+00); out[72] = (real_t)(0.0000000000000000e+00); out[73] = (real_t)(0.0000000000000000e+00); out[74] = (real_t)(0.0000000000000000e+00); out[75] = (real_t)(0.0000000000000000e+00); out[76] = (real_t)(0.0000000000000000e+00); out[77] = (real_t)(0.0000000000000000e+00); out[78] = (real_t)(1.0000000000000000e+00); out[79] = (real_t)(0.0000000000000000e+00); out[80] = (real_t)(0.0000000000000000e+00); out[81] = (real_t)(0.0000000000000000e+00); out[82] = (real_t)(0.0000000000000000e+00); out[83] = (real_t)(0.0000000000000000e+00); out[84] = (real_t)(0.0000000000000000e+00); out[85] = (real_t)(0.0000000000000000e+00); out[86] = (real_t)(0.0000000000000000e+00); out[87] = (real_t)(0.0000000000000000e+00); out[88] = (real_t)(0.0000000000000000e+00); out[89] = (real_t)(0.0000000000000000e+00); out[90] = (real_t)(0.0000000000000000e+00); out[91] = (real_t)(0.0000000000000000e+00); out[92] = (real_t)(0.0000000000000000e+00); out[93] = (real_t)(0.0000000000000000e+00); out[94] = (real_t)(0.0000000000000000e+00); out[95] = (real_t)(0.0000000000000000e+00); out[96] = (real_t)(0.0000000000000000e+00); out[97] = (real_t)(0.0000000000000000e+00); out[98] = (real_t)(0.0000000000000000e+00); out[99] = (real_t)(0.0000000000000000e+00); out[100] = (real_t)(0.0000000000000000e+00); out[101] = (real_t)(0.0000000000000000e+00); out[102] = (real_t)(0.0000000000000000e+00); out[103] = (real_t)(0.0000000000000000e+00); out[104] = ((a[0]*a[2])*u[2]); out[105] = ((a[3]*a[1])*u[2]); out[106] = (real_t)(0.0000000000000000e+00); out[107] = (real_t)(0.0000000000000000e+00); out[108] = (real_t)(0.0000000000000000e+00); out[109] = (real_t)(0.0000000000000000e+00); out[110] = (real_t)(0.0000000000000000e+00); out[111] = (real_t)(0.0000000000000000e+00); out[112] = (real_t)(0.0000000000000000e+00); out[113] = (real_t)(0.0000000000000000e+00); out[114] = (real_t)(0.0000000000000000e+00); out[115] = (real_t)(0.0000000000000000e+00); out[116] = (real_t)(0.0000000000000000e+00); out[117] = (real_t)(0.0000000000000000e+00); out[118] = (real_t)(0.0000000000000000e+00); out[119] = (real_t)(0.0000000000000000e+00); out[120] = (real_t)(0.0000000000000000e+00); out[121] = (real_t)(0.0000000000000000e+00); out[122] = (real_t)(0.0000000000000000e+00); out[123] = (real_t)(0.0000000000000000e+00); out[124] = (real_t)(0.0000000000000000e+00); out[125] = (real_t)(0.0000000000000000e+00); out[126] = (real_t)(0.0000000000000000e+00); out[127] = (real_t)(0.0000000000000000e+00); out[128] = (real_t)(0.0000000000000000e+00); out[129] = (real_t)(0.0000000000000000e+00); out[130] = (real_t)(0.0000000000000000e+00); out[131] = (real_t)(0.0000000000000000e+00); out[132] = (real_t)(0.0000000000000000e+00); out[133] = (real_t)(0.0000000000000000e+00); out[134] = (real_t)(1.0000000000000000e+00); out[135] = (real_t)(0.0000000000000000e+00); out[136] = (real_t)(0.0000000000000000e+00); out[137] = (real_t)(0.0000000000000000e+00); out[138] = (real_t)(1.0000000000000000e+00); out[139] = (real_t)(0.0000000000000000e+00); out[140] = (real_t)(0.0000000000000000e+00); out[141] = (real_t)(0.0000000000000000e+00); out[142] = (a[0]*a[1]); } void acado_evaluateLSQEndTerm(const real_t* in, real_t* out) { const real_t* xd = in; /* Compute outputs: */ out[0] = xd[6]; out[1] = xd[7]; out[2] = xd[8]; out[3] = xd[0]; out[4] = xd[1]; out[5] = xd[2]; } void acado_setObjQ1Q2( real_t* const tmpFx, real_t* const tmpObjS, real_t* const tmpQ1, real_t* const tmpQ2 ) { tmpQ2[0] = + tmpFx[0]*tmpObjS[0] + tmpFx[9]*tmpObjS[11] + tmpFx[18]*tmpObjS[22] + tmpFx[27]*tmpObjS[33] + tmpFx[36]*tmpObjS[44] + tmpFx[45]*tmpObjS[55] + tmpFx[54]*tmpObjS[66] + tmpFx[63]*tmpObjS[77] + tmpFx[72]*tmpObjS[88] + tmpFx[81]*tmpObjS[99] + tmpFx[90]*tmpObjS[110]; tmpQ2[1] = + tmpFx[0]*tmpObjS[1] + tmpFx[9]*tmpObjS[12] + tmpFx[18]*tmpObjS[23] + tmpFx[27]*tmpObjS[34] + tmpFx[36]*tmpObjS[45] + tmpFx[45]*tmpObjS[56] + tmpFx[54]*tmpObjS[67] + tmpFx[63]*tmpObjS[78] + tmpFx[72]*tmpObjS[89] + tmpFx[81]*tmpObjS[100] + tmpFx[90]*tmpObjS[111]; tmpQ2[2] = + tmpFx[0]*tmpObjS[2] + tmpFx[9]*tmpObjS[13] + tmpFx[18]*tmpObjS[24] + tmpFx[27]*tmpObjS[35] + tmpFx[36]*tmpObjS[46] + tmpFx[45]*tmpObjS[57] + tmpFx[54]*tmpObjS[68] + tmpFx[63]*tmpObjS[79] + tmpFx[72]*tmpObjS[90] + tmpFx[81]*tmpObjS[101] + tmpFx[90]*tmpObjS[112]; tmpQ2[3] = + tmpFx[0]*tmpObjS[3] + tmpFx[9]*tmpObjS[14] + tmpFx[18]*tmpObjS[25] + tmpFx[27]*tmpObjS[36] + tmpFx[36]*tmpObjS[47] + tmpFx[45]*tmpObjS[58] + tmpFx[54]*tmpObjS[69] + tmpFx[63]*tmpObjS[80] + tmpFx[72]*tmpObjS[91] + tmpFx[81]*tmpObjS[102] + tmpFx[90]*tmpObjS[113]; tmpQ2[4] = + tmpFx[0]*tmpObjS[4] + tmpFx[9]*tmpObjS[15] + tmpFx[18]*tmpObjS[26] + tmpFx[27]*tmpObjS[37] + tmpFx[36]*tmpObjS[48] + tmpFx[45]*tmpObjS[59] + tmpFx[54]*tmpObjS[70] + tmpFx[63]*tmpObjS[81] + tmpFx[72]*tmpObjS[92] + tmpFx[81]*tmpObjS[103] + tmpFx[90]*tmpObjS[114]; tmpQ2[5] = + tmpFx[0]*tmpObjS[5] + tmpFx[9]*tmpObjS[16] + tmpFx[18]*tmpObjS[27] + tmpFx[27]*tmpObjS[38] + tmpFx[36]*tmpObjS[49] + tmpFx[45]*tmpObjS[60] + tmpFx[54]*tmpObjS[71] + tmpFx[63]*tmpObjS[82] + tmpFx[72]*tmpObjS[93] + tmpFx[81]*tmpObjS[104] + tmpFx[90]*tmpObjS[115]; tmpQ2[6] = + tmpFx[0]*tmpObjS[6] + tmpFx[9]*tmpObjS[17] + tmpFx[18]*tmpObjS[28] + tmpFx[27]*tmpObjS[39] + tmpFx[36]*tmpObjS[50] + tmpFx[45]*tmpObjS[61] + tmpFx[54]*tmpObjS[72] + tmpFx[63]*tmpObjS[83] + tmpFx[72]*tmpObjS[94] + tmpFx[81]*tmpObjS[105] + tmpFx[90]*tmpObjS[116]; tmpQ2[7] = + tmpFx[0]*tmpObjS[7] + tmpFx[9]*tmpObjS[18] + tmpFx[18]*tmpObjS[29] + tmpFx[27]*tmpObjS[40] + tmpFx[36]*tmpObjS[51] + tmpFx[45]*tmpObjS[62] + tmpFx[54]*tmpObjS[73] + tmpFx[63]*tmpObjS[84] + tmpFx[72]*tmpObjS[95] + tmpFx[81]*tmpObjS[106] + tmpFx[90]*tmpObjS[117]; tmpQ2[8] = + tmpFx[0]*tmpObjS[8] + tmpFx[9]*tmpObjS[19] + tmpFx[18]*tmpObjS[30] + tmpFx[27]*tmpObjS[41] + tmpFx[36]*tmpObjS[52] + tmpFx[45]*tmpObjS[63] + tmpFx[54]*tmpObjS[74] + tmpFx[63]*tmpObjS[85] + tmpFx[72]*tmpObjS[96] + tmpFx[81]*tmpObjS[107] + tmpFx[90]*tmpObjS[118]; tmpQ2[9] = + tmpFx[0]*tmpObjS[9] + tmpFx[9]*tmpObjS[20] + tmpFx[18]*tmpObjS[31] + tmpFx[27]*tmpObjS[42] + tmpFx[36]*tmpObjS[53] + tmpFx[45]*tmpObjS[64] + tmpFx[54]*tmpObjS[75] + tmpFx[63]*tmpObjS[86] + tmpFx[72]*tmpObjS[97] + tmpFx[81]*tmpObjS[108] + tmpFx[90]*tmpObjS[119]; tmpQ2[10] = + tmpFx[0]*tmpObjS[10] + tmpFx[9]*tmpObjS[21] + tmpFx[18]*tmpObjS[32] + tmpFx[27]*tmpObjS[43] + tmpFx[36]*tmpObjS[54] + tmpFx[45]*tmpObjS[65] + tmpFx[54]*tmpObjS[76] + tmpFx[63]*tmpObjS[87] + tmpFx[72]*tmpObjS[98] + tmpFx[81]*tmpObjS[109] + tmpFx[90]*tmpObjS[120]; tmpQ2[11] = + tmpFx[1]*tmpObjS[0] + tmpFx[10]*tmpObjS[11] + tmpFx[19]*tmpObjS[22] + tmpFx[28]*tmpObjS[33] + tmpFx[37]*tmpObjS[44] + tmpFx[46]*tmpObjS[55] + tmpFx[55]*tmpObjS[66] + tmpFx[64]*tmpObjS[77] + tmpFx[73]*tmpObjS[88] + tmpFx[82]*tmpObjS[99] + tmpFx[91]*tmpObjS[110]; tmpQ2[12] = + tmpFx[1]*tmpObjS[1] + tmpFx[10]*tmpObjS[12] + tmpFx[19]*tmpObjS[23] + tmpFx[28]*tmpObjS[34] + tmpFx[37]*tmpObjS[45] + tmpFx[46]*tmpObjS[56] + tmpFx[55]*tmpObjS[67] + tmpFx[64]*tmpObjS[78] + tmpFx[73]*tmpObjS[89] + tmpFx[82]*tmpObjS[100] + tmpFx[91]*tmpObjS[111]; tmpQ2[13] = + tmpFx[1]*tmpObjS[2] + tmpFx[10]*tmpObjS[13] + tmpFx[19]*tmpObjS[24] + tmpFx[28]*tmpObjS[35] + tmpFx[37]*tmpObjS[46] + tmpFx[46]*tmpObjS[57] + tmpFx[55]*tmpObjS[68] + tmpFx[64]*tmpObjS[79] + tmpFx[73]*tmpObjS[90] + tmpFx[82]*tmpObjS[101] + tmpFx[91]*tmpObjS[112]; tmpQ2[14] = + tmpFx[1]*tmpObjS[3] + tmpFx[10]*tmpObjS[14] + tmpFx[19]*tmpObjS[25] + tmpFx[28]*tmpObjS[36] + tmpFx[37]*tmpObjS[47] + tmpFx[46]*tmpObjS[58] + tmpFx[55]*tmpObjS[69] + tmpFx[64]*tmpObjS[80] + tmpFx[73]*tmpObjS[91] + tmpFx[82]*tmpObjS[102] + tmpFx[91]*tmpObjS[113]; tmpQ2[15] = + tmpFx[1]*tmpObjS[4] + tmpFx[10]*tmpObjS[15] + tmpFx[19]*tmpObjS[26] + tmpFx[28]*tmpObjS[37] + tmpFx[37]*tmpObjS[48] + tmpFx[46]*tmpObjS[59] + tmpFx[55]*tmpObjS[70] + tmpFx[64]*tmpObjS[81] + tmpFx[73]*tmpObjS[92] + tmpFx[82]*tmpObjS[103] + tmpFx[91]*tmpObjS[114]; tmpQ2[16] = + tmpFx[1]*tmpObjS[5] + tmpFx[10]*tmpObjS[16] + tmpFx[19]*tmpObjS[27] + tmpFx[28]*tmpObjS[38] + tmpFx[37]*tmpObjS[49] + tmpFx[46]*tmpObjS[60] + tmpFx[55]*tmpObjS[71] + tmpFx[64]*tmpObjS[82] + tmpFx[73]*tmpObjS[93] + tmpFx[82]*tmpObjS[104] + tmpFx[91]*tmpObjS[115]; tmpQ2[17] = + tmpFx[1]*tmpObjS[6] + tmpFx[10]*tmpObjS[17] + tmpFx[19]*tmpObjS[28] + tmpFx[28]*tmpObjS[39] + tmpFx[37]*tmpObjS[50] + tmpFx[46]*tmpObjS[61] + tmpFx[55]*tmpObjS[72] + tmpFx[64]*tmpObjS[83] + tmpFx[73]*tmpObjS[94] + tmpFx[82]*tmpObjS[105] + tmpFx[91]*tmpObjS[116]; tmpQ2[18] = + tmpFx[1]*tmpObjS[7] + tmpFx[10]*tmpObjS[18] + tmpFx[19]*tmpObjS[29] + tmpFx[28]*tmpObjS[40] + tmpFx[37]*tmpObjS[51] + tmpFx[46]*tmpObjS[62] + tmpFx[55]*tmpObjS[73] + tmpFx[64]*tmpObjS[84] + tmpFx[73]*tmpObjS[95] + tmpFx[82]*tmpObjS[106] + tmpFx[91]*tmpObjS[117]; tmpQ2[19] = + tmpFx[1]*tmpObjS[8] + tmpFx[10]*tmpObjS[19] + tmpFx[19]*tmpObjS[30] + tmpFx[28]*tmpObjS[41] + tmpFx[37]*tmpObjS[52] + tmpFx[46]*tmpObjS[63] + tmpFx[55]*tmpObjS[74] + tmpFx[64]*tmpObjS[85] + tmpFx[73]*tmpObjS[96] + tmpFx[82]*tmpObjS[107] + tmpFx[91]*tmpObjS[118]; tmpQ2[20] = + tmpFx[1]*tmpObjS[9] + tmpFx[10]*tmpObjS[20] + tmpFx[19]*tmpObjS[31] + tmpFx[28]*tmpObjS[42] + tmpFx[37]*tmpObjS[53] + tmpFx[46]*tmpObjS[64] + tmpFx[55]*tmpObjS[75] + tmpFx[64]*tmpObjS[86] + tmpFx[73]*tmpObjS[97] + tmpFx[82]*tmpObjS[108] + tmpFx[91]*tmpObjS[119]; tmpQ2[21] = + tmpFx[1]*tmpObjS[10] + tmpFx[10]*tmpObjS[21] + tmpFx[19]*tmpObjS[32] + tmpFx[28]*tmpObjS[43] + tmpFx[37]*tmpObjS[54] + tmpFx[46]*tmpObjS[65] + tmpFx[55]*tmpObjS[76] + tmpFx[64]*tmpObjS[87] + tmpFx[73]*tmpObjS[98] + tmpFx[82]*tmpObjS[109] + tmpFx[91]*tmpObjS[120]; tmpQ2[22] = + tmpFx[2]*tmpObjS[0] + tmpFx[11]*tmpObjS[11] + tmpFx[20]*tmpObjS[22] + tmpFx[29]*tmpObjS[33] + tmpFx[38]*tmpObjS[44] + tmpFx[47]*tmpObjS[55] + tmpFx[56]*tmpObjS[66] + tmpFx[65]*tmpObjS[77] + tmpFx[74]*tmpObjS[88] + tmpFx[83]*tmpObjS[99] + tmpFx[92]*tmpObjS[110]; tmpQ2[23] = + tmpFx[2]*tmpObjS[1] + tmpFx[11]*tmpObjS[12] + tmpFx[20]*tmpObjS[23] + tmpFx[29]*tmpObjS[34] + tmpFx[38]*tmpObjS[45] + tmpFx[47]*tmpObjS[56] + tmpFx[56]*tmpObjS[67] + tmpFx[65]*tmpObjS[78] + tmpFx[74]*tmpObjS[89] + tmpFx[83]*tmpObjS[100] + tmpFx[92]*tmpObjS[111]; tmpQ2[24] = + tmpFx[2]*tmpObjS[2] + tmpFx[11]*tmpObjS[13] + tmpFx[20]*tmpObjS[24] + tmpFx[29]*tmpObjS[35] + tmpFx[38]*tmpObjS[46] + tmpFx[47]*tmpObjS[57] + tmpFx[56]*tmpObjS[68] + tmpFx[65]*tmpObjS[79] + tmpFx[74]*tmpObjS[90] + tmpFx[83]*tmpObjS[101] + tmpFx[92]*tmpObjS[112]; tmpQ2[25] = + tmpFx[2]*tmpObjS[3] + tmpFx[11]*tmpObjS[14] + tmpFx[20]*tmpObjS[25] + tmpFx[29]*tmpObjS[36] + tmpFx[38]*tmpObjS[47] + tmpFx[47]*tmpObjS[58] + tmpFx[56]*tmpObjS[69] + tmpFx[65]*tmpObjS[80] + tmpFx[74]*tmpObjS[91] + tmpFx[83]*tmpObjS[102] + tmpFx[92]*tmpObjS[113]; tmpQ2[26] = + tmpFx[2]*tmpObjS[4] + tmpFx[11]*tmpObjS[15] + tmpFx[20]*tmpObjS[26] + tmpFx[29]*tmpObjS[37] + tmpFx[38]*tmpObjS[48] + tmpFx[47]*tmpObjS[59] + tmpFx[56]*tmpObjS[70] + tmpFx[65]*tmpObjS[81] + tmpFx[74]*tmpObjS[92] + tmpFx[83]*tmpObjS[103] + tmpFx[92]*tmpObjS[114]; tmpQ2[27] = + tmpFx[2]*tmpObjS[5] + tmpFx[11]*tmpObjS[16] + tmpFx[20]*tmpObjS[27] + tmpFx[29]*tmpObjS[38] + tmpFx[38]*tmpObjS[49] + tmpFx[47]*tmpObjS[60] + tmpFx[56]*tmpObjS[71] + tmpFx[65]*tmpObjS[82] + tmpFx[74]*tmpObjS[93] + tmpFx[83]*tmpObjS[104] + tmpFx[92]*tmpObjS[115]; tmpQ2[28] = + tmpFx[2]*tmpObjS[6] + tmpFx[11]*tmpObjS[17] + tmpFx[20]*tmpObjS[28] + tmpFx[29]*tmpObjS[39] + tmpFx[38]*tmpObjS[50] + tmpFx[47]*tmpObjS[61] + tmpFx[56]*tmpObjS[72] + tmpFx[65]*tmpObjS[83] + tmpFx[74]*tmpObjS[94] + tmpFx[83]*tmpObjS[105] + tmpFx[92]*tmpObjS[116]; tmpQ2[29] = + tmpFx[2]*tmpObjS[7] + tmpFx[11]*tmpObjS[18] + tmpFx[20]*tmpObjS[29] + tmpFx[29]*tmpObjS[40] + tmpFx[38]*tmpObjS[51] + tmpFx[47]*tmpObjS[62] + tmpFx[56]*tmpObjS[73] + tmpFx[65]*tmpObjS[84] + tmpFx[74]*tmpObjS[95] + tmpFx[83]*tmpObjS[106] + tmpFx[92]*tmpObjS[117]; tmpQ2[30] = + tmpFx[2]*tmpObjS[8] + tmpFx[11]*tmpObjS[19] + tmpFx[20]*tmpObjS[30] + tmpFx[29]*tmpObjS[41] + tmpFx[38]*tmpObjS[52] + tmpFx[47]*tmpObjS[63] + tmpFx[56]*tmpObjS[74] + tmpFx[65]*tmpObjS[85] + tmpFx[74]*tmpObjS[96] + tmpFx[83]*tmpObjS[107] + tmpFx[92]*tmpObjS[118]; tmpQ2[31] = + tmpFx[2]*tmpObjS[9] + tmpFx[11]*tmpObjS[20] + tmpFx[20]*tmpObjS[31] + tmpFx[29]*tmpObjS[42] + tmpFx[38]*tmpObjS[53] + tmpFx[47]*tmpObjS[64] + tmpFx[56]*tmpObjS[75] + tmpFx[65]*tmpObjS[86] + tmpFx[74]*tmpObjS[97] + tmpFx[83]*tmpObjS[108] + tmpFx[92]*tmpObjS[119]; tmpQ2[32] = + tmpFx[2]*tmpObjS[10] + tmpFx[11]*tmpObjS[21] + tmpFx[20]*tmpObjS[32] + tmpFx[29]*tmpObjS[43] + tmpFx[38]*tmpObjS[54] + tmpFx[47]*tmpObjS[65] + tmpFx[56]*tmpObjS[76] + tmpFx[65]*tmpObjS[87] + tmpFx[74]*tmpObjS[98] + tmpFx[83]*tmpObjS[109] + tmpFx[92]*tmpObjS[120]; tmpQ2[33] = + tmpFx[3]*tmpObjS[0] + tmpFx[12]*tmpObjS[11] + tmpFx[21]*tmpObjS[22] + tmpFx[30]*tmpObjS[33] + tmpFx[39]*tmpObjS[44] + tmpFx[48]*tmpObjS[55] + tmpFx[57]*tmpObjS[66] + tmpFx[66]*tmpObjS[77] + tmpFx[75]*tmpObjS[88] + tmpFx[84]*tmpObjS[99] + tmpFx[93]*tmpObjS[110]; tmpQ2[34] = + tmpFx[3]*tmpObjS[1] + tmpFx[12]*tmpObjS[12] + tmpFx[21]*tmpObjS[23] + tmpFx[30]*tmpObjS[34] + tmpFx[39]*tmpObjS[45] + tmpFx[48]*tmpObjS[56] + tmpFx[57]*tmpObjS[67] + tmpFx[66]*tmpObjS[78] + tmpFx[75]*tmpObjS[89] + tmpFx[84]*tmpObjS[100] + tmpFx[93]*tmpObjS[111]; tmpQ2[35] = + tmpFx[3]*tmpObjS[2] + tmpFx[12]*tmpObjS[13] + tmpFx[21]*tmpObjS[24] + tmpFx[30]*tmpObjS[35] + tmpFx[39]*tmpObjS[46] + tmpFx[48]*tmpObjS[57] + tmpFx[57]*tmpObjS[68] + tmpFx[66]*tmpObjS[79] + tmpFx[75]*tmpObjS[90] + tmpFx[84]*tmpObjS[101] + tmpFx[93]*tmpObjS[112]; tmpQ2[36] = + tmpFx[3]*tmpObjS[3] + tmpFx[12]*tmpObjS[14] + tmpFx[21]*tmpObjS[25] + tmpFx[30]*tmpObjS[36] + tmpFx[39]*tmpObjS[47] + tmpFx[48]*tmpObjS[58] + tmpFx[57]*tmpObjS[69] + tmpFx[66]*tmpObjS[80] + tmpFx[75]*tmpObjS[91] + tmpFx[84]*tmpObjS[102] + tmpFx[93]*tmpObjS[113]; tmpQ2[37] = + tmpFx[3]*tmpObjS[4] + tmpFx[12]*tmpObjS[15] + tmpFx[21]*tmpObjS[26] + tmpFx[30]*tmpObjS[37] + tmpFx[39]*tmpObjS[48] + tmpFx[48]*tmpObjS[59] + tmpFx[57]*tmpObjS[70] + tmpFx[66]*tmpObjS[81] + tmpFx[75]*tmpObjS[92] + tmpFx[84]*tmpObjS[103] + tmpFx[93]*tmpObjS[114]; tmpQ2[38] = + tmpFx[3]*tmpObjS[5] + tmpFx[12]*tmpObjS[16] + tmpFx[21]*tmpObjS[27] + tmpFx[30]*tmpObjS[38] + tmpFx[39]*tmpObjS[49] + tmpFx[48]*tmpObjS[60] + tmpFx[57]*tmpObjS[71] + tmpFx[66]*tmpObjS[82] + tmpFx[75]*tmpObjS[93] + tmpFx[84]*tmpObjS[104] + tmpFx[93]*tmpObjS[115]; tmpQ2[39] = + tmpFx[3]*tmpObjS[6] + tmpFx[12]*tmpObjS[17] + tmpFx[21]*tmpObjS[28] + tmpFx[30]*tmpObjS[39] + tmpFx[39]*tmpObjS[50] + tmpFx[48]*tmpObjS[61] + tmpFx[57]*tmpObjS[72] + tmpFx[66]*tmpObjS[83] + tmpFx[75]*tmpObjS[94] + tmpFx[84]*tmpObjS[105] + tmpFx[93]*tmpObjS[116]; tmpQ2[40] = + tmpFx[3]*tmpObjS[7] + tmpFx[12]*tmpObjS[18] + tmpFx[21]*tmpObjS[29] + tmpFx[30]*tmpObjS[40] + tmpFx[39]*tmpObjS[51] + tmpFx[48]*tmpObjS[62] + tmpFx[57]*tmpObjS[73] + tmpFx[66]*tmpObjS[84] + tmpFx[75]*tmpObjS[95] + tmpFx[84]*tmpObjS[106] + tmpFx[93]*tmpObjS[117]; tmpQ2[41] = + tmpFx[3]*tmpObjS[8] + tmpFx[12]*tmpObjS[19] + tmpFx[21]*tmpObjS[30] + tmpFx[30]*tmpObjS[41] + tmpFx[39]*tmpObjS[52] + tmpFx[48]*tmpObjS[63] + tmpFx[57]*tmpObjS[74] + tmpFx[66]*tmpObjS[85] + tmpFx[75]*tmpObjS[96] + tmpFx[84]*tmpObjS[107] + tmpFx[93]*tmpObjS[118]; tmpQ2[42] = + tmpFx[3]*tmpObjS[9] + tmpFx[12]*tmpObjS[20] + tmpFx[21]*tmpObjS[31] + tmpFx[30]*tmpObjS[42] + tmpFx[39]*tmpObjS[53] + tmpFx[48]*tmpObjS[64] + tmpFx[57]*tmpObjS[75] + tmpFx[66]*tmpObjS[86] + tmpFx[75]*tmpObjS[97] + tmpFx[84]*tmpObjS[108] + tmpFx[93]*tmpObjS[119]; tmpQ2[43] = + tmpFx[3]*tmpObjS[10] + tmpFx[12]*tmpObjS[21] + tmpFx[21]*tmpObjS[32] + tmpFx[30]*tmpObjS[43] + tmpFx[39]*tmpObjS[54] + tmpFx[48]*tmpObjS[65] + tmpFx[57]*tmpObjS[76] + tmpFx[66]*tmpObjS[87] + tmpFx[75]*tmpObjS[98] + tmpFx[84]*tmpObjS[109] + tmpFx[93]*tmpObjS[120]; tmpQ2[44] = + tmpFx[4]*tmpObjS[0] + tmpFx[13]*tmpObjS[11] + tmpFx[22]*tmpObjS[22] + tmpFx[31]*tmpObjS[33] + tmpFx[40]*tmpObjS[44] + tmpFx[49]*tmpObjS[55] + tmpFx[58]*tmpObjS[66] + tmpFx[67]*tmpObjS[77] + tmpFx[76]*tmpObjS[88] + tmpFx[85]*tmpObjS[99] + tmpFx[94]*tmpObjS[110]; tmpQ2[45] = + tmpFx[4]*tmpObjS[1] + tmpFx[13]*tmpObjS[12] + tmpFx[22]*tmpObjS[23] + tmpFx[31]*tmpObjS[34] + tmpFx[40]*tmpObjS[45] + tmpFx[49]*tmpObjS[56] + tmpFx[58]*tmpObjS[67] + tmpFx[67]*tmpObjS[78] + tmpFx[76]*tmpObjS[89] + tmpFx[85]*tmpObjS[100] + tmpFx[94]*tmpObjS[111]; tmpQ2[46] = + tmpFx[4]*tmpObjS[2] + tmpFx[13]*tmpObjS[13] + tmpFx[22]*tmpObjS[24] + tmpFx[31]*tmpObjS[35] + tmpFx[40]*tmpObjS[46] + tmpFx[49]*tmpObjS[57] + tmpFx[58]*tmpObjS[68] + tmpFx[67]*tmpObjS[79] + tmpFx[76]*tmpObjS[90] + tmpFx[85]*tmpObjS[101] + tmpFx[94]*tmpObjS[112]; tmpQ2[47] = + tmpFx[4]*tmpObjS[3] + tmpFx[13]*tmpObjS[14] + tmpFx[22]*tmpObjS[25] + tmpFx[31]*tmpObjS[36] + tmpFx[40]*tmpObjS[47] + tmpFx[49]*tmpObjS[58] + tmpFx[58]*tmpObjS[69] + tmpFx[67]*tmpObjS[80] + tmpFx[76]*tmpObjS[91] + tmpFx[85]*tmpObjS[102] + tmpFx[94]*tmpObjS[113]; tmpQ2[48] = + tmpFx[4]*tmpObjS[4] + tmpFx[13]*tmpObjS[15] + tmpFx[22]*tmpObjS[26] + tmpFx[31]*tmpObjS[37] + tmpFx[40]*tmpObjS[48] + tmpFx[49]*tmpObjS[59] + tmpFx[58]*tmpObjS[70] + tmpFx[67]*tmpObjS[81] + tmpFx[76]*tmpObjS[92] + tmpFx[85]*tmpObjS[103] + tmpFx[94]*tmpObjS[114]; tmpQ2[49] = + tmpFx[4]*tmpObjS[5] + tmpFx[13]*tmpObjS[16] + tmpFx[22]*tmpObjS[27] + tmpFx[31]*tmpObjS[38] + tmpFx[40]*tmpObjS[49] + tmpFx[49]*tmpObjS[60] + tmpFx[58]*tmpObjS[71] + tmpFx[67]*tmpObjS[82] + tmpFx[76]*tmpObjS[93] + tmpFx[85]*tmpObjS[104] + tmpFx[94]*tmpObjS[115]; tmpQ2[50] = + tmpFx[4]*tmpObjS[6] + tmpFx[13]*tmpObjS[17] + tmpFx[22]*tmpObjS[28] + tmpFx[31]*tmpObjS[39] + tmpFx[40]*tmpObjS[50] + tmpFx[49]*tmpObjS[61] + tmpFx[58]*tmpObjS[72] + tmpFx[67]*tmpObjS[83] + tmpFx[76]*tmpObjS[94] + tmpFx[85]*tmpObjS[105] + tmpFx[94]*tmpObjS[116]; tmpQ2[51] = + tmpFx[4]*tmpObjS[7] + tmpFx[13]*tmpObjS[18] + tmpFx[22]*tmpObjS[29] + tmpFx[31]*tmpObjS[40] + tmpFx[40]*tmpObjS[51] + tmpFx[49]*tmpObjS[62] + tmpFx[58]*tmpObjS[73] + tmpFx[67]*tmpObjS[84] + tmpFx[76]*tmpObjS[95] + tmpFx[85]*tmpObjS[106] + tmpFx[94]*tmpObjS[117]; tmpQ2[52] = + tmpFx[4]*tmpObjS[8] + tmpFx[13]*tmpObjS[19] + tmpFx[22]*tmpObjS[30] + tmpFx[31]*tmpObjS[41] + tmpFx[40]*tmpObjS[52] + tmpFx[49]*tmpObjS[63] + tmpFx[58]*tmpObjS[74] + tmpFx[67]*tmpObjS[85] + tmpFx[76]*tmpObjS[96] + tmpFx[85]*tmpObjS[107] + tmpFx[94]*tmpObjS[118]; tmpQ2[53] = + tmpFx[4]*tmpObjS[9] + tmpFx[13]*tmpObjS[20] + tmpFx[22]*tmpObjS[31] + tmpFx[31]*tmpObjS[42] + tmpFx[40]*tmpObjS[53] + tmpFx[49]*tmpObjS[64] + tmpFx[58]*tmpObjS[75] + tmpFx[67]*tmpObjS[86] + tmpFx[76]*tmpObjS[97] + tmpFx[85]*tmpObjS[108] + tmpFx[94]*tmpObjS[119]; tmpQ2[54] = + tmpFx[4]*tmpObjS[10] + tmpFx[13]*tmpObjS[21] + tmpFx[22]*tmpObjS[32] + tmpFx[31]*tmpObjS[43] + tmpFx[40]*tmpObjS[54] + tmpFx[49]*tmpObjS[65] + tmpFx[58]*tmpObjS[76] + tmpFx[67]*tmpObjS[87] + tmpFx[76]*tmpObjS[98] + tmpFx[85]*tmpObjS[109] + tmpFx[94]*tmpObjS[120]; tmpQ2[55] = + tmpFx[5]*tmpObjS[0] + tmpFx[14]*tmpObjS[11] + tmpFx[23]*tmpObjS[22] + tmpFx[32]*tmpObjS[33] + tmpFx[41]*tmpObjS[44] + tmpFx[50]*tmpObjS[55] + tmpFx[59]*tmpObjS[66] + tmpFx[68]*tmpObjS[77] + tmpFx[77]*tmpObjS[88] + tmpFx[86]*tmpObjS[99] + tmpFx[95]*tmpObjS[110]; tmpQ2[56] = + tmpFx[5]*tmpObjS[1] + tmpFx[14]*tmpObjS[12] + tmpFx[23]*tmpObjS[23] + tmpFx[32]*tmpObjS[34] + tmpFx[41]*tmpObjS[45] + tmpFx[50]*tmpObjS[56] + tmpFx[59]*tmpObjS[67] + tmpFx[68]*tmpObjS[78] + tmpFx[77]*tmpObjS[89] + tmpFx[86]*tmpObjS[100] + tmpFx[95]*tmpObjS[111]; tmpQ2[57] = + tmpFx[5]*tmpObjS[2] + tmpFx[14]*tmpObjS[13] + tmpFx[23]*tmpObjS[24] + tmpFx[32]*tmpObjS[35] + tmpFx[41]*tmpObjS[46] + tmpFx[50]*tmpObjS[57] + tmpFx[59]*tmpObjS[68] + tmpFx[68]*tmpObjS[79] + tmpFx[77]*tmpObjS[90] + tmpFx[86]*tmpObjS[101] + tmpFx[95]*tmpObjS[112]; tmpQ2[58] = + tmpFx[5]*tmpObjS[3] + tmpFx[14]*tmpObjS[14] + tmpFx[23]*tmpObjS[25] + tmpFx[32]*tmpObjS[36] + tmpFx[41]*tmpObjS[47] + tmpFx[50]*tmpObjS[58] + tmpFx[59]*tmpObjS[69] + tmpFx[68]*tmpObjS[80] + tmpFx[77]*tmpObjS[91] + tmpFx[86]*tmpObjS[102] + tmpFx[95]*tmpObjS[113]; tmpQ2[59] = + tmpFx[5]*tmpObjS[4] + tmpFx[14]*tmpObjS[15] + tmpFx[23]*tmpObjS[26] + tmpFx[32]*tmpObjS[37] + tmpFx[41]*tmpObjS[48] + tmpFx[50]*tmpObjS[59] + tmpFx[59]*tmpObjS[70] + tmpFx[68]*tmpObjS[81] + tmpFx[77]*tmpObjS[92] + tmpFx[86]*tmpObjS[103] + tmpFx[95]*tmpObjS[114]; tmpQ2[60] = + tmpFx[5]*tmpObjS[5] + tmpFx[14]*tmpObjS[16] + tmpFx[23]*tmpObjS[27] + tmpFx[32]*tmpObjS[38] + tmpFx[41]*tmpObjS[49] + tmpFx[50]*tmpObjS[60] + tmpFx[59]*tmpObjS[71] + tmpFx[68]*tmpObjS[82] + tmpFx[77]*tmpObjS[93] + tmpFx[86]*tmpObjS[104] + tmpFx[95]*tmpObjS[115]; tmpQ2[61] = + tmpFx[5]*tmpObjS[6] + tmpFx[14]*tmpObjS[17] + tmpFx[23]*tmpObjS[28] + tmpFx[32]*tmpObjS[39] + tmpFx[41]*tmpObjS[50] + tmpFx[50]*tmpObjS[61] + tmpFx[59]*tmpObjS[72] + tmpFx[68]*tmpObjS[83] + tmpFx[77]*tmpObjS[94] + tmpFx[86]*tmpObjS[105] + tmpFx[95]*tmpObjS[116]; tmpQ2[62] = + tmpFx[5]*tmpObjS[7] + tmpFx[14]*tmpObjS[18] + tmpFx[23]*tmpObjS[29] + tmpFx[32]*tmpObjS[40] + tmpFx[41]*tmpObjS[51] + tmpFx[50]*tmpObjS[62] + tmpFx[59]*tmpObjS[73] + tmpFx[68]*tmpObjS[84] + tmpFx[77]*tmpObjS[95] + tmpFx[86]*tmpObjS[106] + tmpFx[95]*tmpObjS[117]; tmpQ2[63] = + tmpFx[5]*tmpObjS[8] + tmpFx[14]*tmpObjS[19] + tmpFx[23]*tmpObjS[30] + tmpFx[32]*tmpObjS[41] + tmpFx[41]*tmpObjS[52] + tmpFx[50]*tmpObjS[63] + tmpFx[59]*tmpObjS[74] + tmpFx[68]*tmpObjS[85] + tmpFx[77]*tmpObjS[96] + tmpFx[86]*tmpObjS[107] + tmpFx[95]*tmpObjS[118]; tmpQ2[64] = + tmpFx[5]*tmpObjS[9] + tmpFx[14]*tmpObjS[20] + tmpFx[23]*tmpObjS[31] + tmpFx[32]*tmpObjS[42] + tmpFx[41]*tmpObjS[53] + tmpFx[50]*tmpObjS[64] + tmpFx[59]*tmpObjS[75] + tmpFx[68]*tmpObjS[86] + tmpFx[77]*tmpObjS[97] + tmpFx[86]*tmpObjS[108] + tmpFx[95]*tmpObjS[119]; tmpQ2[65] = + tmpFx[5]*tmpObjS[10] + tmpFx[14]*tmpObjS[21] + tmpFx[23]*tmpObjS[32] + tmpFx[32]*tmpObjS[43] + tmpFx[41]*tmpObjS[54] + tmpFx[50]*tmpObjS[65] + tmpFx[59]*tmpObjS[76] + tmpFx[68]*tmpObjS[87] + tmpFx[77]*tmpObjS[98] + tmpFx[86]*tmpObjS[109] + tmpFx[95]*tmpObjS[120]; tmpQ2[66] = + tmpFx[6]*tmpObjS[0] + tmpFx[15]*tmpObjS[11] + tmpFx[24]*tmpObjS[22] + tmpFx[33]*tmpObjS[33] + tmpFx[42]*tmpObjS[44] + tmpFx[51]*tmpObjS[55] + tmpFx[60]*tmpObjS[66] + tmpFx[69]*tmpObjS[77] + tmpFx[78]*tmpObjS[88] + tmpFx[87]*tmpObjS[99] + tmpFx[96]*tmpObjS[110]; tmpQ2[67] = + tmpFx[6]*tmpObjS[1] + tmpFx[15]*tmpObjS[12] + tmpFx[24]*tmpObjS[23] + tmpFx[33]*tmpObjS[34] + tmpFx[42]*tmpObjS[45] + tmpFx[51]*tmpObjS[56] + tmpFx[60]*tmpObjS[67] + tmpFx[69]*tmpObjS[78] + tmpFx[78]*tmpObjS[89] + tmpFx[87]*tmpObjS[100] + tmpFx[96]*tmpObjS[111]; tmpQ2[68] = + tmpFx[6]*tmpObjS[2] + tmpFx[15]*tmpObjS[13] + tmpFx[24]*tmpObjS[24] + tmpFx[33]*tmpObjS[35] + tmpFx[42]*tmpObjS[46] + tmpFx[51]*tmpObjS[57] + tmpFx[60]*tmpObjS[68] + tmpFx[69]*tmpObjS[79] + tmpFx[78]*tmpObjS[90] + tmpFx[87]*tmpObjS[101] + tmpFx[96]*tmpObjS[112]; tmpQ2[69] = + tmpFx[6]*tmpObjS[3] + tmpFx[15]*tmpObjS[14] + tmpFx[24]*tmpObjS[25] + tmpFx[33]*tmpObjS[36] + tmpFx[42]*tmpObjS[47] + tmpFx[51]*tmpObjS[58] + tmpFx[60]*tmpObjS[69] + tmpFx[69]*tmpObjS[80] + tmpFx[78]*tmpObjS[91] + tmpFx[87]*tmpObjS[102] + tmpFx[96]*tmpObjS[113]; tmpQ2[70] = + tmpFx[6]*tmpObjS[4] + tmpFx[15]*tmpObjS[15] + tmpFx[24]*tmpObjS[26] + tmpFx[33]*tmpObjS[37] + tmpFx[42]*tmpObjS[48] + tmpFx[51]*tmpObjS[59] + tmpFx[60]*tmpObjS[70] + tmpFx[69]*tmpObjS[81] + tmpFx[78]*tmpObjS[92] + tmpFx[87]*tmpObjS[103] + tmpFx[96]*tmpObjS[114]; tmpQ2[71] = + tmpFx[6]*tmpObjS[5] + tmpFx[15]*tmpObjS[16] + tmpFx[24]*tmpObjS[27] + tmpFx[33]*tmpObjS[38] + tmpFx[42]*tmpObjS[49] + tmpFx[51]*tmpObjS[60] + tmpFx[60]*tmpObjS[71] + tmpFx[69]*tmpObjS[82] + tmpFx[78]*tmpObjS[93] + tmpFx[87]*tmpObjS[104] + tmpFx[96]*tmpObjS[115]; tmpQ2[72] = + tmpFx[6]*tmpObjS[6] + tmpFx[15]*tmpObjS[17] + tmpFx[24]*tmpObjS[28] + tmpFx[33]*tmpObjS[39] + tmpFx[42]*tmpObjS[50] + tmpFx[51]*tmpObjS[61] + tmpFx[60]*tmpObjS[72] + tmpFx[69]*tmpObjS[83] + tmpFx[78]*tmpObjS[94] + tmpFx[87]*tmpObjS[105] + tmpFx[96]*tmpObjS[116]; tmpQ2[73] = + tmpFx[6]*tmpObjS[7] + tmpFx[15]*tmpObjS[18] + tmpFx[24]*tmpObjS[29] + tmpFx[33]*tmpObjS[40] + tmpFx[42]*tmpObjS[51] + tmpFx[51]*tmpObjS[62] + tmpFx[60]*tmpObjS[73] + tmpFx[69]*tmpObjS[84] + tmpFx[78]*tmpObjS[95] + tmpFx[87]*tmpObjS[106] + tmpFx[96]*tmpObjS[117]; tmpQ2[74] = + tmpFx[6]*tmpObjS[8] + tmpFx[15]*tmpObjS[19] + tmpFx[24]*tmpObjS[30] + tmpFx[33]*tmpObjS[41] + tmpFx[42]*tmpObjS[52] + tmpFx[51]*tmpObjS[63] + tmpFx[60]*tmpObjS[74] + tmpFx[69]*tmpObjS[85] + tmpFx[78]*tmpObjS[96] + tmpFx[87]*tmpObjS[107] + tmpFx[96]*tmpObjS[118]; tmpQ2[75] = + tmpFx[6]*tmpObjS[9] + tmpFx[15]*tmpObjS[20] + tmpFx[24]*tmpObjS[31] + tmpFx[33]*tmpObjS[42] + tmpFx[42]*tmpObjS[53] + tmpFx[51]*tmpObjS[64] + tmpFx[60]*tmpObjS[75] + tmpFx[69]*tmpObjS[86] + tmpFx[78]*tmpObjS[97] + tmpFx[87]*tmpObjS[108] + tmpFx[96]*tmpObjS[119]; tmpQ2[76] = + tmpFx[6]*tmpObjS[10] + tmpFx[15]*tmpObjS[21] + tmpFx[24]*tmpObjS[32] + tmpFx[33]*tmpObjS[43] + tmpFx[42]*tmpObjS[54] + tmpFx[51]*tmpObjS[65] + tmpFx[60]*tmpObjS[76] + tmpFx[69]*tmpObjS[87] + tmpFx[78]*tmpObjS[98] + tmpFx[87]*tmpObjS[109] + tmpFx[96]*tmpObjS[120]; tmpQ2[77] = + tmpFx[7]*tmpObjS[0] + tmpFx[16]*tmpObjS[11] + tmpFx[25]*tmpObjS[22] + tmpFx[34]*tmpObjS[33] + tmpFx[43]*tmpObjS[44] + tmpFx[52]*tmpObjS[55] + tmpFx[61]*tmpObjS[66] + tmpFx[70]*tmpObjS[77] + tmpFx[79]*tmpObjS[88] + tmpFx[88]*tmpObjS[99] + tmpFx[97]*tmpObjS[110]; tmpQ2[78] = + tmpFx[7]*tmpObjS[1] + tmpFx[16]*tmpObjS[12] + tmpFx[25]*tmpObjS[23] + tmpFx[34]*tmpObjS[34] + tmpFx[43]*tmpObjS[45] + tmpFx[52]*tmpObjS[56] + tmpFx[61]*tmpObjS[67] + tmpFx[70]*tmpObjS[78] + tmpFx[79]*tmpObjS[89] + tmpFx[88]*tmpObjS[100] + tmpFx[97]*tmpObjS[111]; tmpQ2[79] = + tmpFx[7]*tmpObjS[2] + tmpFx[16]*tmpObjS[13] + tmpFx[25]*tmpObjS[24] + tmpFx[34]*tmpObjS[35] + tmpFx[43]*tmpObjS[46] + tmpFx[52]*tmpObjS[57] + tmpFx[61]*tmpObjS[68] + tmpFx[70]*tmpObjS[79] + tmpFx[79]*tmpObjS[90] + tmpFx[88]*tmpObjS[101] + tmpFx[97]*tmpObjS[112]; tmpQ2[80] = + tmpFx[7]*tmpObjS[3] + tmpFx[16]*tmpObjS[14] + tmpFx[25]*tmpObjS[25] + tmpFx[34]*tmpObjS[36] + tmpFx[43]*tmpObjS[47] + tmpFx[52]*tmpObjS[58] + tmpFx[61]*tmpObjS[69] + tmpFx[70]*tmpObjS[80] + tmpFx[79]*tmpObjS[91] + tmpFx[88]*tmpObjS[102] + tmpFx[97]*tmpObjS[113]; tmpQ2[81] = + tmpFx[7]*tmpObjS[4] + tmpFx[16]*tmpObjS[15] + tmpFx[25]*tmpObjS[26] + tmpFx[34]*tmpObjS[37] + tmpFx[43]*tmpObjS[48] + tmpFx[52]*tmpObjS[59] + tmpFx[61]*tmpObjS[70] + tmpFx[70]*tmpObjS[81] + tmpFx[79]*tmpObjS[92] + tmpFx[88]*tmpObjS[103] + tmpFx[97]*tmpObjS[114]; tmpQ2[82] = + tmpFx[7]*tmpObjS[5] + tmpFx[16]*tmpObjS[16] + tmpFx[25]*tmpObjS[27] + tmpFx[34]*tmpObjS[38] + tmpFx[43]*tmpObjS[49] + tmpFx[52]*tmpObjS[60] + tmpFx[61]*tmpObjS[71] + tmpFx[70]*tmpObjS[82] + tmpFx[79]*tmpObjS[93] + tmpFx[88]*tmpObjS[104] + tmpFx[97]*tmpObjS[115]; tmpQ2[83] = + tmpFx[7]*tmpObjS[6] + tmpFx[16]*tmpObjS[17] + tmpFx[25]*tmpObjS[28] + tmpFx[34]*tmpObjS[39] + tmpFx[43]*tmpObjS[50] + tmpFx[52]*tmpObjS[61] + tmpFx[61]*tmpObjS[72] + tmpFx[70]*tmpObjS[83] + tmpFx[79]*tmpObjS[94] + tmpFx[88]*tmpObjS[105] + tmpFx[97]*tmpObjS[116]; tmpQ2[84] = + tmpFx[7]*tmpObjS[7] + tmpFx[16]*tmpObjS[18] + tmpFx[25]*tmpObjS[29] + tmpFx[34]*tmpObjS[40] + tmpFx[43]*tmpObjS[51] + tmpFx[52]*tmpObjS[62] + tmpFx[61]*tmpObjS[73] + tmpFx[70]*tmpObjS[84] + tmpFx[79]*tmpObjS[95] + tmpFx[88]*tmpObjS[106] + tmpFx[97]*tmpObjS[117]; tmpQ2[85] = + tmpFx[7]*tmpObjS[8] + tmpFx[16]*tmpObjS[19] + tmpFx[25]*tmpObjS[30] + tmpFx[34]*tmpObjS[41] + tmpFx[43]*tmpObjS[52] + tmpFx[52]*tmpObjS[63] + tmpFx[61]*tmpObjS[74] + tmpFx[70]*tmpObjS[85] + tmpFx[79]*tmpObjS[96] + tmpFx[88]*tmpObjS[107] + tmpFx[97]*tmpObjS[118]; tmpQ2[86] = + tmpFx[7]*tmpObjS[9] + tmpFx[16]*tmpObjS[20] + tmpFx[25]*tmpObjS[31] + tmpFx[34]*tmpObjS[42] + tmpFx[43]*tmpObjS[53] + tmpFx[52]*tmpObjS[64] + tmpFx[61]*tmpObjS[75] + tmpFx[70]*tmpObjS[86] + tmpFx[79]*tmpObjS[97] + tmpFx[88]*tmpObjS[108] + tmpFx[97]*tmpObjS[119]; tmpQ2[87] = + tmpFx[7]*tmpObjS[10] + tmpFx[16]*tmpObjS[21] + tmpFx[25]*tmpObjS[32] + tmpFx[34]*tmpObjS[43] + tmpFx[43]*tmpObjS[54] + tmpFx[52]*tmpObjS[65] + tmpFx[61]*tmpObjS[76] + tmpFx[70]*tmpObjS[87] + tmpFx[79]*tmpObjS[98] + tmpFx[88]*tmpObjS[109] + tmpFx[97]*tmpObjS[120]; tmpQ2[88] = + tmpFx[8]*tmpObjS[0] + tmpFx[17]*tmpObjS[11] + tmpFx[26]*tmpObjS[22] + tmpFx[35]*tmpObjS[33] + tmpFx[44]*tmpObjS[44] + tmpFx[53]*tmpObjS[55] + tmpFx[62]*tmpObjS[66] + tmpFx[71]*tmpObjS[77] + tmpFx[80]*tmpObjS[88] + tmpFx[89]*tmpObjS[99] + tmpFx[98]*tmpObjS[110]; tmpQ2[89] = + tmpFx[8]*tmpObjS[1] + tmpFx[17]*tmpObjS[12] + tmpFx[26]*tmpObjS[23] + tmpFx[35]*tmpObjS[34] + tmpFx[44]*tmpObjS[45] + tmpFx[53]*tmpObjS[56] + tmpFx[62]*tmpObjS[67] + tmpFx[71]*tmpObjS[78] + tmpFx[80]*tmpObjS[89] + tmpFx[89]*tmpObjS[100] + tmpFx[98]*tmpObjS[111]; tmpQ2[90] = + tmpFx[8]*tmpObjS[2] + tmpFx[17]*tmpObjS[13] + tmpFx[26]*tmpObjS[24] + tmpFx[35]*tmpObjS[35] + tmpFx[44]*tmpObjS[46] + tmpFx[53]*tmpObjS[57] + tmpFx[62]*tmpObjS[68] + tmpFx[71]*tmpObjS[79] + tmpFx[80]*tmpObjS[90] + tmpFx[89]*tmpObjS[101] + tmpFx[98]*tmpObjS[112]; tmpQ2[91] = + tmpFx[8]*tmpObjS[3] + tmpFx[17]*tmpObjS[14] + tmpFx[26]*tmpObjS[25] + tmpFx[35]*tmpObjS[36] + tmpFx[44]*tmpObjS[47] + tmpFx[53]*tmpObjS[58] + tmpFx[62]*tmpObjS[69] + tmpFx[71]*tmpObjS[80] + tmpFx[80]*tmpObjS[91] + tmpFx[89]*tmpObjS[102] + tmpFx[98]*tmpObjS[113]; tmpQ2[92] = + tmpFx[8]*tmpObjS[4] + tmpFx[17]*tmpObjS[15] + tmpFx[26]*tmpObjS[26] + tmpFx[35]*tmpObjS[37] + tmpFx[44]*tmpObjS[48] + tmpFx[53]*tmpObjS[59] + tmpFx[62]*tmpObjS[70] + tmpFx[71]*tmpObjS[81] + tmpFx[80]*tmpObjS[92] + tmpFx[89]*tmpObjS[103] + tmpFx[98]*tmpObjS[114]; tmpQ2[93] = + tmpFx[8]*tmpObjS[5] + tmpFx[17]*tmpObjS[16] + tmpFx[26]*tmpObjS[27] + tmpFx[35]*tmpObjS[38] + tmpFx[44]*tmpObjS[49] + tmpFx[53]*tmpObjS[60] + tmpFx[62]*tmpObjS[71] + tmpFx[71]*tmpObjS[82] + tmpFx[80]*tmpObjS[93] + tmpFx[89]*tmpObjS[104] + tmpFx[98]*tmpObjS[115]; tmpQ2[94] = + tmpFx[8]*tmpObjS[6] + tmpFx[17]*tmpObjS[17] + tmpFx[26]*tmpObjS[28] + tmpFx[35]*tmpObjS[39] + tmpFx[44]*tmpObjS[50] + tmpFx[53]*tmpObjS[61] + tmpFx[62]*tmpObjS[72] + tmpFx[71]*tmpObjS[83] + tmpFx[80]*tmpObjS[94] + tmpFx[89]*tmpObjS[105] + tmpFx[98]*tmpObjS[116]; tmpQ2[95] = + tmpFx[8]*tmpObjS[7] + tmpFx[17]*tmpObjS[18] + tmpFx[26]*tmpObjS[29] + tmpFx[35]*tmpObjS[40] + tmpFx[44]*tmpObjS[51] + tmpFx[53]*tmpObjS[62] + tmpFx[62]*tmpObjS[73] + tmpFx[71]*tmpObjS[84] + tmpFx[80]*tmpObjS[95] + tmpFx[89]*tmpObjS[106] + tmpFx[98]*tmpObjS[117]; tmpQ2[96] = + tmpFx[8]*tmpObjS[8] + tmpFx[17]*tmpObjS[19] + tmpFx[26]*tmpObjS[30] + tmpFx[35]*tmpObjS[41] + tmpFx[44]*tmpObjS[52] + tmpFx[53]*tmpObjS[63] + tmpFx[62]*tmpObjS[74] + tmpFx[71]*tmpObjS[85] + tmpFx[80]*tmpObjS[96] + tmpFx[89]*tmpObjS[107] + tmpFx[98]*tmpObjS[118]; tmpQ2[97] = + tmpFx[8]*tmpObjS[9] + tmpFx[17]*tmpObjS[20] + tmpFx[26]*tmpObjS[31] + tmpFx[35]*tmpObjS[42] + tmpFx[44]*tmpObjS[53] + tmpFx[53]*tmpObjS[64] + tmpFx[62]*tmpObjS[75] + tmpFx[71]*tmpObjS[86] + tmpFx[80]*tmpObjS[97] + tmpFx[89]*tmpObjS[108] + tmpFx[98]*tmpObjS[119]; tmpQ2[98] = + tmpFx[8]*tmpObjS[10] + tmpFx[17]*tmpObjS[21] + tmpFx[26]*tmpObjS[32] + tmpFx[35]*tmpObjS[43] + tmpFx[44]*tmpObjS[54] + tmpFx[53]*tmpObjS[65] + tmpFx[62]*tmpObjS[76] + tmpFx[71]*tmpObjS[87] + tmpFx[80]*tmpObjS[98] + tmpFx[89]*tmpObjS[109] + tmpFx[98]*tmpObjS[120]; tmpQ1[0] = + tmpQ2[0]*tmpFx[0] + tmpQ2[1]*tmpFx[9] + tmpQ2[2]*tmpFx[18] + tmpQ2[3]*tmpFx[27] + tmpQ2[4]*tmpFx[36] + tmpQ2[5]*tmpFx[45] + tmpQ2[6]*tmpFx[54] + tmpQ2[7]*tmpFx[63] + tmpQ2[8]*tmpFx[72] + tmpQ2[9]*tmpFx[81] + tmpQ2[10]*tmpFx[90]; tmpQ1[1] = + tmpQ2[0]*tmpFx[1] + tmpQ2[1]*tmpFx[10] + tmpQ2[2]*tmpFx[19] + tmpQ2[3]*tmpFx[28] + tmpQ2[4]*tmpFx[37] + tmpQ2[5]*tmpFx[46] + tmpQ2[6]*tmpFx[55] + tmpQ2[7]*tmpFx[64] + tmpQ2[8]*tmpFx[73] + tmpQ2[9]*tmpFx[82] + tmpQ2[10]*tmpFx[91]; tmpQ1[2] = + tmpQ2[0]*tmpFx[2] + tmpQ2[1]*tmpFx[11] + tmpQ2[2]*tmpFx[20] + tmpQ2[3]*tmpFx[29] + tmpQ2[4]*tmpFx[38] + tmpQ2[5]*tmpFx[47] + tmpQ2[6]*tmpFx[56] + tmpQ2[7]*tmpFx[65] + tmpQ2[8]*tmpFx[74] + tmpQ2[9]*tmpFx[83] + tmpQ2[10]*tmpFx[92]; tmpQ1[3] = + tmpQ2[0]*tmpFx[3] + tmpQ2[1]*tmpFx[12] + tmpQ2[2]*tmpFx[21] + tmpQ2[3]*tmpFx[30] + tmpQ2[4]*tmpFx[39] + tmpQ2[5]*tmpFx[48] + tmpQ2[6]*tmpFx[57] + tmpQ2[7]*tmpFx[66] + tmpQ2[8]*tmpFx[75] + tmpQ2[9]*tmpFx[84] + tmpQ2[10]*tmpFx[93]; tmpQ1[4] = + tmpQ2[0]*tmpFx[4] + tmpQ2[1]*tmpFx[13] + tmpQ2[2]*tmpFx[22] + tmpQ2[3]*tmpFx[31] + tmpQ2[4]*tmpFx[40] + tmpQ2[5]*tmpFx[49] + tmpQ2[6]*tmpFx[58] + tmpQ2[7]*tmpFx[67] + tmpQ2[8]*tmpFx[76] + tmpQ2[9]*tmpFx[85] + tmpQ2[10]*tmpFx[94]; tmpQ1[5] = + tmpQ2[0]*tmpFx[5] + tmpQ2[1]*tmpFx[14] + tmpQ2[2]*tmpFx[23] + tmpQ2[3]*tmpFx[32] + tmpQ2[4]*tmpFx[41] + tmpQ2[5]*tmpFx[50] + tmpQ2[6]*tmpFx[59] + tmpQ2[7]*tmpFx[68] + tmpQ2[8]*tmpFx[77] + tmpQ2[9]*tmpFx[86] + tmpQ2[10]*tmpFx[95]; tmpQ1[6] = + tmpQ2[0]*tmpFx[6] + tmpQ2[1]*tmpFx[15] + tmpQ2[2]*tmpFx[24] + tmpQ2[3]*tmpFx[33] + tmpQ2[4]*tmpFx[42] + tmpQ2[5]*tmpFx[51] + tmpQ2[6]*tmpFx[60] + tmpQ2[7]*tmpFx[69] + tmpQ2[8]*tmpFx[78] + tmpQ2[9]*tmpFx[87] + tmpQ2[10]*tmpFx[96]; tmpQ1[7] = + tmpQ2[0]*tmpFx[7] + tmpQ2[1]*tmpFx[16] + tmpQ2[2]*tmpFx[25] + tmpQ2[3]*tmpFx[34] + tmpQ2[4]*tmpFx[43] + tmpQ2[5]*tmpFx[52] + tmpQ2[6]*tmpFx[61] + tmpQ2[7]*tmpFx[70] + tmpQ2[8]*tmpFx[79] + tmpQ2[9]*tmpFx[88] + tmpQ2[10]*tmpFx[97]; tmpQ1[8] = + tmpQ2[0]*tmpFx[8] + tmpQ2[1]*tmpFx[17] + tmpQ2[2]*tmpFx[26] + tmpQ2[3]*tmpFx[35] + tmpQ2[4]*tmpFx[44] + tmpQ2[5]*tmpFx[53] + tmpQ2[6]*tmpFx[62] + tmpQ2[7]*tmpFx[71] + tmpQ2[8]*tmpFx[80] + tmpQ2[9]*tmpFx[89] + tmpQ2[10]*tmpFx[98]; tmpQ1[9] = + tmpQ2[11]*tmpFx[0] + tmpQ2[12]*tmpFx[9] + tmpQ2[13]*tmpFx[18] + tmpQ2[14]*tmpFx[27] + tmpQ2[15]*tmpFx[36] + tmpQ2[16]*tmpFx[45] + tmpQ2[17]*tmpFx[54] + tmpQ2[18]*tmpFx[63] + tmpQ2[19]*tmpFx[72] + tmpQ2[20]*tmpFx[81] + tmpQ2[21]*tmpFx[90]; tmpQ1[10] = + tmpQ2[11]*tmpFx[1] + tmpQ2[12]*tmpFx[10] + tmpQ2[13]*tmpFx[19] + tmpQ2[14]*tmpFx[28] + tmpQ2[15]*tmpFx[37] + tmpQ2[16]*tmpFx[46] + tmpQ2[17]*tmpFx[55] + tmpQ2[18]*tmpFx[64] + tmpQ2[19]*tmpFx[73] + tmpQ2[20]*tmpFx[82] + tmpQ2[21]*tmpFx[91]; tmpQ1[11] = + tmpQ2[11]*tmpFx[2] + tmpQ2[12]*tmpFx[11] + tmpQ2[13]*tmpFx[20] + tmpQ2[14]*tmpFx[29] + tmpQ2[15]*tmpFx[38] + tmpQ2[16]*tmpFx[47] + tmpQ2[17]*tmpFx[56] + tmpQ2[18]*tmpFx[65] + tmpQ2[19]*tmpFx[74] + tmpQ2[20]*tmpFx[83] + tmpQ2[21]*tmpFx[92]; tmpQ1[12] = + tmpQ2[11]*tmpFx[3] + tmpQ2[12]*tmpFx[12] + tmpQ2[13]*tmpFx[21] + tmpQ2[14]*tmpFx[30] + tmpQ2[15]*tmpFx[39] + tmpQ2[16]*tmpFx[48] + tmpQ2[17]*tmpFx[57] + tmpQ2[18]*tmpFx[66] + tmpQ2[19]*tmpFx[75] + tmpQ2[20]*tmpFx[84] + tmpQ2[21]*tmpFx[93]; tmpQ1[13] = + tmpQ2[11]*tmpFx[4] + tmpQ2[12]*tmpFx[13] + tmpQ2[13]*tmpFx[22] + tmpQ2[14]*tmpFx[31] + tmpQ2[15]*tmpFx[40] + tmpQ2[16]*tmpFx[49] + tmpQ2[17]*tmpFx[58] + tmpQ2[18]*tmpFx[67] + tmpQ2[19]*tmpFx[76] + tmpQ2[20]*tmpFx[85] + tmpQ2[21]*tmpFx[94]; tmpQ1[14] = + tmpQ2[11]*tmpFx[5] + tmpQ2[12]*tmpFx[14] + tmpQ2[13]*tmpFx[23] + tmpQ2[14]*tmpFx[32] + tmpQ2[15]*tmpFx[41] + tmpQ2[16]*tmpFx[50] + tmpQ2[17]*tmpFx[59] + tmpQ2[18]*tmpFx[68] + tmpQ2[19]*tmpFx[77] + tmpQ2[20]*tmpFx[86] + tmpQ2[21]*tmpFx[95]; tmpQ1[15] = + tmpQ2[11]*tmpFx[6] + tmpQ2[12]*tmpFx[15] + tmpQ2[13]*tmpFx[24] + tmpQ2[14]*tmpFx[33] + tmpQ2[15]*tmpFx[42] + tmpQ2[16]*tmpFx[51] + tmpQ2[17]*tmpFx[60] + tmpQ2[18]*tmpFx[69] + tmpQ2[19]*tmpFx[78] + tmpQ2[20]*tmpFx[87] + tmpQ2[21]*tmpFx[96]; tmpQ1[16] = + tmpQ2[11]*tmpFx[7] + tmpQ2[12]*tmpFx[16] + tmpQ2[13]*tmpFx[25] + tmpQ2[14]*tmpFx[34] + tmpQ2[15]*tmpFx[43] + tmpQ2[16]*tmpFx[52] + tmpQ2[17]*tmpFx[61] + tmpQ2[18]*tmpFx[70] + tmpQ2[19]*tmpFx[79] + tmpQ2[20]*tmpFx[88] + tmpQ2[21]*tmpFx[97]; tmpQ1[17] = + tmpQ2[11]*tmpFx[8] + tmpQ2[12]*tmpFx[17] + tmpQ2[13]*tmpFx[26] + tmpQ2[14]*tmpFx[35] + tmpQ2[15]*tmpFx[44] + tmpQ2[16]*tmpFx[53] + tmpQ2[17]*tmpFx[62] + tmpQ2[18]*tmpFx[71] + tmpQ2[19]*tmpFx[80] + tmpQ2[20]*tmpFx[89] + tmpQ2[21]*tmpFx[98]; tmpQ1[18] = + tmpQ2[22]*tmpFx[0] + tmpQ2[23]*tmpFx[9] + tmpQ2[24]*tmpFx[18] + tmpQ2[25]*tmpFx[27] + tmpQ2[26]*tmpFx[36] + tmpQ2[27]*tmpFx[45] + tmpQ2[28]*tmpFx[54] + tmpQ2[29]*tmpFx[63] + tmpQ2[30]*tmpFx[72] + tmpQ2[31]*tmpFx[81] + tmpQ2[32]*tmpFx[90]; tmpQ1[19] = + tmpQ2[22]*tmpFx[1] + tmpQ2[23]*tmpFx[10] + tmpQ2[24]*tmpFx[19] + tmpQ2[25]*tmpFx[28] + tmpQ2[26]*tmpFx[37] + tmpQ2[27]*tmpFx[46] + tmpQ2[28]*tmpFx[55] + tmpQ2[29]*tmpFx[64] + tmpQ2[30]*tmpFx[73] + tmpQ2[31]*tmpFx[82] + tmpQ2[32]*tmpFx[91]; tmpQ1[20] = + tmpQ2[22]*tmpFx[2] + tmpQ2[23]*tmpFx[11] + tmpQ2[24]*tmpFx[20] + tmpQ2[25]*tmpFx[29] + tmpQ2[26]*tmpFx[38] + tmpQ2[27]*tmpFx[47] + tmpQ2[28]*tmpFx[56] + tmpQ2[29]*tmpFx[65] + tmpQ2[30]*tmpFx[74] + tmpQ2[31]*tmpFx[83] + tmpQ2[32]*tmpFx[92]; tmpQ1[21] = + tmpQ2[22]*tmpFx[3] + tmpQ2[23]*tmpFx[12] + tmpQ2[24]*tmpFx[21] + tmpQ2[25]*tmpFx[30] + tmpQ2[26]*tmpFx[39] + tmpQ2[27]*tmpFx[48] + tmpQ2[28]*tmpFx[57] + tmpQ2[29]*tmpFx[66] + tmpQ2[30]*tmpFx[75] + tmpQ2[31]*tmpFx[84] + tmpQ2[32]*tmpFx[93]; tmpQ1[22] = + tmpQ2[22]*tmpFx[4] + tmpQ2[23]*tmpFx[13] + tmpQ2[24]*tmpFx[22] + tmpQ2[25]*tmpFx[31] + tmpQ2[26]*tmpFx[40] + tmpQ2[27]*tmpFx[49] + tmpQ2[28]*tmpFx[58] + tmpQ2[29]*tmpFx[67] + tmpQ2[30]*tmpFx[76] + tmpQ2[31]*tmpFx[85] + tmpQ2[32]*tmpFx[94]; tmpQ1[23] = + tmpQ2[22]*tmpFx[5] + tmpQ2[23]*tmpFx[14] + tmpQ2[24]*tmpFx[23] + tmpQ2[25]*tmpFx[32] + tmpQ2[26]*tmpFx[41] + tmpQ2[27]*tmpFx[50] + tmpQ2[28]*tmpFx[59] + tmpQ2[29]*tmpFx[68] + tmpQ2[30]*tmpFx[77] + tmpQ2[31]*tmpFx[86] + tmpQ2[32]*tmpFx[95]; tmpQ1[24] = + tmpQ2[22]*tmpFx[6] + tmpQ2[23]*tmpFx[15] + tmpQ2[24]*tmpFx[24] + tmpQ2[25]*tmpFx[33] + tmpQ2[26]*tmpFx[42] + tmpQ2[27]*tmpFx[51] + tmpQ2[28]*tmpFx[60] + tmpQ2[29]*tmpFx[69] + tmpQ2[30]*tmpFx[78] + tmpQ2[31]*tmpFx[87] + tmpQ2[32]*tmpFx[96]; tmpQ1[25] = + tmpQ2[22]*tmpFx[7] + tmpQ2[23]*tmpFx[16] + tmpQ2[24]*tmpFx[25] + tmpQ2[25]*tmpFx[34] + tmpQ2[26]*tmpFx[43] + tmpQ2[27]*tmpFx[52] + tmpQ2[28]*tmpFx[61] + tmpQ2[29]*tmpFx[70] + tmpQ2[30]*tmpFx[79] + tmpQ2[31]*tmpFx[88] + tmpQ2[32]*tmpFx[97]; tmpQ1[26] = + tmpQ2[22]*tmpFx[8] + tmpQ2[23]*tmpFx[17] + tmpQ2[24]*tmpFx[26] + tmpQ2[25]*tmpFx[35] + tmpQ2[26]*tmpFx[44] + tmpQ2[27]*tmpFx[53] + tmpQ2[28]*tmpFx[62] + tmpQ2[29]*tmpFx[71] + tmpQ2[30]*tmpFx[80] + tmpQ2[31]*tmpFx[89] + tmpQ2[32]*tmpFx[98]; tmpQ1[27] = + tmpQ2[33]*tmpFx[0] + tmpQ2[34]*tmpFx[9] + tmpQ2[35]*tmpFx[18] + tmpQ2[36]*tmpFx[27] + tmpQ2[37]*tmpFx[36] + tmpQ2[38]*tmpFx[45] + tmpQ2[39]*tmpFx[54] + tmpQ2[40]*tmpFx[63] + tmpQ2[41]*tmpFx[72] + tmpQ2[42]*tmpFx[81] + tmpQ2[43]*tmpFx[90]; tmpQ1[28] = + tmpQ2[33]*tmpFx[1] + tmpQ2[34]*tmpFx[10] + tmpQ2[35]*tmpFx[19] + tmpQ2[36]*tmpFx[28] + tmpQ2[37]*tmpFx[37] + tmpQ2[38]*tmpFx[46] + tmpQ2[39]*tmpFx[55] + tmpQ2[40]*tmpFx[64] + tmpQ2[41]*tmpFx[73] + tmpQ2[42]*tmpFx[82] + tmpQ2[43]*tmpFx[91]; tmpQ1[29] = + tmpQ2[33]*tmpFx[2] + tmpQ2[34]*tmpFx[11] + tmpQ2[35]*tmpFx[20] + tmpQ2[36]*tmpFx[29] + tmpQ2[37]*tmpFx[38] + tmpQ2[38]*tmpFx[47] + tmpQ2[39]*tmpFx[56] + tmpQ2[40]*tmpFx[65] + tmpQ2[41]*tmpFx[74] + tmpQ2[42]*tmpFx[83] + tmpQ2[43]*tmpFx[92]; tmpQ1[30] = + tmpQ2[33]*tmpFx[3] + tmpQ2[34]*tmpFx[12] + tmpQ2[35]*tmpFx[21] + tmpQ2[36]*tmpFx[30] + tmpQ2[37]*tmpFx[39] + tmpQ2[38]*tmpFx[48] + tmpQ2[39]*tmpFx[57] + tmpQ2[40]*tmpFx[66] + tmpQ2[41]*tmpFx[75] + tmpQ2[42]*tmpFx[84] + tmpQ2[43]*tmpFx[93]; tmpQ1[31] = + tmpQ2[33]*tmpFx[4] + tmpQ2[34]*tmpFx[13] + tmpQ2[35]*tmpFx[22] + tmpQ2[36]*tmpFx[31] + tmpQ2[37]*tmpFx[40] + tmpQ2[38]*tmpFx[49] + tmpQ2[39]*tmpFx[58] + tmpQ2[40]*tmpFx[67] + tmpQ2[41]*tmpFx[76] + tmpQ2[42]*tmpFx[85] + tmpQ2[43]*tmpFx[94]; tmpQ1[32] = + tmpQ2[33]*tmpFx[5] + tmpQ2[34]*tmpFx[14] + tmpQ2[35]*tmpFx[23] + tmpQ2[36]*tmpFx[32] + tmpQ2[37]*tmpFx[41] + tmpQ2[38]*tmpFx[50] + tmpQ2[39]*tmpFx[59] + tmpQ2[40]*tmpFx[68] + tmpQ2[41]*tmpFx[77] + tmpQ2[42]*tmpFx[86] + tmpQ2[43]*tmpFx[95]; tmpQ1[33] = + tmpQ2[33]*tmpFx[6] + tmpQ2[34]*tmpFx[15] + tmpQ2[35]*tmpFx[24] + tmpQ2[36]*tmpFx[33] + tmpQ2[37]*tmpFx[42] + tmpQ2[38]*tmpFx[51] + tmpQ2[39]*tmpFx[60] + tmpQ2[40]*tmpFx[69] + tmpQ2[41]*tmpFx[78] + tmpQ2[42]*tmpFx[87] + tmpQ2[43]*tmpFx[96]; tmpQ1[34] = + tmpQ2[33]*tmpFx[7] + tmpQ2[34]*tmpFx[16] + tmpQ2[35]*tmpFx[25] + tmpQ2[36]*tmpFx[34] + tmpQ2[37]*tmpFx[43] + tmpQ2[38]*tmpFx[52] + tmpQ2[39]*tmpFx[61] + tmpQ2[40]*tmpFx[70] + tmpQ2[41]*tmpFx[79] + tmpQ2[42]*tmpFx[88] + tmpQ2[43]*tmpFx[97]; tmpQ1[35] = + tmpQ2[33]*tmpFx[8] + tmpQ2[34]*tmpFx[17] + tmpQ2[35]*tmpFx[26] + tmpQ2[36]*tmpFx[35] + tmpQ2[37]*tmpFx[44] + tmpQ2[38]*tmpFx[53] + tmpQ2[39]*tmpFx[62] + tmpQ2[40]*tmpFx[71] + tmpQ2[41]*tmpFx[80] + tmpQ2[42]*tmpFx[89] + tmpQ2[43]*tmpFx[98]; tmpQ1[36] = + tmpQ2[44]*tmpFx[0] + tmpQ2[45]*tmpFx[9] + tmpQ2[46]*tmpFx[18] + tmpQ2[47]*tmpFx[27] + tmpQ2[48]*tmpFx[36] + tmpQ2[49]*tmpFx[45] + tmpQ2[50]*tmpFx[54] + tmpQ2[51]*tmpFx[63] + tmpQ2[52]*tmpFx[72] + tmpQ2[53]*tmpFx[81] + tmpQ2[54]*tmpFx[90]; tmpQ1[37] = + tmpQ2[44]*tmpFx[1] + tmpQ2[45]*tmpFx[10] + tmpQ2[46]*tmpFx[19] + tmpQ2[47]*tmpFx[28] + tmpQ2[48]*tmpFx[37] + tmpQ2[49]*tmpFx[46] + tmpQ2[50]*tmpFx[55] + tmpQ2[51]*tmpFx[64] + tmpQ2[52]*tmpFx[73] + tmpQ2[53]*tmpFx[82] + tmpQ2[54]*tmpFx[91]; tmpQ1[38] = + tmpQ2[44]*tmpFx[2] + tmpQ2[45]*tmpFx[11] + tmpQ2[46]*tmpFx[20] + tmpQ2[47]*tmpFx[29] + tmpQ2[48]*tmpFx[38] + tmpQ2[49]*tmpFx[47] + tmpQ2[50]*tmpFx[56] + tmpQ2[51]*tmpFx[65] + tmpQ2[52]*tmpFx[74] + tmpQ2[53]*tmpFx[83] + tmpQ2[54]*tmpFx[92]; tmpQ1[39] = + tmpQ2[44]*tmpFx[3] + tmpQ2[45]*tmpFx[12] + tmpQ2[46]*tmpFx[21] + tmpQ2[47]*tmpFx[30] + tmpQ2[48]*tmpFx[39] + tmpQ2[49]*tmpFx[48] + tmpQ2[50]*tmpFx[57] + tmpQ2[51]*tmpFx[66] + tmpQ2[52]*tmpFx[75] + tmpQ2[53]*tmpFx[84] + tmpQ2[54]*tmpFx[93]; tmpQ1[40] = + tmpQ2[44]*tmpFx[4] + tmpQ2[45]*tmpFx[13] + tmpQ2[46]*tmpFx[22] + tmpQ2[47]*tmpFx[31] + tmpQ2[48]*tmpFx[40] + tmpQ2[49]*tmpFx[49] + tmpQ2[50]*tmpFx[58] + tmpQ2[51]*tmpFx[67] + tmpQ2[52]*tmpFx[76] + tmpQ2[53]*tmpFx[85] + tmpQ2[54]*tmpFx[94]; tmpQ1[41] = + tmpQ2[44]*tmpFx[5] + tmpQ2[45]*tmpFx[14] + tmpQ2[46]*tmpFx[23] + tmpQ2[47]*tmpFx[32] + tmpQ2[48]*tmpFx[41] + tmpQ2[49]*tmpFx[50] + tmpQ2[50]*tmpFx[59] + tmpQ2[51]*tmpFx[68] + tmpQ2[52]*tmpFx[77] + tmpQ2[53]*tmpFx[86] + tmpQ2[54]*tmpFx[95]; tmpQ1[42] = + tmpQ2[44]*tmpFx[6] + tmpQ2[45]*tmpFx[15] + tmpQ2[46]*tmpFx[24] + tmpQ2[47]*tmpFx[33] + tmpQ2[48]*tmpFx[42] + tmpQ2[49]*tmpFx[51] + tmpQ2[50]*tmpFx[60] + tmpQ2[51]*tmpFx[69] + tmpQ2[52]*tmpFx[78] + tmpQ2[53]*tmpFx[87] + tmpQ2[54]*tmpFx[96]; tmpQ1[43] = + tmpQ2[44]*tmpFx[7] + tmpQ2[45]*tmpFx[16] + tmpQ2[46]*tmpFx[25] + tmpQ2[47]*tmpFx[34] + tmpQ2[48]*tmpFx[43] + tmpQ2[49]*tmpFx[52] + tmpQ2[50]*tmpFx[61] + tmpQ2[51]*tmpFx[70] + tmpQ2[52]*tmpFx[79] + tmpQ2[53]*tmpFx[88] + tmpQ2[54]*tmpFx[97]; tmpQ1[44] = + tmpQ2[44]*tmpFx[8] + tmpQ2[45]*tmpFx[17] + tmpQ2[46]*tmpFx[26] + tmpQ2[47]*tmpFx[35] + tmpQ2[48]*tmpFx[44] + tmpQ2[49]*tmpFx[53] + tmpQ2[50]*tmpFx[62] + tmpQ2[51]*tmpFx[71] + tmpQ2[52]*tmpFx[80] + tmpQ2[53]*tmpFx[89] + tmpQ2[54]*tmpFx[98]; tmpQ1[45] = + tmpQ2[55]*tmpFx[0] + tmpQ2[56]*tmpFx[9] + tmpQ2[57]*tmpFx[18] + tmpQ2[58]*tmpFx[27] + tmpQ2[59]*tmpFx[36] + tmpQ2[60]*tmpFx[45] + tmpQ2[61]*tmpFx[54] + tmpQ2[62]*tmpFx[63] + tmpQ2[63]*tmpFx[72] + tmpQ2[64]*tmpFx[81] + tmpQ2[65]*tmpFx[90]; tmpQ1[46] = + tmpQ2[55]*tmpFx[1] + tmpQ2[56]*tmpFx[10] + tmpQ2[57]*tmpFx[19] + tmpQ2[58]*tmpFx[28] + tmpQ2[59]*tmpFx[37] + tmpQ2[60]*tmpFx[46] + tmpQ2[61]*tmpFx[55] + tmpQ2[62]*tmpFx[64] + tmpQ2[63]*tmpFx[73] + tmpQ2[64]*tmpFx[82] + tmpQ2[65]*tmpFx[91]; tmpQ1[47] = + tmpQ2[55]*tmpFx[2] + tmpQ2[56]*tmpFx[11] + tmpQ2[57]*tmpFx[20] + tmpQ2[58]*tmpFx[29] + tmpQ2[59]*tmpFx[38] + tmpQ2[60]*tmpFx[47] + tmpQ2[61]*tmpFx[56] + tmpQ2[62]*tmpFx[65] + tmpQ2[63]*tmpFx[74] + tmpQ2[64]*tmpFx[83] + tmpQ2[65]*tmpFx[92]; tmpQ1[48] = + tmpQ2[55]*tmpFx[3] + tmpQ2[56]*tmpFx[12] + tmpQ2[57]*tmpFx[21] + tmpQ2[58]*tmpFx[30] + tmpQ2[59]*tmpFx[39] + tmpQ2[60]*tmpFx[48] + tmpQ2[61]*tmpFx[57] + tmpQ2[62]*tmpFx[66] + tmpQ2[63]*tmpFx[75] + tmpQ2[64]*tmpFx[84] + tmpQ2[65]*tmpFx[93]; tmpQ1[49] = + tmpQ2[55]*tmpFx[4] + tmpQ2[56]*tmpFx[13] + tmpQ2[57]*tmpFx[22] + tmpQ2[58]*tmpFx[31] + tmpQ2[59]*tmpFx[40] + tmpQ2[60]*tmpFx[49] + tmpQ2[61]*tmpFx[58] + tmpQ2[62]*tmpFx[67] + tmpQ2[63]*tmpFx[76] + tmpQ2[64]*tmpFx[85] + tmpQ2[65]*tmpFx[94]; tmpQ1[50] = + tmpQ2[55]*tmpFx[5] + tmpQ2[56]*tmpFx[14] + tmpQ2[57]*tmpFx[23] + tmpQ2[58]*tmpFx[32] + tmpQ2[59]*tmpFx[41] + tmpQ2[60]*tmpFx[50] + tmpQ2[61]*tmpFx[59] + tmpQ2[62]*tmpFx[68] + tmpQ2[63]*tmpFx[77] + tmpQ2[64]*tmpFx[86] + tmpQ2[65]*tmpFx[95]; tmpQ1[51] = + tmpQ2[55]*tmpFx[6] + tmpQ2[56]*tmpFx[15] + tmpQ2[57]*tmpFx[24] + tmpQ2[58]*tmpFx[33] + tmpQ2[59]*tmpFx[42] + tmpQ2[60]*tmpFx[51] + tmpQ2[61]*tmpFx[60] + tmpQ2[62]*tmpFx[69] + tmpQ2[63]*tmpFx[78] + tmpQ2[64]*tmpFx[87] + tmpQ2[65]*tmpFx[96]; tmpQ1[52] = + tmpQ2[55]*tmpFx[7] + tmpQ2[56]*tmpFx[16] + tmpQ2[57]*tmpFx[25] + tmpQ2[58]*tmpFx[34] + tmpQ2[59]*tmpFx[43] + tmpQ2[60]*tmpFx[52] + tmpQ2[61]*tmpFx[61] + tmpQ2[62]*tmpFx[70] + tmpQ2[63]*tmpFx[79] + tmpQ2[64]*tmpFx[88] + tmpQ2[65]*tmpFx[97]; tmpQ1[53] = + tmpQ2[55]*tmpFx[8] + tmpQ2[56]*tmpFx[17] + tmpQ2[57]*tmpFx[26] + tmpQ2[58]*tmpFx[35] + tmpQ2[59]*tmpFx[44] + tmpQ2[60]*tmpFx[53] + tmpQ2[61]*tmpFx[62] + tmpQ2[62]*tmpFx[71] + tmpQ2[63]*tmpFx[80] + tmpQ2[64]*tmpFx[89] + tmpQ2[65]*tmpFx[98]; tmpQ1[54] = + tmpQ2[66]*tmpFx[0] + tmpQ2[67]*tmpFx[9] + tmpQ2[68]*tmpFx[18] + tmpQ2[69]*tmpFx[27] + tmpQ2[70]*tmpFx[36] + tmpQ2[71]*tmpFx[45] + tmpQ2[72]*tmpFx[54] + tmpQ2[73]*tmpFx[63] + tmpQ2[74]*tmpFx[72] + tmpQ2[75]*tmpFx[81] + tmpQ2[76]*tmpFx[90]; tmpQ1[55] = + tmpQ2[66]*tmpFx[1] + tmpQ2[67]*tmpFx[10] + tmpQ2[68]*tmpFx[19] + tmpQ2[69]*tmpFx[28] + tmpQ2[70]*tmpFx[37] + tmpQ2[71]*tmpFx[46] + tmpQ2[72]*tmpFx[55] + tmpQ2[73]*tmpFx[64] + tmpQ2[74]*tmpFx[73] + tmpQ2[75]*tmpFx[82] + tmpQ2[76]*tmpFx[91]; tmpQ1[56] = + tmpQ2[66]*tmpFx[2] + tmpQ2[67]*tmpFx[11] + tmpQ2[68]*tmpFx[20] + tmpQ2[69]*tmpFx[29] + tmpQ2[70]*tmpFx[38] + tmpQ2[71]*tmpFx[47] + tmpQ2[72]*tmpFx[56] + tmpQ2[73]*tmpFx[65] + tmpQ2[74]*tmpFx[74] + tmpQ2[75]*tmpFx[83] + tmpQ2[76]*tmpFx[92]; tmpQ1[57] = + tmpQ2[66]*tmpFx[3] + tmpQ2[67]*tmpFx[12] + tmpQ2[68]*tmpFx[21] + tmpQ2[69]*tmpFx[30] + tmpQ2[70]*tmpFx[39] + tmpQ2[71]*tmpFx[48] + tmpQ2[72]*tmpFx[57] + tmpQ2[73]*tmpFx[66] + tmpQ2[74]*tmpFx[75] + tmpQ2[75]*tmpFx[84] + tmpQ2[76]*tmpFx[93]; tmpQ1[58] = + tmpQ2[66]*tmpFx[4] + tmpQ2[67]*tmpFx[13] + tmpQ2[68]*tmpFx[22] + tmpQ2[69]*tmpFx[31] + tmpQ2[70]*tmpFx[40] + tmpQ2[71]*tmpFx[49] + tmpQ2[72]*tmpFx[58] + tmpQ2[73]*tmpFx[67] + tmpQ2[74]*tmpFx[76] + tmpQ2[75]*tmpFx[85] + tmpQ2[76]*tmpFx[94]; tmpQ1[59] = + tmpQ2[66]*tmpFx[5] + tmpQ2[67]*tmpFx[14] + tmpQ2[68]*tmpFx[23] + tmpQ2[69]*tmpFx[32] + tmpQ2[70]*tmpFx[41] + tmpQ2[71]*tmpFx[50] + tmpQ2[72]*tmpFx[59] + tmpQ2[73]*tmpFx[68] + tmpQ2[74]*tmpFx[77] + tmpQ2[75]*tmpFx[86] + tmpQ2[76]*tmpFx[95]; tmpQ1[60] = + tmpQ2[66]*tmpFx[6] + tmpQ2[67]*tmpFx[15] + tmpQ2[68]*tmpFx[24] + tmpQ2[69]*tmpFx[33] + tmpQ2[70]*tmpFx[42] + tmpQ2[71]*tmpFx[51] + tmpQ2[72]*tmpFx[60] + tmpQ2[73]*tmpFx[69] + tmpQ2[74]*tmpFx[78] + tmpQ2[75]*tmpFx[87] + tmpQ2[76]*tmpFx[96]; tmpQ1[61] = + tmpQ2[66]*tmpFx[7] + tmpQ2[67]*tmpFx[16] + tmpQ2[68]*tmpFx[25] + tmpQ2[69]*tmpFx[34] + tmpQ2[70]*tmpFx[43] + tmpQ2[71]*tmpFx[52] + tmpQ2[72]*tmpFx[61] + tmpQ2[73]*tmpFx[70] + tmpQ2[74]*tmpFx[79] + tmpQ2[75]*tmpFx[88] + tmpQ2[76]*tmpFx[97]; tmpQ1[62] = + tmpQ2[66]*tmpFx[8] + tmpQ2[67]*tmpFx[17] + tmpQ2[68]*tmpFx[26] + tmpQ2[69]*tmpFx[35] + tmpQ2[70]*tmpFx[44] + tmpQ2[71]*tmpFx[53] + tmpQ2[72]*tmpFx[62] + tmpQ2[73]*tmpFx[71] + tmpQ2[74]*tmpFx[80] + tmpQ2[75]*tmpFx[89] + tmpQ2[76]*tmpFx[98]; tmpQ1[63] = + tmpQ2[77]*tmpFx[0] + tmpQ2[78]*tmpFx[9] + tmpQ2[79]*tmpFx[18] + tmpQ2[80]*tmpFx[27] + tmpQ2[81]*tmpFx[36] + tmpQ2[82]*tmpFx[45] + tmpQ2[83]*tmpFx[54] + tmpQ2[84]*tmpFx[63] + tmpQ2[85]*tmpFx[72] + tmpQ2[86]*tmpFx[81] + tmpQ2[87]*tmpFx[90]; tmpQ1[64] = + tmpQ2[77]*tmpFx[1] + tmpQ2[78]*tmpFx[10] + tmpQ2[79]*tmpFx[19] + tmpQ2[80]*tmpFx[28] + tmpQ2[81]*tmpFx[37] + tmpQ2[82]*tmpFx[46] + tmpQ2[83]*tmpFx[55] + tmpQ2[84]*tmpFx[64] + tmpQ2[85]*tmpFx[73] + tmpQ2[86]*tmpFx[82] + tmpQ2[87]*tmpFx[91]; tmpQ1[65] = + tmpQ2[77]*tmpFx[2] + tmpQ2[78]*tmpFx[11] + tmpQ2[79]*tmpFx[20] + tmpQ2[80]*tmpFx[29] + tmpQ2[81]*tmpFx[38] + tmpQ2[82]*tmpFx[47] + tmpQ2[83]*tmpFx[56] + tmpQ2[84]*tmpFx[65] + tmpQ2[85]*tmpFx[74] + tmpQ2[86]*tmpFx[83] + tmpQ2[87]*tmpFx[92]; tmpQ1[66] = + tmpQ2[77]*tmpFx[3] + tmpQ2[78]*tmpFx[12] + tmpQ2[79]*tmpFx[21] + tmpQ2[80]*tmpFx[30] + tmpQ2[81]*tmpFx[39] + tmpQ2[82]*tmpFx[48] + tmpQ2[83]*tmpFx[57] + tmpQ2[84]*tmpFx[66] + tmpQ2[85]*tmpFx[75] + tmpQ2[86]*tmpFx[84] + tmpQ2[87]*tmpFx[93]; tmpQ1[67] = + tmpQ2[77]*tmpFx[4] + tmpQ2[78]*tmpFx[13] + tmpQ2[79]*tmpFx[22] + tmpQ2[80]*tmpFx[31] + tmpQ2[81]*tmpFx[40] + tmpQ2[82]*tmpFx[49] + tmpQ2[83]*tmpFx[58] + tmpQ2[84]*tmpFx[67] + tmpQ2[85]*tmpFx[76] + tmpQ2[86]*tmpFx[85] + tmpQ2[87]*tmpFx[94]; tmpQ1[68] = + tmpQ2[77]*tmpFx[5] + tmpQ2[78]*tmpFx[14] + tmpQ2[79]*tmpFx[23] + tmpQ2[80]*tmpFx[32] + tmpQ2[81]*tmpFx[41] + tmpQ2[82]*tmpFx[50] + tmpQ2[83]*tmpFx[59] + tmpQ2[84]*tmpFx[68] + tmpQ2[85]*tmpFx[77] + tmpQ2[86]*tmpFx[86] + tmpQ2[87]*tmpFx[95]; tmpQ1[69] = + tmpQ2[77]*tmpFx[6] + tmpQ2[78]*tmpFx[15] + tmpQ2[79]*tmpFx[24] + tmpQ2[80]*tmpFx[33] + tmpQ2[81]*tmpFx[42] + tmpQ2[82]*tmpFx[51] + tmpQ2[83]*tmpFx[60] + tmpQ2[84]*tmpFx[69] + tmpQ2[85]*tmpFx[78] + tmpQ2[86]*tmpFx[87] + tmpQ2[87]*tmpFx[96]; tmpQ1[70] = + tmpQ2[77]*tmpFx[7] + tmpQ2[78]*tmpFx[16] + tmpQ2[79]*tmpFx[25] + tmpQ2[80]*tmpFx[34] + tmpQ2[81]*tmpFx[43] + tmpQ2[82]*tmpFx[52] + tmpQ2[83]*tmpFx[61] + tmpQ2[84]*tmpFx[70] + tmpQ2[85]*tmpFx[79] + tmpQ2[86]*tmpFx[88] + tmpQ2[87]*tmpFx[97]; tmpQ1[71] = + tmpQ2[77]*tmpFx[8] + tmpQ2[78]*tmpFx[17] + tmpQ2[79]*tmpFx[26] + tmpQ2[80]*tmpFx[35] + tmpQ2[81]*tmpFx[44] + tmpQ2[82]*tmpFx[53] + tmpQ2[83]*tmpFx[62] + tmpQ2[84]*tmpFx[71] + tmpQ2[85]*tmpFx[80] + tmpQ2[86]*tmpFx[89] + tmpQ2[87]*tmpFx[98]; tmpQ1[72] = + tmpQ2[88]*tmpFx[0] + tmpQ2[89]*tmpFx[9] + tmpQ2[90]*tmpFx[18] + tmpQ2[91]*tmpFx[27] + tmpQ2[92]*tmpFx[36] + tmpQ2[93]*tmpFx[45] + tmpQ2[94]*tmpFx[54] + tmpQ2[95]*tmpFx[63] + tmpQ2[96]*tmpFx[72] + tmpQ2[97]*tmpFx[81] + tmpQ2[98]*tmpFx[90]; tmpQ1[73] = + tmpQ2[88]*tmpFx[1] + tmpQ2[89]*tmpFx[10] + tmpQ2[90]*tmpFx[19] + tmpQ2[91]*tmpFx[28] + tmpQ2[92]*tmpFx[37] + tmpQ2[93]*tmpFx[46] + tmpQ2[94]*tmpFx[55] + tmpQ2[95]*tmpFx[64] + tmpQ2[96]*tmpFx[73] + tmpQ2[97]*tmpFx[82] + tmpQ2[98]*tmpFx[91]; tmpQ1[74] = + tmpQ2[88]*tmpFx[2] + tmpQ2[89]*tmpFx[11] + tmpQ2[90]*tmpFx[20] + tmpQ2[91]*tmpFx[29] + tmpQ2[92]*tmpFx[38] + tmpQ2[93]*tmpFx[47] + tmpQ2[94]*tmpFx[56] + tmpQ2[95]*tmpFx[65] + tmpQ2[96]*tmpFx[74] + tmpQ2[97]*tmpFx[83] + tmpQ2[98]*tmpFx[92]; tmpQ1[75] = + tmpQ2[88]*tmpFx[3] + tmpQ2[89]*tmpFx[12] + tmpQ2[90]*tmpFx[21] + tmpQ2[91]*tmpFx[30] + tmpQ2[92]*tmpFx[39] + tmpQ2[93]*tmpFx[48] + tmpQ2[94]*tmpFx[57] + tmpQ2[95]*tmpFx[66] + tmpQ2[96]*tmpFx[75] + tmpQ2[97]*tmpFx[84] + tmpQ2[98]*tmpFx[93]; tmpQ1[76] = + tmpQ2[88]*tmpFx[4] + tmpQ2[89]*tmpFx[13] + tmpQ2[90]*tmpFx[22] + tmpQ2[91]*tmpFx[31] + tmpQ2[92]*tmpFx[40] + tmpQ2[93]*tmpFx[49] + tmpQ2[94]*tmpFx[58] + tmpQ2[95]*tmpFx[67] + tmpQ2[96]*tmpFx[76] + tmpQ2[97]*tmpFx[85] + tmpQ2[98]*tmpFx[94]; tmpQ1[77] = + tmpQ2[88]*tmpFx[5] + tmpQ2[89]*tmpFx[14] + tmpQ2[90]*tmpFx[23] + tmpQ2[91]*tmpFx[32] + tmpQ2[92]*tmpFx[41] + tmpQ2[93]*tmpFx[50] + tmpQ2[94]*tmpFx[59] + tmpQ2[95]*tmpFx[68] + tmpQ2[96]*tmpFx[77] + tmpQ2[97]*tmpFx[86] + tmpQ2[98]*tmpFx[95]; tmpQ1[78] = + tmpQ2[88]*tmpFx[6] + tmpQ2[89]*tmpFx[15] + tmpQ2[90]*tmpFx[24] + tmpQ2[91]*tmpFx[33] + tmpQ2[92]*tmpFx[42] + tmpQ2[93]*tmpFx[51] + tmpQ2[94]*tmpFx[60] + tmpQ2[95]*tmpFx[69] + tmpQ2[96]*tmpFx[78] + tmpQ2[97]*tmpFx[87] + tmpQ2[98]*tmpFx[96]; tmpQ1[79] = + tmpQ2[88]*tmpFx[7] + tmpQ2[89]*tmpFx[16] + tmpQ2[90]*tmpFx[25] + tmpQ2[91]*tmpFx[34] + tmpQ2[92]*tmpFx[43] + tmpQ2[93]*tmpFx[52] + tmpQ2[94]*tmpFx[61] + tmpQ2[95]*tmpFx[70] + tmpQ2[96]*tmpFx[79] + tmpQ2[97]*tmpFx[88] + tmpQ2[98]*tmpFx[97]; tmpQ1[80] = + tmpQ2[88]*tmpFx[8] + tmpQ2[89]*tmpFx[17] + tmpQ2[90]*tmpFx[26] + tmpQ2[91]*tmpFx[35] + tmpQ2[92]*tmpFx[44] + tmpQ2[93]*tmpFx[53] + tmpQ2[94]*tmpFx[62] + tmpQ2[95]*tmpFx[71] + tmpQ2[96]*tmpFx[80] + tmpQ2[97]*tmpFx[89] + tmpQ2[98]*tmpFx[98]; } void acado_setObjR1R2( real_t* const tmpFu, real_t* const tmpObjS, real_t* const tmpR1, real_t* const tmpR2 ) { tmpR2[0] = + tmpFu[0]*tmpObjS[0] + tmpFu[3]*tmpObjS[11] + tmpFu[6]*tmpObjS[22] + tmpFu[9]*tmpObjS[33] + tmpFu[12]*tmpObjS[44] + tmpFu[15]*tmpObjS[55] + tmpFu[18]*tmpObjS[66] + tmpFu[21]*tmpObjS[77] + tmpFu[24]*tmpObjS[88] + tmpFu[27]*tmpObjS[99] + tmpFu[30]*tmpObjS[110]; tmpR2[1] = + tmpFu[0]*tmpObjS[1] + tmpFu[3]*tmpObjS[12] + tmpFu[6]*tmpObjS[23] + tmpFu[9]*tmpObjS[34] + tmpFu[12]*tmpObjS[45] + tmpFu[15]*tmpObjS[56] + tmpFu[18]*tmpObjS[67] + tmpFu[21]*tmpObjS[78] + tmpFu[24]*tmpObjS[89] + tmpFu[27]*tmpObjS[100] + tmpFu[30]*tmpObjS[111]; tmpR2[2] = + tmpFu[0]*tmpObjS[2] + tmpFu[3]*tmpObjS[13] + tmpFu[6]*tmpObjS[24] + tmpFu[9]*tmpObjS[35] + tmpFu[12]*tmpObjS[46] + tmpFu[15]*tmpObjS[57] + tmpFu[18]*tmpObjS[68] + tmpFu[21]*tmpObjS[79] + tmpFu[24]*tmpObjS[90] + tmpFu[27]*tmpObjS[101] + tmpFu[30]*tmpObjS[112]; tmpR2[3] = + tmpFu[0]*tmpObjS[3] + tmpFu[3]*tmpObjS[14] + tmpFu[6]*tmpObjS[25] + tmpFu[9]*tmpObjS[36] + tmpFu[12]*tmpObjS[47] + tmpFu[15]*tmpObjS[58] + tmpFu[18]*tmpObjS[69] + tmpFu[21]*tmpObjS[80] + tmpFu[24]*tmpObjS[91] + tmpFu[27]*tmpObjS[102] + tmpFu[30]*tmpObjS[113]; tmpR2[4] = + tmpFu[0]*tmpObjS[4] + tmpFu[3]*tmpObjS[15] + tmpFu[6]*tmpObjS[26] + tmpFu[9]*tmpObjS[37] + tmpFu[12]*tmpObjS[48] + tmpFu[15]*tmpObjS[59] + tmpFu[18]*tmpObjS[70] + tmpFu[21]*tmpObjS[81] + tmpFu[24]*tmpObjS[92] + tmpFu[27]*tmpObjS[103] + tmpFu[30]*tmpObjS[114]; tmpR2[5] = + tmpFu[0]*tmpObjS[5] + tmpFu[3]*tmpObjS[16] + tmpFu[6]*tmpObjS[27] + tmpFu[9]*tmpObjS[38] + tmpFu[12]*tmpObjS[49] + tmpFu[15]*tmpObjS[60] + tmpFu[18]*tmpObjS[71] + tmpFu[21]*tmpObjS[82] + tmpFu[24]*tmpObjS[93] + tmpFu[27]*tmpObjS[104] + tmpFu[30]*tmpObjS[115]; tmpR2[6] = + tmpFu[0]*tmpObjS[6] + tmpFu[3]*tmpObjS[17] + tmpFu[6]*tmpObjS[28] + tmpFu[9]*tmpObjS[39] + tmpFu[12]*tmpObjS[50] + tmpFu[15]*tmpObjS[61] + tmpFu[18]*tmpObjS[72] + tmpFu[21]*tmpObjS[83] + tmpFu[24]*tmpObjS[94] + tmpFu[27]*tmpObjS[105] + tmpFu[30]*tmpObjS[116]; tmpR2[7] = + tmpFu[0]*tmpObjS[7] + tmpFu[3]*tmpObjS[18] + tmpFu[6]*tmpObjS[29] + tmpFu[9]*tmpObjS[40] + tmpFu[12]*tmpObjS[51] + tmpFu[15]*tmpObjS[62] + tmpFu[18]*tmpObjS[73] + tmpFu[21]*tmpObjS[84] + tmpFu[24]*tmpObjS[95] + tmpFu[27]*tmpObjS[106] + tmpFu[30]*tmpObjS[117]; tmpR2[8] = + tmpFu[0]*tmpObjS[8] + tmpFu[3]*tmpObjS[19] + tmpFu[6]*tmpObjS[30] + tmpFu[9]*tmpObjS[41] + tmpFu[12]*tmpObjS[52] + tmpFu[15]*tmpObjS[63] + tmpFu[18]*tmpObjS[74] + tmpFu[21]*tmpObjS[85] + tmpFu[24]*tmpObjS[96] + tmpFu[27]*tmpObjS[107] + tmpFu[30]*tmpObjS[118]; tmpR2[9] = + tmpFu[0]*tmpObjS[9] + tmpFu[3]*tmpObjS[20] + tmpFu[6]*tmpObjS[31] + tmpFu[9]*tmpObjS[42] + tmpFu[12]*tmpObjS[53] + tmpFu[15]*tmpObjS[64] + tmpFu[18]*tmpObjS[75] + tmpFu[21]*tmpObjS[86] + tmpFu[24]*tmpObjS[97] + tmpFu[27]*tmpObjS[108] + tmpFu[30]*tmpObjS[119]; tmpR2[10] = + tmpFu[0]*tmpObjS[10] + tmpFu[3]*tmpObjS[21] + tmpFu[6]*tmpObjS[32] + tmpFu[9]*tmpObjS[43] + tmpFu[12]*tmpObjS[54] + tmpFu[15]*tmpObjS[65] + tmpFu[18]*tmpObjS[76] + tmpFu[21]*tmpObjS[87] + tmpFu[24]*tmpObjS[98] + tmpFu[27]*tmpObjS[109] + tmpFu[30]*tmpObjS[120]; tmpR2[11] = + tmpFu[1]*tmpObjS[0] + tmpFu[4]*tmpObjS[11] + tmpFu[7]*tmpObjS[22] + tmpFu[10]*tmpObjS[33] + tmpFu[13]*tmpObjS[44] + tmpFu[16]*tmpObjS[55] + tmpFu[19]*tmpObjS[66] + tmpFu[22]*tmpObjS[77] + tmpFu[25]*tmpObjS[88] + tmpFu[28]*tmpObjS[99] + tmpFu[31]*tmpObjS[110]; tmpR2[12] = + tmpFu[1]*tmpObjS[1] + tmpFu[4]*tmpObjS[12] + tmpFu[7]*tmpObjS[23] + tmpFu[10]*tmpObjS[34] + tmpFu[13]*tmpObjS[45] + tmpFu[16]*tmpObjS[56] + tmpFu[19]*tmpObjS[67] + tmpFu[22]*tmpObjS[78] + tmpFu[25]*tmpObjS[89] + tmpFu[28]*tmpObjS[100] + tmpFu[31]*tmpObjS[111]; tmpR2[13] = + tmpFu[1]*tmpObjS[2] + tmpFu[4]*tmpObjS[13] + tmpFu[7]*tmpObjS[24] + tmpFu[10]*tmpObjS[35] + tmpFu[13]*tmpObjS[46] + tmpFu[16]*tmpObjS[57] + tmpFu[19]*tmpObjS[68] + tmpFu[22]*tmpObjS[79] + tmpFu[25]*tmpObjS[90] + tmpFu[28]*tmpObjS[101] + tmpFu[31]*tmpObjS[112]; tmpR2[14] = + tmpFu[1]*tmpObjS[3] + tmpFu[4]*tmpObjS[14] + tmpFu[7]*tmpObjS[25] + tmpFu[10]*tmpObjS[36] + tmpFu[13]*tmpObjS[47] + tmpFu[16]*tmpObjS[58] + tmpFu[19]*tmpObjS[69] + tmpFu[22]*tmpObjS[80] + tmpFu[25]*tmpObjS[91] + tmpFu[28]*tmpObjS[102] + tmpFu[31]*tmpObjS[113]; tmpR2[15] = + tmpFu[1]*tmpObjS[4] + tmpFu[4]*tmpObjS[15] + tmpFu[7]*tmpObjS[26] + tmpFu[10]*tmpObjS[37] + tmpFu[13]*tmpObjS[48] + tmpFu[16]*tmpObjS[59] + tmpFu[19]*tmpObjS[70] + tmpFu[22]*tmpObjS[81] + tmpFu[25]*tmpObjS[92] + tmpFu[28]*tmpObjS[103] + tmpFu[31]*tmpObjS[114]; tmpR2[16] = + tmpFu[1]*tmpObjS[5] + tmpFu[4]*tmpObjS[16] + tmpFu[7]*tmpObjS[27] + tmpFu[10]*tmpObjS[38] + tmpFu[13]*tmpObjS[49] + tmpFu[16]*tmpObjS[60] + tmpFu[19]*tmpObjS[71] + tmpFu[22]*tmpObjS[82] + tmpFu[25]*tmpObjS[93] + tmpFu[28]*tmpObjS[104] + tmpFu[31]*tmpObjS[115]; tmpR2[17] = + tmpFu[1]*tmpObjS[6] + tmpFu[4]*tmpObjS[17] + tmpFu[7]*tmpObjS[28] + tmpFu[10]*tmpObjS[39] + tmpFu[13]*tmpObjS[50] + tmpFu[16]*tmpObjS[61] + tmpFu[19]*tmpObjS[72] + tmpFu[22]*tmpObjS[83] + tmpFu[25]*tmpObjS[94] + tmpFu[28]*tmpObjS[105] + tmpFu[31]*tmpObjS[116]; tmpR2[18] = + tmpFu[1]*tmpObjS[7] + tmpFu[4]*tmpObjS[18] + tmpFu[7]*tmpObjS[29] + tmpFu[10]*tmpObjS[40] + tmpFu[13]*tmpObjS[51] + tmpFu[16]*tmpObjS[62] + tmpFu[19]*tmpObjS[73] + tmpFu[22]*tmpObjS[84] + tmpFu[25]*tmpObjS[95] + tmpFu[28]*tmpObjS[106] + tmpFu[31]*tmpObjS[117]; tmpR2[19] = + tmpFu[1]*tmpObjS[8] + tmpFu[4]*tmpObjS[19] + tmpFu[7]*tmpObjS[30] + tmpFu[10]*tmpObjS[41] + tmpFu[13]*tmpObjS[52] + tmpFu[16]*tmpObjS[63] + tmpFu[19]*tmpObjS[74] + tmpFu[22]*tmpObjS[85] + tmpFu[25]*tmpObjS[96] + tmpFu[28]*tmpObjS[107] + tmpFu[31]*tmpObjS[118]; tmpR2[20] = + tmpFu[1]*tmpObjS[9] + tmpFu[4]*tmpObjS[20] + tmpFu[7]*tmpObjS[31] + tmpFu[10]*tmpObjS[42] + tmpFu[13]*tmpObjS[53] + tmpFu[16]*tmpObjS[64] + tmpFu[19]*tmpObjS[75] + tmpFu[22]*tmpObjS[86] + tmpFu[25]*tmpObjS[97] + tmpFu[28]*tmpObjS[108] + tmpFu[31]*tmpObjS[119]; tmpR2[21] = + tmpFu[1]*tmpObjS[10] + tmpFu[4]*tmpObjS[21] + tmpFu[7]*tmpObjS[32] + tmpFu[10]*tmpObjS[43] + tmpFu[13]*tmpObjS[54] + tmpFu[16]*tmpObjS[65] + tmpFu[19]*tmpObjS[76] + tmpFu[22]*tmpObjS[87] + tmpFu[25]*tmpObjS[98] + tmpFu[28]*tmpObjS[109] + tmpFu[31]*tmpObjS[120]; tmpR2[22] = + tmpFu[2]*tmpObjS[0] + tmpFu[5]*tmpObjS[11] + tmpFu[8]*tmpObjS[22] + tmpFu[11]*tmpObjS[33] + tmpFu[14]*tmpObjS[44] + tmpFu[17]*tmpObjS[55] + tmpFu[20]*tmpObjS[66] + tmpFu[23]*tmpObjS[77] + tmpFu[26]*tmpObjS[88] + tmpFu[29]*tmpObjS[99] + tmpFu[32]*tmpObjS[110]; tmpR2[23] = + tmpFu[2]*tmpObjS[1] + tmpFu[5]*tmpObjS[12] + tmpFu[8]*tmpObjS[23] + tmpFu[11]*tmpObjS[34] + tmpFu[14]*tmpObjS[45] + tmpFu[17]*tmpObjS[56] + tmpFu[20]*tmpObjS[67] + tmpFu[23]*tmpObjS[78] + tmpFu[26]*tmpObjS[89] + tmpFu[29]*tmpObjS[100] + tmpFu[32]*tmpObjS[111]; tmpR2[24] = + tmpFu[2]*tmpObjS[2] + tmpFu[5]*tmpObjS[13] + tmpFu[8]*tmpObjS[24] + tmpFu[11]*tmpObjS[35] + tmpFu[14]*tmpObjS[46] + tmpFu[17]*tmpObjS[57] + tmpFu[20]*tmpObjS[68] + tmpFu[23]*tmpObjS[79] + tmpFu[26]*tmpObjS[90] + tmpFu[29]*tmpObjS[101] + tmpFu[32]*tmpObjS[112]; tmpR2[25] = + tmpFu[2]*tmpObjS[3] + tmpFu[5]*tmpObjS[14] + tmpFu[8]*tmpObjS[25] + tmpFu[11]*tmpObjS[36] + tmpFu[14]*tmpObjS[47] + tmpFu[17]*tmpObjS[58] + tmpFu[20]*tmpObjS[69] + tmpFu[23]*tmpObjS[80] + tmpFu[26]*tmpObjS[91] + tmpFu[29]*tmpObjS[102] + tmpFu[32]*tmpObjS[113]; tmpR2[26] = + tmpFu[2]*tmpObjS[4] + tmpFu[5]*tmpObjS[15] + tmpFu[8]*tmpObjS[26] + tmpFu[11]*tmpObjS[37] + tmpFu[14]*tmpObjS[48] + tmpFu[17]*tmpObjS[59] + tmpFu[20]*tmpObjS[70] + tmpFu[23]*tmpObjS[81] + tmpFu[26]*tmpObjS[92] + tmpFu[29]*tmpObjS[103] + tmpFu[32]*tmpObjS[114]; tmpR2[27] = + tmpFu[2]*tmpObjS[5] + tmpFu[5]*tmpObjS[16] + tmpFu[8]*tmpObjS[27] + tmpFu[11]*tmpObjS[38] + tmpFu[14]*tmpObjS[49] + tmpFu[17]*tmpObjS[60] + tmpFu[20]*tmpObjS[71] + tmpFu[23]*tmpObjS[82] + tmpFu[26]*tmpObjS[93] + tmpFu[29]*tmpObjS[104] + tmpFu[32]*tmpObjS[115]; tmpR2[28] = + tmpFu[2]*tmpObjS[6] + tmpFu[5]*tmpObjS[17] + tmpFu[8]*tmpObjS[28] + tmpFu[11]*tmpObjS[39] + tmpFu[14]*tmpObjS[50] + tmpFu[17]*tmpObjS[61] + tmpFu[20]*tmpObjS[72] + tmpFu[23]*tmpObjS[83] + tmpFu[26]*tmpObjS[94] + tmpFu[29]*tmpObjS[105] + tmpFu[32]*tmpObjS[116]; tmpR2[29] = + tmpFu[2]*tmpObjS[7] + tmpFu[5]*tmpObjS[18] + tmpFu[8]*tmpObjS[29] + tmpFu[11]*tmpObjS[40] + tmpFu[14]*tmpObjS[51] + tmpFu[17]*tmpObjS[62] + tmpFu[20]*tmpObjS[73] + tmpFu[23]*tmpObjS[84] + tmpFu[26]*tmpObjS[95] + tmpFu[29]*tmpObjS[106] + tmpFu[32]*tmpObjS[117]; tmpR2[30] = + tmpFu[2]*tmpObjS[8] + tmpFu[5]*tmpObjS[19] + tmpFu[8]*tmpObjS[30] + tmpFu[11]*tmpObjS[41] + tmpFu[14]*tmpObjS[52] + tmpFu[17]*tmpObjS[63] + tmpFu[20]*tmpObjS[74] + tmpFu[23]*tmpObjS[85] + tmpFu[26]*tmpObjS[96] + tmpFu[29]*tmpObjS[107] + tmpFu[32]*tmpObjS[118]; tmpR2[31] = + tmpFu[2]*tmpObjS[9] + tmpFu[5]*tmpObjS[20] + tmpFu[8]*tmpObjS[31] + tmpFu[11]*tmpObjS[42] + tmpFu[14]*tmpObjS[53] + tmpFu[17]*tmpObjS[64] + tmpFu[20]*tmpObjS[75] + tmpFu[23]*tmpObjS[86] + tmpFu[26]*tmpObjS[97] + tmpFu[29]*tmpObjS[108] + tmpFu[32]*tmpObjS[119]; tmpR2[32] = + tmpFu[2]*tmpObjS[10] + tmpFu[5]*tmpObjS[21] + tmpFu[8]*tmpObjS[32] + tmpFu[11]*tmpObjS[43] + tmpFu[14]*tmpObjS[54] + tmpFu[17]*tmpObjS[65] + tmpFu[20]*tmpObjS[76] + tmpFu[23]*tmpObjS[87] + tmpFu[26]*tmpObjS[98] + tmpFu[29]*tmpObjS[109] + tmpFu[32]*tmpObjS[120]; tmpR1[0] = + tmpR2[0]*tmpFu[0] + tmpR2[1]*tmpFu[3] + tmpR2[2]*tmpFu[6] + tmpR2[3]*tmpFu[9] + tmpR2[4]*tmpFu[12] + tmpR2[5]*tmpFu[15] + tmpR2[6]*tmpFu[18] + tmpR2[7]*tmpFu[21] + tmpR2[8]*tmpFu[24] + tmpR2[9]*tmpFu[27] + tmpR2[10]*tmpFu[30]; tmpR1[1] = + tmpR2[0]*tmpFu[1] + tmpR2[1]*tmpFu[4] + tmpR2[2]*tmpFu[7] + tmpR2[3]*tmpFu[10] + tmpR2[4]*tmpFu[13] + tmpR2[5]*tmpFu[16] + tmpR2[6]*tmpFu[19] + tmpR2[7]*tmpFu[22] + tmpR2[8]*tmpFu[25] + tmpR2[9]*tmpFu[28] + tmpR2[10]*tmpFu[31]; tmpR1[2] = + tmpR2[0]*tmpFu[2] + tmpR2[1]*tmpFu[5] + tmpR2[2]*tmpFu[8] + tmpR2[3]*tmpFu[11] + tmpR2[4]*tmpFu[14] + tmpR2[5]*tmpFu[17] + tmpR2[6]*tmpFu[20] + tmpR2[7]*tmpFu[23] + tmpR2[8]*tmpFu[26] + tmpR2[9]*tmpFu[29] + tmpR2[10]*tmpFu[32]; tmpR1[3] = + tmpR2[11]*tmpFu[0] + tmpR2[12]*tmpFu[3] + tmpR2[13]*tmpFu[6] + tmpR2[14]*tmpFu[9] + tmpR2[15]*tmpFu[12] + tmpR2[16]*tmpFu[15] + tmpR2[17]*tmpFu[18] + tmpR2[18]*tmpFu[21] + tmpR2[19]*tmpFu[24] + tmpR2[20]*tmpFu[27] + tmpR2[21]*tmpFu[30]; tmpR1[4] = + tmpR2[11]*tmpFu[1] + tmpR2[12]*tmpFu[4] + tmpR2[13]*tmpFu[7] + tmpR2[14]*tmpFu[10] + tmpR2[15]*tmpFu[13] + tmpR2[16]*tmpFu[16] + tmpR2[17]*tmpFu[19] + tmpR2[18]*tmpFu[22] + tmpR2[19]*tmpFu[25] + tmpR2[20]*tmpFu[28] + tmpR2[21]*tmpFu[31]; tmpR1[5] = + tmpR2[11]*tmpFu[2] + tmpR2[12]*tmpFu[5] + tmpR2[13]*tmpFu[8] + tmpR2[14]*tmpFu[11] + tmpR2[15]*tmpFu[14] + tmpR2[16]*tmpFu[17] + tmpR2[17]*tmpFu[20] + tmpR2[18]*tmpFu[23] + tmpR2[19]*tmpFu[26] + tmpR2[20]*tmpFu[29] + tmpR2[21]*tmpFu[32]; tmpR1[6] = + tmpR2[22]*tmpFu[0] + tmpR2[23]*tmpFu[3] + tmpR2[24]*tmpFu[6] + tmpR2[25]*tmpFu[9] + tmpR2[26]*tmpFu[12] + tmpR2[27]*tmpFu[15] + tmpR2[28]*tmpFu[18] + tmpR2[29]*tmpFu[21] + tmpR2[30]*tmpFu[24] + tmpR2[31]*tmpFu[27] + tmpR2[32]*tmpFu[30]; tmpR1[7] = + tmpR2[22]*tmpFu[1] + tmpR2[23]*tmpFu[4] + tmpR2[24]*tmpFu[7] + tmpR2[25]*tmpFu[10] + tmpR2[26]*tmpFu[13] + tmpR2[27]*tmpFu[16] + tmpR2[28]*tmpFu[19] + tmpR2[29]*tmpFu[22] + tmpR2[30]*tmpFu[25] + tmpR2[31]*tmpFu[28] + tmpR2[32]*tmpFu[31]; tmpR1[8] = + tmpR2[22]*tmpFu[2] + tmpR2[23]*tmpFu[5] + tmpR2[24]*tmpFu[8] + tmpR2[25]*tmpFu[11] + tmpR2[26]*tmpFu[14] + tmpR2[27]*tmpFu[17] + tmpR2[28]*tmpFu[20] + tmpR2[29]*tmpFu[23] + tmpR2[30]*tmpFu[26] + tmpR2[31]*tmpFu[29] + tmpR2[32]*tmpFu[32]; } void acado_setObjS1( real_t* const tmpFx, real_t* const tmpFu, real_t* const tmpObjS, real_t* const tmpS1 ) { /** Matrix of size: 9 x 11 (row major format) */ real_t tmpS2[ 99 ]; tmpS2[0] = + tmpFx[0]*tmpObjS[0] + tmpFx[9]*tmpObjS[11] + tmpFx[18]*tmpObjS[22] + tmpFx[27]*tmpObjS[33] + tmpFx[36]*tmpObjS[44] + tmpFx[45]*tmpObjS[55] + tmpFx[54]*tmpObjS[66] + tmpFx[63]*tmpObjS[77] + tmpFx[72]*tmpObjS[88] + tmpFx[81]*tmpObjS[99] + tmpFx[90]*tmpObjS[110]; tmpS2[1] = + tmpFx[0]*tmpObjS[1] + tmpFx[9]*tmpObjS[12] + tmpFx[18]*tmpObjS[23] + tmpFx[27]*tmpObjS[34] + tmpFx[36]*tmpObjS[45] + tmpFx[45]*tmpObjS[56] + tmpFx[54]*tmpObjS[67] + tmpFx[63]*tmpObjS[78] + tmpFx[72]*tmpObjS[89] + tmpFx[81]*tmpObjS[100] + tmpFx[90]*tmpObjS[111]; tmpS2[2] = + tmpFx[0]*tmpObjS[2] + tmpFx[9]*tmpObjS[13] + tmpFx[18]*tmpObjS[24] + tmpFx[27]*tmpObjS[35] + tmpFx[36]*tmpObjS[46] + tmpFx[45]*tmpObjS[57] + tmpFx[54]*tmpObjS[68] + tmpFx[63]*tmpObjS[79] + tmpFx[72]*tmpObjS[90] + tmpFx[81]*tmpObjS[101] + tmpFx[90]*tmpObjS[112]; tmpS2[3] = + tmpFx[0]*tmpObjS[3] + tmpFx[9]*tmpObjS[14] + tmpFx[18]*tmpObjS[25] + tmpFx[27]*tmpObjS[36] + tmpFx[36]*tmpObjS[47] + tmpFx[45]*tmpObjS[58] + tmpFx[54]*tmpObjS[69] + tmpFx[63]*tmpObjS[80] + tmpFx[72]*tmpObjS[91] + tmpFx[81]*tmpObjS[102] + tmpFx[90]*tmpObjS[113]; tmpS2[4] = + tmpFx[0]*tmpObjS[4] + tmpFx[9]*tmpObjS[15] + tmpFx[18]*tmpObjS[26] + tmpFx[27]*tmpObjS[37] + tmpFx[36]*tmpObjS[48] + tmpFx[45]*tmpObjS[59] + tmpFx[54]*tmpObjS[70] + tmpFx[63]*tmpObjS[81] + tmpFx[72]*tmpObjS[92] + tmpFx[81]*tmpObjS[103] + tmpFx[90]*tmpObjS[114]; tmpS2[5] = + tmpFx[0]*tmpObjS[5] + tmpFx[9]*tmpObjS[16] + tmpFx[18]*tmpObjS[27] + tmpFx[27]*tmpObjS[38] + tmpFx[36]*tmpObjS[49] + tmpFx[45]*tmpObjS[60] + tmpFx[54]*tmpObjS[71] + tmpFx[63]*tmpObjS[82] + tmpFx[72]*tmpObjS[93] + tmpFx[81]*tmpObjS[104] + tmpFx[90]*tmpObjS[115]; tmpS2[6] = + tmpFx[0]*tmpObjS[6] + tmpFx[9]*tmpObjS[17] + tmpFx[18]*tmpObjS[28] + tmpFx[27]*tmpObjS[39] + tmpFx[36]*tmpObjS[50] + tmpFx[45]*tmpObjS[61] + tmpFx[54]*tmpObjS[72] + tmpFx[63]*tmpObjS[83] + tmpFx[72]*tmpObjS[94] + tmpFx[81]*tmpObjS[105] + tmpFx[90]*tmpObjS[116]; tmpS2[7] = + tmpFx[0]*tmpObjS[7] + tmpFx[9]*tmpObjS[18] + tmpFx[18]*tmpObjS[29] + tmpFx[27]*tmpObjS[40] + tmpFx[36]*tmpObjS[51] + tmpFx[45]*tmpObjS[62] + tmpFx[54]*tmpObjS[73] + tmpFx[63]*tmpObjS[84] + tmpFx[72]*tmpObjS[95] + tmpFx[81]*tmpObjS[106] + tmpFx[90]*tmpObjS[117]; tmpS2[8] = + tmpFx[0]*tmpObjS[8] + tmpFx[9]*tmpObjS[19] + tmpFx[18]*tmpObjS[30] + tmpFx[27]*tmpObjS[41] + tmpFx[36]*tmpObjS[52] + tmpFx[45]*tmpObjS[63] + tmpFx[54]*tmpObjS[74] + tmpFx[63]*tmpObjS[85] + tmpFx[72]*tmpObjS[96] + tmpFx[81]*tmpObjS[107] + tmpFx[90]*tmpObjS[118]; tmpS2[9] = + tmpFx[0]*tmpObjS[9] + tmpFx[9]*tmpObjS[20] + tmpFx[18]*tmpObjS[31] + tmpFx[27]*tmpObjS[42] + tmpFx[36]*tmpObjS[53] + tmpFx[45]*tmpObjS[64] + tmpFx[54]*tmpObjS[75] + tmpFx[63]*tmpObjS[86] + tmpFx[72]*tmpObjS[97] + tmpFx[81]*tmpObjS[108] + tmpFx[90]*tmpObjS[119]; tmpS2[10] = + tmpFx[0]*tmpObjS[10] + tmpFx[9]*tmpObjS[21] + tmpFx[18]*tmpObjS[32] + tmpFx[27]*tmpObjS[43] + tmpFx[36]*tmpObjS[54] + tmpFx[45]*tmpObjS[65] + tmpFx[54]*tmpObjS[76] + tmpFx[63]*tmpObjS[87] + tmpFx[72]*tmpObjS[98] + tmpFx[81]*tmpObjS[109] + tmpFx[90]*tmpObjS[120]; tmpS2[11] = + tmpFx[1]*tmpObjS[0] + tmpFx[10]*tmpObjS[11] + tmpFx[19]*tmpObjS[22] + tmpFx[28]*tmpObjS[33] + tmpFx[37]*tmpObjS[44] + tmpFx[46]*tmpObjS[55] + tmpFx[55]*tmpObjS[66] + tmpFx[64]*tmpObjS[77] + tmpFx[73]*tmpObjS[88] + tmpFx[82]*tmpObjS[99] + tmpFx[91]*tmpObjS[110]; tmpS2[12] = + tmpFx[1]*tmpObjS[1] + tmpFx[10]*tmpObjS[12] + tmpFx[19]*tmpObjS[23] + tmpFx[28]*tmpObjS[34] + tmpFx[37]*tmpObjS[45] + tmpFx[46]*tmpObjS[56] + tmpFx[55]*tmpObjS[67] + tmpFx[64]*tmpObjS[78] + tmpFx[73]*tmpObjS[89] + tmpFx[82]*tmpObjS[100] + tmpFx[91]*tmpObjS[111]; tmpS2[13] = + tmpFx[1]*tmpObjS[2] + tmpFx[10]*tmpObjS[13] + tmpFx[19]*tmpObjS[24] + tmpFx[28]*tmpObjS[35] + tmpFx[37]*tmpObjS[46] + tmpFx[46]*tmpObjS[57] + tmpFx[55]*tmpObjS[68] + tmpFx[64]*tmpObjS[79] + tmpFx[73]*tmpObjS[90] + tmpFx[82]*tmpObjS[101] + tmpFx[91]*tmpObjS[112]; tmpS2[14] = + tmpFx[1]*tmpObjS[3] + tmpFx[10]*tmpObjS[14] + tmpFx[19]*tmpObjS[25] + tmpFx[28]*tmpObjS[36] + tmpFx[37]*tmpObjS[47] + tmpFx[46]*tmpObjS[58] + tmpFx[55]*tmpObjS[69] + tmpFx[64]*tmpObjS[80] + tmpFx[73]*tmpObjS[91] + tmpFx[82]*tmpObjS[102] + tmpFx[91]*tmpObjS[113]; tmpS2[15] = + tmpFx[1]*tmpObjS[4] + tmpFx[10]*tmpObjS[15] + tmpFx[19]*tmpObjS[26] + tmpFx[28]*tmpObjS[37] + tmpFx[37]*tmpObjS[48] + tmpFx[46]*tmpObjS[59] + tmpFx[55]*tmpObjS[70] + tmpFx[64]*tmpObjS[81] + tmpFx[73]*tmpObjS[92] + tmpFx[82]*tmpObjS[103] + tmpFx[91]*tmpObjS[114]; tmpS2[16] = + tmpFx[1]*tmpObjS[5] + tmpFx[10]*tmpObjS[16] + tmpFx[19]*tmpObjS[27] + tmpFx[28]*tmpObjS[38] + tmpFx[37]*tmpObjS[49] + tmpFx[46]*tmpObjS[60] + tmpFx[55]*tmpObjS[71] + tmpFx[64]*tmpObjS[82] + tmpFx[73]*tmpObjS[93] + tmpFx[82]*tmpObjS[104] + tmpFx[91]*tmpObjS[115]; tmpS2[17] = + tmpFx[1]*tmpObjS[6] + tmpFx[10]*tmpObjS[17] + tmpFx[19]*tmpObjS[28] + tmpFx[28]*tmpObjS[39] + tmpFx[37]*tmpObjS[50] + tmpFx[46]*tmpObjS[61] + tmpFx[55]*tmpObjS[72] + tmpFx[64]*tmpObjS[83] + tmpFx[73]*tmpObjS[94] + tmpFx[82]*tmpObjS[105] + tmpFx[91]*tmpObjS[116]; tmpS2[18] = + tmpFx[1]*tmpObjS[7] + tmpFx[10]*tmpObjS[18] + tmpFx[19]*tmpObjS[29] + tmpFx[28]*tmpObjS[40] + tmpFx[37]*tmpObjS[51] + tmpFx[46]*tmpObjS[62] + tmpFx[55]*tmpObjS[73] + tmpFx[64]*tmpObjS[84] + tmpFx[73]*tmpObjS[95] + tmpFx[82]*tmpObjS[106] + tmpFx[91]*tmpObjS[117]; tmpS2[19] = + tmpFx[1]*tmpObjS[8] + tmpFx[10]*tmpObjS[19] + tmpFx[19]*tmpObjS[30] + tmpFx[28]*tmpObjS[41] + tmpFx[37]*tmpObjS[52] + tmpFx[46]*tmpObjS[63] + tmpFx[55]*tmpObjS[74] + tmpFx[64]*tmpObjS[85] + tmpFx[73]*tmpObjS[96] + tmpFx[82]*tmpObjS[107] + tmpFx[91]*tmpObjS[118]; tmpS2[20] = + tmpFx[1]*tmpObjS[9] + tmpFx[10]*tmpObjS[20] + tmpFx[19]*tmpObjS[31] + tmpFx[28]*tmpObjS[42] + tmpFx[37]*tmpObjS[53] + tmpFx[46]*tmpObjS[64] + tmpFx[55]*tmpObjS[75] + tmpFx[64]*tmpObjS[86] + tmpFx[73]*tmpObjS[97] + tmpFx[82]*tmpObjS[108] + tmpFx[91]*tmpObjS[119]; tmpS2[21] = + tmpFx[1]*tmpObjS[10] + tmpFx[10]*tmpObjS[21] + tmpFx[19]*tmpObjS[32] + tmpFx[28]*tmpObjS[43] + tmpFx[37]*tmpObjS[54] + tmpFx[46]*tmpObjS[65] + tmpFx[55]*tmpObjS[76] + tmpFx[64]*tmpObjS[87] + tmpFx[73]*tmpObjS[98] + tmpFx[82]*tmpObjS[109] + tmpFx[91]*tmpObjS[120]; tmpS2[22] = + tmpFx[2]*tmpObjS[0] + tmpFx[11]*tmpObjS[11] + tmpFx[20]*tmpObjS[22] + tmpFx[29]*tmpObjS[33] + tmpFx[38]*tmpObjS[44] + tmpFx[47]*tmpObjS[55] + tmpFx[56]*tmpObjS[66] + tmpFx[65]*tmpObjS[77] + tmpFx[74]*tmpObjS[88] + tmpFx[83]*tmpObjS[99] + tmpFx[92]*tmpObjS[110]; tmpS2[23] = + tmpFx[2]*tmpObjS[1] + tmpFx[11]*tmpObjS[12] + tmpFx[20]*tmpObjS[23] + tmpFx[29]*tmpObjS[34] + tmpFx[38]*tmpObjS[45] + tmpFx[47]*tmpObjS[56] + tmpFx[56]*tmpObjS[67] + tmpFx[65]*tmpObjS[78] + tmpFx[74]*tmpObjS[89] + tmpFx[83]*tmpObjS[100] + tmpFx[92]*tmpObjS[111]; tmpS2[24] = + tmpFx[2]*tmpObjS[2] + tmpFx[11]*tmpObjS[13] + tmpFx[20]*tmpObjS[24] + tmpFx[29]*tmpObjS[35] + tmpFx[38]*tmpObjS[46] + tmpFx[47]*tmpObjS[57] + tmpFx[56]*tmpObjS[68] + tmpFx[65]*tmpObjS[79] + tmpFx[74]*tmpObjS[90] + tmpFx[83]*tmpObjS[101] + tmpFx[92]*tmpObjS[112]; tmpS2[25] = + tmpFx[2]*tmpObjS[3] + tmpFx[11]*tmpObjS[14] + tmpFx[20]*tmpObjS[25] + tmpFx[29]*tmpObjS[36] + tmpFx[38]*tmpObjS[47] + tmpFx[47]*tmpObjS[58] + tmpFx[56]*tmpObjS[69] + tmpFx[65]*tmpObjS[80] + tmpFx[74]*tmpObjS[91] + tmpFx[83]*tmpObjS[102] + tmpFx[92]*tmpObjS[113]; tmpS2[26] = + tmpFx[2]*tmpObjS[4] + tmpFx[11]*tmpObjS[15] + tmpFx[20]*tmpObjS[26] + tmpFx[29]*tmpObjS[37] + tmpFx[38]*tmpObjS[48] + tmpFx[47]*tmpObjS[59] + tmpFx[56]*tmpObjS[70] + tmpFx[65]*tmpObjS[81] + tmpFx[74]*tmpObjS[92] + tmpFx[83]*tmpObjS[103] + tmpFx[92]*tmpObjS[114]; tmpS2[27] = + tmpFx[2]*tmpObjS[5] + tmpFx[11]*tmpObjS[16] + tmpFx[20]*tmpObjS[27] + tmpFx[29]*tmpObjS[38] + tmpFx[38]*tmpObjS[49] + tmpFx[47]*tmpObjS[60] + tmpFx[56]*tmpObjS[71] + tmpFx[65]*tmpObjS[82] + tmpFx[74]*tmpObjS[93] + tmpFx[83]*tmpObjS[104] + tmpFx[92]*tmpObjS[115]; tmpS2[28] = + tmpFx[2]*tmpObjS[6] + tmpFx[11]*tmpObjS[17] + tmpFx[20]*tmpObjS[28] + tmpFx[29]*tmpObjS[39] + tmpFx[38]*tmpObjS[50] + tmpFx[47]*tmpObjS[61] + tmpFx[56]*tmpObjS[72] + tmpFx[65]*tmpObjS[83] + tmpFx[74]*tmpObjS[94] + tmpFx[83]*tmpObjS[105] + tmpFx[92]*tmpObjS[116]; tmpS2[29] = + tmpFx[2]*tmpObjS[7] + tmpFx[11]*tmpObjS[18] + tmpFx[20]*tmpObjS[29] + tmpFx[29]*tmpObjS[40] + tmpFx[38]*tmpObjS[51] + tmpFx[47]*tmpObjS[62] + tmpFx[56]*tmpObjS[73] + tmpFx[65]*tmpObjS[84] + tmpFx[74]*tmpObjS[95] + tmpFx[83]*tmpObjS[106] + tmpFx[92]*tmpObjS[117]; tmpS2[30] = + tmpFx[2]*tmpObjS[8] + tmpFx[11]*tmpObjS[19] + tmpFx[20]*tmpObjS[30] + tmpFx[29]*tmpObjS[41] + tmpFx[38]*tmpObjS[52] + tmpFx[47]*tmpObjS[63] + tmpFx[56]*tmpObjS[74] + tmpFx[65]*tmpObjS[85] + tmpFx[74]*tmpObjS[96] + tmpFx[83]*tmpObjS[107] + tmpFx[92]*tmpObjS[118]; tmpS2[31] = + tmpFx[2]*tmpObjS[9] + tmpFx[11]*tmpObjS[20] + tmpFx[20]*tmpObjS[31] + tmpFx[29]*tmpObjS[42] + tmpFx[38]*tmpObjS[53] + tmpFx[47]*tmpObjS[64] + tmpFx[56]*tmpObjS[75] + tmpFx[65]*tmpObjS[86] + tmpFx[74]*tmpObjS[97] + tmpFx[83]*tmpObjS[108] + tmpFx[92]*tmpObjS[119]; tmpS2[32] = + tmpFx[2]*tmpObjS[10] + tmpFx[11]*tmpObjS[21] + tmpFx[20]*tmpObjS[32] + tmpFx[29]*tmpObjS[43] + tmpFx[38]*tmpObjS[54] + tmpFx[47]*tmpObjS[65] + tmpFx[56]*tmpObjS[76] + tmpFx[65]*tmpObjS[87] + tmpFx[74]*tmpObjS[98] + tmpFx[83]*tmpObjS[109] + tmpFx[92]*tmpObjS[120]; tmpS2[33] = + tmpFx[3]*tmpObjS[0] + tmpFx[12]*tmpObjS[11] + tmpFx[21]*tmpObjS[22] + tmpFx[30]*tmpObjS[33] + tmpFx[39]*tmpObjS[44] + tmpFx[48]*tmpObjS[55] + tmpFx[57]*tmpObjS[66] + tmpFx[66]*tmpObjS[77] + tmpFx[75]*tmpObjS[88] + tmpFx[84]*tmpObjS[99] + tmpFx[93]*tmpObjS[110]; tmpS2[34] = + tmpFx[3]*tmpObjS[1] + tmpFx[12]*tmpObjS[12] + tmpFx[21]*tmpObjS[23] + tmpFx[30]*tmpObjS[34] + tmpFx[39]*tmpObjS[45] + tmpFx[48]*tmpObjS[56] + tmpFx[57]*tmpObjS[67] + tmpFx[66]*tmpObjS[78] + tmpFx[75]*tmpObjS[89] + tmpFx[84]*tmpObjS[100] + tmpFx[93]*tmpObjS[111]; tmpS2[35] = + tmpFx[3]*tmpObjS[2] + tmpFx[12]*tmpObjS[13] + tmpFx[21]*tmpObjS[24] + tmpFx[30]*tmpObjS[35] + tmpFx[39]*tmpObjS[46] + tmpFx[48]*tmpObjS[57] + tmpFx[57]*tmpObjS[68] + tmpFx[66]*tmpObjS[79] + tmpFx[75]*tmpObjS[90] + tmpFx[84]*tmpObjS[101] + tmpFx[93]*tmpObjS[112]; tmpS2[36] = + tmpFx[3]*tmpObjS[3] + tmpFx[12]*tmpObjS[14] + tmpFx[21]*tmpObjS[25] + tmpFx[30]*tmpObjS[36] + tmpFx[39]*tmpObjS[47] + tmpFx[48]*tmpObjS[58] + tmpFx[57]*tmpObjS[69] + tmpFx[66]*tmpObjS[80] + tmpFx[75]*tmpObjS[91] + tmpFx[84]*tmpObjS[102] + tmpFx[93]*tmpObjS[113]; tmpS2[37] = + tmpFx[3]*tmpObjS[4] + tmpFx[12]*tmpObjS[15] + tmpFx[21]*tmpObjS[26] + tmpFx[30]*tmpObjS[37] + tmpFx[39]*tmpObjS[48] + tmpFx[48]*tmpObjS[59] + tmpFx[57]*tmpObjS[70] + tmpFx[66]*tmpObjS[81] + tmpFx[75]*tmpObjS[92] + tmpFx[84]*tmpObjS[103] + tmpFx[93]*tmpObjS[114]; tmpS2[38] = + tmpFx[3]*tmpObjS[5] + tmpFx[12]*tmpObjS[16] + tmpFx[21]*tmpObjS[27] + tmpFx[30]*tmpObjS[38] + tmpFx[39]*tmpObjS[49] + tmpFx[48]*tmpObjS[60] + tmpFx[57]*tmpObjS[71] + tmpFx[66]*tmpObjS[82] + tmpFx[75]*tmpObjS[93] + tmpFx[84]*tmpObjS[104] + tmpFx[93]*tmpObjS[115]; tmpS2[39] = + tmpFx[3]*tmpObjS[6] + tmpFx[12]*tmpObjS[17] + tmpFx[21]*tmpObjS[28] + tmpFx[30]*tmpObjS[39] + tmpFx[39]*tmpObjS[50] + tmpFx[48]*tmpObjS[61] + tmpFx[57]*tmpObjS[72] + tmpFx[66]*tmpObjS[83] + tmpFx[75]*tmpObjS[94] + tmpFx[84]*tmpObjS[105] + tmpFx[93]*tmpObjS[116]; tmpS2[40] = + tmpFx[3]*tmpObjS[7] + tmpFx[12]*tmpObjS[18] + tmpFx[21]*tmpObjS[29] + tmpFx[30]*tmpObjS[40] + tmpFx[39]*tmpObjS[51] + tmpFx[48]*tmpObjS[62] + tmpFx[57]*tmpObjS[73] + tmpFx[66]*tmpObjS[84] + tmpFx[75]*tmpObjS[95] + tmpFx[84]*tmpObjS[106] + tmpFx[93]*tmpObjS[117]; tmpS2[41] = + tmpFx[3]*tmpObjS[8] + tmpFx[12]*tmpObjS[19] + tmpFx[21]*tmpObjS[30] + tmpFx[30]*tmpObjS[41] + tmpFx[39]*tmpObjS[52] + tmpFx[48]*tmpObjS[63] + tmpFx[57]*tmpObjS[74] + tmpFx[66]*tmpObjS[85] + tmpFx[75]*tmpObjS[96] + tmpFx[84]*tmpObjS[107] + tmpFx[93]*tmpObjS[118]; tmpS2[42] = + tmpFx[3]*tmpObjS[9] + tmpFx[12]*tmpObjS[20] + tmpFx[21]*tmpObjS[31] + tmpFx[30]*tmpObjS[42] + tmpFx[39]*tmpObjS[53] + tmpFx[48]*tmpObjS[64] + tmpFx[57]*tmpObjS[75] + tmpFx[66]*tmpObjS[86] + tmpFx[75]*tmpObjS[97] + tmpFx[84]*tmpObjS[108] + tmpFx[93]*tmpObjS[119]; tmpS2[43] = + tmpFx[3]*tmpObjS[10] + tmpFx[12]*tmpObjS[21] + tmpFx[21]*tmpObjS[32] + tmpFx[30]*tmpObjS[43] + tmpFx[39]*tmpObjS[54] + tmpFx[48]*tmpObjS[65] + tmpFx[57]*tmpObjS[76] + tmpFx[66]*tmpObjS[87] + tmpFx[75]*tmpObjS[98] + tmpFx[84]*tmpObjS[109] + tmpFx[93]*tmpObjS[120]; tmpS2[44] = + tmpFx[4]*tmpObjS[0] + tmpFx[13]*tmpObjS[11] + tmpFx[22]*tmpObjS[22] + tmpFx[31]*tmpObjS[33] + tmpFx[40]*tmpObjS[44] + tmpFx[49]*tmpObjS[55] + tmpFx[58]*tmpObjS[66] + tmpFx[67]*tmpObjS[77] + tmpFx[76]*tmpObjS[88] + tmpFx[85]*tmpObjS[99] + tmpFx[94]*tmpObjS[110]; tmpS2[45] = + tmpFx[4]*tmpObjS[1] + tmpFx[13]*tmpObjS[12] + tmpFx[22]*tmpObjS[23] + tmpFx[31]*tmpObjS[34] + tmpFx[40]*tmpObjS[45] + tmpFx[49]*tmpObjS[56] + tmpFx[58]*tmpObjS[67] + tmpFx[67]*tmpObjS[78] + tmpFx[76]*tmpObjS[89] + tmpFx[85]*tmpObjS[100] + tmpFx[94]*tmpObjS[111]; tmpS2[46] = + tmpFx[4]*tmpObjS[2] + tmpFx[13]*tmpObjS[13] + tmpFx[22]*tmpObjS[24] + tmpFx[31]*tmpObjS[35] + tmpFx[40]*tmpObjS[46] + tmpFx[49]*tmpObjS[57] + tmpFx[58]*tmpObjS[68] + tmpFx[67]*tmpObjS[79] + tmpFx[76]*tmpObjS[90] + tmpFx[85]*tmpObjS[101] + tmpFx[94]*tmpObjS[112]; tmpS2[47] = + tmpFx[4]*tmpObjS[3] + tmpFx[13]*tmpObjS[14] + tmpFx[22]*tmpObjS[25] + tmpFx[31]*tmpObjS[36] + tmpFx[40]*tmpObjS[47] + tmpFx[49]*tmpObjS[58] + tmpFx[58]*tmpObjS[69] + tmpFx[67]*tmpObjS[80] + tmpFx[76]*tmpObjS[91] + tmpFx[85]*tmpObjS[102] + tmpFx[94]*tmpObjS[113]; tmpS2[48] = + tmpFx[4]*tmpObjS[4] + tmpFx[13]*tmpObjS[15] + tmpFx[22]*tmpObjS[26] + tmpFx[31]*tmpObjS[37] + tmpFx[40]*tmpObjS[48] + tmpFx[49]*tmpObjS[59] + tmpFx[58]*tmpObjS[70] + tmpFx[67]*tmpObjS[81] + tmpFx[76]*tmpObjS[92] + tmpFx[85]*tmpObjS[103] + tmpFx[94]*tmpObjS[114]; tmpS2[49] = + tmpFx[4]*tmpObjS[5] + tmpFx[13]*tmpObjS[16] + tmpFx[22]*tmpObjS[27] + tmpFx[31]*tmpObjS[38] + tmpFx[40]*tmpObjS[49] + tmpFx[49]*tmpObjS[60] + tmpFx[58]*tmpObjS[71] + tmpFx[67]*tmpObjS[82] + tmpFx[76]*tmpObjS[93] + tmpFx[85]*tmpObjS[104] + tmpFx[94]*tmpObjS[115]; tmpS2[50] = + tmpFx[4]*tmpObjS[6] + tmpFx[13]*tmpObjS[17] + tmpFx[22]*tmpObjS[28] + tmpFx[31]*tmpObjS[39] + tmpFx[40]*tmpObjS[50] + tmpFx[49]*tmpObjS[61] + tmpFx[58]*tmpObjS[72] + tmpFx[67]*tmpObjS[83] + tmpFx[76]*tmpObjS[94] + tmpFx[85]*tmpObjS[105] + tmpFx[94]*tmpObjS[116]; tmpS2[51] = + tmpFx[4]*tmpObjS[7] + tmpFx[13]*tmpObjS[18] + tmpFx[22]*tmpObjS[29] + tmpFx[31]*tmpObjS[40] + tmpFx[40]*tmpObjS[51] + tmpFx[49]*tmpObjS[62] + tmpFx[58]*tmpObjS[73] + tmpFx[67]*tmpObjS[84] + tmpFx[76]*tmpObjS[95] + tmpFx[85]*tmpObjS[106] + tmpFx[94]*tmpObjS[117]; tmpS2[52] = + tmpFx[4]*tmpObjS[8] + tmpFx[13]*tmpObjS[19] + tmpFx[22]*tmpObjS[30] + tmpFx[31]*tmpObjS[41] + tmpFx[40]*tmpObjS[52] + tmpFx[49]*tmpObjS[63] + tmpFx[58]*tmpObjS[74] + tmpFx[67]*tmpObjS[85] + tmpFx[76]*tmpObjS[96] + tmpFx[85]*tmpObjS[107] + tmpFx[94]*tmpObjS[118]; tmpS2[53] = + tmpFx[4]*tmpObjS[9] + tmpFx[13]*tmpObjS[20] + tmpFx[22]*tmpObjS[31] + tmpFx[31]*tmpObjS[42] + tmpFx[40]*tmpObjS[53] + tmpFx[49]*tmpObjS[64] + tmpFx[58]*tmpObjS[75] + tmpFx[67]*tmpObjS[86] + tmpFx[76]*tmpObjS[97] + tmpFx[85]*tmpObjS[108] + tmpFx[94]*tmpObjS[119]; tmpS2[54] = + tmpFx[4]*tmpObjS[10] + tmpFx[13]*tmpObjS[21] + tmpFx[22]*tmpObjS[32] + tmpFx[31]*tmpObjS[43] + tmpFx[40]*tmpObjS[54] + tmpFx[49]*tmpObjS[65] + tmpFx[58]*tmpObjS[76] + tmpFx[67]*tmpObjS[87] + tmpFx[76]*tmpObjS[98] + tmpFx[85]*tmpObjS[109] + tmpFx[94]*tmpObjS[120]; tmpS2[55] = + tmpFx[5]*tmpObjS[0] + tmpFx[14]*tmpObjS[11] + tmpFx[23]*tmpObjS[22] + tmpFx[32]*tmpObjS[33] + tmpFx[41]*tmpObjS[44] + tmpFx[50]*tmpObjS[55] + tmpFx[59]*tmpObjS[66] + tmpFx[68]*tmpObjS[77] + tmpFx[77]*tmpObjS[88] + tmpFx[86]*tmpObjS[99] + tmpFx[95]*tmpObjS[110]; tmpS2[56] = + tmpFx[5]*tmpObjS[1] + tmpFx[14]*tmpObjS[12] + tmpFx[23]*tmpObjS[23] + tmpFx[32]*tmpObjS[34] + tmpFx[41]*tmpObjS[45] + tmpFx[50]*tmpObjS[56] + tmpFx[59]*tmpObjS[67] + tmpFx[68]*tmpObjS[78] + tmpFx[77]*tmpObjS[89] + tmpFx[86]*tmpObjS[100] + tmpFx[95]*tmpObjS[111]; tmpS2[57] = + tmpFx[5]*tmpObjS[2] + tmpFx[14]*tmpObjS[13] + tmpFx[23]*tmpObjS[24] + tmpFx[32]*tmpObjS[35] + tmpFx[41]*tmpObjS[46] + tmpFx[50]*tmpObjS[57] + tmpFx[59]*tmpObjS[68] + tmpFx[68]*tmpObjS[79] + tmpFx[77]*tmpObjS[90] + tmpFx[86]*tmpObjS[101] + tmpFx[95]*tmpObjS[112]; tmpS2[58] = + tmpFx[5]*tmpObjS[3] + tmpFx[14]*tmpObjS[14] + tmpFx[23]*tmpObjS[25] + tmpFx[32]*tmpObjS[36] + tmpFx[41]*tmpObjS[47] + tmpFx[50]*tmpObjS[58] + tmpFx[59]*tmpObjS[69] + tmpFx[68]*tmpObjS[80] + tmpFx[77]*tmpObjS[91] + tmpFx[86]*tmpObjS[102] + tmpFx[95]*tmpObjS[113]; tmpS2[59] = + tmpFx[5]*tmpObjS[4] + tmpFx[14]*tmpObjS[15] + tmpFx[23]*tmpObjS[26] + tmpFx[32]*tmpObjS[37] + tmpFx[41]*tmpObjS[48] + tmpFx[50]*tmpObjS[59] + tmpFx[59]*tmpObjS[70] + tmpFx[68]*tmpObjS[81] + tmpFx[77]*tmpObjS[92] + tmpFx[86]*tmpObjS[103] + tmpFx[95]*tmpObjS[114]; tmpS2[60] = + tmpFx[5]*tmpObjS[5] + tmpFx[14]*tmpObjS[16] + tmpFx[23]*tmpObjS[27] + tmpFx[32]*tmpObjS[38] + tmpFx[41]*tmpObjS[49] + tmpFx[50]*tmpObjS[60] + tmpFx[59]*tmpObjS[71] + tmpFx[68]*tmpObjS[82] + tmpFx[77]*tmpObjS[93] + tmpFx[86]*tmpObjS[104] + tmpFx[95]*tmpObjS[115]; tmpS2[61] = + tmpFx[5]*tmpObjS[6] + tmpFx[14]*tmpObjS[17] + tmpFx[23]*tmpObjS[28] + tmpFx[32]*tmpObjS[39] + tmpFx[41]*tmpObjS[50] + tmpFx[50]*tmpObjS[61] + tmpFx[59]*tmpObjS[72] + tmpFx[68]*tmpObjS[83] + tmpFx[77]*tmpObjS[94] + tmpFx[86]*tmpObjS[105] + tmpFx[95]*tmpObjS[116]; tmpS2[62] = + tmpFx[5]*tmpObjS[7] + tmpFx[14]*tmpObjS[18] + tmpFx[23]*tmpObjS[29] + tmpFx[32]*tmpObjS[40] + tmpFx[41]*tmpObjS[51] + tmpFx[50]*tmpObjS[62] + tmpFx[59]*tmpObjS[73] + tmpFx[68]*tmpObjS[84] + tmpFx[77]*tmpObjS[95] + tmpFx[86]*tmpObjS[106] + tmpFx[95]*tmpObjS[117]; tmpS2[63] = + tmpFx[5]*tmpObjS[8] + tmpFx[14]*tmpObjS[19] + tmpFx[23]*tmpObjS[30] + tmpFx[32]*tmpObjS[41] + tmpFx[41]*tmpObjS[52] + tmpFx[50]*tmpObjS[63] + tmpFx[59]*tmpObjS[74] + tmpFx[68]*tmpObjS[85] + tmpFx[77]*tmpObjS[96] + tmpFx[86]*tmpObjS[107] + tmpFx[95]*tmpObjS[118]; tmpS2[64] = + tmpFx[5]*tmpObjS[9] + tmpFx[14]*tmpObjS[20] + tmpFx[23]*tmpObjS[31] + tmpFx[32]*tmpObjS[42] + tmpFx[41]*tmpObjS[53] + tmpFx[50]*tmpObjS[64] + tmpFx[59]*tmpObjS[75] + tmpFx[68]*tmpObjS[86] + tmpFx[77]*tmpObjS[97] + tmpFx[86]*tmpObjS[108] + tmpFx[95]*tmpObjS[119]; tmpS2[65] = + tmpFx[5]*tmpObjS[10] + tmpFx[14]*tmpObjS[21] + tmpFx[23]*tmpObjS[32] + tmpFx[32]*tmpObjS[43] + tmpFx[41]*tmpObjS[54] + tmpFx[50]*tmpObjS[65] + tmpFx[59]*tmpObjS[76] + tmpFx[68]*tmpObjS[87] + tmpFx[77]*tmpObjS[98] + tmpFx[86]*tmpObjS[109] + tmpFx[95]*tmpObjS[120]; tmpS2[66] = + tmpFx[6]*tmpObjS[0] + tmpFx[15]*tmpObjS[11] + tmpFx[24]*tmpObjS[22] + tmpFx[33]*tmpObjS[33] + tmpFx[42]*tmpObjS[44] + tmpFx[51]*tmpObjS[55] + tmpFx[60]*tmpObjS[66] + tmpFx[69]*tmpObjS[77] + tmpFx[78]*tmpObjS[88] + tmpFx[87]*tmpObjS[99] + tmpFx[96]*tmpObjS[110]; tmpS2[67] = + tmpFx[6]*tmpObjS[1] + tmpFx[15]*tmpObjS[12] + tmpFx[24]*tmpObjS[23] + tmpFx[33]*tmpObjS[34] + tmpFx[42]*tmpObjS[45] + tmpFx[51]*tmpObjS[56] + tmpFx[60]*tmpObjS[67] + tmpFx[69]*tmpObjS[78] + tmpFx[78]*tmpObjS[89] + tmpFx[87]*tmpObjS[100] + tmpFx[96]*tmpObjS[111]; tmpS2[68] = + tmpFx[6]*tmpObjS[2] + tmpFx[15]*tmpObjS[13] + tmpFx[24]*tmpObjS[24] + tmpFx[33]*tmpObjS[35] + tmpFx[42]*tmpObjS[46] + tmpFx[51]*tmpObjS[57] + tmpFx[60]*tmpObjS[68] + tmpFx[69]*tmpObjS[79] + tmpFx[78]*tmpObjS[90] + tmpFx[87]*tmpObjS[101] + tmpFx[96]*tmpObjS[112]; tmpS2[69] = + tmpFx[6]*tmpObjS[3] + tmpFx[15]*tmpObjS[14] + tmpFx[24]*tmpObjS[25] + tmpFx[33]*tmpObjS[36] + tmpFx[42]*tmpObjS[47] + tmpFx[51]*tmpObjS[58] + tmpFx[60]*tmpObjS[69] + tmpFx[69]*tmpObjS[80] + tmpFx[78]*tmpObjS[91] + tmpFx[87]*tmpObjS[102] + tmpFx[96]*tmpObjS[113]; tmpS2[70] = + tmpFx[6]*tmpObjS[4] + tmpFx[15]*tmpObjS[15] + tmpFx[24]*tmpObjS[26] + tmpFx[33]*tmpObjS[37] + tmpFx[42]*tmpObjS[48] + tmpFx[51]*tmpObjS[59] + tmpFx[60]*tmpObjS[70] + tmpFx[69]*tmpObjS[81] + tmpFx[78]*tmpObjS[92] + tmpFx[87]*tmpObjS[103] + tmpFx[96]*tmpObjS[114]; tmpS2[71] = + tmpFx[6]*tmpObjS[5] + tmpFx[15]*tmpObjS[16] + tmpFx[24]*tmpObjS[27] + tmpFx[33]*tmpObjS[38] + tmpFx[42]*tmpObjS[49] + tmpFx[51]*tmpObjS[60] + tmpFx[60]*tmpObjS[71] + tmpFx[69]*tmpObjS[82] + tmpFx[78]*tmpObjS[93] + tmpFx[87]*tmpObjS[104] + tmpFx[96]*tmpObjS[115]; tmpS2[72] = + tmpFx[6]*tmpObjS[6] + tmpFx[15]*tmpObjS[17] + tmpFx[24]*tmpObjS[28] + tmpFx[33]*tmpObjS[39] + tmpFx[42]*tmpObjS[50] + tmpFx[51]*tmpObjS[61] + tmpFx[60]*tmpObjS[72] + tmpFx[69]*tmpObjS[83] + tmpFx[78]*tmpObjS[94] + tmpFx[87]*tmpObjS[105] + tmpFx[96]*tmpObjS[116]; tmpS2[73] = + tmpFx[6]*tmpObjS[7] + tmpFx[15]*tmpObjS[18] + tmpFx[24]*tmpObjS[29] + tmpFx[33]*tmpObjS[40] + tmpFx[42]*tmpObjS[51] + tmpFx[51]*tmpObjS[62] + tmpFx[60]*tmpObjS[73] + tmpFx[69]*tmpObjS[84] + tmpFx[78]*tmpObjS[95] + tmpFx[87]*tmpObjS[106] + tmpFx[96]*tmpObjS[117]; tmpS2[74] = + tmpFx[6]*tmpObjS[8] + tmpFx[15]*tmpObjS[19] + tmpFx[24]*tmpObjS[30] + tmpFx[33]*tmpObjS[41] + tmpFx[42]*tmpObjS[52] + tmpFx[51]*tmpObjS[63] + tmpFx[60]*tmpObjS[74] + tmpFx[69]*tmpObjS[85] + tmpFx[78]*tmpObjS[96] + tmpFx[87]*tmpObjS[107] + tmpFx[96]*tmpObjS[118]; tmpS2[75] = + tmpFx[6]*tmpObjS[9] + tmpFx[15]*tmpObjS[20] + tmpFx[24]*tmpObjS[31] + tmpFx[33]*tmpObjS[42] + tmpFx[42]*tmpObjS[53] + tmpFx[51]*tmpObjS[64] + tmpFx[60]*tmpObjS[75] + tmpFx[69]*tmpObjS[86] + tmpFx[78]*tmpObjS[97] + tmpFx[87]*tmpObjS[108] + tmpFx[96]*tmpObjS[119]; tmpS2[76] = + tmpFx[6]*tmpObjS[10] + tmpFx[15]*tmpObjS[21] + tmpFx[24]*tmpObjS[32] + tmpFx[33]*tmpObjS[43] + tmpFx[42]*tmpObjS[54] + tmpFx[51]*tmpObjS[65] + tmpFx[60]*tmpObjS[76] + tmpFx[69]*tmpObjS[87] + tmpFx[78]*tmpObjS[98] + tmpFx[87]*tmpObjS[109] + tmpFx[96]*tmpObjS[120]; tmpS2[77] = + tmpFx[7]*tmpObjS[0] + tmpFx[16]*tmpObjS[11] + tmpFx[25]*tmpObjS[22] + tmpFx[34]*tmpObjS[33] + tmpFx[43]*tmpObjS[44] + tmpFx[52]*tmpObjS[55] + tmpFx[61]*tmpObjS[66] + tmpFx[70]*tmpObjS[77] + tmpFx[79]*tmpObjS[88] + tmpFx[88]*tmpObjS[99] + tmpFx[97]*tmpObjS[110]; tmpS2[78] = + tmpFx[7]*tmpObjS[1] + tmpFx[16]*tmpObjS[12] + tmpFx[25]*tmpObjS[23] + tmpFx[34]*tmpObjS[34] + tmpFx[43]*tmpObjS[45] + tmpFx[52]*tmpObjS[56] + tmpFx[61]*tmpObjS[67] + tmpFx[70]*tmpObjS[78] + tmpFx[79]*tmpObjS[89] + tmpFx[88]*tmpObjS[100] + tmpFx[97]*tmpObjS[111]; tmpS2[79] = + tmpFx[7]*tmpObjS[2] + tmpFx[16]*tmpObjS[13] + tmpFx[25]*tmpObjS[24] + tmpFx[34]*tmpObjS[35] + tmpFx[43]*tmpObjS[46] + tmpFx[52]*tmpObjS[57] + tmpFx[61]*tmpObjS[68] + tmpFx[70]*tmpObjS[79] + tmpFx[79]*tmpObjS[90] + tmpFx[88]*tmpObjS[101] + tmpFx[97]*tmpObjS[112]; tmpS2[80] = + tmpFx[7]*tmpObjS[3] + tmpFx[16]*tmpObjS[14] + tmpFx[25]*tmpObjS[25] + tmpFx[34]*tmpObjS[36] + tmpFx[43]*tmpObjS[47] + tmpFx[52]*tmpObjS[58] + tmpFx[61]*tmpObjS[69] + tmpFx[70]*tmpObjS[80] + tmpFx[79]*tmpObjS[91] + tmpFx[88]*tmpObjS[102] + tmpFx[97]*tmpObjS[113]; tmpS2[81] = + tmpFx[7]*tmpObjS[4] + tmpFx[16]*tmpObjS[15] + tmpFx[25]*tmpObjS[26] + tmpFx[34]*tmpObjS[37] + tmpFx[43]*tmpObjS[48] + tmpFx[52]*tmpObjS[59] + tmpFx[61]*tmpObjS[70] + tmpFx[70]*tmpObjS[81] + tmpFx[79]*tmpObjS[92] + tmpFx[88]*tmpObjS[103] + tmpFx[97]*tmpObjS[114]; tmpS2[82] = + tmpFx[7]*tmpObjS[5] + tmpFx[16]*tmpObjS[16] + tmpFx[25]*tmpObjS[27] + tmpFx[34]*tmpObjS[38] + tmpFx[43]*tmpObjS[49] + tmpFx[52]*tmpObjS[60] + tmpFx[61]*tmpObjS[71] + tmpFx[70]*tmpObjS[82] + tmpFx[79]*tmpObjS[93] + tmpFx[88]*tmpObjS[104] + tmpFx[97]*tmpObjS[115]; tmpS2[83] = + tmpFx[7]*tmpObjS[6] + tmpFx[16]*tmpObjS[17] + tmpFx[25]*tmpObjS[28] + tmpFx[34]*tmpObjS[39] + tmpFx[43]*tmpObjS[50] + tmpFx[52]*tmpObjS[61] + tmpFx[61]*tmpObjS[72] + tmpFx[70]*tmpObjS[83] + tmpFx[79]*tmpObjS[94] + tmpFx[88]*tmpObjS[105] + tmpFx[97]*tmpObjS[116]; tmpS2[84] = + tmpFx[7]*tmpObjS[7] + tmpFx[16]*tmpObjS[18] + tmpFx[25]*tmpObjS[29] + tmpFx[34]*tmpObjS[40] + tmpFx[43]*tmpObjS[51] + tmpFx[52]*tmpObjS[62] + tmpFx[61]*tmpObjS[73] + tmpFx[70]*tmpObjS[84] + tmpFx[79]*tmpObjS[95] + tmpFx[88]*tmpObjS[106] + tmpFx[97]*tmpObjS[117]; tmpS2[85] = + tmpFx[7]*tmpObjS[8] + tmpFx[16]*tmpObjS[19] + tmpFx[25]*tmpObjS[30] + tmpFx[34]*tmpObjS[41] + tmpFx[43]*tmpObjS[52] + tmpFx[52]*tmpObjS[63] + tmpFx[61]*tmpObjS[74] + tmpFx[70]*tmpObjS[85] + tmpFx[79]*tmpObjS[96] + tmpFx[88]*tmpObjS[107] + tmpFx[97]*tmpObjS[118]; tmpS2[86] = + tmpFx[7]*tmpObjS[9] + tmpFx[16]*tmpObjS[20] + tmpFx[25]*tmpObjS[31] + tmpFx[34]*tmpObjS[42] + tmpFx[43]*tmpObjS[53] + tmpFx[52]*tmpObjS[64] + tmpFx[61]*tmpObjS[75] + tmpFx[70]*tmpObjS[86] + tmpFx[79]*tmpObjS[97] + tmpFx[88]*tmpObjS[108] + tmpFx[97]*tmpObjS[119]; tmpS2[87] = + tmpFx[7]*tmpObjS[10] + tmpFx[16]*tmpObjS[21] + tmpFx[25]*tmpObjS[32] + tmpFx[34]*tmpObjS[43] + tmpFx[43]*tmpObjS[54] + tmpFx[52]*tmpObjS[65] + tmpFx[61]*tmpObjS[76] + tmpFx[70]*tmpObjS[87] + tmpFx[79]*tmpObjS[98] + tmpFx[88]*tmpObjS[109] + tmpFx[97]*tmpObjS[120]; tmpS2[88] = + tmpFx[8]*tmpObjS[0] + tmpFx[17]*tmpObjS[11] + tmpFx[26]*tmpObjS[22] + tmpFx[35]*tmpObjS[33] + tmpFx[44]*tmpObjS[44] + tmpFx[53]*tmpObjS[55] + tmpFx[62]*tmpObjS[66] + tmpFx[71]*tmpObjS[77] + tmpFx[80]*tmpObjS[88] + tmpFx[89]*tmpObjS[99] + tmpFx[98]*tmpObjS[110]; tmpS2[89] = + tmpFx[8]*tmpObjS[1] + tmpFx[17]*tmpObjS[12] + tmpFx[26]*tmpObjS[23] + tmpFx[35]*tmpObjS[34] + tmpFx[44]*tmpObjS[45] + tmpFx[53]*tmpObjS[56] + tmpFx[62]*tmpObjS[67] + tmpFx[71]*tmpObjS[78] + tmpFx[80]*tmpObjS[89] + tmpFx[89]*tmpObjS[100] + tmpFx[98]*tmpObjS[111]; tmpS2[90] = + tmpFx[8]*tmpObjS[2] + tmpFx[17]*tmpObjS[13] + tmpFx[26]*tmpObjS[24] + tmpFx[35]*tmpObjS[35] + tmpFx[44]*tmpObjS[46] + tmpFx[53]*tmpObjS[57] + tmpFx[62]*tmpObjS[68] + tmpFx[71]*tmpObjS[79] + tmpFx[80]*tmpObjS[90] + tmpFx[89]*tmpObjS[101] + tmpFx[98]*tmpObjS[112]; tmpS2[91] = + tmpFx[8]*tmpObjS[3] + tmpFx[17]*tmpObjS[14] + tmpFx[26]*tmpObjS[25] + tmpFx[35]*tmpObjS[36] + tmpFx[44]*tmpObjS[47] + tmpFx[53]*tmpObjS[58] + tmpFx[62]*tmpObjS[69] + tmpFx[71]*tmpObjS[80] + tmpFx[80]*tmpObjS[91] + tmpFx[89]*tmpObjS[102] + tmpFx[98]*tmpObjS[113]; tmpS2[92] = + tmpFx[8]*tmpObjS[4] + tmpFx[17]*tmpObjS[15] + tmpFx[26]*tmpObjS[26] + tmpFx[35]*tmpObjS[37] + tmpFx[44]*tmpObjS[48] + tmpFx[53]*tmpObjS[59] + tmpFx[62]*tmpObjS[70] + tmpFx[71]*tmpObjS[81] + tmpFx[80]*tmpObjS[92] + tmpFx[89]*tmpObjS[103] + tmpFx[98]*tmpObjS[114]; tmpS2[93] = + tmpFx[8]*tmpObjS[5] + tmpFx[17]*tmpObjS[16] + tmpFx[26]*tmpObjS[27] + tmpFx[35]*tmpObjS[38] + tmpFx[44]*tmpObjS[49] + tmpFx[53]*tmpObjS[60] + tmpFx[62]*tmpObjS[71] + tmpFx[71]*tmpObjS[82] + tmpFx[80]*tmpObjS[93] + tmpFx[89]*tmpObjS[104] + tmpFx[98]*tmpObjS[115]; tmpS2[94] = + tmpFx[8]*tmpObjS[6] + tmpFx[17]*tmpObjS[17] + tmpFx[26]*tmpObjS[28] + tmpFx[35]*tmpObjS[39] + tmpFx[44]*tmpObjS[50] + tmpFx[53]*tmpObjS[61] + tmpFx[62]*tmpObjS[72] + tmpFx[71]*tmpObjS[83] + tmpFx[80]*tmpObjS[94] + tmpFx[89]*tmpObjS[105] + tmpFx[98]*tmpObjS[116]; tmpS2[95] = + tmpFx[8]*tmpObjS[7] + tmpFx[17]*tmpObjS[18] + tmpFx[26]*tmpObjS[29] + tmpFx[35]*tmpObjS[40] + tmpFx[44]*tmpObjS[51] + tmpFx[53]*tmpObjS[62] + tmpFx[62]*tmpObjS[73] + tmpFx[71]*tmpObjS[84] + tmpFx[80]*tmpObjS[95] + tmpFx[89]*tmpObjS[106] + tmpFx[98]*tmpObjS[117]; tmpS2[96] = + tmpFx[8]*tmpObjS[8] + tmpFx[17]*tmpObjS[19] + tmpFx[26]*tmpObjS[30] + tmpFx[35]*tmpObjS[41] + tmpFx[44]*tmpObjS[52] + tmpFx[53]*tmpObjS[63] + tmpFx[62]*tmpObjS[74] + tmpFx[71]*tmpObjS[85] + tmpFx[80]*tmpObjS[96] + tmpFx[89]*tmpObjS[107] + tmpFx[98]*tmpObjS[118]; tmpS2[97] = + tmpFx[8]*tmpObjS[9] + tmpFx[17]*tmpObjS[20] + tmpFx[26]*tmpObjS[31] + tmpFx[35]*tmpObjS[42] + tmpFx[44]*tmpObjS[53] + tmpFx[53]*tmpObjS[64] + tmpFx[62]*tmpObjS[75] + tmpFx[71]*tmpObjS[86] + tmpFx[80]*tmpObjS[97] + tmpFx[89]*tmpObjS[108] + tmpFx[98]*tmpObjS[119]; tmpS2[98] = + tmpFx[8]*tmpObjS[10] + tmpFx[17]*tmpObjS[21] + tmpFx[26]*tmpObjS[32] + tmpFx[35]*tmpObjS[43] + tmpFx[44]*tmpObjS[54] + tmpFx[53]*tmpObjS[65] + tmpFx[62]*tmpObjS[76] + tmpFx[71]*tmpObjS[87] + tmpFx[80]*tmpObjS[98] + tmpFx[89]*tmpObjS[109] + tmpFx[98]*tmpObjS[120]; tmpS1[0] = + tmpS2[0]*tmpFu[0] + tmpS2[1]*tmpFu[3] + tmpS2[2]*tmpFu[6] + tmpS2[3]*tmpFu[9] + tmpS2[4]*tmpFu[12] + tmpS2[5]*tmpFu[15] + tmpS2[6]*tmpFu[18] + tmpS2[7]*tmpFu[21] + tmpS2[8]*tmpFu[24] + tmpS2[9]*tmpFu[27] + tmpS2[10]*tmpFu[30]; tmpS1[1] = + tmpS2[0]*tmpFu[1] + tmpS2[1]*tmpFu[4] + tmpS2[2]*tmpFu[7] + tmpS2[3]*tmpFu[10] + tmpS2[4]*tmpFu[13] + tmpS2[5]*tmpFu[16] + tmpS2[6]*tmpFu[19] + tmpS2[7]*tmpFu[22] + tmpS2[8]*tmpFu[25] + tmpS2[9]*tmpFu[28] + tmpS2[10]*tmpFu[31]; tmpS1[2] = + tmpS2[0]*tmpFu[2] + tmpS2[1]*tmpFu[5] + tmpS2[2]*tmpFu[8] + tmpS2[3]*tmpFu[11] + tmpS2[4]*tmpFu[14] + tmpS2[5]*tmpFu[17] + tmpS2[6]*tmpFu[20] + tmpS2[7]*tmpFu[23] + tmpS2[8]*tmpFu[26] + tmpS2[9]*tmpFu[29] + tmpS2[10]*tmpFu[32]; tmpS1[3] = + tmpS2[11]*tmpFu[0] + tmpS2[12]*tmpFu[3] + tmpS2[13]*tmpFu[6] + tmpS2[14]*tmpFu[9] + tmpS2[15]*tmpFu[12] + tmpS2[16]*tmpFu[15] + tmpS2[17]*tmpFu[18] + tmpS2[18]*tmpFu[21] + tmpS2[19]*tmpFu[24] + tmpS2[20]*tmpFu[27] + tmpS2[21]*tmpFu[30]; tmpS1[4] = + tmpS2[11]*tmpFu[1] + tmpS2[12]*tmpFu[4] + tmpS2[13]*tmpFu[7] + tmpS2[14]*tmpFu[10] + tmpS2[15]*tmpFu[13] + tmpS2[16]*tmpFu[16] + tmpS2[17]*tmpFu[19] + tmpS2[18]*tmpFu[22] + tmpS2[19]*tmpFu[25] + tmpS2[20]*tmpFu[28] + tmpS2[21]*tmpFu[31]; tmpS1[5] = + tmpS2[11]*tmpFu[2] + tmpS2[12]*tmpFu[5] + tmpS2[13]*tmpFu[8] + tmpS2[14]*tmpFu[11] + tmpS2[15]*tmpFu[14] + tmpS2[16]*tmpFu[17] + tmpS2[17]*tmpFu[20] + tmpS2[18]*tmpFu[23] + tmpS2[19]*tmpFu[26] + tmpS2[20]*tmpFu[29] + tmpS2[21]*tmpFu[32]; tmpS1[6] = + tmpS2[22]*tmpFu[0] + tmpS2[23]*tmpFu[3] + tmpS2[24]*tmpFu[6] + tmpS2[25]*tmpFu[9] + tmpS2[26]*tmpFu[12] + tmpS2[27]*tmpFu[15] + tmpS2[28]*tmpFu[18] + tmpS2[29]*tmpFu[21] + tmpS2[30]*tmpFu[24] + tmpS2[31]*tmpFu[27] + tmpS2[32]*tmpFu[30]; tmpS1[7] = + tmpS2[22]*tmpFu[1] + tmpS2[23]*tmpFu[4] + tmpS2[24]*tmpFu[7] + tmpS2[25]*tmpFu[10] + tmpS2[26]*tmpFu[13] + tmpS2[27]*tmpFu[16] + tmpS2[28]*tmpFu[19] + tmpS2[29]*tmpFu[22] + tmpS2[30]*tmpFu[25] + tmpS2[31]*tmpFu[28] + tmpS2[32]*tmpFu[31]; tmpS1[8] = + tmpS2[22]*tmpFu[2] + tmpS2[23]*tmpFu[5] + tmpS2[24]*tmpFu[8] + tmpS2[25]*tmpFu[11] + tmpS2[26]*tmpFu[14] + tmpS2[27]*tmpFu[17] + tmpS2[28]*tmpFu[20] + tmpS2[29]*tmpFu[23] + tmpS2[30]*tmpFu[26] + tmpS2[31]*tmpFu[29] + tmpS2[32]*tmpFu[32]; tmpS1[9] = + tmpS2[33]*tmpFu[0] + tmpS2[34]*tmpFu[3] + tmpS2[35]*tmpFu[6] + tmpS2[36]*tmpFu[9] + tmpS2[37]*tmpFu[12] + tmpS2[38]*tmpFu[15] + tmpS2[39]*tmpFu[18] + tmpS2[40]*tmpFu[21] + tmpS2[41]*tmpFu[24] + tmpS2[42]*tmpFu[27] + tmpS2[43]*tmpFu[30]; tmpS1[10] = + tmpS2[33]*tmpFu[1] + tmpS2[34]*tmpFu[4] + tmpS2[35]*tmpFu[7] + tmpS2[36]*tmpFu[10] + tmpS2[37]*tmpFu[13] + tmpS2[38]*tmpFu[16] + tmpS2[39]*tmpFu[19] + tmpS2[40]*tmpFu[22] + tmpS2[41]*tmpFu[25] + tmpS2[42]*tmpFu[28] + tmpS2[43]*tmpFu[31]; tmpS1[11] = + tmpS2[33]*tmpFu[2] + tmpS2[34]*tmpFu[5] + tmpS2[35]*tmpFu[8] + tmpS2[36]*tmpFu[11] + tmpS2[37]*tmpFu[14] + tmpS2[38]*tmpFu[17] + tmpS2[39]*tmpFu[20] + tmpS2[40]*tmpFu[23] + tmpS2[41]*tmpFu[26] + tmpS2[42]*tmpFu[29] + tmpS2[43]*tmpFu[32]; tmpS1[12] = + tmpS2[44]*tmpFu[0] + tmpS2[45]*tmpFu[3] + tmpS2[46]*tmpFu[6] + tmpS2[47]*tmpFu[9] + tmpS2[48]*tmpFu[12] + tmpS2[49]*tmpFu[15] + tmpS2[50]*tmpFu[18] + tmpS2[51]*tmpFu[21] + tmpS2[52]*tmpFu[24] + tmpS2[53]*tmpFu[27] + tmpS2[54]*tmpFu[30]; tmpS1[13] = + tmpS2[44]*tmpFu[1] + tmpS2[45]*tmpFu[4] + tmpS2[46]*tmpFu[7] + tmpS2[47]*tmpFu[10] + tmpS2[48]*tmpFu[13] + tmpS2[49]*tmpFu[16] + tmpS2[50]*tmpFu[19] + tmpS2[51]*tmpFu[22] + tmpS2[52]*tmpFu[25] + tmpS2[53]*tmpFu[28] + tmpS2[54]*tmpFu[31]; tmpS1[14] = + tmpS2[44]*tmpFu[2] + tmpS2[45]*tmpFu[5] + tmpS2[46]*tmpFu[8] + tmpS2[47]*tmpFu[11] + tmpS2[48]*tmpFu[14] + tmpS2[49]*tmpFu[17] + tmpS2[50]*tmpFu[20] + tmpS2[51]*tmpFu[23] + tmpS2[52]*tmpFu[26] + tmpS2[53]*tmpFu[29] + tmpS2[54]*tmpFu[32]; tmpS1[15] = + tmpS2[55]*tmpFu[0] + tmpS2[56]*tmpFu[3] + tmpS2[57]*tmpFu[6] + tmpS2[58]*tmpFu[9] + tmpS2[59]*tmpFu[12] + tmpS2[60]*tmpFu[15] + tmpS2[61]*tmpFu[18] + tmpS2[62]*tmpFu[21] + tmpS2[63]*tmpFu[24] + tmpS2[64]*tmpFu[27] + tmpS2[65]*tmpFu[30]; tmpS1[16] = + tmpS2[55]*tmpFu[1] + tmpS2[56]*tmpFu[4] + tmpS2[57]*tmpFu[7] + tmpS2[58]*tmpFu[10] + tmpS2[59]*tmpFu[13] + tmpS2[60]*tmpFu[16] + tmpS2[61]*tmpFu[19] + tmpS2[62]*tmpFu[22] + tmpS2[63]*tmpFu[25] + tmpS2[64]*tmpFu[28] + tmpS2[65]*tmpFu[31]; tmpS1[17] = + tmpS2[55]*tmpFu[2] + tmpS2[56]*tmpFu[5] + tmpS2[57]*tmpFu[8] + tmpS2[58]*tmpFu[11] + tmpS2[59]*tmpFu[14] + tmpS2[60]*tmpFu[17] + tmpS2[61]*tmpFu[20] + tmpS2[62]*tmpFu[23] + tmpS2[63]*tmpFu[26] + tmpS2[64]*tmpFu[29] + tmpS2[65]*tmpFu[32]; tmpS1[18] = + tmpS2[66]*tmpFu[0] + tmpS2[67]*tmpFu[3] + tmpS2[68]*tmpFu[6] + tmpS2[69]*tmpFu[9] + tmpS2[70]*tmpFu[12] + tmpS2[71]*tmpFu[15] + tmpS2[72]*tmpFu[18] + tmpS2[73]*tmpFu[21] + tmpS2[74]*tmpFu[24] + tmpS2[75]*tmpFu[27] + tmpS2[76]*tmpFu[30]; tmpS1[19] = + tmpS2[66]*tmpFu[1] + tmpS2[67]*tmpFu[4] + tmpS2[68]*tmpFu[7] + tmpS2[69]*tmpFu[10] + tmpS2[70]*tmpFu[13] + tmpS2[71]*tmpFu[16] + tmpS2[72]*tmpFu[19] + tmpS2[73]*tmpFu[22] + tmpS2[74]*tmpFu[25] + tmpS2[75]*tmpFu[28] + tmpS2[76]*tmpFu[31]; tmpS1[20] = + tmpS2[66]*tmpFu[2] + tmpS2[67]*tmpFu[5] + tmpS2[68]*tmpFu[8] + tmpS2[69]*tmpFu[11] + tmpS2[70]*tmpFu[14] + tmpS2[71]*tmpFu[17] + tmpS2[72]*tmpFu[20] + tmpS2[73]*tmpFu[23] + tmpS2[74]*tmpFu[26] + tmpS2[75]*tmpFu[29] + tmpS2[76]*tmpFu[32]; tmpS1[21] = + tmpS2[77]*tmpFu[0] + tmpS2[78]*tmpFu[3] + tmpS2[79]*tmpFu[6] + tmpS2[80]*tmpFu[9] + tmpS2[81]*tmpFu[12] + tmpS2[82]*tmpFu[15] + tmpS2[83]*tmpFu[18] + tmpS2[84]*tmpFu[21] + tmpS2[85]*tmpFu[24] + tmpS2[86]*tmpFu[27] + tmpS2[87]*tmpFu[30]; tmpS1[22] = + tmpS2[77]*tmpFu[1] + tmpS2[78]*tmpFu[4] + tmpS2[79]*tmpFu[7] + tmpS2[80]*tmpFu[10] + tmpS2[81]*tmpFu[13] + tmpS2[82]*tmpFu[16] + tmpS2[83]*tmpFu[19] + tmpS2[84]*tmpFu[22] + tmpS2[85]*tmpFu[25] + tmpS2[86]*tmpFu[28] + tmpS2[87]*tmpFu[31]; tmpS1[23] = + tmpS2[77]*tmpFu[2] + tmpS2[78]*tmpFu[5] + tmpS2[79]*tmpFu[8] + tmpS2[80]*tmpFu[11] + tmpS2[81]*tmpFu[14] + tmpS2[82]*tmpFu[17] + tmpS2[83]*tmpFu[20] + tmpS2[84]*tmpFu[23] + tmpS2[85]*tmpFu[26] + tmpS2[86]*tmpFu[29] + tmpS2[87]*tmpFu[32]; tmpS1[24] = + tmpS2[88]*tmpFu[0] + tmpS2[89]*tmpFu[3] + tmpS2[90]*tmpFu[6] + tmpS2[91]*tmpFu[9] + tmpS2[92]*tmpFu[12] + tmpS2[93]*tmpFu[15] + tmpS2[94]*tmpFu[18] + tmpS2[95]*tmpFu[21] + tmpS2[96]*tmpFu[24] + tmpS2[97]*tmpFu[27] + tmpS2[98]*tmpFu[30]; tmpS1[25] = + tmpS2[88]*tmpFu[1] + tmpS2[89]*tmpFu[4] + tmpS2[90]*tmpFu[7] + tmpS2[91]*tmpFu[10] + tmpS2[92]*tmpFu[13] + tmpS2[93]*tmpFu[16] + tmpS2[94]*tmpFu[19] + tmpS2[95]*tmpFu[22] + tmpS2[96]*tmpFu[25] + tmpS2[97]*tmpFu[28] + tmpS2[98]*tmpFu[31]; tmpS1[26] = + tmpS2[88]*tmpFu[2] + tmpS2[89]*tmpFu[5] + tmpS2[90]*tmpFu[8] + tmpS2[91]*tmpFu[11] + tmpS2[92]*tmpFu[14] + tmpS2[93]*tmpFu[17] + tmpS2[94]*tmpFu[20] + tmpS2[95]*tmpFu[23] + tmpS2[96]*tmpFu[26] + tmpS2[97]*tmpFu[29] + tmpS2[98]*tmpFu[32]; } void acado_setObjQN1QN2( real_t* const tmpObjSEndTerm, real_t* const tmpQN1, real_t* const tmpQN2 ) { tmpQN2[0] = +tmpObjSEndTerm[18]; tmpQN2[1] = +tmpObjSEndTerm[19]; tmpQN2[2] = +tmpObjSEndTerm[20]; tmpQN2[3] = +tmpObjSEndTerm[21]; tmpQN2[4] = +tmpObjSEndTerm[22]; tmpQN2[5] = +tmpObjSEndTerm[23]; tmpQN2[6] = +tmpObjSEndTerm[24]; tmpQN2[7] = +tmpObjSEndTerm[25]; tmpQN2[8] = +tmpObjSEndTerm[26]; tmpQN2[9] = +tmpObjSEndTerm[27]; tmpQN2[10] = +tmpObjSEndTerm[28]; tmpQN2[11] = +tmpObjSEndTerm[29]; tmpQN2[12] = +tmpObjSEndTerm[30]; tmpQN2[13] = +tmpObjSEndTerm[31]; tmpQN2[14] = +tmpObjSEndTerm[32]; tmpQN2[15] = +tmpObjSEndTerm[33]; tmpQN2[16] = +tmpObjSEndTerm[34]; tmpQN2[17] = +tmpObjSEndTerm[35]; tmpQN2[18] = 0.0; ; tmpQN2[19] = 0.0; ; tmpQN2[20] = 0.0; ; tmpQN2[21] = 0.0; ; tmpQN2[22] = 0.0; ; tmpQN2[23] = 0.0; ; tmpQN2[24] = 0.0; ; tmpQN2[25] = 0.0; ; tmpQN2[26] = 0.0; ; tmpQN2[27] = 0.0; ; tmpQN2[28] = 0.0; ; tmpQN2[29] = 0.0; ; tmpQN2[30] = 0.0; ; tmpQN2[31] = 0.0; ; tmpQN2[32] = 0.0; ; tmpQN2[33] = 0.0; ; tmpQN2[34] = 0.0; ; tmpQN2[35] = 0.0; ; tmpQN2[36] = +tmpObjSEndTerm[0]; tmpQN2[37] = +tmpObjSEndTerm[1]; tmpQN2[38] = +tmpObjSEndTerm[2]; tmpQN2[39] = +tmpObjSEndTerm[3]; tmpQN2[40] = +tmpObjSEndTerm[4]; tmpQN2[41] = +tmpObjSEndTerm[5]; tmpQN2[42] = +tmpObjSEndTerm[6]; tmpQN2[43] = +tmpObjSEndTerm[7]; tmpQN2[44] = +tmpObjSEndTerm[8]; tmpQN2[45] = +tmpObjSEndTerm[9]; tmpQN2[46] = +tmpObjSEndTerm[10]; tmpQN2[47] = +tmpObjSEndTerm[11]; tmpQN2[48] = +tmpObjSEndTerm[12]; tmpQN2[49] = +tmpObjSEndTerm[13]; tmpQN2[50] = +tmpObjSEndTerm[14]; tmpQN2[51] = +tmpObjSEndTerm[15]; tmpQN2[52] = +tmpObjSEndTerm[16]; tmpQN2[53] = +tmpObjSEndTerm[17]; tmpQN1[0] = + tmpQN2[3]; tmpQN1[1] = + tmpQN2[4]; tmpQN1[2] = + tmpQN2[5]; tmpQN1[3] = 0.0; ; tmpQN1[4] = 0.0; ; tmpQN1[5] = 0.0; ; tmpQN1[6] = + tmpQN2[0]; tmpQN1[7] = + tmpQN2[1]; tmpQN1[8] = + tmpQN2[2]; tmpQN1[9] = + tmpQN2[9]; tmpQN1[10] = + tmpQN2[10]; tmpQN1[11] = + tmpQN2[11]; tmpQN1[12] = 0.0; ; tmpQN1[13] = 0.0; ; tmpQN1[14] = 0.0; ; tmpQN1[15] = + tmpQN2[6]; tmpQN1[16] = + tmpQN2[7]; tmpQN1[17] = + tmpQN2[8]; tmpQN1[18] = + tmpQN2[15]; tmpQN1[19] = + tmpQN2[16]; tmpQN1[20] = + tmpQN2[17]; tmpQN1[21] = 0.0; ; tmpQN1[22] = 0.0; ; tmpQN1[23] = 0.0; ; tmpQN1[24] = + tmpQN2[12]; tmpQN1[25] = + tmpQN2[13]; tmpQN1[26] = + tmpQN2[14]; tmpQN1[27] = + tmpQN2[21]; tmpQN1[28] = + tmpQN2[22]; tmpQN1[29] = + tmpQN2[23]; tmpQN1[30] = 0.0; ; tmpQN1[31] = 0.0; ; tmpQN1[32] = 0.0; ; tmpQN1[33] = + tmpQN2[18]; tmpQN1[34] = + tmpQN2[19]; tmpQN1[35] = + tmpQN2[20]; tmpQN1[36] = + tmpQN2[27]; tmpQN1[37] = + tmpQN2[28]; tmpQN1[38] = + tmpQN2[29]; tmpQN1[39] = 0.0; ; tmpQN1[40] = 0.0; ; tmpQN1[41] = 0.0; ; tmpQN1[42] = + tmpQN2[24]; tmpQN1[43] = + tmpQN2[25]; tmpQN1[44] = + tmpQN2[26]; tmpQN1[45] = + tmpQN2[33]; tmpQN1[46] = + tmpQN2[34]; tmpQN1[47] = + tmpQN2[35]; tmpQN1[48] = 0.0; ; tmpQN1[49] = 0.0; ; tmpQN1[50] = 0.0; ; tmpQN1[51] = + tmpQN2[30]; tmpQN1[52] = + tmpQN2[31]; tmpQN1[53] = + tmpQN2[32]; tmpQN1[54] = + tmpQN2[39]; tmpQN1[55] = + tmpQN2[40]; tmpQN1[56] = + tmpQN2[41]; tmpQN1[57] = 0.0; ; tmpQN1[58] = 0.0; ; tmpQN1[59] = 0.0; ; tmpQN1[60] = + tmpQN2[36]; tmpQN1[61] = + tmpQN2[37]; tmpQN1[62] = + tmpQN2[38]; tmpQN1[63] = + tmpQN2[45]; tmpQN1[64] = + tmpQN2[46]; tmpQN1[65] = + tmpQN2[47]; tmpQN1[66] = 0.0; ; tmpQN1[67] = 0.0; ; tmpQN1[68] = 0.0; ; tmpQN1[69] = + tmpQN2[42]; tmpQN1[70] = + tmpQN2[43]; tmpQN1[71] = + tmpQN2[44]; tmpQN1[72] = + tmpQN2[51]; tmpQN1[73] = + tmpQN2[52]; tmpQN1[74] = + tmpQN2[53]; tmpQN1[75] = 0.0; ; tmpQN1[76] = 0.0; ; tmpQN1[77] = 0.0; ; tmpQN1[78] = + tmpQN2[48]; tmpQN1[79] = + tmpQN2[49]; tmpQN1[80] = + tmpQN2[50]; } void acado_evaluateObjective( ) { int runObj; for (runObj = 0; runObj < 20; ++runObj) { acadoWorkspace.objValueIn[0] = acadoVariables.x[runObj * 9]; acadoWorkspace.objValueIn[1] = acadoVariables.x[runObj * 9 + 1]; acadoWorkspace.objValueIn[2] = acadoVariables.x[runObj * 9 + 2]; acadoWorkspace.objValueIn[3] = acadoVariables.x[runObj * 9 + 3]; acadoWorkspace.objValueIn[4] = acadoVariables.x[runObj * 9 + 4]; acadoWorkspace.objValueIn[5] = acadoVariables.x[runObj * 9 + 5]; acadoWorkspace.objValueIn[6] = acadoVariables.x[runObj * 9 + 6]; acadoWorkspace.objValueIn[7] = acadoVariables.x[runObj * 9 + 7]; acadoWorkspace.objValueIn[8] = acadoVariables.x[runObj * 9 + 8]; acadoWorkspace.objValueIn[9] = acadoVariables.u[runObj * 3]; acadoWorkspace.objValueIn[10] = acadoVariables.u[runObj * 3 + 1]; acadoWorkspace.objValueIn[11] = acadoVariables.u[runObj * 3 + 2]; acadoWorkspace.objValueIn[12] = acadoVariables.od[runObj * 9]; acadoWorkspace.objValueIn[13] = acadoVariables.od[runObj * 9 + 1]; acadoWorkspace.objValueIn[14] = acadoVariables.od[runObj * 9 + 2]; acadoWorkspace.objValueIn[15] = acadoVariables.od[runObj * 9 + 3]; acadoWorkspace.objValueIn[16] = acadoVariables.od[runObj * 9 + 4]; acadoWorkspace.objValueIn[17] = acadoVariables.od[runObj * 9 + 5]; acadoWorkspace.objValueIn[18] = acadoVariables.od[runObj * 9 + 6]; acadoWorkspace.objValueIn[19] = acadoVariables.od[runObj * 9 + 7]; acadoWorkspace.objValueIn[20] = acadoVariables.od[runObj * 9 + 8]; acado_evaluateLSQ( acadoWorkspace.objValueIn, acadoWorkspace.objValueOut ); acadoWorkspace.Dy[runObj * 11] = acadoWorkspace.objValueOut[0]; acadoWorkspace.Dy[runObj * 11 + 1] = acadoWorkspace.objValueOut[1]; acadoWorkspace.Dy[runObj * 11 + 2] = acadoWorkspace.objValueOut[2]; acadoWorkspace.Dy[runObj * 11 + 3] = acadoWorkspace.objValueOut[3]; acadoWorkspace.Dy[runObj * 11 + 4] = acadoWorkspace.objValueOut[4]; acadoWorkspace.Dy[runObj * 11 + 5] = acadoWorkspace.objValueOut[5]; acadoWorkspace.Dy[runObj * 11 + 6] = acadoWorkspace.objValueOut[6]; acadoWorkspace.Dy[runObj * 11 + 7] = acadoWorkspace.objValueOut[7]; acadoWorkspace.Dy[runObj * 11 + 8] = acadoWorkspace.objValueOut[8]; acadoWorkspace.Dy[runObj * 11 + 9] = acadoWorkspace.objValueOut[9]; acadoWorkspace.Dy[runObj * 11 + 10] = acadoWorkspace.objValueOut[10]; acado_setObjQ1Q2( &(acadoWorkspace.objValueOut[ 11 ]), acadoVariables.W, &(acadoWorkspace.Q1[ runObj * 81 ]), &(acadoWorkspace.Q2[ runObj * 99 ]) ); acado_setObjR1R2( &(acadoWorkspace.objValueOut[ 110 ]), acadoVariables.W, &(acadoWorkspace.R1[ runObj * 9 ]), &(acadoWorkspace.R2[ runObj * 33 ]) ); acado_setObjS1( &(acadoWorkspace.objValueOut[ 11 ]), &(acadoWorkspace.objValueOut[ 110 ]), acadoVariables.W, &(acadoWorkspace.S1[ runObj * 27 ]) ); } acadoWorkspace.objValueIn[0] = acadoVariables.x[180]; acadoWorkspace.objValueIn[1] = acadoVariables.x[181]; acadoWorkspace.objValueIn[2] = acadoVariables.x[182]; acadoWorkspace.objValueIn[3] = acadoVariables.x[183]; acadoWorkspace.objValueIn[4] = acadoVariables.x[184]; acadoWorkspace.objValueIn[5] = acadoVariables.x[185]; acadoWorkspace.objValueIn[6] = acadoVariables.x[186]; acadoWorkspace.objValueIn[7] = acadoVariables.x[187]; acadoWorkspace.objValueIn[8] = acadoVariables.x[188]; acadoWorkspace.objValueIn[9] = acadoVariables.od[180]; acadoWorkspace.objValueIn[10] = acadoVariables.od[181]; acadoWorkspace.objValueIn[11] = acadoVariables.od[182]; acadoWorkspace.objValueIn[12] = acadoVariables.od[183]; acadoWorkspace.objValueIn[13] = acadoVariables.od[184]; acadoWorkspace.objValueIn[14] = acadoVariables.od[185]; acadoWorkspace.objValueIn[15] = acadoVariables.od[186]; acadoWorkspace.objValueIn[16] = acadoVariables.od[187]; acadoWorkspace.objValueIn[17] = acadoVariables.od[188]; acado_evaluateLSQEndTerm( acadoWorkspace.objValueIn, acadoWorkspace.objValueOut ); acadoWorkspace.DyN[0] = acadoWorkspace.objValueOut[0]; acadoWorkspace.DyN[1] = acadoWorkspace.objValueOut[1]; acadoWorkspace.DyN[2] = acadoWorkspace.objValueOut[2]; acadoWorkspace.DyN[3] = acadoWorkspace.objValueOut[3]; acadoWorkspace.DyN[4] = acadoWorkspace.objValueOut[4]; acadoWorkspace.DyN[5] = acadoWorkspace.objValueOut[5]; acado_setObjQN1QN2( acadoVariables.WN, acadoWorkspace.QN1, acadoWorkspace.QN2 ); } void acado_multGxGu( real_t* const Gx1, real_t* const Gu1, real_t* const Gu2 ) { Gu2[0] = + Gx1[0]*Gu1[0] + Gx1[1]*Gu1[3] + Gx1[2]*Gu1[6] + Gx1[3]*Gu1[9] + Gx1[4]*Gu1[12] + Gx1[5]*Gu1[15] + Gx1[6]*Gu1[18] + Gx1[7]*Gu1[21] + Gx1[8]*Gu1[24]; Gu2[1] = + Gx1[0]*Gu1[1] + Gx1[1]*Gu1[4] + Gx1[2]*Gu1[7] + Gx1[3]*Gu1[10] + Gx1[4]*Gu1[13] + Gx1[5]*Gu1[16] + Gx1[6]*Gu1[19] + Gx1[7]*Gu1[22] + Gx1[8]*Gu1[25]; Gu2[2] = + Gx1[0]*Gu1[2] + Gx1[1]*Gu1[5] + Gx1[2]*Gu1[8] + Gx1[3]*Gu1[11] + Gx1[4]*Gu1[14] + Gx1[5]*Gu1[17] + Gx1[6]*Gu1[20] + Gx1[7]*Gu1[23] + Gx1[8]*Gu1[26]; Gu2[3] = + Gx1[9]*Gu1[0] + Gx1[10]*Gu1[3] + Gx1[11]*Gu1[6] + Gx1[12]*Gu1[9] + Gx1[13]*Gu1[12] + Gx1[14]*Gu1[15] + Gx1[15]*Gu1[18] + Gx1[16]*Gu1[21] + Gx1[17]*Gu1[24]; Gu2[4] = + Gx1[9]*Gu1[1] + Gx1[10]*Gu1[4] + Gx1[11]*Gu1[7] + Gx1[12]*Gu1[10] + Gx1[13]*Gu1[13] + Gx1[14]*Gu1[16] + Gx1[15]*Gu1[19] + Gx1[16]*Gu1[22] + Gx1[17]*Gu1[25]; Gu2[5] = + Gx1[9]*Gu1[2] + Gx1[10]*Gu1[5] + Gx1[11]*Gu1[8] + Gx1[12]*Gu1[11] + Gx1[13]*Gu1[14] + Gx1[14]*Gu1[17] + Gx1[15]*Gu1[20] + Gx1[16]*Gu1[23] + Gx1[17]*Gu1[26]; Gu2[6] = + Gx1[18]*Gu1[0] + Gx1[19]*Gu1[3] + Gx1[20]*Gu1[6] + Gx1[21]*Gu1[9] + Gx1[22]*Gu1[12] + Gx1[23]*Gu1[15] + Gx1[24]*Gu1[18] + Gx1[25]*Gu1[21] + Gx1[26]*Gu1[24]; Gu2[7] = + Gx1[18]*Gu1[1] + Gx1[19]*Gu1[4] + Gx1[20]*Gu1[7] + Gx1[21]*Gu1[10] + Gx1[22]*Gu1[13] + Gx1[23]*Gu1[16] + Gx1[24]*Gu1[19] + Gx1[25]*Gu1[22] + Gx1[26]*Gu1[25]; Gu2[8] = + Gx1[18]*Gu1[2] + Gx1[19]*Gu1[5] + Gx1[20]*Gu1[8] + Gx1[21]*Gu1[11] + Gx1[22]*Gu1[14] + Gx1[23]*Gu1[17] + Gx1[24]*Gu1[20] + Gx1[25]*Gu1[23] + Gx1[26]*Gu1[26]; Gu2[9] = + Gx1[27]*Gu1[0] + Gx1[28]*Gu1[3] + Gx1[29]*Gu1[6] + Gx1[30]*Gu1[9] + Gx1[31]*Gu1[12] + Gx1[32]*Gu1[15] + Gx1[33]*Gu1[18] + Gx1[34]*Gu1[21] + Gx1[35]*Gu1[24]; Gu2[10] = + Gx1[27]*Gu1[1] + Gx1[28]*Gu1[4] + Gx1[29]*Gu1[7] + Gx1[30]*Gu1[10] + Gx1[31]*Gu1[13] + Gx1[32]*Gu1[16] + Gx1[33]*Gu1[19] + Gx1[34]*Gu1[22] + Gx1[35]*Gu1[25]; Gu2[11] = + Gx1[27]*Gu1[2] + Gx1[28]*Gu1[5] + Gx1[29]*Gu1[8] + Gx1[30]*Gu1[11] + Gx1[31]*Gu1[14] + Gx1[32]*Gu1[17] + Gx1[33]*Gu1[20] + Gx1[34]*Gu1[23] + Gx1[35]*Gu1[26]; Gu2[12] = + Gx1[36]*Gu1[0] + Gx1[37]*Gu1[3] + Gx1[38]*Gu1[6] + Gx1[39]*Gu1[9] + Gx1[40]*Gu1[12] + Gx1[41]*Gu1[15] + Gx1[42]*Gu1[18] + Gx1[43]*Gu1[21] + Gx1[44]*Gu1[24]; Gu2[13] = + Gx1[36]*Gu1[1] + Gx1[37]*Gu1[4] + Gx1[38]*Gu1[7] + Gx1[39]*Gu1[10] + Gx1[40]*Gu1[13] + Gx1[41]*Gu1[16] + Gx1[42]*Gu1[19] + Gx1[43]*Gu1[22] + Gx1[44]*Gu1[25]; Gu2[14] = + Gx1[36]*Gu1[2] + Gx1[37]*Gu1[5] + Gx1[38]*Gu1[8] + Gx1[39]*Gu1[11] + Gx1[40]*Gu1[14] + Gx1[41]*Gu1[17] + Gx1[42]*Gu1[20] + Gx1[43]*Gu1[23] + Gx1[44]*Gu1[26]; Gu2[15] = + Gx1[45]*Gu1[0] + Gx1[46]*Gu1[3] + Gx1[47]*Gu1[6] + Gx1[48]*Gu1[9] + Gx1[49]*Gu1[12] + Gx1[50]*Gu1[15] + Gx1[51]*Gu1[18] + Gx1[52]*Gu1[21] + Gx1[53]*Gu1[24]; Gu2[16] = + Gx1[45]*Gu1[1] + Gx1[46]*Gu1[4] + Gx1[47]*Gu1[7] + Gx1[48]*Gu1[10] + Gx1[49]*Gu1[13] + Gx1[50]*Gu1[16] + Gx1[51]*Gu1[19] + Gx1[52]*Gu1[22] + Gx1[53]*Gu1[25]; Gu2[17] = + Gx1[45]*Gu1[2] + Gx1[46]*Gu1[5] + Gx1[47]*Gu1[8] + Gx1[48]*Gu1[11] + Gx1[49]*Gu1[14] + Gx1[50]*Gu1[17] + Gx1[51]*Gu1[20] + Gx1[52]*Gu1[23] + Gx1[53]*Gu1[26]; Gu2[18] = + Gx1[54]*Gu1[0] + Gx1[55]*Gu1[3] + Gx1[56]*Gu1[6] + Gx1[57]*Gu1[9] + Gx1[58]*Gu1[12] + Gx1[59]*Gu1[15] + Gx1[60]*Gu1[18] + Gx1[61]*Gu1[21] + Gx1[62]*Gu1[24]; Gu2[19] = + Gx1[54]*Gu1[1] + Gx1[55]*Gu1[4] + Gx1[56]*Gu1[7] + Gx1[57]*Gu1[10] + Gx1[58]*Gu1[13] + Gx1[59]*Gu1[16] + Gx1[60]*Gu1[19] + Gx1[61]*Gu1[22] + Gx1[62]*Gu1[25]; Gu2[20] = + Gx1[54]*Gu1[2] + Gx1[55]*Gu1[5] + Gx1[56]*Gu1[8] + Gx1[57]*Gu1[11] + Gx1[58]*Gu1[14] + Gx1[59]*Gu1[17] + Gx1[60]*Gu1[20] + Gx1[61]*Gu1[23] + Gx1[62]*Gu1[26]; Gu2[21] = + Gx1[63]*Gu1[0] + Gx1[64]*Gu1[3] + Gx1[65]*Gu1[6] + Gx1[66]*Gu1[9] + Gx1[67]*Gu1[12] + Gx1[68]*Gu1[15] + Gx1[69]*Gu1[18] + Gx1[70]*Gu1[21] + Gx1[71]*Gu1[24]; Gu2[22] = + Gx1[63]*Gu1[1] + Gx1[64]*Gu1[4] + Gx1[65]*Gu1[7] + Gx1[66]*Gu1[10] + Gx1[67]*Gu1[13] + Gx1[68]*Gu1[16] + Gx1[69]*Gu1[19] + Gx1[70]*Gu1[22] + Gx1[71]*Gu1[25]; Gu2[23] = + Gx1[63]*Gu1[2] + Gx1[64]*Gu1[5] + Gx1[65]*Gu1[8] + Gx1[66]*Gu1[11] + Gx1[67]*Gu1[14] + Gx1[68]*Gu1[17] + Gx1[69]*Gu1[20] + Gx1[70]*Gu1[23] + Gx1[71]*Gu1[26]; Gu2[24] = + Gx1[72]*Gu1[0] + Gx1[73]*Gu1[3] + Gx1[74]*Gu1[6] + Gx1[75]*Gu1[9] + Gx1[76]*Gu1[12] + Gx1[77]*Gu1[15] + Gx1[78]*Gu1[18] + Gx1[79]*Gu1[21] + Gx1[80]*Gu1[24]; Gu2[25] = + Gx1[72]*Gu1[1] + Gx1[73]*Gu1[4] + Gx1[74]*Gu1[7] + Gx1[75]*Gu1[10] + Gx1[76]*Gu1[13] + Gx1[77]*Gu1[16] + Gx1[78]*Gu1[19] + Gx1[79]*Gu1[22] + Gx1[80]*Gu1[25]; Gu2[26] = + Gx1[72]*Gu1[2] + Gx1[73]*Gu1[5] + Gx1[74]*Gu1[8] + Gx1[75]*Gu1[11] + Gx1[76]*Gu1[14] + Gx1[77]*Gu1[17] + Gx1[78]*Gu1[20] + Gx1[79]*Gu1[23] + Gx1[80]*Gu1[26]; } void acado_moveGuE( real_t* const Gu1, real_t* const Gu2 ) { Gu2[0] = Gu1[0]; Gu2[1] = Gu1[1]; Gu2[2] = Gu1[2]; Gu2[3] = Gu1[3]; Gu2[4] = Gu1[4]; Gu2[5] = Gu1[5]; Gu2[6] = Gu1[6]; Gu2[7] = Gu1[7]; Gu2[8] = Gu1[8]; Gu2[9] = Gu1[9]; Gu2[10] = Gu1[10]; Gu2[11] = Gu1[11]; Gu2[12] = Gu1[12]; Gu2[13] = Gu1[13]; Gu2[14] = Gu1[14]; Gu2[15] = Gu1[15]; Gu2[16] = Gu1[16]; Gu2[17] = Gu1[17]; Gu2[18] = Gu1[18]; Gu2[19] = Gu1[19]; Gu2[20] = Gu1[20]; Gu2[21] = Gu1[21]; Gu2[22] = Gu1[22]; Gu2[23] = Gu1[23]; Gu2[24] = Gu1[24]; Gu2[25] = Gu1[25]; Gu2[26] = Gu1[26]; } void acado_multBTW1( real_t* const Gu1, real_t* const Gu2, int iRow, int iCol ) { acadoWorkspace.H[(iRow * 180) + (iCol * 3)] = + Gu1[0]*Gu2[0] + Gu1[3]*Gu2[3] + Gu1[6]*Gu2[6] + Gu1[9]*Gu2[9] + Gu1[12]*Gu2[12] + Gu1[15]*Gu2[15] + Gu1[18]*Gu2[18] + Gu1[21]*Gu2[21] + Gu1[24]*Gu2[24]; acadoWorkspace.H[(iRow * 180) + (iCol * 3 + 1)] = + Gu1[0]*Gu2[1] + Gu1[3]*Gu2[4] + Gu1[6]*Gu2[7] + Gu1[9]*Gu2[10] + Gu1[12]*Gu2[13] + Gu1[15]*Gu2[16] + Gu1[18]*Gu2[19] + Gu1[21]*Gu2[22] + Gu1[24]*Gu2[25]; acadoWorkspace.H[(iRow * 180) + (iCol * 3 + 2)] = + Gu1[0]*Gu2[2] + Gu1[3]*Gu2[5] + Gu1[6]*Gu2[8] + Gu1[9]*Gu2[11] + Gu1[12]*Gu2[14] + Gu1[15]*Gu2[17] + Gu1[18]*Gu2[20] + Gu1[21]*Gu2[23] + Gu1[24]*Gu2[26]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3)] = + Gu1[1]*Gu2[0] + Gu1[4]*Gu2[3] + Gu1[7]*Gu2[6] + Gu1[10]*Gu2[9] + Gu1[13]*Gu2[12] + Gu1[16]*Gu2[15] + Gu1[19]*Gu2[18] + Gu1[22]*Gu2[21] + Gu1[25]*Gu2[24]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3 + 1)] = + Gu1[1]*Gu2[1] + Gu1[4]*Gu2[4] + Gu1[7]*Gu2[7] + Gu1[10]*Gu2[10] + Gu1[13]*Gu2[13] + Gu1[16]*Gu2[16] + Gu1[19]*Gu2[19] + Gu1[22]*Gu2[22] + Gu1[25]*Gu2[25]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3 + 2)] = + Gu1[1]*Gu2[2] + Gu1[4]*Gu2[5] + Gu1[7]*Gu2[8] + Gu1[10]*Gu2[11] + Gu1[13]*Gu2[14] + Gu1[16]*Gu2[17] + Gu1[19]*Gu2[20] + Gu1[22]*Gu2[23] + Gu1[25]*Gu2[26]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3)] = + Gu1[2]*Gu2[0] + Gu1[5]*Gu2[3] + Gu1[8]*Gu2[6] + Gu1[11]*Gu2[9] + Gu1[14]*Gu2[12] + Gu1[17]*Gu2[15] + Gu1[20]*Gu2[18] + Gu1[23]*Gu2[21] + Gu1[26]*Gu2[24]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3 + 1)] = + Gu1[2]*Gu2[1] + Gu1[5]*Gu2[4] + Gu1[8]*Gu2[7] + Gu1[11]*Gu2[10] + Gu1[14]*Gu2[13] + Gu1[17]*Gu2[16] + Gu1[20]*Gu2[19] + Gu1[23]*Gu2[22] + Gu1[26]*Gu2[25]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3 + 2)] = + Gu1[2]*Gu2[2] + Gu1[5]*Gu2[5] + Gu1[8]*Gu2[8] + Gu1[11]*Gu2[11] + Gu1[14]*Gu2[14] + Gu1[17]*Gu2[17] + Gu1[20]*Gu2[20] + Gu1[23]*Gu2[23] + Gu1[26]*Gu2[26]; } void acado_mac_S1T_E( real_t* const Gu1, real_t* const Gu2, int iRow, int iCol ) { acadoWorkspace.H[(iRow * 180) + (iCol * 3)] += + Gu1[0]*Gu2[0] + Gu1[3]*Gu2[3] + Gu1[6]*Gu2[6] + Gu1[9]*Gu2[9] + Gu1[12]*Gu2[12] + Gu1[15]*Gu2[15] + Gu1[18]*Gu2[18] + Gu1[21]*Gu2[21] + Gu1[24]*Gu2[24]; acadoWorkspace.H[(iRow * 180) + (iCol * 3 + 1)] += + Gu1[0]*Gu2[1] + Gu1[3]*Gu2[4] + Gu1[6]*Gu2[7] + Gu1[9]*Gu2[10] + Gu1[12]*Gu2[13] + Gu1[15]*Gu2[16] + Gu1[18]*Gu2[19] + Gu1[21]*Gu2[22] + Gu1[24]*Gu2[25]; acadoWorkspace.H[(iRow * 180) + (iCol * 3 + 2)] += + Gu1[0]*Gu2[2] + Gu1[3]*Gu2[5] + Gu1[6]*Gu2[8] + Gu1[9]*Gu2[11] + Gu1[12]*Gu2[14] + Gu1[15]*Gu2[17] + Gu1[18]*Gu2[20] + Gu1[21]*Gu2[23] + Gu1[24]*Gu2[26]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3)] += + Gu1[1]*Gu2[0] + Gu1[4]*Gu2[3] + Gu1[7]*Gu2[6] + Gu1[10]*Gu2[9] + Gu1[13]*Gu2[12] + Gu1[16]*Gu2[15] + Gu1[19]*Gu2[18] + Gu1[22]*Gu2[21] + Gu1[25]*Gu2[24]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3 + 1)] += + Gu1[1]*Gu2[1] + Gu1[4]*Gu2[4] + Gu1[7]*Gu2[7] + Gu1[10]*Gu2[10] + Gu1[13]*Gu2[13] + Gu1[16]*Gu2[16] + Gu1[19]*Gu2[19] + Gu1[22]*Gu2[22] + Gu1[25]*Gu2[25]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3 + 2)] += + Gu1[1]*Gu2[2] + Gu1[4]*Gu2[5] + Gu1[7]*Gu2[8] + Gu1[10]*Gu2[11] + Gu1[13]*Gu2[14] + Gu1[16]*Gu2[17] + Gu1[19]*Gu2[20] + Gu1[22]*Gu2[23] + Gu1[25]*Gu2[26]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3)] += + Gu1[2]*Gu2[0] + Gu1[5]*Gu2[3] + Gu1[8]*Gu2[6] + Gu1[11]*Gu2[9] + Gu1[14]*Gu2[12] + Gu1[17]*Gu2[15] + Gu1[20]*Gu2[18] + Gu1[23]*Gu2[21] + Gu1[26]*Gu2[24]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3 + 1)] += + Gu1[2]*Gu2[1] + Gu1[5]*Gu2[4] + Gu1[8]*Gu2[7] + Gu1[11]*Gu2[10] + Gu1[14]*Gu2[13] + Gu1[17]*Gu2[16] + Gu1[20]*Gu2[19] + Gu1[23]*Gu2[22] + Gu1[26]*Gu2[25]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3 + 2)] += + Gu1[2]*Gu2[2] + Gu1[5]*Gu2[5] + Gu1[8]*Gu2[8] + Gu1[11]*Gu2[11] + Gu1[14]*Gu2[14] + Gu1[17]*Gu2[17] + Gu1[20]*Gu2[20] + Gu1[23]*Gu2[23] + Gu1[26]*Gu2[26]; } void acado_multBTW1_R1( real_t* const R11, real_t* const Gu1, real_t* const Gu2, int iRow ) { acadoWorkspace.H[iRow * 183] = + Gu1[0]*Gu2[0] + Gu1[3]*Gu2[3] + Gu1[6]*Gu2[6] + Gu1[9]*Gu2[9] + Gu1[12]*Gu2[12] + Gu1[15]*Gu2[15] + Gu1[18]*Gu2[18] + Gu1[21]*Gu2[21] + Gu1[24]*Gu2[24] + R11[0]; acadoWorkspace.H[iRow * 183 + 1] = + Gu1[0]*Gu2[1] + Gu1[3]*Gu2[4] + Gu1[6]*Gu2[7] + Gu1[9]*Gu2[10] + Gu1[12]*Gu2[13] + Gu1[15]*Gu2[16] + Gu1[18]*Gu2[19] + Gu1[21]*Gu2[22] + Gu1[24]*Gu2[25] + R11[1]; acadoWorkspace.H[iRow * 183 + 2] = + Gu1[0]*Gu2[2] + Gu1[3]*Gu2[5] + Gu1[6]*Gu2[8] + Gu1[9]*Gu2[11] + Gu1[12]*Gu2[14] + Gu1[15]*Gu2[17] + Gu1[18]*Gu2[20] + Gu1[21]*Gu2[23] + Gu1[24]*Gu2[26] + R11[2]; acadoWorkspace.H[iRow * 183 + 60] = + Gu1[1]*Gu2[0] + Gu1[4]*Gu2[3] + Gu1[7]*Gu2[6] + Gu1[10]*Gu2[9] + Gu1[13]*Gu2[12] + Gu1[16]*Gu2[15] + Gu1[19]*Gu2[18] + Gu1[22]*Gu2[21] + Gu1[25]*Gu2[24] + R11[3]; acadoWorkspace.H[iRow * 183 + 61] = + Gu1[1]*Gu2[1] + Gu1[4]*Gu2[4] + Gu1[7]*Gu2[7] + Gu1[10]*Gu2[10] + Gu1[13]*Gu2[13] + Gu1[16]*Gu2[16] + Gu1[19]*Gu2[19] + Gu1[22]*Gu2[22] + Gu1[25]*Gu2[25] + R11[4]; acadoWorkspace.H[iRow * 183 + 62] = + Gu1[1]*Gu2[2] + Gu1[4]*Gu2[5] + Gu1[7]*Gu2[8] + Gu1[10]*Gu2[11] + Gu1[13]*Gu2[14] + Gu1[16]*Gu2[17] + Gu1[19]*Gu2[20] + Gu1[22]*Gu2[23] + Gu1[25]*Gu2[26] + R11[5]; acadoWorkspace.H[iRow * 183 + 120] = + Gu1[2]*Gu2[0] + Gu1[5]*Gu2[3] + Gu1[8]*Gu2[6] + Gu1[11]*Gu2[9] + Gu1[14]*Gu2[12] + Gu1[17]*Gu2[15] + Gu1[20]*Gu2[18] + Gu1[23]*Gu2[21] + Gu1[26]*Gu2[24] + R11[6]; acadoWorkspace.H[iRow * 183 + 121] = + Gu1[2]*Gu2[1] + Gu1[5]*Gu2[4] + Gu1[8]*Gu2[7] + Gu1[11]*Gu2[10] + Gu1[14]*Gu2[13] + Gu1[17]*Gu2[16] + Gu1[20]*Gu2[19] + Gu1[23]*Gu2[22] + Gu1[26]*Gu2[25] + R11[7]; acadoWorkspace.H[iRow * 183 + 122] = + Gu1[2]*Gu2[2] + Gu1[5]*Gu2[5] + Gu1[8]*Gu2[8] + Gu1[11]*Gu2[11] + Gu1[14]*Gu2[14] + Gu1[17]*Gu2[17] + Gu1[20]*Gu2[20] + Gu1[23]*Gu2[23] + Gu1[26]*Gu2[26] + R11[8]; acadoWorkspace.H[iRow * 183] += 1.0000000000000000e-10; acadoWorkspace.H[iRow * 183 + 61] += 1.0000000000000000e-10; acadoWorkspace.H[iRow * 183 + 122] += 1.0000000000000000e-10; } void acado_multGxTGu( real_t* const Gx1, real_t* const Gu1, real_t* const Gu2 ) { Gu2[0] = + Gx1[0]*Gu1[0] + Gx1[9]*Gu1[3] + Gx1[18]*Gu1[6] + Gx1[27]*Gu1[9] + Gx1[36]*Gu1[12] + Gx1[45]*Gu1[15] + Gx1[54]*Gu1[18] + Gx1[63]*Gu1[21] + Gx1[72]*Gu1[24]; Gu2[1] = + Gx1[0]*Gu1[1] + Gx1[9]*Gu1[4] + Gx1[18]*Gu1[7] + Gx1[27]*Gu1[10] + Gx1[36]*Gu1[13] + Gx1[45]*Gu1[16] + Gx1[54]*Gu1[19] + Gx1[63]*Gu1[22] + Gx1[72]*Gu1[25]; Gu2[2] = + Gx1[0]*Gu1[2] + Gx1[9]*Gu1[5] + Gx1[18]*Gu1[8] + Gx1[27]*Gu1[11] + Gx1[36]*Gu1[14] + Gx1[45]*Gu1[17] + Gx1[54]*Gu1[20] + Gx1[63]*Gu1[23] + Gx1[72]*Gu1[26]; Gu2[3] = + Gx1[1]*Gu1[0] + Gx1[10]*Gu1[3] + Gx1[19]*Gu1[6] + Gx1[28]*Gu1[9] + Gx1[37]*Gu1[12] + Gx1[46]*Gu1[15] + Gx1[55]*Gu1[18] + Gx1[64]*Gu1[21] + Gx1[73]*Gu1[24]; Gu2[4] = + Gx1[1]*Gu1[1] + Gx1[10]*Gu1[4] + Gx1[19]*Gu1[7] + Gx1[28]*Gu1[10] + Gx1[37]*Gu1[13] + Gx1[46]*Gu1[16] + Gx1[55]*Gu1[19] + Gx1[64]*Gu1[22] + Gx1[73]*Gu1[25]; Gu2[5] = + Gx1[1]*Gu1[2] + Gx1[10]*Gu1[5] + Gx1[19]*Gu1[8] + Gx1[28]*Gu1[11] + Gx1[37]*Gu1[14] + Gx1[46]*Gu1[17] + Gx1[55]*Gu1[20] + Gx1[64]*Gu1[23] + Gx1[73]*Gu1[26]; Gu2[6] = + Gx1[2]*Gu1[0] + Gx1[11]*Gu1[3] + Gx1[20]*Gu1[6] + Gx1[29]*Gu1[9] + Gx1[38]*Gu1[12] + Gx1[47]*Gu1[15] + Gx1[56]*Gu1[18] + Gx1[65]*Gu1[21] + Gx1[74]*Gu1[24]; Gu2[7] = + Gx1[2]*Gu1[1] + Gx1[11]*Gu1[4] + Gx1[20]*Gu1[7] + Gx1[29]*Gu1[10] + Gx1[38]*Gu1[13] + Gx1[47]*Gu1[16] + Gx1[56]*Gu1[19] + Gx1[65]*Gu1[22] + Gx1[74]*Gu1[25]; Gu2[8] = + Gx1[2]*Gu1[2] + Gx1[11]*Gu1[5] + Gx1[20]*Gu1[8] + Gx1[29]*Gu1[11] + Gx1[38]*Gu1[14] + Gx1[47]*Gu1[17] + Gx1[56]*Gu1[20] + Gx1[65]*Gu1[23] + Gx1[74]*Gu1[26]; Gu2[9] = + Gx1[3]*Gu1[0] + Gx1[12]*Gu1[3] + Gx1[21]*Gu1[6] + Gx1[30]*Gu1[9] + Gx1[39]*Gu1[12] + Gx1[48]*Gu1[15] + Gx1[57]*Gu1[18] + Gx1[66]*Gu1[21] + Gx1[75]*Gu1[24]; Gu2[10] = + Gx1[3]*Gu1[1] + Gx1[12]*Gu1[4] + Gx1[21]*Gu1[7] + Gx1[30]*Gu1[10] + Gx1[39]*Gu1[13] + Gx1[48]*Gu1[16] + Gx1[57]*Gu1[19] + Gx1[66]*Gu1[22] + Gx1[75]*Gu1[25]; Gu2[11] = + Gx1[3]*Gu1[2] + Gx1[12]*Gu1[5] + Gx1[21]*Gu1[8] + Gx1[30]*Gu1[11] + Gx1[39]*Gu1[14] + Gx1[48]*Gu1[17] + Gx1[57]*Gu1[20] + Gx1[66]*Gu1[23] + Gx1[75]*Gu1[26]; Gu2[12] = + Gx1[4]*Gu1[0] + Gx1[13]*Gu1[3] + Gx1[22]*Gu1[6] + Gx1[31]*Gu1[9] + Gx1[40]*Gu1[12] + Gx1[49]*Gu1[15] + Gx1[58]*Gu1[18] + Gx1[67]*Gu1[21] + Gx1[76]*Gu1[24]; Gu2[13] = + Gx1[4]*Gu1[1] + Gx1[13]*Gu1[4] + Gx1[22]*Gu1[7] + Gx1[31]*Gu1[10] + Gx1[40]*Gu1[13] + Gx1[49]*Gu1[16] + Gx1[58]*Gu1[19] + Gx1[67]*Gu1[22] + Gx1[76]*Gu1[25]; Gu2[14] = + Gx1[4]*Gu1[2] + Gx1[13]*Gu1[5] + Gx1[22]*Gu1[8] + Gx1[31]*Gu1[11] + Gx1[40]*Gu1[14] + Gx1[49]*Gu1[17] + Gx1[58]*Gu1[20] + Gx1[67]*Gu1[23] + Gx1[76]*Gu1[26]; Gu2[15] = + Gx1[5]*Gu1[0] + Gx1[14]*Gu1[3] + Gx1[23]*Gu1[6] + Gx1[32]*Gu1[9] + Gx1[41]*Gu1[12] + Gx1[50]*Gu1[15] + Gx1[59]*Gu1[18] + Gx1[68]*Gu1[21] + Gx1[77]*Gu1[24]; Gu2[16] = + Gx1[5]*Gu1[1] + Gx1[14]*Gu1[4] + Gx1[23]*Gu1[7] + Gx1[32]*Gu1[10] + Gx1[41]*Gu1[13] + Gx1[50]*Gu1[16] + Gx1[59]*Gu1[19] + Gx1[68]*Gu1[22] + Gx1[77]*Gu1[25]; Gu2[17] = + Gx1[5]*Gu1[2] + Gx1[14]*Gu1[5] + Gx1[23]*Gu1[8] + Gx1[32]*Gu1[11] + Gx1[41]*Gu1[14] + Gx1[50]*Gu1[17] + Gx1[59]*Gu1[20] + Gx1[68]*Gu1[23] + Gx1[77]*Gu1[26]; Gu2[18] = + Gx1[6]*Gu1[0] + Gx1[15]*Gu1[3] + Gx1[24]*Gu1[6] + Gx1[33]*Gu1[9] + Gx1[42]*Gu1[12] + Gx1[51]*Gu1[15] + Gx1[60]*Gu1[18] + Gx1[69]*Gu1[21] + Gx1[78]*Gu1[24]; Gu2[19] = + Gx1[6]*Gu1[1] + Gx1[15]*Gu1[4] + Gx1[24]*Gu1[7] + Gx1[33]*Gu1[10] + Gx1[42]*Gu1[13] + Gx1[51]*Gu1[16] + Gx1[60]*Gu1[19] + Gx1[69]*Gu1[22] + Gx1[78]*Gu1[25]; Gu2[20] = + Gx1[6]*Gu1[2] + Gx1[15]*Gu1[5] + Gx1[24]*Gu1[8] + Gx1[33]*Gu1[11] + Gx1[42]*Gu1[14] + Gx1[51]*Gu1[17] + Gx1[60]*Gu1[20] + Gx1[69]*Gu1[23] + Gx1[78]*Gu1[26]; Gu2[21] = + Gx1[7]*Gu1[0] + Gx1[16]*Gu1[3] + Gx1[25]*Gu1[6] + Gx1[34]*Gu1[9] + Gx1[43]*Gu1[12] + Gx1[52]*Gu1[15] + Gx1[61]*Gu1[18] + Gx1[70]*Gu1[21] + Gx1[79]*Gu1[24]; Gu2[22] = + Gx1[7]*Gu1[1] + Gx1[16]*Gu1[4] + Gx1[25]*Gu1[7] + Gx1[34]*Gu1[10] + Gx1[43]*Gu1[13] + Gx1[52]*Gu1[16] + Gx1[61]*Gu1[19] + Gx1[70]*Gu1[22] + Gx1[79]*Gu1[25]; Gu2[23] = + Gx1[7]*Gu1[2] + Gx1[16]*Gu1[5] + Gx1[25]*Gu1[8] + Gx1[34]*Gu1[11] + Gx1[43]*Gu1[14] + Gx1[52]*Gu1[17] + Gx1[61]*Gu1[20] + Gx1[70]*Gu1[23] + Gx1[79]*Gu1[26]; Gu2[24] = + Gx1[8]*Gu1[0] + Gx1[17]*Gu1[3] + Gx1[26]*Gu1[6] + Gx1[35]*Gu1[9] + Gx1[44]*Gu1[12] + Gx1[53]*Gu1[15] + Gx1[62]*Gu1[18] + Gx1[71]*Gu1[21] + Gx1[80]*Gu1[24]; Gu2[25] = + Gx1[8]*Gu1[1] + Gx1[17]*Gu1[4] + Gx1[26]*Gu1[7] + Gx1[35]*Gu1[10] + Gx1[44]*Gu1[13] + Gx1[53]*Gu1[16] + Gx1[62]*Gu1[19] + Gx1[71]*Gu1[22] + Gx1[80]*Gu1[25]; Gu2[26] = + Gx1[8]*Gu1[2] + Gx1[17]*Gu1[5] + Gx1[26]*Gu1[8] + Gx1[35]*Gu1[11] + Gx1[44]*Gu1[14] + Gx1[53]*Gu1[17] + Gx1[62]*Gu1[20] + Gx1[71]*Gu1[23] + Gx1[80]*Gu1[26]; } void acado_multQEW2( real_t* const Q11, real_t* const Gu1, real_t* const Gu2, real_t* const Gu3 ) { Gu3[0] = + Q11[0]*Gu1[0] + Q11[1]*Gu1[3] + Q11[2]*Gu1[6] + Q11[3]*Gu1[9] + Q11[4]*Gu1[12] + Q11[5]*Gu1[15] + Q11[6]*Gu1[18] + Q11[7]*Gu1[21] + Q11[8]*Gu1[24] + Gu2[0]; Gu3[1] = + Q11[0]*Gu1[1] + Q11[1]*Gu1[4] + Q11[2]*Gu1[7] + Q11[3]*Gu1[10] + Q11[4]*Gu1[13] + Q11[5]*Gu1[16] + Q11[6]*Gu1[19] + Q11[7]*Gu1[22] + Q11[8]*Gu1[25] + Gu2[1]; Gu3[2] = + Q11[0]*Gu1[2] + Q11[1]*Gu1[5] + Q11[2]*Gu1[8] + Q11[3]*Gu1[11] + Q11[4]*Gu1[14] + Q11[5]*Gu1[17] + Q11[6]*Gu1[20] + Q11[7]*Gu1[23] + Q11[8]*Gu1[26] + Gu2[2]; Gu3[3] = + Q11[9]*Gu1[0] + Q11[10]*Gu1[3] + Q11[11]*Gu1[6] + Q11[12]*Gu1[9] + Q11[13]*Gu1[12] + Q11[14]*Gu1[15] + Q11[15]*Gu1[18] + Q11[16]*Gu1[21] + Q11[17]*Gu1[24] + Gu2[3]; Gu3[4] = + Q11[9]*Gu1[1] + Q11[10]*Gu1[4] + Q11[11]*Gu1[7] + Q11[12]*Gu1[10] + Q11[13]*Gu1[13] + Q11[14]*Gu1[16] + Q11[15]*Gu1[19] + Q11[16]*Gu1[22] + Q11[17]*Gu1[25] + Gu2[4]; Gu3[5] = + Q11[9]*Gu1[2] + Q11[10]*Gu1[5] + Q11[11]*Gu1[8] + Q11[12]*Gu1[11] + Q11[13]*Gu1[14] + Q11[14]*Gu1[17] + Q11[15]*Gu1[20] + Q11[16]*Gu1[23] + Q11[17]*Gu1[26] + Gu2[5]; Gu3[6] = + Q11[18]*Gu1[0] + Q11[19]*Gu1[3] + Q11[20]*Gu1[6] + Q11[21]*Gu1[9] + Q11[22]*Gu1[12] + Q11[23]*Gu1[15] + Q11[24]*Gu1[18] + Q11[25]*Gu1[21] + Q11[26]*Gu1[24] + Gu2[6]; Gu3[7] = + Q11[18]*Gu1[1] + Q11[19]*Gu1[4] + Q11[20]*Gu1[7] + Q11[21]*Gu1[10] + Q11[22]*Gu1[13] + Q11[23]*Gu1[16] + Q11[24]*Gu1[19] + Q11[25]*Gu1[22] + Q11[26]*Gu1[25] + Gu2[7]; Gu3[8] = + Q11[18]*Gu1[2] + Q11[19]*Gu1[5] + Q11[20]*Gu1[8] + Q11[21]*Gu1[11] + Q11[22]*Gu1[14] + Q11[23]*Gu1[17] + Q11[24]*Gu1[20] + Q11[25]*Gu1[23] + Q11[26]*Gu1[26] + Gu2[8]; Gu3[9] = + Q11[27]*Gu1[0] + Q11[28]*Gu1[3] + Q11[29]*Gu1[6] + Q11[30]*Gu1[9] + Q11[31]*Gu1[12] + Q11[32]*Gu1[15] + Q11[33]*Gu1[18] + Q11[34]*Gu1[21] + Q11[35]*Gu1[24] + Gu2[9]; Gu3[10] = + Q11[27]*Gu1[1] + Q11[28]*Gu1[4] + Q11[29]*Gu1[7] + Q11[30]*Gu1[10] + Q11[31]*Gu1[13] + Q11[32]*Gu1[16] + Q11[33]*Gu1[19] + Q11[34]*Gu1[22] + Q11[35]*Gu1[25] + Gu2[10]; Gu3[11] = + Q11[27]*Gu1[2] + Q11[28]*Gu1[5] + Q11[29]*Gu1[8] + Q11[30]*Gu1[11] + Q11[31]*Gu1[14] + Q11[32]*Gu1[17] + Q11[33]*Gu1[20] + Q11[34]*Gu1[23] + Q11[35]*Gu1[26] + Gu2[11]; Gu3[12] = + Q11[36]*Gu1[0] + Q11[37]*Gu1[3] + Q11[38]*Gu1[6] + Q11[39]*Gu1[9] + Q11[40]*Gu1[12] + Q11[41]*Gu1[15] + Q11[42]*Gu1[18] + Q11[43]*Gu1[21] + Q11[44]*Gu1[24] + Gu2[12]; Gu3[13] = + Q11[36]*Gu1[1] + Q11[37]*Gu1[4] + Q11[38]*Gu1[7] + Q11[39]*Gu1[10] + Q11[40]*Gu1[13] + Q11[41]*Gu1[16] + Q11[42]*Gu1[19] + Q11[43]*Gu1[22] + Q11[44]*Gu1[25] + Gu2[13]; Gu3[14] = + Q11[36]*Gu1[2] + Q11[37]*Gu1[5] + Q11[38]*Gu1[8] + Q11[39]*Gu1[11] + Q11[40]*Gu1[14] + Q11[41]*Gu1[17] + Q11[42]*Gu1[20] + Q11[43]*Gu1[23] + Q11[44]*Gu1[26] + Gu2[14]; Gu3[15] = + Q11[45]*Gu1[0] + Q11[46]*Gu1[3] + Q11[47]*Gu1[6] + Q11[48]*Gu1[9] + Q11[49]*Gu1[12] + Q11[50]*Gu1[15] + Q11[51]*Gu1[18] + Q11[52]*Gu1[21] + Q11[53]*Gu1[24] + Gu2[15]; Gu3[16] = + Q11[45]*Gu1[1] + Q11[46]*Gu1[4] + Q11[47]*Gu1[7] + Q11[48]*Gu1[10] + Q11[49]*Gu1[13] + Q11[50]*Gu1[16] + Q11[51]*Gu1[19] + Q11[52]*Gu1[22] + Q11[53]*Gu1[25] + Gu2[16]; Gu3[17] = + Q11[45]*Gu1[2] + Q11[46]*Gu1[5] + Q11[47]*Gu1[8] + Q11[48]*Gu1[11] + Q11[49]*Gu1[14] + Q11[50]*Gu1[17] + Q11[51]*Gu1[20] + Q11[52]*Gu1[23] + Q11[53]*Gu1[26] + Gu2[17]; Gu3[18] = + Q11[54]*Gu1[0] + Q11[55]*Gu1[3] + Q11[56]*Gu1[6] + Q11[57]*Gu1[9] + Q11[58]*Gu1[12] + Q11[59]*Gu1[15] + Q11[60]*Gu1[18] + Q11[61]*Gu1[21] + Q11[62]*Gu1[24] + Gu2[18]; Gu3[19] = + Q11[54]*Gu1[1] + Q11[55]*Gu1[4] + Q11[56]*Gu1[7] + Q11[57]*Gu1[10] + Q11[58]*Gu1[13] + Q11[59]*Gu1[16] + Q11[60]*Gu1[19] + Q11[61]*Gu1[22] + Q11[62]*Gu1[25] + Gu2[19]; Gu3[20] = + Q11[54]*Gu1[2] + Q11[55]*Gu1[5] + Q11[56]*Gu1[8] + Q11[57]*Gu1[11] + Q11[58]*Gu1[14] + Q11[59]*Gu1[17] + Q11[60]*Gu1[20] + Q11[61]*Gu1[23] + Q11[62]*Gu1[26] + Gu2[20]; Gu3[21] = + Q11[63]*Gu1[0] + Q11[64]*Gu1[3] + Q11[65]*Gu1[6] + Q11[66]*Gu1[9] + Q11[67]*Gu1[12] + Q11[68]*Gu1[15] + Q11[69]*Gu1[18] + Q11[70]*Gu1[21] + Q11[71]*Gu1[24] + Gu2[21]; Gu3[22] = + Q11[63]*Gu1[1] + Q11[64]*Gu1[4] + Q11[65]*Gu1[7] + Q11[66]*Gu1[10] + Q11[67]*Gu1[13] + Q11[68]*Gu1[16] + Q11[69]*Gu1[19] + Q11[70]*Gu1[22] + Q11[71]*Gu1[25] + Gu2[22]; Gu3[23] = + Q11[63]*Gu1[2] + Q11[64]*Gu1[5] + Q11[65]*Gu1[8] + Q11[66]*Gu1[11] + Q11[67]*Gu1[14] + Q11[68]*Gu1[17] + Q11[69]*Gu1[20] + Q11[70]*Gu1[23] + Q11[71]*Gu1[26] + Gu2[23]; Gu3[24] = + Q11[72]*Gu1[0] + Q11[73]*Gu1[3] + Q11[74]*Gu1[6] + Q11[75]*Gu1[9] + Q11[76]*Gu1[12] + Q11[77]*Gu1[15] + Q11[78]*Gu1[18] + Q11[79]*Gu1[21] + Q11[80]*Gu1[24] + Gu2[24]; Gu3[25] = + Q11[72]*Gu1[1] + Q11[73]*Gu1[4] + Q11[74]*Gu1[7] + Q11[75]*Gu1[10] + Q11[76]*Gu1[13] + Q11[77]*Gu1[16] + Q11[78]*Gu1[19] + Q11[79]*Gu1[22] + Q11[80]*Gu1[25] + Gu2[25]; Gu3[26] = + Q11[72]*Gu1[2] + Q11[73]*Gu1[5] + Q11[74]*Gu1[8] + Q11[75]*Gu1[11] + Q11[76]*Gu1[14] + Q11[77]*Gu1[17] + Q11[78]*Gu1[20] + Q11[79]*Gu1[23] + Q11[80]*Gu1[26] + Gu2[26]; } void acado_macATw1QDy( real_t* const Gx1, real_t* const w11, real_t* const w12, real_t* const w13 ) { w13[0] = + Gx1[0]*w11[0] + Gx1[9]*w11[1] + Gx1[18]*w11[2] + Gx1[27]*w11[3] + Gx1[36]*w11[4] + Gx1[45]*w11[5] + Gx1[54]*w11[6] + Gx1[63]*w11[7] + Gx1[72]*w11[8] + w12[0]; w13[1] = + Gx1[1]*w11[0] + Gx1[10]*w11[1] + Gx1[19]*w11[2] + Gx1[28]*w11[3] + Gx1[37]*w11[4] + Gx1[46]*w11[5] + Gx1[55]*w11[6] + Gx1[64]*w11[7] + Gx1[73]*w11[8] + w12[1]; w13[2] = + Gx1[2]*w11[0] + Gx1[11]*w11[1] + Gx1[20]*w11[2] + Gx1[29]*w11[3] + Gx1[38]*w11[4] + Gx1[47]*w11[5] + Gx1[56]*w11[6] + Gx1[65]*w11[7] + Gx1[74]*w11[8] + w12[2]; w13[3] = + Gx1[3]*w11[0] + Gx1[12]*w11[1] + Gx1[21]*w11[2] + Gx1[30]*w11[3] + Gx1[39]*w11[4] + Gx1[48]*w11[5] + Gx1[57]*w11[6] + Gx1[66]*w11[7] + Gx1[75]*w11[8] + w12[3]; w13[4] = + Gx1[4]*w11[0] + Gx1[13]*w11[1] + Gx1[22]*w11[2] + Gx1[31]*w11[3] + Gx1[40]*w11[4] + Gx1[49]*w11[5] + Gx1[58]*w11[6] + Gx1[67]*w11[7] + Gx1[76]*w11[8] + w12[4]; w13[5] = + Gx1[5]*w11[0] + Gx1[14]*w11[1] + Gx1[23]*w11[2] + Gx1[32]*w11[3] + Gx1[41]*w11[4] + Gx1[50]*w11[5] + Gx1[59]*w11[6] + Gx1[68]*w11[7] + Gx1[77]*w11[8] + w12[5]; w13[6] = + Gx1[6]*w11[0] + Gx1[15]*w11[1] + Gx1[24]*w11[2] + Gx1[33]*w11[3] + Gx1[42]*w11[4] + Gx1[51]*w11[5] + Gx1[60]*w11[6] + Gx1[69]*w11[7] + Gx1[78]*w11[8] + w12[6]; w13[7] = + Gx1[7]*w11[0] + Gx1[16]*w11[1] + Gx1[25]*w11[2] + Gx1[34]*w11[3] + Gx1[43]*w11[4] + Gx1[52]*w11[5] + Gx1[61]*w11[6] + Gx1[70]*w11[7] + Gx1[79]*w11[8] + w12[7]; w13[8] = + Gx1[8]*w11[0] + Gx1[17]*w11[1] + Gx1[26]*w11[2] + Gx1[35]*w11[3] + Gx1[44]*w11[4] + Gx1[53]*w11[5] + Gx1[62]*w11[6] + Gx1[71]*w11[7] + Gx1[80]*w11[8] + w12[8]; } void acado_macBTw1( real_t* const Gu1, real_t* const w11, real_t* const U1 ) { U1[0] += + Gu1[0]*w11[0] + Gu1[3]*w11[1] + Gu1[6]*w11[2] + Gu1[9]*w11[3] + Gu1[12]*w11[4] + Gu1[15]*w11[5] + Gu1[18]*w11[6] + Gu1[21]*w11[7] + Gu1[24]*w11[8]; U1[1] += + Gu1[1]*w11[0] + Gu1[4]*w11[1] + Gu1[7]*w11[2] + Gu1[10]*w11[3] + Gu1[13]*w11[4] + Gu1[16]*w11[5] + Gu1[19]*w11[6] + Gu1[22]*w11[7] + Gu1[25]*w11[8]; U1[2] += + Gu1[2]*w11[0] + Gu1[5]*w11[1] + Gu1[8]*w11[2] + Gu1[11]*w11[3] + Gu1[14]*w11[4] + Gu1[17]*w11[5] + Gu1[20]*w11[6] + Gu1[23]*w11[7] + Gu1[26]*w11[8]; } void acado_macS1TSbar( real_t* const Gu1, real_t* const w11, real_t* const U1 ) { U1[0] += + Gu1[0]*w11[0] + Gu1[3]*w11[1] + Gu1[6]*w11[2] + Gu1[9]*w11[3] + Gu1[12]*w11[4] + Gu1[15]*w11[5] + Gu1[18]*w11[6] + Gu1[21]*w11[7] + Gu1[24]*w11[8]; U1[1] += + Gu1[1]*w11[0] + Gu1[4]*w11[1] + Gu1[7]*w11[2] + Gu1[10]*w11[3] + Gu1[13]*w11[4] + Gu1[16]*w11[5] + Gu1[19]*w11[6] + Gu1[22]*w11[7] + Gu1[25]*w11[8]; U1[2] += + Gu1[2]*w11[0] + Gu1[5]*w11[1] + Gu1[8]*w11[2] + Gu1[11]*w11[3] + Gu1[14]*w11[4] + Gu1[17]*w11[5] + Gu1[20]*w11[6] + Gu1[23]*w11[7] + Gu1[26]*w11[8]; } void acado_macQSbarW2( real_t* const Q11, real_t* const w11, real_t* const w12, real_t* const w13 ) { w13[0] = + Q11[0]*w11[0] + Q11[1]*w11[1] + Q11[2]*w11[2] + Q11[3]*w11[3] + Q11[4]*w11[4] + Q11[5]*w11[5] + Q11[6]*w11[6] + Q11[7]*w11[7] + Q11[8]*w11[8] + w12[0]; w13[1] = + Q11[9]*w11[0] + Q11[10]*w11[1] + Q11[11]*w11[2] + Q11[12]*w11[3] + Q11[13]*w11[4] + Q11[14]*w11[5] + Q11[15]*w11[6] + Q11[16]*w11[7] + Q11[17]*w11[8] + w12[1]; w13[2] = + Q11[18]*w11[0] + Q11[19]*w11[1] + Q11[20]*w11[2] + Q11[21]*w11[3] + Q11[22]*w11[4] + Q11[23]*w11[5] + Q11[24]*w11[6] + Q11[25]*w11[7] + Q11[26]*w11[8] + w12[2]; w13[3] = + Q11[27]*w11[0] + Q11[28]*w11[1] + Q11[29]*w11[2] + Q11[30]*w11[3] + Q11[31]*w11[4] + Q11[32]*w11[5] + Q11[33]*w11[6] + Q11[34]*w11[7] + Q11[35]*w11[8] + w12[3]; w13[4] = + Q11[36]*w11[0] + Q11[37]*w11[1] + Q11[38]*w11[2] + Q11[39]*w11[3] + Q11[40]*w11[4] + Q11[41]*w11[5] + Q11[42]*w11[6] + Q11[43]*w11[7] + Q11[44]*w11[8] + w12[4]; w13[5] = + Q11[45]*w11[0] + Q11[46]*w11[1] + Q11[47]*w11[2] + Q11[48]*w11[3] + Q11[49]*w11[4] + Q11[50]*w11[5] + Q11[51]*w11[6] + Q11[52]*w11[7] + Q11[53]*w11[8] + w12[5]; w13[6] = + Q11[54]*w11[0] + Q11[55]*w11[1] + Q11[56]*w11[2] + Q11[57]*w11[3] + Q11[58]*w11[4] + Q11[59]*w11[5] + Q11[60]*w11[6] + Q11[61]*w11[7] + Q11[62]*w11[8] + w12[6]; w13[7] = + Q11[63]*w11[0] + Q11[64]*w11[1] + Q11[65]*w11[2] + Q11[66]*w11[3] + Q11[67]*w11[4] + Q11[68]*w11[5] + Q11[69]*w11[6] + Q11[70]*w11[7] + Q11[71]*w11[8] + w12[7]; w13[8] = + Q11[72]*w11[0] + Q11[73]*w11[1] + Q11[74]*w11[2] + Q11[75]*w11[3] + Q11[76]*w11[4] + Q11[77]*w11[5] + Q11[78]*w11[6] + Q11[79]*w11[7] + Q11[80]*w11[8] + w12[8]; } void acado_macASbar( real_t* const Gx1, real_t* const w11, real_t* const w12 ) { w12[0] += + Gx1[0]*w11[0] + Gx1[1]*w11[1] + Gx1[2]*w11[2] + Gx1[3]*w11[3] + Gx1[4]*w11[4] + Gx1[5]*w11[5] + Gx1[6]*w11[6] + Gx1[7]*w11[7] + Gx1[8]*w11[8]; w12[1] += + Gx1[9]*w11[0] + Gx1[10]*w11[1] + Gx1[11]*w11[2] + Gx1[12]*w11[3] + Gx1[13]*w11[4] + Gx1[14]*w11[5] + Gx1[15]*w11[6] + Gx1[16]*w11[7] + Gx1[17]*w11[8]; w12[2] += + Gx1[18]*w11[0] + Gx1[19]*w11[1] + Gx1[20]*w11[2] + Gx1[21]*w11[3] + Gx1[22]*w11[4] + Gx1[23]*w11[5] + Gx1[24]*w11[6] + Gx1[25]*w11[7] + Gx1[26]*w11[8]; w12[3] += + Gx1[27]*w11[0] + Gx1[28]*w11[1] + Gx1[29]*w11[2] + Gx1[30]*w11[3] + Gx1[31]*w11[4] + Gx1[32]*w11[5] + Gx1[33]*w11[6] + Gx1[34]*w11[7] + Gx1[35]*w11[8]; w12[4] += + Gx1[36]*w11[0] + Gx1[37]*w11[1] + Gx1[38]*w11[2] + Gx1[39]*w11[3] + Gx1[40]*w11[4] + Gx1[41]*w11[5] + Gx1[42]*w11[6] + Gx1[43]*w11[7] + Gx1[44]*w11[8]; w12[5] += + Gx1[45]*w11[0] + Gx1[46]*w11[1] + Gx1[47]*w11[2] + Gx1[48]*w11[3] + Gx1[49]*w11[4] + Gx1[50]*w11[5] + Gx1[51]*w11[6] + Gx1[52]*w11[7] + Gx1[53]*w11[8]; w12[6] += + Gx1[54]*w11[0] + Gx1[55]*w11[1] + Gx1[56]*w11[2] + Gx1[57]*w11[3] + Gx1[58]*w11[4] + Gx1[59]*w11[5] + Gx1[60]*w11[6] + Gx1[61]*w11[7] + Gx1[62]*w11[8]; w12[7] += + Gx1[63]*w11[0] + Gx1[64]*w11[1] + Gx1[65]*w11[2] + Gx1[66]*w11[3] + Gx1[67]*w11[4] + Gx1[68]*w11[5] + Gx1[69]*w11[6] + Gx1[70]*w11[7] + Gx1[71]*w11[8]; w12[8] += + Gx1[72]*w11[0] + Gx1[73]*w11[1] + Gx1[74]*w11[2] + Gx1[75]*w11[3] + Gx1[76]*w11[4] + Gx1[77]*w11[5] + Gx1[78]*w11[6] + Gx1[79]*w11[7] + Gx1[80]*w11[8]; } void acado_expansionStep( real_t* const Gx1, real_t* const Gu1, real_t* const U1, real_t* const w11, real_t* const w12 ) { w12[0] += + Gx1[0]*w11[0] + Gx1[1]*w11[1] + Gx1[2]*w11[2] + Gx1[3]*w11[3] + Gx1[4]*w11[4] + Gx1[5]*w11[5] + Gx1[6]*w11[6] + Gx1[7]*w11[7] + Gx1[8]*w11[8]; w12[1] += + Gx1[9]*w11[0] + Gx1[10]*w11[1] + Gx1[11]*w11[2] + Gx1[12]*w11[3] + Gx1[13]*w11[4] + Gx1[14]*w11[5] + Gx1[15]*w11[6] + Gx1[16]*w11[7] + Gx1[17]*w11[8]; w12[2] += + Gx1[18]*w11[0] + Gx1[19]*w11[1] + Gx1[20]*w11[2] + Gx1[21]*w11[3] + Gx1[22]*w11[4] + Gx1[23]*w11[5] + Gx1[24]*w11[6] + Gx1[25]*w11[7] + Gx1[26]*w11[8]; w12[3] += + Gx1[27]*w11[0] + Gx1[28]*w11[1] + Gx1[29]*w11[2] + Gx1[30]*w11[3] + Gx1[31]*w11[4] + Gx1[32]*w11[5] + Gx1[33]*w11[6] + Gx1[34]*w11[7] + Gx1[35]*w11[8]; w12[4] += + Gx1[36]*w11[0] + Gx1[37]*w11[1] + Gx1[38]*w11[2] + Gx1[39]*w11[3] + Gx1[40]*w11[4] + Gx1[41]*w11[5] + Gx1[42]*w11[6] + Gx1[43]*w11[7] + Gx1[44]*w11[8]; w12[5] += + Gx1[45]*w11[0] + Gx1[46]*w11[1] + Gx1[47]*w11[2] + Gx1[48]*w11[3] + Gx1[49]*w11[4] + Gx1[50]*w11[5] + Gx1[51]*w11[6] + Gx1[52]*w11[7] + Gx1[53]*w11[8]; w12[6] += + Gx1[54]*w11[0] + Gx1[55]*w11[1] + Gx1[56]*w11[2] + Gx1[57]*w11[3] + Gx1[58]*w11[4] + Gx1[59]*w11[5] + Gx1[60]*w11[6] + Gx1[61]*w11[7] + Gx1[62]*w11[8]; w12[7] += + Gx1[63]*w11[0] + Gx1[64]*w11[1] + Gx1[65]*w11[2] + Gx1[66]*w11[3] + Gx1[67]*w11[4] + Gx1[68]*w11[5] + Gx1[69]*w11[6] + Gx1[70]*w11[7] + Gx1[71]*w11[8]; w12[8] += + Gx1[72]*w11[0] + Gx1[73]*w11[1] + Gx1[74]*w11[2] + Gx1[75]*w11[3] + Gx1[76]*w11[4] + Gx1[77]*w11[5] + Gx1[78]*w11[6] + Gx1[79]*w11[7] + Gx1[80]*w11[8]; w12[0] += + Gu1[0]*U1[0] + Gu1[1]*U1[1] + Gu1[2]*U1[2]; w12[1] += + Gu1[3]*U1[0] + Gu1[4]*U1[1] + Gu1[5]*U1[2]; w12[2] += + Gu1[6]*U1[0] + Gu1[7]*U1[1] + Gu1[8]*U1[2]; w12[3] += + Gu1[9]*U1[0] + Gu1[10]*U1[1] + Gu1[11]*U1[2]; w12[4] += + Gu1[12]*U1[0] + Gu1[13]*U1[1] + Gu1[14]*U1[2]; w12[5] += + Gu1[15]*U1[0] + Gu1[16]*U1[1] + Gu1[17]*U1[2]; w12[6] += + Gu1[18]*U1[0] + Gu1[19]*U1[1] + Gu1[20]*U1[2]; w12[7] += + Gu1[21]*U1[0] + Gu1[22]*U1[1] + Gu1[23]*U1[2]; w12[8] += + Gu1[24]*U1[0] + Gu1[25]*U1[1] + Gu1[26]*U1[2]; } void acado_copyHTH( int iRow, int iCol ) { acadoWorkspace.H[(iRow * 180) + (iCol * 3)] = acadoWorkspace.H[(iCol * 180) + (iRow * 3)]; acadoWorkspace.H[(iRow * 180) + (iCol * 3 + 1)] = acadoWorkspace.H[(iCol * 180 + 60) + (iRow * 3)]; acadoWorkspace.H[(iRow * 180) + (iCol * 3 + 2)] = acadoWorkspace.H[(iCol * 180 + 120) + (iRow * 3)]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3)] = acadoWorkspace.H[(iCol * 180) + (iRow * 3 + 1)]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3 + 1)] = acadoWorkspace.H[(iCol * 180 + 60) + (iRow * 3 + 1)]; acadoWorkspace.H[(iRow * 180 + 60) + (iCol * 3 + 2)] = acadoWorkspace.H[(iCol * 180 + 120) + (iRow * 3 + 1)]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3)] = acadoWorkspace.H[(iCol * 180) + (iRow * 3 + 2)]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3 + 1)] = acadoWorkspace.H[(iCol * 180 + 60) + (iRow * 3 + 2)]; acadoWorkspace.H[(iRow * 180 + 120) + (iCol * 3 + 2)] = acadoWorkspace.H[(iCol * 180 + 120) + (iRow * 3 + 2)]; } void acado_multRDy( real_t* const R2, real_t* const Dy1, real_t* const RDy1 ) { RDy1[0] = + R2[0]*Dy1[0] + R2[1]*Dy1[1] + R2[2]*Dy1[2] + R2[3]*Dy1[3] + R2[4]*Dy1[4] + R2[5]*Dy1[5] + R2[6]*Dy1[6] + R2[7]*Dy1[7] + R2[8]*Dy1[8] + R2[9]*Dy1[9] + R2[10]*Dy1[10]; RDy1[1] = + R2[11]*Dy1[0] + R2[12]*Dy1[1] + R2[13]*Dy1[2] + R2[14]*Dy1[3] + R2[15]*Dy1[4] + R2[16]*Dy1[5] + R2[17]*Dy1[6] + R2[18]*Dy1[7] + R2[19]*Dy1[8] + R2[20]*Dy1[9] + R2[21]*Dy1[10]; RDy1[2] = + R2[22]*Dy1[0] + R2[23]*Dy1[1] + R2[24]*Dy1[2] + R2[25]*Dy1[3] + R2[26]*Dy1[4] + R2[27]*Dy1[5] + R2[28]*Dy1[6] + R2[29]*Dy1[7] + R2[30]*Dy1[8] + R2[31]*Dy1[9] + R2[32]*Dy1[10]; } void acado_multQDy( real_t* const Q2, real_t* const Dy1, real_t* const QDy1 ) { QDy1[0] = + Q2[0]*Dy1[0] + Q2[1]*Dy1[1] + Q2[2]*Dy1[2] + Q2[3]*Dy1[3] + Q2[4]*Dy1[4] + Q2[5]*Dy1[5] + Q2[6]*Dy1[6] + Q2[7]*Dy1[7] + Q2[8]*Dy1[8] + Q2[9]*Dy1[9] + Q2[10]*Dy1[10]; QDy1[1] = + Q2[11]*Dy1[0] + Q2[12]*Dy1[1] + Q2[13]*Dy1[2] + Q2[14]*Dy1[3] + Q2[15]*Dy1[4] + Q2[16]*Dy1[5] + Q2[17]*Dy1[6] + Q2[18]*Dy1[7] + Q2[19]*Dy1[8] + Q2[20]*Dy1[9] + Q2[21]*Dy1[10]; QDy1[2] = + Q2[22]*Dy1[0] + Q2[23]*Dy1[1] + Q2[24]*Dy1[2] + Q2[25]*Dy1[3] + Q2[26]*Dy1[4] + Q2[27]*Dy1[5] + Q2[28]*Dy1[6] + Q2[29]*Dy1[7] + Q2[30]*Dy1[8] + Q2[31]*Dy1[9] + Q2[32]*Dy1[10]; QDy1[3] = + Q2[33]*Dy1[0] + Q2[34]*Dy1[1] + Q2[35]*Dy1[2] + Q2[36]*Dy1[3] + Q2[37]*Dy1[4] + Q2[38]*Dy1[5] + Q2[39]*Dy1[6] + Q2[40]*Dy1[7] + Q2[41]*Dy1[8] + Q2[42]*Dy1[9] + Q2[43]*Dy1[10]; QDy1[4] = + Q2[44]*Dy1[0] + Q2[45]*Dy1[1] + Q2[46]*Dy1[2] + Q2[47]*Dy1[3] + Q2[48]*Dy1[4] + Q2[49]*Dy1[5] + Q2[50]*Dy1[6] + Q2[51]*Dy1[7] + Q2[52]*Dy1[8] + Q2[53]*Dy1[9] + Q2[54]*Dy1[10]; QDy1[5] = + Q2[55]*Dy1[0] + Q2[56]*Dy1[1] + Q2[57]*Dy1[2] + Q2[58]*Dy1[3] + Q2[59]*Dy1[4] + Q2[60]*Dy1[5] + Q2[61]*Dy1[6] + Q2[62]*Dy1[7] + Q2[63]*Dy1[8] + Q2[64]*Dy1[9] + Q2[65]*Dy1[10]; QDy1[6] = + Q2[66]*Dy1[0] + Q2[67]*Dy1[1] + Q2[68]*Dy1[2] + Q2[69]*Dy1[3] + Q2[70]*Dy1[4] + Q2[71]*Dy1[5] + Q2[72]*Dy1[6] + Q2[73]*Dy1[7] + Q2[74]*Dy1[8] + Q2[75]*Dy1[9] + Q2[76]*Dy1[10]; QDy1[7] = + Q2[77]*Dy1[0] + Q2[78]*Dy1[1] + Q2[79]*Dy1[2] + Q2[80]*Dy1[3] + Q2[81]*Dy1[4] + Q2[82]*Dy1[5] + Q2[83]*Dy1[6] + Q2[84]*Dy1[7] + Q2[85]*Dy1[8] + Q2[86]*Dy1[9] + Q2[87]*Dy1[10]; QDy1[8] = + Q2[88]*Dy1[0] + Q2[89]*Dy1[1] + Q2[90]*Dy1[2] + Q2[91]*Dy1[3] + Q2[92]*Dy1[4] + Q2[93]*Dy1[5] + Q2[94]*Dy1[6] + Q2[95]*Dy1[7] + Q2[96]*Dy1[8] + Q2[97]*Dy1[9] + Q2[98]*Dy1[10]; } void acado_condensePrep( ) { int lRun1; int lRun2; int lRun3; for (lRun2 = 0; lRun2 < 20; ++lRun2) { lRun3 = ((lRun2) * (lRun2 * -1 + 41)) / (2); acado_moveGuE( &(acadoWorkspace.evGu[ lRun2 * 27 ]), &(acadoWorkspace.E[ lRun3 * 27 ]) ); for (lRun1 = 1; lRun1 < lRun2 * -1 + 20; ++lRun1) { acado_multGxGu( &(acadoWorkspace.evGx[ ((((lRun2) + (lRun1)) * (9)) * (9)) + (0) ]), &(acadoWorkspace.E[ (((((lRun3) + (lRun1)) - (1)) * (9)) * (3)) + (0) ]), &(acadoWorkspace.E[ ((((lRun3) + (lRun1)) * (9)) * (3)) + (0) ]) ); } acado_multGxGu( acadoWorkspace.QN1, &(acadoWorkspace.E[ ((((((lRun3) - (lRun2)) + (20)) - (1)) * (9)) * (3)) + (0) ]), acadoWorkspace.W1 ); for (lRun1 = 19; lRun2 < lRun1; --lRun1) { acado_multBTW1( &(acadoWorkspace.evGu[ lRun1 * 27 ]), acadoWorkspace.W1, lRun1, lRun2 ); acado_mac_S1T_E( &(acadoWorkspace.S1[ lRun1 * 27 ]), &(acadoWorkspace.E[ ((((((lRun3) + (lRun1)) - (lRun2)) - (1)) * (9)) * (3)) + (0) ]), lRun1, lRun2 ); acado_multGxTGu( &(acadoWorkspace.evGx[ lRun1 * 81 ]), acadoWorkspace.W1, acadoWorkspace.W2 ); acado_multQEW2( &(acadoWorkspace.Q1[ lRun1 * 81 ]), &(acadoWorkspace.E[ ((((((lRun3) + (lRun1)) - (lRun2)) - (1)) * (9)) * (3)) + (0) ]), acadoWorkspace.W2, acadoWorkspace.W1 ); } acado_multBTW1_R1( &(acadoWorkspace.R1[ lRun2 * 9 ]), &(acadoWorkspace.evGu[ lRun2 * 27 ]), acadoWorkspace.W1, lRun2 ); } acado_copyHTH( 0, 1 ); acado_copyHTH( 0, 2 ); acado_copyHTH( 1, 2 ); acado_copyHTH( 0, 3 ); acado_copyHTH( 1, 3 ); acado_copyHTH( 2, 3 ); acado_copyHTH( 0, 4 ); acado_copyHTH( 1, 4 ); acado_copyHTH( 2, 4 ); acado_copyHTH( 3, 4 ); acado_copyHTH( 0, 5 ); acado_copyHTH( 1, 5 ); acado_copyHTH( 2, 5 ); acado_copyHTH( 3, 5 ); acado_copyHTH( 4, 5 ); acado_copyHTH( 0, 6 ); acado_copyHTH( 1, 6 ); acado_copyHTH( 2, 6 ); acado_copyHTH( 3, 6 ); acado_copyHTH( 4, 6 ); acado_copyHTH( 5, 6 ); acado_copyHTH( 0, 7 ); acado_copyHTH( 1, 7 ); acado_copyHTH( 2, 7 ); acado_copyHTH( 3, 7 ); acado_copyHTH( 4, 7 ); acado_copyHTH( 5, 7 ); acado_copyHTH( 6, 7 ); acado_copyHTH( 0, 8 ); acado_copyHTH( 1, 8 ); acado_copyHTH( 2, 8 ); acado_copyHTH( 3, 8 ); acado_copyHTH( 4, 8 ); acado_copyHTH( 5, 8 ); acado_copyHTH( 6, 8 ); acado_copyHTH( 7, 8 ); acado_copyHTH( 0, 9 ); acado_copyHTH( 1, 9 ); acado_copyHTH( 2, 9 ); acado_copyHTH( 3, 9 ); acado_copyHTH( 4, 9 ); acado_copyHTH( 5, 9 ); acado_copyHTH( 6, 9 ); acado_copyHTH( 7, 9 ); acado_copyHTH( 8, 9 ); acado_copyHTH( 0, 10 ); acado_copyHTH( 1, 10 ); acado_copyHTH( 2, 10 ); acado_copyHTH( 3, 10 ); acado_copyHTH( 4, 10 ); acado_copyHTH( 5, 10 ); acado_copyHTH( 6, 10 ); acado_copyHTH( 7, 10 ); acado_copyHTH( 8, 10 ); acado_copyHTH( 9, 10 ); acado_copyHTH( 0, 11 ); acado_copyHTH( 1, 11 ); acado_copyHTH( 2, 11 ); acado_copyHTH( 3, 11 ); acado_copyHTH( 4, 11 ); acado_copyHTH( 5, 11 ); acado_copyHTH( 6, 11 ); acado_copyHTH( 7, 11 ); acado_copyHTH( 8, 11 ); acado_copyHTH( 9, 11 ); acado_copyHTH( 10, 11 ); acado_copyHTH( 0, 12 ); acado_copyHTH( 1, 12 ); acado_copyHTH( 2, 12 ); acado_copyHTH( 3, 12 ); acado_copyHTH( 4, 12 ); acado_copyHTH( 5, 12 ); acado_copyHTH( 6, 12 ); acado_copyHTH( 7, 12 ); acado_copyHTH( 8, 12 ); acado_copyHTH( 9, 12 ); acado_copyHTH( 10, 12 ); acado_copyHTH( 11, 12 ); acado_copyHTH( 0, 13 ); acado_copyHTH( 1, 13 ); acado_copyHTH( 2, 13 ); acado_copyHTH( 3, 13 ); acado_copyHTH( 4, 13 ); acado_copyHTH( 5, 13 ); acado_copyHTH( 6, 13 ); acado_copyHTH( 7, 13 ); acado_copyHTH( 8, 13 ); acado_copyHTH( 9, 13 ); acado_copyHTH( 10, 13 ); acado_copyHTH( 11, 13 ); acado_copyHTH( 12, 13 ); acado_copyHTH( 0, 14 ); acado_copyHTH( 1, 14 ); acado_copyHTH( 2, 14 ); acado_copyHTH( 3, 14 ); acado_copyHTH( 4, 14 ); acado_copyHTH( 5, 14 ); acado_copyHTH( 6, 14 ); acado_copyHTH( 7, 14 ); acado_copyHTH( 8, 14 ); acado_copyHTH( 9, 14 ); acado_copyHTH( 10, 14 ); acado_copyHTH( 11, 14 ); acado_copyHTH( 12, 14 ); acado_copyHTH( 13, 14 ); acado_copyHTH( 0, 15 ); acado_copyHTH( 1, 15 ); acado_copyHTH( 2, 15 ); acado_copyHTH( 3, 15 ); acado_copyHTH( 4, 15 ); acado_copyHTH( 5, 15 ); acado_copyHTH( 6, 15 ); acado_copyHTH( 7, 15 ); acado_copyHTH( 8, 15 ); acado_copyHTH( 9, 15 ); acado_copyHTH( 10, 15 ); acado_copyHTH( 11, 15 ); acado_copyHTH( 12, 15 ); acado_copyHTH( 13, 15 ); acado_copyHTH( 14, 15 ); acado_copyHTH( 0, 16 ); acado_copyHTH( 1, 16 ); acado_copyHTH( 2, 16 ); acado_copyHTH( 3, 16 ); acado_copyHTH( 4, 16 ); acado_copyHTH( 5, 16 ); acado_copyHTH( 6, 16 ); acado_copyHTH( 7, 16 ); acado_copyHTH( 8, 16 ); acado_copyHTH( 9, 16 ); acado_copyHTH( 10, 16 ); acado_copyHTH( 11, 16 ); acado_copyHTH( 12, 16 ); acado_copyHTH( 13, 16 ); acado_copyHTH( 14, 16 ); acado_copyHTH( 15, 16 ); acado_copyHTH( 0, 17 ); acado_copyHTH( 1, 17 ); acado_copyHTH( 2, 17 ); acado_copyHTH( 3, 17 ); acado_copyHTH( 4, 17 ); acado_copyHTH( 5, 17 ); acado_copyHTH( 6, 17 ); acado_copyHTH( 7, 17 ); acado_copyHTH( 8, 17 ); acado_copyHTH( 9, 17 ); acado_copyHTH( 10, 17 ); acado_copyHTH( 11, 17 ); acado_copyHTH( 12, 17 ); acado_copyHTH( 13, 17 ); acado_copyHTH( 14, 17 ); acado_copyHTH( 15, 17 ); acado_copyHTH( 16, 17 ); acado_copyHTH( 0, 18 ); acado_copyHTH( 1, 18 ); acado_copyHTH( 2, 18 ); acado_copyHTH( 3, 18 ); acado_copyHTH( 4, 18 ); acado_copyHTH( 5, 18 ); acado_copyHTH( 6, 18 ); acado_copyHTH( 7, 18 ); acado_copyHTH( 8, 18 ); acado_copyHTH( 9, 18 ); acado_copyHTH( 10, 18 ); acado_copyHTH( 11, 18 ); acado_copyHTH( 12, 18 ); acado_copyHTH( 13, 18 ); acado_copyHTH( 14, 18 ); acado_copyHTH( 15, 18 ); acado_copyHTH( 16, 18 ); acado_copyHTH( 17, 18 ); acado_copyHTH( 0, 19 ); acado_copyHTH( 1, 19 ); acado_copyHTH( 2, 19 ); acado_copyHTH( 3, 19 ); acado_copyHTH( 4, 19 ); acado_copyHTH( 5, 19 ); acado_copyHTH( 6, 19 ); acado_copyHTH( 7, 19 ); acado_copyHTH( 8, 19 ); acado_copyHTH( 9, 19 ); acado_copyHTH( 10, 19 ); acado_copyHTH( 11, 19 ); acado_copyHTH( 12, 19 ); acado_copyHTH( 13, 19 ); acado_copyHTH( 14, 19 ); acado_copyHTH( 15, 19 ); acado_copyHTH( 16, 19 ); acado_copyHTH( 17, 19 ); acado_copyHTH( 18, 19 ); for (lRun1 = 0; lRun1 < 180; ++lRun1) acadoWorkspace.sbar[lRun1 + 9] = acadoWorkspace.d[lRun1]; } void acado_condenseFdb( ) { int lRun1; acadoWorkspace.Dx0[0] = acadoVariables.x0[0] - acadoVariables.x[0]; acadoWorkspace.Dx0[1] = acadoVariables.x0[1] - acadoVariables.x[1]; acadoWorkspace.Dx0[2] = acadoVariables.x0[2] - acadoVariables.x[2]; acadoWorkspace.Dx0[3] = acadoVariables.x0[3] - acadoVariables.x[3]; acadoWorkspace.Dx0[4] = acadoVariables.x0[4] - acadoVariables.x[4]; acadoWorkspace.Dx0[5] = acadoVariables.x0[5] - acadoVariables.x[5]; acadoWorkspace.Dx0[6] = acadoVariables.x0[6] - acadoVariables.x[6]; acadoWorkspace.Dx0[7] = acadoVariables.x0[7] - acadoVariables.x[7]; acadoWorkspace.Dx0[8] = acadoVariables.x0[8] - acadoVariables.x[8]; for (lRun1 = 0; lRun1 < 220; ++lRun1) acadoWorkspace.Dy[lRun1] -= acadoVariables.y[lRun1]; acadoWorkspace.DyN[0] -= acadoVariables.yN[0]; acadoWorkspace.DyN[1] -= acadoVariables.yN[1]; acadoWorkspace.DyN[2] -= acadoVariables.yN[2]; acadoWorkspace.DyN[3] -= acadoVariables.yN[3]; acadoWorkspace.DyN[4] -= acadoVariables.yN[4]; acadoWorkspace.DyN[5] -= acadoVariables.yN[5]; acado_multRDy( acadoWorkspace.R2, acadoWorkspace.Dy, acadoWorkspace.g ); acado_multRDy( &(acadoWorkspace.R2[ 33 ]), &(acadoWorkspace.Dy[ 11 ]), &(acadoWorkspace.g[ 3 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 66 ]), &(acadoWorkspace.Dy[ 22 ]), &(acadoWorkspace.g[ 6 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 99 ]), &(acadoWorkspace.Dy[ 33 ]), &(acadoWorkspace.g[ 9 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 132 ]), &(acadoWorkspace.Dy[ 44 ]), &(acadoWorkspace.g[ 12 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 165 ]), &(acadoWorkspace.Dy[ 55 ]), &(acadoWorkspace.g[ 15 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 198 ]), &(acadoWorkspace.Dy[ 66 ]), &(acadoWorkspace.g[ 18 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 231 ]), &(acadoWorkspace.Dy[ 77 ]), &(acadoWorkspace.g[ 21 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 264 ]), &(acadoWorkspace.Dy[ 88 ]), &(acadoWorkspace.g[ 24 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 297 ]), &(acadoWorkspace.Dy[ 99 ]), &(acadoWorkspace.g[ 27 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 330 ]), &(acadoWorkspace.Dy[ 110 ]), &(acadoWorkspace.g[ 30 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 363 ]), &(acadoWorkspace.Dy[ 121 ]), &(acadoWorkspace.g[ 33 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 396 ]), &(acadoWorkspace.Dy[ 132 ]), &(acadoWorkspace.g[ 36 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 429 ]), &(acadoWorkspace.Dy[ 143 ]), &(acadoWorkspace.g[ 39 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 462 ]), &(acadoWorkspace.Dy[ 154 ]), &(acadoWorkspace.g[ 42 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 495 ]), &(acadoWorkspace.Dy[ 165 ]), &(acadoWorkspace.g[ 45 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 528 ]), &(acadoWorkspace.Dy[ 176 ]), &(acadoWorkspace.g[ 48 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 561 ]), &(acadoWorkspace.Dy[ 187 ]), &(acadoWorkspace.g[ 51 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 594 ]), &(acadoWorkspace.Dy[ 198 ]), &(acadoWorkspace.g[ 54 ]) ); acado_multRDy( &(acadoWorkspace.R2[ 627 ]), &(acadoWorkspace.Dy[ 209 ]), &(acadoWorkspace.g[ 57 ]) ); acado_multQDy( acadoWorkspace.Q2, acadoWorkspace.Dy, acadoWorkspace.QDy ); acado_multQDy( &(acadoWorkspace.Q2[ 99 ]), &(acadoWorkspace.Dy[ 11 ]), &(acadoWorkspace.QDy[ 9 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 198 ]), &(acadoWorkspace.Dy[ 22 ]), &(acadoWorkspace.QDy[ 18 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 297 ]), &(acadoWorkspace.Dy[ 33 ]), &(acadoWorkspace.QDy[ 27 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 396 ]), &(acadoWorkspace.Dy[ 44 ]), &(acadoWorkspace.QDy[ 36 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 495 ]), &(acadoWorkspace.Dy[ 55 ]), &(acadoWorkspace.QDy[ 45 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 594 ]), &(acadoWorkspace.Dy[ 66 ]), &(acadoWorkspace.QDy[ 54 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 693 ]), &(acadoWorkspace.Dy[ 77 ]), &(acadoWorkspace.QDy[ 63 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 792 ]), &(acadoWorkspace.Dy[ 88 ]), &(acadoWorkspace.QDy[ 72 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 891 ]), &(acadoWorkspace.Dy[ 99 ]), &(acadoWorkspace.QDy[ 81 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 990 ]), &(acadoWorkspace.Dy[ 110 ]), &(acadoWorkspace.QDy[ 90 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1089 ]), &(acadoWorkspace.Dy[ 121 ]), &(acadoWorkspace.QDy[ 99 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1188 ]), &(acadoWorkspace.Dy[ 132 ]), &(acadoWorkspace.QDy[ 108 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1287 ]), &(acadoWorkspace.Dy[ 143 ]), &(acadoWorkspace.QDy[ 117 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1386 ]), &(acadoWorkspace.Dy[ 154 ]), &(acadoWorkspace.QDy[ 126 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1485 ]), &(acadoWorkspace.Dy[ 165 ]), &(acadoWorkspace.QDy[ 135 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1584 ]), &(acadoWorkspace.Dy[ 176 ]), &(acadoWorkspace.QDy[ 144 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1683 ]), &(acadoWorkspace.Dy[ 187 ]), &(acadoWorkspace.QDy[ 153 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1782 ]), &(acadoWorkspace.Dy[ 198 ]), &(acadoWorkspace.QDy[ 162 ]) ); acado_multQDy( &(acadoWorkspace.Q2[ 1881 ]), &(acadoWorkspace.Dy[ 209 ]), &(acadoWorkspace.QDy[ 171 ]) ); acadoWorkspace.QDy[180] = + acadoWorkspace.QN2[0]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[1]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[2]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[3]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[4]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[5]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[181] = + acadoWorkspace.QN2[6]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[7]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[8]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[9]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[10]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[11]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[182] = + acadoWorkspace.QN2[12]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[13]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[14]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[15]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[16]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[17]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[183] = + acadoWorkspace.QN2[18]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[19]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[20]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[21]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[22]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[23]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[184] = + acadoWorkspace.QN2[24]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[25]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[26]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[27]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[28]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[29]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[185] = + acadoWorkspace.QN2[30]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[31]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[32]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[33]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[34]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[35]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[186] = + acadoWorkspace.QN2[36]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[37]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[38]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[39]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[40]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[41]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[187] = + acadoWorkspace.QN2[42]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[43]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[44]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[45]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[46]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[47]*acadoWorkspace.DyN[5]; acadoWorkspace.QDy[188] = + acadoWorkspace.QN2[48]*acadoWorkspace.DyN[0] + acadoWorkspace.QN2[49]*acadoWorkspace.DyN[1] + acadoWorkspace.QN2[50]*acadoWorkspace.DyN[2] + acadoWorkspace.QN2[51]*acadoWorkspace.DyN[3] + acadoWorkspace.QN2[52]*acadoWorkspace.DyN[4] + acadoWorkspace.QN2[53]*acadoWorkspace.DyN[5]; acadoWorkspace.sbar[0] = acadoWorkspace.Dx0[0]; acadoWorkspace.sbar[1] = acadoWorkspace.Dx0[1]; acadoWorkspace.sbar[2] = acadoWorkspace.Dx0[2]; acadoWorkspace.sbar[3] = acadoWorkspace.Dx0[3]; acadoWorkspace.sbar[4] = acadoWorkspace.Dx0[4]; acadoWorkspace.sbar[5] = acadoWorkspace.Dx0[5]; acadoWorkspace.sbar[6] = acadoWorkspace.Dx0[6]; acadoWorkspace.sbar[7] = acadoWorkspace.Dx0[7]; acadoWorkspace.sbar[8] = acadoWorkspace.Dx0[8]; acado_macASbar( acadoWorkspace.evGx, acadoWorkspace.sbar, &(acadoWorkspace.sbar[ 9 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 81 ]), &(acadoWorkspace.sbar[ 9 ]), &(acadoWorkspace.sbar[ 18 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 162 ]), &(acadoWorkspace.sbar[ 18 ]), &(acadoWorkspace.sbar[ 27 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 243 ]), &(acadoWorkspace.sbar[ 27 ]), &(acadoWorkspace.sbar[ 36 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 324 ]), &(acadoWorkspace.sbar[ 36 ]), &(acadoWorkspace.sbar[ 45 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 405 ]), &(acadoWorkspace.sbar[ 45 ]), &(acadoWorkspace.sbar[ 54 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 486 ]), &(acadoWorkspace.sbar[ 54 ]), &(acadoWorkspace.sbar[ 63 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 567 ]), &(acadoWorkspace.sbar[ 63 ]), &(acadoWorkspace.sbar[ 72 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 648 ]), &(acadoWorkspace.sbar[ 72 ]), &(acadoWorkspace.sbar[ 81 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 729 ]), &(acadoWorkspace.sbar[ 81 ]), &(acadoWorkspace.sbar[ 90 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 810 ]), &(acadoWorkspace.sbar[ 90 ]), &(acadoWorkspace.sbar[ 99 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 891 ]), &(acadoWorkspace.sbar[ 99 ]), &(acadoWorkspace.sbar[ 108 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 972 ]), &(acadoWorkspace.sbar[ 108 ]), &(acadoWorkspace.sbar[ 117 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 1053 ]), &(acadoWorkspace.sbar[ 117 ]), &(acadoWorkspace.sbar[ 126 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 1134 ]), &(acadoWorkspace.sbar[ 126 ]), &(acadoWorkspace.sbar[ 135 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 1215 ]), &(acadoWorkspace.sbar[ 135 ]), &(acadoWorkspace.sbar[ 144 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 1296 ]), &(acadoWorkspace.sbar[ 144 ]), &(acadoWorkspace.sbar[ 153 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 1377 ]), &(acadoWorkspace.sbar[ 153 ]), &(acadoWorkspace.sbar[ 162 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 1458 ]), &(acadoWorkspace.sbar[ 162 ]), &(acadoWorkspace.sbar[ 171 ]) ); acado_macASbar( &(acadoWorkspace.evGx[ 1539 ]), &(acadoWorkspace.sbar[ 171 ]), &(acadoWorkspace.sbar[ 180 ]) ); acadoWorkspace.w1[0] = + acadoWorkspace.QN1[0]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[1]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[2]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[3]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[4]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[5]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[6]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[7]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[8]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[180]; acadoWorkspace.w1[1] = + acadoWorkspace.QN1[9]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[10]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[11]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[12]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[13]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[14]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[15]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[16]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[17]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[181]; acadoWorkspace.w1[2] = + acadoWorkspace.QN1[18]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[19]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[20]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[21]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[22]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[23]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[24]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[25]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[26]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[182]; acadoWorkspace.w1[3] = + acadoWorkspace.QN1[27]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[28]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[29]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[30]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[31]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[32]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[33]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[34]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[35]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[183]; acadoWorkspace.w1[4] = + acadoWorkspace.QN1[36]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[37]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[38]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[39]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[40]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[41]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[42]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[43]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[44]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[184]; acadoWorkspace.w1[5] = + acadoWorkspace.QN1[45]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[46]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[47]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[48]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[49]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[50]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[51]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[52]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[53]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[185]; acadoWorkspace.w1[6] = + acadoWorkspace.QN1[54]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[55]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[56]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[57]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[58]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[59]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[60]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[61]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[62]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[186]; acadoWorkspace.w1[7] = + acadoWorkspace.QN1[63]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[64]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[65]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[66]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[67]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[68]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[69]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[70]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[71]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[187]; acadoWorkspace.w1[8] = + acadoWorkspace.QN1[72]*acadoWorkspace.sbar[180] + acadoWorkspace.QN1[73]*acadoWorkspace.sbar[181] + acadoWorkspace.QN1[74]*acadoWorkspace.sbar[182] + acadoWorkspace.QN1[75]*acadoWorkspace.sbar[183] + acadoWorkspace.QN1[76]*acadoWorkspace.sbar[184] + acadoWorkspace.QN1[77]*acadoWorkspace.sbar[185] + acadoWorkspace.QN1[78]*acadoWorkspace.sbar[186] + acadoWorkspace.QN1[79]*acadoWorkspace.sbar[187] + acadoWorkspace.QN1[80]*acadoWorkspace.sbar[188] + acadoWorkspace.QDy[188]; acado_macBTw1( &(acadoWorkspace.evGu[ 513 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 57 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 513 ]), &(acadoWorkspace.sbar[ 171 ]), &(acadoWorkspace.g[ 57 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 1539 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 171 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 1539 ]), &(acadoWorkspace.sbar[ 171 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 486 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 54 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 486 ]), &(acadoWorkspace.sbar[ 162 ]), &(acadoWorkspace.g[ 54 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 1458 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 162 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 1458 ]), &(acadoWorkspace.sbar[ 162 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 459 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 51 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 459 ]), &(acadoWorkspace.sbar[ 153 ]), &(acadoWorkspace.g[ 51 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 1377 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 153 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 1377 ]), &(acadoWorkspace.sbar[ 153 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 432 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 48 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 432 ]), &(acadoWorkspace.sbar[ 144 ]), &(acadoWorkspace.g[ 48 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 1296 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 144 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 1296 ]), &(acadoWorkspace.sbar[ 144 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 405 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 45 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 405 ]), &(acadoWorkspace.sbar[ 135 ]), &(acadoWorkspace.g[ 45 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 1215 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 135 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 1215 ]), &(acadoWorkspace.sbar[ 135 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 378 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 42 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 378 ]), &(acadoWorkspace.sbar[ 126 ]), &(acadoWorkspace.g[ 42 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 1134 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 126 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 1134 ]), &(acadoWorkspace.sbar[ 126 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 351 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 39 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 351 ]), &(acadoWorkspace.sbar[ 117 ]), &(acadoWorkspace.g[ 39 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 1053 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 117 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 1053 ]), &(acadoWorkspace.sbar[ 117 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 324 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 36 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 324 ]), &(acadoWorkspace.sbar[ 108 ]), &(acadoWorkspace.g[ 36 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 972 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 108 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 972 ]), &(acadoWorkspace.sbar[ 108 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 297 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 33 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 297 ]), &(acadoWorkspace.sbar[ 99 ]), &(acadoWorkspace.g[ 33 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 891 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 99 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 891 ]), &(acadoWorkspace.sbar[ 99 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 270 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 30 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 270 ]), &(acadoWorkspace.sbar[ 90 ]), &(acadoWorkspace.g[ 30 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 810 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 90 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 810 ]), &(acadoWorkspace.sbar[ 90 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 243 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 27 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 243 ]), &(acadoWorkspace.sbar[ 81 ]), &(acadoWorkspace.g[ 27 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 729 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 81 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 729 ]), &(acadoWorkspace.sbar[ 81 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 216 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 24 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 216 ]), &(acadoWorkspace.sbar[ 72 ]), &(acadoWorkspace.g[ 24 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 648 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 72 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 648 ]), &(acadoWorkspace.sbar[ 72 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 189 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 21 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 189 ]), &(acadoWorkspace.sbar[ 63 ]), &(acadoWorkspace.g[ 21 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 567 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 63 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 567 ]), &(acadoWorkspace.sbar[ 63 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 162 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 18 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 162 ]), &(acadoWorkspace.sbar[ 54 ]), &(acadoWorkspace.g[ 18 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 486 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 54 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 486 ]), &(acadoWorkspace.sbar[ 54 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 135 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 15 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 135 ]), &(acadoWorkspace.sbar[ 45 ]), &(acadoWorkspace.g[ 15 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 405 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 45 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 405 ]), &(acadoWorkspace.sbar[ 45 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 108 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 12 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 108 ]), &(acadoWorkspace.sbar[ 36 ]), &(acadoWorkspace.g[ 12 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 324 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 36 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 324 ]), &(acadoWorkspace.sbar[ 36 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 81 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 9 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 81 ]), &(acadoWorkspace.sbar[ 27 ]), &(acadoWorkspace.g[ 9 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 243 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 27 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 243 ]), &(acadoWorkspace.sbar[ 27 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 54 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 6 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 54 ]), &(acadoWorkspace.sbar[ 18 ]), &(acadoWorkspace.g[ 6 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 162 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 18 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 162 ]), &(acadoWorkspace.sbar[ 18 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( &(acadoWorkspace.evGu[ 27 ]), acadoWorkspace.w1, &(acadoWorkspace.g[ 3 ]) ); acado_macS1TSbar( &(acadoWorkspace.S1[ 27 ]), &(acadoWorkspace.sbar[ 9 ]), &(acadoWorkspace.g[ 3 ]) ); acado_macATw1QDy( &(acadoWorkspace.evGx[ 81 ]), acadoWorkspace.w1, &(acadoWorkspace.QDy[ 9 ]), acadoWorkspace.w2 ); acado_macQSbarW2( &(acadoWorkspace.Q1[ 81 ]), &(acadoWorkspace.sbar[ 9 ]), acadoWorkspace.w2, acadoWorkspace.w1 ); acado_macBTw1( acadoWorkspace.evGu, acadoWorkspace.w1, acadoWorkspace.g ); acado_macS1TSbar( acadoWorkspace.S1, acadoWorkspace.sbar, acadoWorkspace.g ); acadoWorkspace.lb[0] = acadoVariables.lbValues[0] - acadoVariables.u[0]; acadoWorkspace.lb[1] = acadoVariables.lbValues[1] - acadoVariables.u[1]; acadoWorkspace.lb[2] = acadoVariables.lbValues[2] - acadoVariables.u[2]; acadoWorkspace.lb[3] = acadoVariables.lbValues[3] - acadoVariables.u[3]; acadoWorkspace.lb[4] = acadoVariables.lbValues[4] - acadoVariables.u[4]; acadoWorkspace.lb[5] = acadoVariables.lbValues[5] - acadoVariables.u[5]; acadoWorkspace.lb[6] = acadoVariables.lbValues[6] - acadoVariables.u[6]; acadoWorkspace.lb[7] = acadoVariables.lbValues[7] - acadoVariables.u[7]; acadoWorkspace.lb[8] = acadoVariables.lbValues[8] - acadoVariables.u[8]; acadoWorkspace.lb[9] = acadoVariables.lbValues[9] - acadoVariables.u[9]; acadoWorkspace.lb[10] = acadoVariables.lbValues[10] - acadoVariables.u[10]; acadoWorkspace.lb[11] = acadoVariables.lbValues[11] - acadoVariables.u[11]; acadoWorkspace.lb[12] = acadoVariables.lbValues[12] - acadoVariables.u[12]; acadoWorkspace.lb[13] = acadoVariables.lbValues[13] - acadoVariables.u[13]; acadoWorkspace.lb[14] = acadoVariables.lbValues[14] - acadoVariables.u[14]; acadoWorkspace.lb[15] = acadoVariables.lbValues[15] - acadoVariables.u[15]; acadoWorkspace.lb[16] = acadoVariables.lbValues[16] - acadoVariables.u[16]; acadoWorkspace.lb[17] = acadoVariables.lbValues[17] - acadoVariables.u[17]; acadoWorkspace.lb[18] = acadoVariables.lbValues[18] - acadoVariables.u[18]; acadoWorkspace.lb[19] = acadoVariables.lbValues[19] - acadoVariables.u[19]; acadoWorkspace.lb[20] = acadoVariables.lbValues[20] - acadoVariables.u[20]; acadoWorkspace.lb[21] = acadoVariables.lbValues[21] - acadoVariables.u[21]; acadoWorkspace.lb[22] = acadoVariables.lbValues[22] - acadoVariables.u[22]; acadoWorkspace.lb[23] = acadoVariables.lbValues[23] - acadoVariables.u[23]; acadoWorkspace.lb[24] = acadoVariables.lbValues[24] - acadoVariables.u[24]; acadoWorkspace.lb[25] = acadoVariables.lbValues[25] - acadoVariables.u[25]; acadoWorkspace.lb[26] = acadoVariables.lbValues[26] - acadoVariables.u[26]; acadoWorkspace.lb[27] = acadoVariables.lbValues[27] - acadoVariables.u[27]; acadoWorkspace.lb[28] = acadoVariables.lbValues[28] - acadoVariables.u[28]; acadoWorkspace.lb[29] = acadoVariables.lbValues[29] - acadoVariables.u[29]; acadoWorkspace.lb[30] = acadoVariables.lbValues[30] - acadoVariables.u[30]; acadoWorkspace.lb[31] = acadoVariables.lbValues[31] - acadoVariables.u[31]; acadoWorkspace.lb[32] = acadoVariables.lbValues[32] - acadoVariables.u[32]; acadoWorkspace.lb[33] = acadoVariables.lbValues[33] - acadoVariables.u[33]; acadoWorkspace.lb[34] = acadoVariables.lbValues[34] - acadoVariables.u[34]; acadoWorkspace.lb[35] = acadoVariables.lbValues[35] - acadoVariables.u[35]; acadoWorkspace.lb[36] = acadoVariables.lbValues[36] - acadoVariables.u[36]; acadoWorkspace.lb[37] = acadoVariables.lbValues[37] - acadoVariables.u[37]; acadoWorkspace.lb[38] = acadoVariables.lbValues[38] - acadoVariables.u[38]; acadoWorkspace.lb[39] = acadoVariables.lbValues[39] - acadoVariables.u[39]; acadoWorkspace.lb[40] = acadoVariables.lbValues[40] - acadoVariables.u[40]; acadoWorkspace.lb[41] = acadoVariables.lbValues[41] - acadoVariables.u[41]; acadoWorkspace.lb[42] = acadoVariables.lbValues[42] - acadoVariables.u[42]; acadoWorkspace.lb[43] = acadoVariables.lbValues[43] - acadoVariables.u[43]; acadoWorkspace.lb[44] = acadoVariables.lbValues[44] - acadoVariables.u[44]; acadoWorkspace.lb[45] = acadoVariables.lbValues[45] - acadoVariables.u[45]; acadoWorkspace.lb[46] = acadoVariables.lbValues[46] - acadoVariables.u[46]; acadoWorkspace.lb[47] = acadoVariables.lbValues[47] - acadoVariables.u[47]; acadoWorkspace.lb[48] = acadoVariables.lbValues[48] - acadoVariables.u[48]; acadoWorkspace.lb[49] = acadoVariables.lbValues[49] - acadoVariables.u[49]; acadoWorkspace.lb[50] = acadoVariables.lbValues[50] - acadoVariables.u[50]; acadoWorkspace.lb[51] = acadoVariables.lbValues[51] - acadoVariables.u[51]; acadoWorkspace.lb[52] = acadoVariables.lbValues[52] - acadoVariables.u[52]; acadoWorkspace.lb[53] = acadoVariables.lbValues[53] - acadoVariables.u[53]; acadoWorkspace.lb[54] = acadoVariables.lbValues[54] - acadoVariables.u[54]; acadoWorkspace.lb[55] = acadoVariables.lbValues[55] - acadoVariables.u[55]; acadoWorkspace.lb[56] = acadoVariables.lbValues[56] - acadoVariables.u[56]; acadoWorkspace.lb[57] = acadoVariables.lbValues[57] - acadoVariables.u[57]; acadoWorkspace.lb[58] = acadoVariables.lbValues[58] - acadoVariables.u[58]; acadoWorkspace.lb[59] = acadoVariables.lbValues[59] - acadoVariables.u[59]; acadoWorkspace.ub[0] = acadoVariables.ubValues[0] - acadoVariables.u[0]; acadoWorkspace.ub[1] = acadoVariables.ubValues[1] - acadoVariables.u[1]; acadoWorkspace.ub[2] = acadoVariables.ubValues[2] - acadoVariables.u[2]; acadoWorkspace.ub[3] = acadoVariables.ubValues[3] - acadoVariables.u[3]; acadoWorkspace.ub[4] = acadoVariables.ubValues[4] - acadoVariables.u[4]; acadoWorkspace.ub[5] = acadoVariables.ubValues[5] - acadoVariables.u[5]; acadoWorkspace.ub[6] = acadoVariables.ubValues[6] - acadoVariables.u[6]; acadoWorkspace.ub[7] = acadoVariables.ubValues[7] - acadoVariables.u[7]; acadoWorkspace.ub[8] = acadoVariables.ubValues[8] - acadoVariables.u[8]; acadoWorkspace.ub[9] = acadoVariables.ubValues[9] - acadoVariables.u[9]; acadoWorkspace.ub[10] = acadoVariables.ubValues[10] - acadoVariables.u[10]; acadoWorkspace.ub[11] = acadoVariables.ubValues[11] - acadoVariables.u[11]; acadoWorkspace.ub[12] = acadoVariables.ubValues[12] - acadoVariables.u[12]; acadoWorkspace.ub[13] = acadoVariables.ubValues[13] - acadoVariables.u[13]; acadoWorkspace.ub[14] = acadoVariables.ubValues[14] - acadoVariables.u[14]; acadoWorkspace.ub[15] = acadoVariables.ubValues[15] - acadoVariables.u[15]; acadoWorkspace.ub[16] = acadoVariables.ubValues[16] - acadoVariables.u[16]; acadoWorkspace.ub[17] = acadoVariables.ubValues[17] - acadoVariables.u[17]; acadoWorkspace.ub[18] = acadoVariables.ubValues[18] - acadoVariables.u[18]; acadoWorkspace.ub[19] = acadoVariables.ubValues[19] - acadoVariables.u[19]; acadoWorkspace.ub[20] = acadoVariables.ubValues[20] - acadoVariables.u[20]; acadoWorkspace.ub[21] = acadoVariables.ubValues[21] - acadoVariables.u[21]; acadoWorkspace.ub[22] = acadoVariables.ubValues[22] - acadoVariables.u[22]; acadoWorkspace.ub[23] = acadoVariables.ubValues[23] - acadoVariables.u[23]; acadoWorkspace.ub[24] = acadoVariables.ubValues[24] - acadoVariables.u[24]; acadoWorkspace.ub[25] = acadoVariables.ubValues[25] - acadoVariables.u[25]; acadoWorkspace.ub[26] = acadoVariables.ubValues[26] - acadoVariables.u[26]; acadoWorkspace.ub[27] = acadoVariables.ubValues[27] - acadoVariables.u[27]; acadoWorkspace.ub[28] = acadoVariables.ubValues[28] - acadoVariables.u[28]; acadoWorkspace.ub[29] = acadoVariables.ubValues[29] - acadoVariables.u[29]; acadoWorkspace.ub[30] = acadoVariables.ubValues[30] - acadoVariables.u[30]; acadoWorkspace.ub[31] = acadoVariables.ubValues[31] - acadoVariables.u[31]; acadoWorkspace.ub[32] = acadoVariables.ubValues[32] - acadoVariables.u[32]; acadoWorkspace.ub[33] = acadoVariables.ubValues[33] - acadoVariables.u[33]; acadoWorkspace.ub[34] = acadoVariables.ubValues[34] - acadoVariables.u[34]; acadoWorkspace.ub[35] = acadoVariables.ubValues[35] - acadoVariables.u[35]; acadoWorkspace.ub[36] = acadoVariables.ubValues[36] - acadoVariables.u[36]; acadoWorkspace.ub[37] = acadoVariables.ubValues[37] - acadoVariables.u[37]; acadoWorkspace.ub[38] = acadoVariables.ubValues[38] - acadoVariables.u[38]; acadoWorkspace.ub[39] = acadoVariables.ubValues[39] - acadoVariables.u[39]; acadoWorkspace.ub[40] = acadoVariables.ubValues[40] - acadoVariables.u[40]; acadoWorkspace.ub[41] = acadoVariables.ubValues[41] - acadoVariables.u[41]; acadoWorkspace.ub[42] = acadoVariables.ubValues[42] - acadoVariables.u[42]; acadoWorkspace.ub[43] = acadoVariables.ubValues[43] - acadoVariables.u[43]; acadoWorkspace.ub[44] = acadoVariables.ubValues[44] - acadoVariables.u[44]; acadoWorkspace.ub[45] = acadoVariables.ubValues[45] - acadoVariables.u[45]; acadoWorkspace.ub[46] = acadoVariables.ubValues[46] - acadoVariables.u[46]; acadoWorkspace.ub[47] = acadoVariables.ubValues[47] - acadoVariables.u[47]; acadoWorkspace.ub[48] = acadoVariables.ubValues[48] - acadoVariables.u[48]; acadoWorkspace.ub[49] = acadoVariables.ubValues[49] - acadoVariables.u[49]; acadoWorkspace.ub[50] = acadoVariables.ubValues[50] - acadoVariables.u[50]; acadoWorkspace.ub[51] = acadoVariables.ubValues[51] - acadoVariables.u[51]; acadoWorkspace.ub[52] = acadoVariables.ubValues[52] - acadoVariables.u[52]; acadoWorkspace.ub[53] = acadoVariables.ubValues[53] - acadoVariables.u[53]; acadoWorkspace.ub[54] = acadoVariables.ubValues[54] - acadoVariables.u[54]; acadoWorkspace.ub[55] = acadoVariables.ubValues[55] - acadoVariables.u[55]; acadoWorkspace.ub[56] = acadoVariables.ubValues[56] - acadoVariables.u[56]; acadoWorkspace.ub[57] = acadoVariables.ubValues[57] - acadoVariables.u[57]; acadoWorkspace.ub[58] = acadoVariables.ubValues[58] - acadoVariables.u[58]; acadoWorkspace.ub[59] = acadoVariables.ubValues[59] - acadoVariables.u[59]; } void acado_expand( ) { int lRun1; acadoVariables.u[0] += acadoWorkspace.x[0]; acadoVariables.u[1] += acadoWorkspace.x[1]; acadoVariables.u[2] += acadoWorkspace.x[2]; acadoVariables.u[3] += acadoWorkspace.x[3]; acadoVariables.u[4] += acadoWorkspace.x[4]; acadoVariables.u[5] += acadoWorkspace.x[5]; acadoVariables.u[6] += acadoWorkspace.x[6]; acadoVariables.u[7] += acadoWorkspace.x[7]; acadoVariables.u[8] += acadoWorkspace.x[8]; acadoVariables.u[9] += acadoWorkspace.x[9]; acadoVariables.u[10] += acadoWorkspace.x[10]; acadoVariables.u[11] += acadoWorkspace.x[11]; acadoVariables.u[12] += acadoWorkspace.x[12]; acadoVariables.u[13] += acadoWorkspace.x[13]; acadoVariables.u[14] += acadoWorkspace.x[14]; acadoVariables.u[15] += acadoWorkspace.x[15]; acadoVariables.u[16] += acadoWorkspace.x[16]; acadoVariables.u[17] += acadoWorkspace.x[17]; acadoVariables.u[18] += acadoWorkspace.x[18]; acadoVariables.u[19] += acadoWorkspace.x[19]; acadoVariables.u[20] += acadoWorkspace.x[20]; acadoVariables.u[21] += acadoWorkspace.x[21]; acadoVariables.u[22] += acadoWorkspace.x[22]; acadoVariables.u[23] += acadoWorkspace.x[23]; acadoVariables.u[24] += acadoWorkspace.x[24]; acadoVariables.u[25] += acadoWorkspace.x[25]; acadoVariables.u[26] += acadoWorkspace.x[26]; acadoVariables.u[27] += acadoWorkspace.x[27]; acadoVariables.u[28] += acadoWorkspace.x[28]; acadoVariables.u[29] += acadoWorkspace.x[29]; acadoVariables.u[30] += acadoWorkspace.x[30]; acadoVariables.u[31] += acadoWorkspace.x[31]; acadoVariables.u[32] += acadoWorkspace.x[32]; acadoVariables.u[33] += acadoWorkspace.x[33]; acadoVariables.u[34] += acadoWorkspace.x[34]; acadoVariables.u[35] += acadoWorkspace.x[35]; acadoVariables.u[36] += acadoWorkspace.x[36]; acadoVariables.u[37] += acadoWorkspace.x[37]; acadoVariables.u[38] += acadoWorkspace.x[38]; acadoVariables.u[39] += acadoWorkspace.x[39]; acadoVariables.u[40] += acadoWorkspace.x[40]; acadoVariables.u[41] += acadoWorkspace.x[41]; acadoVariables.u[42] += acadoWorkspace.x[42]; acadoVariables.u[43] += acadoWorkspace.x[43]; acadoVariables.u[44] += acadoWorkspace.x[44]; acadoVariables.u[45] += acadoWorkspace.x[45]; acadoVariables.u[46] += acadoWorkspace.x[46]; acadoVariables.u[47] += acadoWorkspace.x[47]; acadoVariables.u[48] += acadoWorkspace.x[48]; acadoVariables.u[49] += acadoWorkspace.x[49]; acadoVariables.u[50] += acadoWorkspace.x[50]; acadoVariables.u[51] += acadoWorkspace.x[51]; acadoVariables.u[52] += acadoWorkspace.x[52]; acadoVariables.u[53] += acadoWorkspace.x[53]; acadoVariables.u[54] += acadoWorkspace.x[54]; acadoVariables.u[55] += acadoWorkspace.x[55]; acadoVariables.u[56] += acadoWorkspace.x[56]; acadoVariables.u[57] += acadoWorkspace.x[57]; acadoVariables.u[58] += acadoWorkspace.x[58]; acadoVariables.u[59] += acadoWorkspace.x[59]; acadoWorkspace.sbar[0] = acadoWorkspace.Dx0[0]; acadoWorkspace.sbar[1] = acadoWorkspace.Dx0[1]; acadoWorkspace.sbar[2] = acadoWorkspace.Dx0[2]; acadoWorkspace.sbar[3] = acadoWorkspace.Dx0[3]; acadoWorkspace.sbar[4] = acadoWorkspace.Dx0[4]; acadoWorkspace.sbar[5] = acadoWorkspace.Dx0[5]; acadoWorkspace.sbar[6] = acadoWorkspace.Dx0[6]; acadoWorkspace.sbar[7] = acadoWorkspace.Dx0[7]; acadoWorkspace.sbar[8] = acadoWorkspace.Dx0[8]; for (lRun1 = 0; lRun1 < 180; ++lRun1) acadoWorkspace.sbar[lRun1 + 9] = acadoWorkspace.d[lRun1]; acado_expansionStep( acadoWorkspace.evGx, acadoWorkspace.evGu, acadoWorkspace.x, acadoWorkspace.sbar, &(acadoWorkspace.sbar[ 9 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 81 ]), &(acadoWorkspace.evGu[ 27 ]), &(acadoWorkspace.x[ 3 ]), &(acadoWorkspace.sbar[ 9 ]), &(acadoWorkspace.sbar[ 18 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 162 ]), &(acadoWorkspace.evGu[ 54 ]), &(acadoWorkspace.x[ 6 ]), &(acadoWorkspace.sbar[ 18 ]), &(acadoWorkspace.sbar[ 27 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 243 ]), &(acadoWorkspace.evGu[ 81 ]), &(acadoWorkspace.x[ 9 ]), &(acadoWorkspace.sbar[ 27 ]), &(acadoWorkspace.sbar[ 36 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 324 ]), &(acadoWorkspace.evGu[ 108 ]), &(acadoWorkspace.x[ 12 ]), &(acadoWorkspace.sbar[ 36 ]), &(acadoWorkspace.sbar[ 45 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 405 ]), &(acadoWorkspace.evGu[ 135 ]), &(acadoWorkspace.x[ 15 ]), &(acadoWorkspace.sbar[ 45 ]), &(acadoWorkspace.sbar[ 54 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 486 ]), &(acadoWorkspace.evGu[ 162 ]), &(acadoWorkspace.x[ 18 ]), &(acadoWorkspace.sbar[ 54 ]), &(acadoWorkspace.sbar[ 63 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 567 ]), &(acadoWorkspace.evGu[ 189 ]), &(acadoWorkspace.x[ 21 ]), &(acadoWorkspace.sbar[ 63 ]), &(acadoWorkspace.sbar[ 72 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 648 ]), &(acadoWorkspace.evGu[ 216 ]), &(acadoWorkspace.x[ 24 ]), &(acadoWorkspace.sbar[ 72 ]), &(acadoWorkspace.sbar[ 81 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 729 ]), &(acadoWorkspace.evGu[ 243 ]), &(acadoWorkspace.x[ 27 ]), &(acadoWorkspace.sbar[ 81 ]), &(acadoWorkspace.sbar[ 90 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 810 ]), &(acadoWorkspace.evGu[ 270 ]), &(acadoWorkspace.x[ 30 ]), &(acadoWorkspace.sbar[ 90 ]), &(acadoWorkspace.sbar[ 99 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 891 ]), &(acadoWorkspace.evGu[ 297 ]), &(acadoWorkspace.x[ 33 ]), &(acadoWorkspace.sbar[ 99 ]), &(acadoWorkspace.sbar[ 108 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 972 ]), &(acadoWorkspace.evGu[ 324 ]), &(acadoWorkspace.x[ 36 ]), &(acadoWorkspace.sbar[ 108 ]), &(acadoWorkspace.sbar[ 117 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 1053 ]), &(acadoWorkspace.evGu[ 351 ]), &(acadoWorkspace.x[ 39 ]), &(acadoWorkspace.sbar[ 117 ]), &(acadoWorkspace.sbar[ 126 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 1134 ]), &(acadoWorkspace.evGu[ 378 ]), &(acadoWorkspace.x[ 42 ]), &(acadoWorkspace.sbar[ 126 ]), &(acadoWorkspace.sbar[ 135 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 1215 ]), &(acadoWorkspace.evGu[ 405 ]), &(acadoWorkspace.x[ 45 ]), &(acadoWorkspace.sbar[ 135 ]), &(acadoWorkspace.sbar[ 144 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 1296 ]), &(acadoWorkspace.evGu[ 432 ]), &(acadoWorkspace.x[ 48 ]), &(acadoWorkspace.sbar[ 144 ]), &(acadoWorkspace.sbar[ 153 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 1377 ]), &(acadoWorkspace.evGu[ 459 ]), &(acadoWorkspace.x[ 51 ]), &(acadoWorkspace.sbar[ 153 ]), &(acadoWorkspace.sbar[ 162 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 1458 ]), &(acadoWorkspace.evGu[ 486 ]), &(acadoWorkspace.x[ 54 ]), &(acadoWorkspace.sbar[ 162 ]), &(acadoWorkspace.sbar[ 171 ]) ); acado_expansionStep( &(acadoWorkspace.evGx[ 1539 ]), &(acadoWorkspace.evGu[ 513 ]), &(acadoWorkspace.x[ 57 ]), &(acadoWorkspace.sbar[ 171 ]), &(acadoWorkspace.sbar[ 180 ]) ); for (lRun1 = 0; lRun1 < 189; ++lRun1) acadoVariables.x[lRun1] += acadoWorkspace.sbar[lRun1]; } int acado_preparationStep( ) { int ret; ret = acado_modelSimulation(); acado_evaluateObjective( ); acado_condensePrep( ); return ret; } int acado_feedbackStep( ) { int tmp; acado_condenseFdb( ); tmp = acado_solve( ); acado_expand( ); return tmp; } int acado_initializeSolver( ) { int ret; /* This is a function which must be called once before any other function call! */ ret = 0; memset(&acadoWorkspace, 0, sizeof( acadoWorkspace )); acadoVariables.lbValues[0] = -7.8539816339744828e-01; acadoVariables.lbValues[1] = -7.8539816339744828e-01; acadoVariables.lbValues[2] = 4.9032999999999998e+00; acadoVariables.lbValues[3] = -7.8539816339744828e-01; acadoVariables.lbValues[4] = -7.8539816339744828e-01; acadoVariables.lbValues[5] = 4.9032999999999998e+00; acadoVariables.lbValues[6] = -7.8539816339744828e-01; acadoVariables.lbValues[7] = -7.8539816339744828e-01; acadoVariables.lbValues[8] = 4.9032999999999998e+00; acadoVariables.lbValues[9] = -7.8539816339744828e-01; acadoVariables.lbValues[10] = -7.8539816339744828e-01; acadoVariables.lbValues[11] = 4.9032999999999998e+00; acadoVariables.lbValues[12] = -7.8539816339744828e-01; acadoVariables.lbValues[13] = -7.8539816339744828e-01; acadoVariables.lbValues[14] = 4.9032999999999998e+00; acadoVariables.lbValues[15] = -7.8539816339744828e-01; acadoVariables.lbValues[16] = -7.8539816339744828e-01; acadoVariables.lbValues[17] = 4.9032999999999998e+00; acadoVariables.lbValues[18] = -7.8539816339744828e-01; acadoVariables.lbValues[19] = -7.8539816339744828e-01; acadoVariables.lbValues[20] = 4.9032999999999998e+00; acadoVariables.lbValues[21] = -7.8539816339744828e-01; acadoVariables.lbValues[22] = -7.8539816339744828e-01; acadoVariables.lbValues[23] = 4.9032999999999998e+00; acadoVariables.lbValues[24] = -7.8539816339744828e-01; acadoVariables.lbValues[25] = -7.8539816339744828e-01; acadoVariables.lbValues[26] = 4.9032999999999998e+00; acadoVariables.lbValues[27] = -7.8539816339744828e-01; acadoVariables.lbValues[28] = -7.8539816339744828e-01; acadoVariables.lbValues[29] = 4.9032999999999998e+00; acadoVariables.lbValues[30] = -7.8539816339744828e-01; acadoVariables.lbValues[31] = -7.8539816339744828e-01; acadoVariables.lbValues[32] = 4.9032999999999998e+00; acadoVariables.lbValues[33] = -7.8539816339744828e-01; acadoVariables.lbValues[34] = -7.8539816339744828e-01; acadoVariables.lbValues[35] = 4.9032999999999998e+00; acadoVariables.lbValues[36] = -7.8539816339744828e-01; acadoVariables.lbValues[37] = -7.8539816339744828e-01; acadoVariables.lbValues[38] = 4.9032999999999998e+00; acadoVariables.lbValues[39] = -7.8539816339744828e-01; acadoVariables.lbValues[40] = -7.8539816339744828e-01; acadoVariables.lbValues[41] = 4.9032999999999998e+00; acadoVariables.lbValues[42] = -7.8539816339744828e-01; acadoVariables.lbValues[43] = -7.8539816339744828e-01; acadoVariables.lbValues[44] = 4.9032999999999998e+00; acadoVariables.lbValues[45] = -7.8539816339744828e-01; acadoVariables.lbValues[46] = -7.8539816339744828e-01; acadoVariables.lbValues[47] = 4.9032999999999998e+00; acadoVariables.lbValues[48] = -7.8539816339744828e-01; acadoVariables.lbValues[49] = -7.8539816339744828e-01; acadoVariables.lbValues[50] = 4.9032999999999998e+00; acadoVariables.lbValues[51] = -7.8539816339744828e-01; acadoVariables.lbValues[52] = -7.8539816339744828e-01; acadoVariables.lbValues[53] = 4.9032999999999998e+00; acadoVariables.lbValues[54] = -7.8539816339744828e-01; acadoVariables.lbValues[55] = -7.8539816339744828e-01; acadoVariables.lbValues[56] = 4.9032999999999998e+00; acadoVariables.lbValues[57] = -7.8539816339744828e-01; acadoVariables.lbValues[58] = -7.8539816339744828e-01; acadoVariables.lbValues[59] = 4.9032999999999998e+00; acadoVariables.ubValues[0] = 7.8539816339744828e-01; acadoVariables.ubValues[1] = 7.8539816339744828e-01; acadoVariables.ubValues[2] = 1.4709899999999999e+01; acadoVariables.ubValues[3] = 7.8539816339744828e-01; acadoVariables.ubValues[4] = 7.8539816339744828e-01; acadoVariables.ubValues[5] = 1.4709899999999999e+01; acadoVariables.ubValues[6] = 7.8539816339744828e-01; acadoVariables.ubValues[7] = 7.8539816339744828e-01; acadoVariables.ubValues[8] = 1.4709899999999999e+01; acadoVariables.ubValues[9] = 7.8539816339744828e-01; acadoVariables.ubValues[10] = 7.8539816339744828e-01; acadoVariables.ubValues[11] = 1.4709899999999999e+01; acadoVariables.ubValues[12] = 7.8539816339744828e-01; acadoVariables.ubValues[13] = 7.8539816339744828e-01; acadoVariables.ubValues[14] = 1.4709899999999999e+01; acadoVariables.ubValues[15] = 7.8539816339744828e-01; acadoVariables.ubValues[16] = 7.8539816339744828e-01; acadoVariables.ubValues[17] = 1.4709899999999999e+01; acadoVariables.ubValues[18] = 7.8539816339744828e-01; acadoVariables.ubValues[19] = 7.8539816339744828e-01; acadoVariables.ubValues[20] = 1.4709899999999999e+01; acadoVariables.ubValues[21] = 7.8539816339744828e-01; acadoVariables.ubValues[22] = 7.8539816339744828e-01; acadoVariables.ubValues[23] = 1.4709899999999999e+01; acadoVariables.ubValues[24] = 7.8539816339744828e-01; acadoVariables.ubValues[25] = 7.8539816339744828e-01; acadoVariables.ubValues[26] = 1.4709899999999999e+01; acadoVariables.ubValues[27] = 7.8539816339744828e-01; acadoVariables.ubValues[28] = 7.8539816339744828e-01; acadoVariables.ubValues[29] = 1.4709899999999999e+01; acadoVariables.ubValues[30] = 7.8539816339744828e-01; acadoVariables.ubValues[31] = 7.8539816339744828e-01; acadoVariables.ubValues[32] = 1.4709899999999999e+01; acadoVariables.ubValues[33] = 7.8539816339744828e-01; acadoVariables.ubValues[34] = 7.8539816339744828e-01; acadoVariables.ubValues[35] = 1.4709899999999999e+01; acadoVariables.ubValues[36] = 7.8539816339744828e-01; acadoVariables.ubValues[37] = 7.8539816339744828e-01; acadoVariables.ubValues[38] = 1.4709899999999999e+01; acadoVariables.ubValues[39] = 7.8539816339744828e-01; acadoVariables.ubValues[40] = 7.8539816339744828e-01; acadoVariables.ubValues[41] = 1.4709899999999999e+01; acadoVariables.ubValues[42] = 7.8539816339744828e-01; acadoVariables.ubValues[43] = 7.8539816339744828e-01; acadoVariables.ubValues[44] = 1.4709899999999999e+01; acadoVariables.ubValues[45] = 7.8539816339744828e-01; acadoVariables.ubValues[46] = 7.8539816339744828e-01; acadoVariables.ubValues[47] = 1.4709899999999999e+01; acadoVariables.ubValues[48] = 7.8539816339744828e-01; acadoVariables.ubValues[49] = 7.8539816339744828e-01; acadoVariables.ubValues[50] = 1.4709899999999999e+01; acadoVariables.ubValues[51] = 7.8539816339744828e-01; acadoVariables.ubValues[52] = 7.8539816339744828e-01; acadoVariables.ubValues[53] = 1.4709899999999999e+01; acadoVariables.ubValues[54] = 7.8539816339744828e-01; acadoVariables.ubValues[55] = 7.8539816339744828e-01; acadoVariables.ubValues[56] = 1.4709899999999999e+01; acadoVariables.ubValues[57] = 7.8539816339744828e-01; acadoVariables.ubValues[58] = 7.8539816339744828e-01; acadoVariables.ubValues[59] = 1.4709899999999999e+01; return ret; } void acado_initializeNodesByForwardSimulation( ) { int index; for (index = 0; index < 20; ++index) { state[0] = acadoVariables.x[index * 9]; state[1] = acadoVariables.x[index * 9 + 1]; state[2] = acadoVariables.x[index * 9 + 2]; state[3] = acadoVariables.x[index * 9 + 3]; state[4] = acadoVariables.x[index * 9 + 4]; state[5] = acadoVariables.x[index * 9 + 5]; state[6] = acadoVariables.x[index * 9 + 6]; state[7] = acadoVariables.x[index * 9 + 7]; state[8] = acadoVariables.x[index * 9 + 8]; state[117] = acadoVariables.u[index * 3]; state[118] = acadoVariables.u[index * 3 + 1]; state[119] = acadoVariables.u[index * 3 + 2]; state[120] = acadoVariables.od[index * 9]; state[121] = acadoVariables.od[index * 9 + 1]; state[122] = acadoVariables.od[index * 9 + 2]; state[123] = acadoVariables.od[index * 9 + 3]; state[124] = acadoVariables.od[index * 9 + 4]; state[125] = acadoVariables.od[index * 9 + 5]; state[126] = acadoVariables.od[index * 9 + 6]; state[127] = acadoVariables.od[index * 9 + 7]; state[128] = acadoVariables.od[index * 9 + 8]; acado_integrate(state, index == 0); acadoVariables.x[index * 9 + 9] = state[0]; acadoVariables.x[index * 9 + 10] = state[1]; acadoVariables.x[index * 9 + 11] = state[2]; acadoVariables.x[index * 9 + 12] = state[3]; acadoVariables.x[index * 9 + 13] = state[4]; acadoVariables.x[index * 9 + 14] = state[5]; acadoVariables.x[index * 9 + 15] = state[6]; acadoVariables.x[index * 9 + 16] = state[7]; acadoVariables.x[index * 9 + 17] = state[8]; } } void acado_shiftStates( int strategy, real_t* const xEnd, real_t* const uEnd ) { int index; for (index = 0; index < 20; ++index) { acadoVariables.x[index * 9] = acadoVariables.x[index * 9 + 9]; acadoVariables.x[index * 9 + 1] = acadoVariables.x[index * 9 + 10]; acadoVariables.x[index * 9 + 2] = acadoVariables.x[index * 9 + 11]; acadoVariables.x[index * 9 + 3] = acadoVariables.x[index * 9 + 12]; acadoVariables.x[index * 9 + 4] = acadoVariables.x[index * 9 + 13]; acadoVariables.x[index * 9 + 5] = acadoVariables.x[index * 9 + 14]; acadoVariables.x[index * 9 + 6] = acadoVariables.x[index * 9 + 15]; acadoVariables.x[index * 9 + 7] = acadoVariables.x[index * 9 + 16]; acadoVariables.x[index * 9 + 8] = acadoVariables.x[index * 9 + 17]; } if (strategy == 1 && xEnd != 0) { acadoVariables.x[180] = xEnd[0]; acadoVariables.x[181] = xEnd[1]; acadoVariables.x[182] = xEnd[2]; acadoVariables.x[183] = xEnd[3]; acadoVariables.x[184] = xEnd[4]; acadoVariables.x[185] = xEnd[5]; acadoVariables.x[186] = xEnd[6]; acadoVariables.x[187] = xEnd[7]; acadoVariables.x[188] = xEnd[8]; } else if (strategy == 2) { state[0] = acadoVariables.x[180]; state[1] = acadoVariables.x[181]; state[2] = acadoVariables.x[182]; state[3] = acadoVariables.x[183]; state[4] = acadoVariables.x[184]; state[5] = acadoVariables.x[185]; state[6] = acadoVariables.x[186]; state[7] = acadoVariables.x[187]; state[8] = acadoVariables.x[188]; if (uEnd != 0) { state[117] = uEnd[0]; state[118] = uEnd[1]; state[119] = uEnd[2]; } else { state[117] = acadoVariables.u[57]; state[118] = acadoVariables.u[58]; state[119] = acadoVariables.u[59]; } state[120] = acadoVariables.od[180]; state[121] = acadoVariables.od[181]; state[122] = acadoVariables.od[182]; state[123] = acadoVariables.od[183]; state[124] = acadoVariables.od[184]; state[125] = acadoVariables.od[185]; state[126] = acadoVariables.od[186]; state[127] = acadoVariables.od[187]; state[128] = acadoVariables.od[188]; acado_integrate(state, 1); acadoVariables.x[180] = state[0]; acadoVariables.x[181] = state[1]; acadoVariables.x[182] = state[2]; acadoVariables.x[183] = state[3]; acadoVariables.x[184] = state[4]; acadoVariables.x[185] = state[5]; acadoVariables.x[186] = state[6]; acadoVariables.x[187] = state[7]; acadoVariables.x[188] = state[8]; } } void acado_shiftControls( real_t* const uEnd ) { int index; for (index = 0; index < 19; ++index) { acadoVariables.u[index * 3] = acadoVariables.u[index * 3 + 3]; acadoVariables.u[index * 3 + 1] = acadoVariables.u[index * 3 + 4]; acadoVariables.u[index * 3 + 2] = acadoVariables.u[index * 3 + 5]; } if (uEnd != 0) { acadoVariables.u[57] = uEnd[0]; acadoVariables.u[58] = uEnd[1]; acadoVariables.u[59] = uEnd[2]; } } real_t acado_getKKT( ) { real_t kkt; int index; real_t prd; kkt = + acadoWorkspace.g[0]*acadoWorkspace.x[0] + acadoWorkspace.g[1]*acadoWorkspace.x[1] + acadoWorkspace.g[2]*acadoWorkspace.x[2] + acadoWorkspace.g[3]*acadoWorkspace.x[3] + acadoWorkspace.g[4]*acadoWorkspace.x[4] + acadoWorkspace.g[5]*acadoWorkspace.x[5] + acadoWorkspace.g[6]*acadoWorkspace.x[6] + acadoWorkspace.g[7]*acadoWorkspace.x[7] + acadoWorkspace.g[8]*acadoWorkspace.x[8] + acadoWorkspace.g[9]*acadoWorkspace.x[9] + acadoWorkspace.g[10]*acadoWorkspace.x[10] + acadoWorkspace.g[11]*acadoWorkspace.x[11] + acadoWorkspace.g[12]*acadoWorkspace.x[12] + acadoWorkspace.g[13]*acadoWorkspace.x[13] + acadoWorkspace.g[14]*acadoWorkspace.x[14] + acadoWorkspace.g[15]*acadoWorkspace.x[15] + acadoWorkspace.g[16]*acadoWorkspace.x[16] + acadoWorkspace.g[17]*acadoWorkspace.x[17] + acadoWorkspace.g[18]*acadoWorkspace.x[18] + acadoWorkspace.g[19]*acadoWorkspace.x[19] + acadoWorkspace.g[20]*acadoWorkspace.x[20] + acadoWorkspace.g[21]*acadoWorkspace.x[21] + acadoWorkspace.g[22]*acadoWorkspace.x[22] + acadoWorkspace.g[23]*acadoWorkspace.x[23] + acadoWorkspace.g[24]*acadoWorkspace.x[24] + acadoWorkspace.g[25]*acadoWorkspace.x[25] + acadoWorkspace.g[26]*acadoWorkspace.x[26] + acadoWorkspace.g[27]*acadoWorkspace.x[27] + acadoWorkspace.g[28]*acadoWorkspace.x[28] + acadoWorkspace.g[29]*acadoWorkspace.x[29] + acadoWorkspace.g[30]*acadoWorkspace.x[30] + acadoWorkspace.g[31]*acadoWorkspace.x[31] + acadoWorkspace.g[32]*acadoWorkspace.x[32] + acadoWorkspace.g[33]*acadoWorkspace.x[33] + acadoWorkspace.g[34]*acadoWorkspace.x[34] + acadoWorkspace.g[35]*acadoWorkspace.x[35] + acadoWorkspace.g[36]*acadoWorkspace.x[36] + acadoWorkspace.g[37]*acadoWorkspace.x[37] + acadoWorkspace.g[38]*acadoWorkspace.x[38] + acadoWorkspace.g[39]*acadoWorkspace.x[39] + acadoWorkspace.g[40]*acadoWorkspace.x[40] + acadoWorkspace.g[41]*acadoWorkspace.x[41] + acadoWorkspace.g[42]*acadoWorkspace.x[42] + acadoWorkspace.g[43]*acadoWorkspace.x[43] + acadoWorkspace.g[44]*acadoWorkspace.x[44] + acadoWorkspace.g[45]*acadoWorkspace.x[45] + acadoWorkspace.g[46]*acadoWorkspace.x[46] + acadoWorkspace.g[47]*acadoWorkspace.x[47] + acadoWorkspace.g[48]*acadoWorkspace.x[48] + acadoWorkspace.g[49]*acadoWorkspace.x[49] + acadoWorkspace.g[50]*acadoWorkspace.x[50] + acadoWorkspace.g[51]*acadoWorkspace.x[51] + acadoWorkspace.g[52]*acadoWorkspace.x[52] + acadoWorkspace.g[53]*acadoWorkspace.x[53] + acadoWorkspace.g[54]*acadoWorkspace.x[54] + acadoWorkspace.g[55]*acadoWorkspace.x[55] + acadoWorkspace.g[56]*acadoWorkspace.x[56] + acadoWorkspace.g[57]*acadoWorkspace.x[57] + acadoWorkspace.g[58]*acadoWorkspace.x[58] + acadoWorkspace.g[59]*acadoWorkspace.x[59]; kkt = fabs( kkt ); for (index = 0; index < 60; ++index) { prd = acadoWorkspace.y[index]; if (prd > 1e-12) kkt += fabs(acadoWorkspace.lb[index] * prd); else if (prd < -1e-12) kkt += fabs(acadoWorkspace.ub[index] * prd); } return kkt; } real_t acado_getObjective( ) { real_t objVal; int lRun1; /** Row vector of size: 11 */ real_t tmpDy[ 11 ]; /** Row vector of size: 6 */ real_t tmpDyN[ 6 ]; for (lRun1 = 0; lRun1 < 20; ++lRun1) { acadoWorkspace.objValueIn[0] = acadoVariables.x[lRun1 * 9]; acadoWorkspace.objValueIn[1] = acadoVariables.x[lRun1 * 9 + 1]; acadoWorkspace.objValueIn[2] = acadoVariables.x[lRun1 * 9 + 2]; acadoWorkspace.objValueIn[3] = acadoVariables.x[lRun1 * 9 + 3]; acadoWorkspace.objValueIn[4] = acadoVariables.x[lRun1 * 9 + 4]; acadoWorkspace.objValueIn[5] = acadoVariables.x[lRun1 * 9 + 5]; acadoWorkspace.objValueIn[6] = acadoVariables.x[lRun1 * 9 + 6]; acadoWorkspace.objValueIn[7] = acadoVariables.x[lRun1 * 9 + 7]; acadoWorkspace.objValueIn[8] = acadoVariables.x[lRun1 * 9 + 8]; acadoWorkspace.objValueIn[9] = acadoVariables.u[lRun1 * 3]; acadoWorkspace.objValueIn[10] = acadoVariables.u[lRun1 * 3 + 1]; acadoWorkspace.objValueIn[11] = acadoVariables.u[lRun1 * 3 + 2]; acadoWorkspace.objValueIn[12] = acadoVariables.od[lRun1 * 9]; acadoWorkspace.objValueIn[13] = acadoVariables.od[lRun1 * 9 + 1]; acadoWorkspace.objValueIn[14] = acadoVariables.od[lRun1 * 9 + 2]; acadoWorkspace.objValueIn[15] = acadoVariables.od[lRun1 * 9 + 3]; acadoWorkspace.objValueIn[16] = acadoVariables.od[lRun1 * 9 + 4]; acadoWorkspace.objValueIn[17] = acadoVariables.od[lRun1 * 9 + 5]; acadoWorkspace.objValueIn[18] = acadoVariables.od[lRun1 * 9 + 6]; acadoWorkspace.objValueIn[19] = acadoVariables.od[lRun1 * 9 + 7]; acadoWorkspace.objValueIn[20] = acadoVariables.od[lRun1 * 9 + 8]; acado_evaluateLSQ( acadoWorkspace.objValueIn, acadoWorkspace.objValueOut ); acadoWorkspace.Dy[lRun1 * 11] = acadoWorkspace.objValueOut[0] - acadoVariables.y[lRun1 * 11]; acadoWorkspace.Dy[lRun1 * 11 + 1] = acadoWorkspace.objValueOut[1] - acadoVariables.y[lRun1 * 11 + 1]; acadoWorkspace.Dy[lRun1 * 11 + 2] = acadoWorkspace.objValueOut[2] - acadoVariables.y[lRun1 * 11 + 2]; acadoWorkspace.Dy[lRun1 * 11 + 3] = acadoWorkspace.objValueOut[3] - acadoVariables.y[lRun1 * 11 + 3]; acadoWorkspace.Dy[lRun1 * 11 + 4] = acadoWorkspace.objValueOut[4] - acadoVariables.y[lRun1 * 11 + 4]; acadoWorkspace.Dy[lRun1 * 11 + 5] = acadoWorkspace.objValueOut[5] - acadoVariables.y[lRun1 * 11 + 5]; acadoWorkspace.Dy[lRun1 * 11 + 6] = acadoWorkspace.objValueOut[6] - acadoVariables.y[lRun1 * 11 + 6]; acadoWorkspace.Dy[lRun1 * 11 + 7] = acadoWorkspace.objValueOut[7] - acadoVariables.y[lRun1 * 11 + 7]; acadoWorkspace.Dy[lRun1 * 11 + 8] = acadoWorkspace.objValueOut[8] - acadoVariables.y[lRun1 * 11 + 8]; acadoWorkspace.Dy[lRun1 * 11 + 9] = acadoWorkspace.objValueOut[9] - acadoVariables.y[lRun1 * 11 + 9]; acadoWorkspace.Dy[lRun1 * 11 + 10] = acadoWorkspace.objValueOut[10] - acadoVariables.y[lRun1 * 11 + 10]; } acadoWorkspace.objValueIn[0] = acadoVariables.x[180]; acadoWorkspace.objValueIn[1] = acadoVariables.x[181]; acadoWorkspace.objValueIn[2] = acadoVariables.x[182]; acadoWorkspace.objValueIn[3] = acadoVariables.x[183]; acadoWorkspace.objValueIn[4] = acadoVariables.x[184]; acadoWorkspace.objValueIn[5] = acadoVariables.x[185]; acadoWorkspace.objValueIn[6] = acadoVariables.x[186]; acadoWorkspace.objValueIn[7] = acadoVariables.x[187]; acadoWorkspace.objValueIn[8] = acadoVariables.x[188]; acadoWorkspace.objValueIn[9] = acadoVariables.od[180]; acadoWorkspace.objValueIn[10] = acadoVariables.od[181]; acadoWorkspace.objValueIn[11] = acadoVariables.od[182]; acadoWorkspace.objValueIn[12] = acadoVariables.od[183]; acadoWorkspace.objValueIn[13] = acadoVariables.od[184]; acadoWorkspace.objValueIn[14] = acadoVariables.od[185]; acadoWorkspace.objValueIn[15] = acadoVariables.od[186]; acadoWorkspace.objValueIn[16] = acadoVariables.od[187]; acadoWorkspace.objValueIn[17] = acadoVariables.od[188]; acado_evaluateLSQEndTerm( acadoWorkspace.objValueIn, acadoWorkspace.objValueOut ); acadoWorkspace.DyN[0] = acadoWorkspace.objValueOut[0] - acadoVariables.yN[0]; acadoWorkspace.DyN[1] = acadoWorkspace.objValueOut[1] - acadoVariables.yN[1]; acadoWorkspace.DyN[2] = acadoWorkspace.objValueOut[2] - acadoVariables.yN[2]; acadoWorkspace.DyN[3] = acadoWorkspace.objValueOut[3] - acadoVariables.yN[3]; acadoWorkspace.DyN[4] = acadoWorkspace.objValueOut[4] - acadoVariables.yN[4]; acadoWorkspace.DyN[5] = acadoWorkspace.objValueOut[5] - acadoVariables.yN[5]; objVal = 0.0000000000000000e+00; for (lRun1 = 0; lRun1 < 20; ++lRun1) { tmpDy[0] = + acadoWorkspace.Dy[lRun1 * 11]*acadoVariables.W[0]; tmpDy[1] = + acadoWorkspace.Dy[lRun1 * 11 + 1]*acadoVariables.W[12]; tmpDy[2] = + acadoWorkspace.Dy[lRun1 * 11 + 2]*acadoVariables.W[24]; tmpDy[3] = + acadoWorkspace.Dy[lRun1 * 11 + 3]*acadoVariables.W[36]; tmpDy[4] = + acadoWorkspace.Dy[lRun1 * 11 + 4]*acadoVariables.W[48]; tmpDy[5] = + acadoWorkspace.Dy[lRun1 * 11 + 5]*acadoVariables.W[60]; tmpDy[6] = + acadoWorkspace.Dy[lRun1 * 11 + 6]*acadoVariables.W[72]; tmpDy[7] = + acadoWorkspace.Dy[lRun1 * 11 + 7]*acadoVariables.W[84]; tmpDy[8] = + acadoWorkspace.Dy[lRun1 * 11 + 8]*acadoVariables.W[96]; tmpDy[9] = + acadoWorkspace.Dy[lRun1 * 11 + 9]*acadoVariables.W[108]; tmpDy[10] = + acadoWorkspace.Dy[lRun1 * 11 + 10]*acadoVariables.W[120]; objVal += + acadoWorkspace.Dy[lRun1 * 11]*tmpDy[0] + acadoWorkspace.Dy[lRun1 * 11 + 1]*tmpDy[1] + acadoWorkspace.Dy[lRun1 * 11 + 2]*tmpDy[2] + acadoWorkspace.Dy[lRun1 * 11 + 3]*tmpDy[3] + acadoWorkspace.Dy[lRun1 * 11 + 4]*tmpDy[4] + acadoWorkspace.Dy[lRun1 * 11 + 5]*tmpDy[5] + acadoWorkspace.Dy[lRun1 * 11 + 6]*tmpDy[6] + acadoWorkspace.Dy[lRun1 * 11 + 7]*tmpDy[7] + acadoWorkspace.Dy[lRun1 * 11 + 8]*tmpDy[8] + acadoWorkspace.Dy[lRun1 * 11 + 9]*tmpDy[9] + acadoWorkspace.Dy[lRun1 * 11 + 10]*tmpDy[10]; } tmpDyN[0] = + acadoWorkspace.DyN[0]*acadoVariables.WN[0]; tmpDyN[1] = + acadoWorkspace.DyN[1]*acadoVariables.WN[7]; tmpDyN[2] = + acadoWorkspace.DyN[2]*acadoVariables.WN[14]; tmpDyN[3] = + acadoWorkspace.DyN[3]*acadoVariables.WN[21]; tmpDyN[4] = + acadoWorkspace.DyN[4]*acadoVariables.WN[28]; tmpDyN[5] = + acadoWorkspace.DyN[5]*acadoVariables.WN[35]; objVal += + acadoWorkspace.DyN[0]*tmpDyN[0] + acadoWorkspace.DyN[1]*tmpDyN[1] + acadoWorkspace.DyN[2]*tmpDyN[2] + acadoWorkspace.DyN[3]*tmpDyN[3] + acadoWorkspace.DyN[4]*tmpDyN[4] + acadoWorkspace.DyN[5]*tmpDyN[5]; objVal *= 0.5; return objVal; }
parallel_for_lastprivate.c
#include <stdio.h> #include <math.h> #include "omp_testsuite.h" int check_parallel_for_lastprivate (FILE * logFile) { int sum = 0; /*int sum0=0; */ int known_sum; int i; int i0 = -1; #pragma omp parallel for reduction(+:sum) schedule(static,7) lastprivate(i0) for (i = 1; i <= LOOPCOUNT; i++) { sum = sum + i; i0 = i; } /*end of for */ /* end of parallel */ known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; return ((known_sum == sum) && (i0 == LOOPCOUNT)); } /* end of check_parallel_for_lastprivate */ int crosscheck_parallel_for_lastprivate (FILE * logFile) { int sum = 0; /*int sum0=0; */ int known_sum; int i; int i0 = -1; #pragma omp parallel for reduction(+:sum) schedule(static,7) private(i0) for (i = 1; i <= LOOPCOUNT; i++) { sum = sum + i; i0 = i; } /*end of for */ /* end of parallel */ known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; return ((known_sum == sum) && (i0 == LOOPCOUNT)); } /* end of check_parallel_for_lastprivate */
residualbased_newton_raphson_strategy.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ \. // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // #if !defined(KRATOS_RESIDUALBASED_NEWTON_RAPHSON_STRATEGY) #define KRATOS_RESIDUALBASED_NEWTON_RAPHSON_STRATEGY // System includes // External includes // Project includes #include "includes/define.h" #include "solving_strategies/strategies/solving_strategy.h" #include "solving_strategies/convergencecriterias/convergence_criteria.h" #include "utilities/builtin_timer.h" //default builder and solver #include "solving_strategies/builder_and_solvers/residualbased_block_builder_and_solver.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedNewtonRaphsonStrategy * @ingroup KratosCore * @brief This is the base Newton Raphson strategy * @details This strategy iterates until the convergence is achieved (or the maximum number of iterations is surpassed) using a Newton Raphson algorithm * @author Riccardo Rossi */ template <class TSparseSpace, class TDenseSpace, // = DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class ResidualBasedNewtonRaphsonStrategy : public SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> { public: ///@name Type Definitions ///@{ typedef ConvergenceCriteria<TSparseSpace, TDenseSpace> TConvergenceCriteriaType; // Counted pointer of ClassName KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedNewtonRaphsonStrategy); typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TBuilderAndSolverType TBuilderAndSolverType; typedef typename BaseType::TDataType TDataType; typedef TSparseSpace SparseSpaceType; typedef typename BaseType::TSchemeType TSchemeType; //typedef typename BaseType::DofSetType DofSetType; 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; ///@} ///@name Life Cycle ///@{ /** * Default constructor * @param rModelPart The model part of the problem * @param pScheme The integration scheme * @param pNewLinearSolver The linear solver employed * @param pNewConvergenceCriteria The convergence criteria employed * @param MaxIterations The maximum number of non-linear iterations to be considered when solving the problem * @param CalculateReactions The flag for the reaction calculation * @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF * @param MoveMeshFlag The flag that allows to move the mesh */ ResidualBasedNewtonRaphsonStrategy( ModelPart& rModelPart, typename TSchemeType::Pointer pScheme, typename TLinearSolver::Pointer pNewLinearSolver, typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria, int MaxIterations = 30, bool CalculateReactions = false, bool ReformDofSetAtEachStep = false, bool MoveMeshFlag = false) : SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, MoveMeshFlag) { KRATOS_TRY; mKeepSystemConstantDuringIterations = false; // Set flags to default values SetMaxIterationNumber(MaxIterations); mCalculateReactionsFlag = CalculateReactions; mReformDofSetAtEachStep = ReformDofSetAtEachStep; // Saving the convergence criteria to be used mpConvergenceCriteria = pNewConvergenceCriteria; // Saving the scheme mpScheme = pScheme; // Saving the linear solver mpLinearSolver = pNewLinearSolver; // Setting up the default builder and solver mpBuilderAndSolver = typename TBuilderAndSolverType::Pointer( new ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>(mpLinearSolver)); // Set flags to start correcty the calculations mSolutionStepIsInitialized = false; mInitializeWasPerformed = false; // Tells to the builder and solver if the reactions have to be Calculated or not GetBuilderAndSolver()->SetCalculateReactionsFlag(mCalculateReactionsFlag); // Tells to the Builder And Solver if the system matrix and vectors need to // be reshaped at each step or not GetBuilderAndSolver()->SetReshapeMatrixFlag(mReformDofSetAtEachStep); // Set EchoLevel to the default value (only time is displayed) SetEchoLevel(1); // By default the matrices are rebuilt at each iteration this->SetRebuildLevel(2); mpA = TSparseSpace::CreateEmptyMatrixPointer(); mpDx = TSparseSpace::CreateEmptyVectorPointer(); mpb = TSparseSpace::CreateEmptyVectorPointer(); KRATOS_CATCH(""); } /** * Constructor specifying the builder and solver * @param rModelPart The model part of the problem * @param pScheme The integration scheme * @param pNewLinearSolver The linear solver employed * @param pNewConvergenceCriteria The convergence criteria employed * @param pNewBuilderAndSolver The builder and solver employed * @param MaxIterations The maximum number of non-linear iterations to be considered when solving the problem * @param CalculateReactions The flag for the reaction calculation * @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF * @param MoveMeshFlag The flag that allows to move the mesh */ ResidualBasedNewtonRaphsonStrategy( ModelPart& rModelPart, typename TSchemeType::Pointer pScheme, typename TLinearSolver::Pointer pNewLinearSolver, typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria, typename TBuilderAndSolverType::Pointer pNewBuilderAndSolver, int MaxIterations = 30, bool CalculateReactions = false, bool ReformDofSetAtEachStep = false, bool MoveMeshFlag = false) : SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, MoveMeshFlag) { KRATOS_TRY mKeepSystemConstantDuringIterations = false; // Set flags to default values SetMaxIterationNumber(MaxIterations); mCalculateReactionsFlag = CalculateReactions; mReformDofSetAtEachStep = ReformDofSetAtEachStep; // Saving the convergence criteria to be used mpConvergenceCriteria = pNewConvergenceCriteria; // Saving the scheme mpScheme = pScheme; // Saving the linear solver mpLinearSolver = pNewLinearSolver; // Setting up the default builder and solver mpBuilderAndSolver = pNewBuilderAndSolver; // Set flags to start correcty the calculations mSolutionStepIsInitialized = false; mInitializeWasPerformed = false; // Tells to the builder and solver if the reactions have to be Calculated or not GetBuilderAndSolver()->SetCalculateReactionsFlag(mCalculateReactionsFlag); // Tells to the Builder And Solver if the system matrix and vectors need to //be reshaped at each step or not GetBuilderAndSolver()->SetReshapeMatrixFlag(mReformDofSetAtEachStep); // Set EchoLevel to the default value (only time is displayed) SetEchoLevel(1); // By default the matrices are rebuilt at each iteration this->SetRebuildLevel(2); mpA = TSparseSpace::CreateEmptyMatrixPointer(); mpDx = TSparseSpace::CreateEmptyVectorPointer(); mpb = TSparseSpace::CreateEmptyVectorPointer(); KRATOS_CATCH("") } /** * @brief Destructor. * @details In trilinos third party library, the linear solver's preconditioner should be freed before the system matrix. We control the deallocation order with Clear(). */ ~ResidualBasedNewtonRaphsonStrategy() override { // If the linear solver has not been deallocated, clean it before // deallocating mpA. This prevents a memory error with the the ML // solver (which holds a reference to it). auto p_linear_solver = GetBuilderAndSolver()->GetLinearSystemSolver(); if (p_linear_solver != nullptr) p_linear_solver->Clear(); // Deallocating system vectors to avoid errors in MPI. Clear calls // TrilinosSpace::Clear for the vectors, which preserves the Map of // current vectors, performing MPI calls in the process. Due to the // way Python garbage collection works, this may happen after // MPI_Finalize has already been called and is an error. Resetting // the pointers here prevents Clear from operating with the // (now deallocated) vectors. mpA.reset(); mpDx.reset(); mpb.reset(); Clear(); } /** * @brief Set method for the time scheme * @param pScheme The pointer to the time scheme considered */ void SetScheme(typename TSchemeType::Pointer pScheme) { mpScheme = pScheme; }; /** * @brief Get method for the time scheme * @return mpScheme: The pointer to the time scheme considered */ typename TSchemeType::Pointer GetScheme() { return mpScheme; }; /** * @brief Set method for the builder and solver * @param pNewBuilderAndSolver The pointer to the builder and solver considered */ void SetBuilderAndSolver(typename TBuilderAndSolverType::Pointer pNewBuilderAndSolver) { mpBuilderAndSolver = pNewBuilderAndSolver; }; /** * @brief Get method for the builder and solver * @return mpBuilderAndSolver: The pointer to the builder and solver considered */ typename TBuilderAndSolverType::Pointer GetBuilderAndSolver() { return mpBuilderAndSolver; }; /** * @brief This method sets the flag mInitializeWasPerformed * @param InitializePerformedFlag The flag that tells if the initialize has been computed */ void SetInitializePerformedFlag(bool InitializePerformedFlag = true) { mInitializeWasPerformed = InitializePerformedFlag; } /** * @brief This method gets the flag mInitializeWasPerformed * @return mInitializeWasPerformed: The flag that tells if the initialize has been computed */ bool GetInitializePerformedFlag() { return mInitializeWasPerformed; } /** * @brief This method sets the flag mCalculateReactionsFlag * @param CalculateReactionsFlag The flag that tells if the reactions are computed */ void SetCalculateReactionsFlag(bool CalculateReactionsFlag) { mCalculateReactionsFlag = CalculateReactionsFlag; } /** * @brief This method returns the flag mCalculateReactionsFlag * @return The flag that tells if the reactions are computed */ bool GetCalculateReactionsFlag() { return mCalculateReactionsFlag; } /** * @brief This method sets the flag mReformDofSetAtEachStep * @param Flag The flag that tells if each time step the system is rebuilt */ void SetReformDofSetAtEachStepFlag(bool Flag) { mReformDofSetAtEachStep = Flag; GetBuilderAndSolver()->SetReshapeMatrixFlag(mReformDofSetAtEachStep); } /** * @brief This method returns the flag mReformDofSetAtEachStep * @return The flag that tells if each time step the system is rebuilt */ bool GetReformDofSetAtEachStepFlag() { return mReformDofSetAtEachStep; } /** * @brief This method sets the flag mMaxIterationNumber * @param MaxIterationNumber This is the maximum number of on linear iterations */ void SetMaxIterationNumber(unsigned int MaxIterationNumber) { mMaxIterationNumber = MaxIterationNumber; } /** * @brief This method gets the flag mMaxIterationNumber * @return mMaxIterationNumber: This is the maximum number of on linear iterations */ unsigned int GetMaxIterationNumber() { return mMaxIterationNumber; } /** * @brief It sets the level of echo for the solving strategy * @param Level The level to set * @details The different levels of echo are: * - 0: Mute... no echo at all * - 1: Printing time and basic informations * - 2: Printing linear solver data * - 3: Print of debug informations: Echo of stiffness matrix, Dx, b... */ void SetEchoLevel(int Level) override { BaseType::mEchoLevel = Level; GetBuilderAndSolver()->SetEchoLevel(Level); } //********************************************************************************* /**OPERATIONS ACCESSIBLE FROM THE INPUT: **/ /** * @brief Operation to predict the solution ... if it is not called a trivial predictor is used in which the values of the solution step of interest are assumed equal to the old values */ void Predict() override { KRATOS_TRY //OPERATIONS THAT SHOULD BE DONE ONCE - internal check to avoid repetitions //if the operations needed were already performed this does nothing if (mInitializeWasPerformed == false) Initialize(); //initialize solution step if (mSolutionStepIsInitialized == false) InitializeSolutionStep(); TSystemMatrixType& rA = *mpA; TSystemVectorType& rDx = *mpDx; TSystemVectorType& rb = *mpb; DofsArrayType& r_dof_set = GetBuilderAndSolver()->GetDofSet(); GetScheme()->Predict(BaseType::GetModelPart(), r_dof_set, rA, rDx, rb); if(BaseType::GetModelPart().MasterSlaveConstraints().size() != 0) { const auto& rProcessInfo = BaseType::GetModelPart().GetProcessInfo(); auto it_begin = BaseType::GetModelPart().MasterSlaveConstraints().begin(); #pragma omp parallel for firstprivate(it_begin) for(int i=0; i<static_cast<int>(BaseType::GetModelPart().MasterSlaveConstraints().size()); ++i) (it_begin+i)->ResetSlaveDofs(rProcessInfo); #pragma omp parallel for firstprivate(it_begin) for(int i=0; i<static_cast<int>(BaseType::GetModelPart().MasterSlaveConstraints().size()); ++i) (it_begin+i)->Apply(rProcessInfo); //the following is needed since we need to eventually compute time derivatives after applying //Master slave relations TSparseSpace::SetToZero(rDx); this->GetScheme()->Update(BaseType::GetModelPart(), r_dof_set, rA, rDx, rb); } //move the mesh if needed if (this->MoveMeshFlag() == true) BaseType::MoveMesh(); KRATOS_CATCH("") } /** * @brief Initialization of member variables and prior operations */ void Initialize() override { KRATOS_TRY; if (mInitializeWasPerformed == false) { //pointers needed in the solution typename TSchemeType::Pointer p_scheme = GetScheme(); typename TConvergenceCriteriaType::Pointer p_convergence_criteria = mpConvergenceCriteria; //Initialize The Scheme - OPERATIONS TO BE DONE ONCE if (p_scheme->SchemeIsInitialized() == false) p_scheme->Initialize(BaseType::GetModelPart()); //Initialize The Elements - OPERATIONS TO BE DONE ONCE if (p_scheme->ElementsAreInitialized() == false) p_scheme->InitializeElements(BaseType::GetModelPart()); //Initialize The Conditions - OPERATIONS TO BE DONE ONCE if (p_scheme->ConditionsAreInitialized() == false) p_scheme->InitializeConditions(BaseType::GetModelPart()); //initialisation of the convergence criteria if (p_convergence_criteria->IsInitialized() == false) p_convergence_criteria->Initialize(BaseType::GetModelPart()); mInitializeWasPerformed = true; } KRATOS_CATCH(""); } /** * @brief Clears the internal storage */ void Clear() override { KRATOS_TRY; // if the preconditioner is saved between solves, it // should be cleared here. GetBuilderAndSolver()->GetLinearSystemSolver()->Clear(); if (mpA != nullptr) SparseSpaceType::Clear(mpA); if (mpDx != nullptr) SparseSpaceType::Clear(mpDx); if (mpb != nullptr) SparseSpaceType::Clear(mpb); //setting to zero the internal flag to ensure that the dof sets are recalculated GetBuilderAndSolver()->SetDofSetIsInitializedFlag(false); GetBuilderAndSolver()->Clear(); GetScheme()->Clear(); mInitializeWasPerformed = false; mSolutionStepIsInitialized = false; KRATOS_CATCH(""); } /** * @brief This should be considered as a "post solution" convergence check which is useful for coupled analysis - the convergence criteria used is the one used inside the "solve" step */ bool IsConverged() override { KRATOS_TRY; TSystemMatrixType& rA = *mpA; TSystemVectorType& rDx = *mpDx; TSystemVectorType& rb = *mpb; if (mpConvergenceCriteria->GetActualizeRHSflag() == true) GetBuilderAndSolver()->BuildRHS(GetScheme(), BaseType::GetModelPart(), rb); return mpConvergenceCriteria->PostCriteria(BaseType::GetModelPart(), GetBuilderAndSolver()->GetDofSet(), rA, rDx, rb); KRATOS_CATCH(""); } /** * @brief This operations should be called before printing the results when non trivial results * (e.g. stresses) * Need to be calculated given the solution of the step * @details This operations should be called only when needed, before printing as it can involve a non * negligible cost */ void CalculateOutputData() override { TSystemMatrixType& rA = *mpA; TSystemVectorType& rDx = *mpDx; TSystemVectorType& rb = *mpb; GetScheme()->CalculateOutputData(BaseType::GetModelPart(), GetBuilderAndSolver()->GetDofSet(), rA, rDx, rb); } /** * @brief Performs all the required operations that should be done (for each step) before solving the solution step. * @details A member variable should be used as a flag to make sure this function is called only once per step. */ void InitializeSolutionStep() override { KRATOS_TRY; if (!mSolutionStepIsInitialized) { // Pointers needed in the solution typename TSchemeType::Pointer p_scheme = GetScheme(); typename TBuilderAndSolverType::Pointer p_builder_and_solver = GetBuilderAndSolver(); ModelPart& r_model_part = BaseType::GetModelPart(); const int rank = r_model_part.GetCommunicator().MyPID(); //set up the system, operation performed just once unless it is required //to reform the dof set at each iteration BuiltinTimer system_construction_time; if (p_builder_and_solver->GetDofSetIsInitializedFlag() == false || mReformDofSetAtEachStep == true) { //setting up the list of the DOFs to be solved BuiltinTimer setup_dofs_time; p_builder_and_solver->SetUpDofSet(p_scheme, r_model_part); KRATOS_INFO_IF("Setup Dofs Time", BaseType::GetEchoLevel() > 0 && rank == 0) << setup_dofs_time.ElapsedSeconds() << std::endl; //shaping correctly the system BuiltinTimer setup_system_time; p_builder_and_solver->SetUpSystem(r_model_part); KRATOS_INFO_IF("Setup System Time", BaseType::GetEchoLevel() > 0 && rank == 0) << setup_system_time.ElapsedSeconds() << std::endl; //setting up the Vectors involved to the correct size BuiltinTimer system_matrix_resize_time; p_builder_and_solver->ResizeAndInitializeVectors(p_scheme, mpA, mpDx, mpb, r_model_part); KRATOS_INFO_IF("System Matrix Resize Time", BaseType::GetEchoLevel() > 0 && rank == 0) << system_matrix_resize_time.ElapsedSeconds() << std::endl; } KRATOS_INFO_IF("System Construction Time", BaseType::GetEchoLevel() > 0 && rank == 0) << system_construction_time.ElapsedSeconds() << std::endl; TSystemMatrixType& rA = *mpA; TSystemVectorType& rDx = *mpDx; TSystemVectorType& rb = *mpb; // Initial operations ... things that are constant over the Solution Step p_builder_and_solver->InitializeSolutionStep(r_model_part, rA, rDx, rb); // Initial operations ... things that are constant over the Solution Step p_scheme->InitializeSolutionStep(r_model_part, rA, rDx, rb); // Initialisation of the convergence criteria if (mpConvergenceCriteria->GetActualizeRHSflag() == true) { TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHS(p_scheme, r_model_part, rb); } mpConvergenceCriteria->InitializeSolutionStep(r_model_part, p_builder_and_solver->GetDofSet(), rA, rDx, rb); if (mpConvergenceCriteria->GetActualizeRHSflag() == true) TSparseSpace::SetToZero(rb); mSolutionStepIsInitialized = true; } KRATOS_CATCH(""); } /** * @brief Performs all the required operations that should be done (for each step) after solving the solution step. * @details A member variable should be used as a flag to make sure this function is called only once per step. */ void FinalizeSolutionStep() override { KRATOS_TRY; typename TSchemeType::Pointer p_scheme = GetScheme(); typename TBuilderAndSolverType::Pointer p_builder_and_solver = GetBuilderAndSolver(); TSystemMatrixType& rA = *mpA; TSystemVectorType& rDx = *mpDx; TSystemVectorType& rb = *mpb; //Finalisation of the solution step, //operations to be done after achieving convergence, for example the //Final Residual Vector (mb) has to be saved in there //to avoid error accumulation p_scheme->FinalizeSolutionStep(BaseType::GetModelPart(), rA, rDx, rb); p_builder_and_solver->FinalizeSolutionStep(BaseType::GetModelPart(), rA, rDx, rb); //Cleaning memory after the solution p_scheme->Clean(); //reset flags for next step mSolutionStepIsInitialized = false; if (mReformDofSetAtEachStep == true) //deallocate the systemvectors { SparseSpaceType::Clear(mpA); SparseSpaceType::Clear(mpDx); SparseSpaceType::Clear(mpb); this->Clear(); } KRATOS_CATCH(""); } /** * @brief Solves the current step. This function returns true if a solution has been found, false otherwise. */ bool SolveSolutionStep() override { // Pointers needed in the solution typename TSchemeType::Pointer p_scheme = GetScheme(); typename TBuilderAndSolverType::Pointer p_builder_and_solver = GetBuilderAndSolver(); TSystemMatrixType& rA = *mpA; TSystemVectorType& rDx = *mpDx; TSystemVectorType& rb = *mpb; //initializing the parameters of the Newton-Raphson cycle unsigned int iteration_number = 1; BaseType::GetModelPart().GetProcessInfo()[NL_ITERATION_NUMBER] = iteration_number; bool is_converged = false; bool residual_is_updated = false; p_scheme->InitializeNonLinIteration(BaseType::GetModelPart(), rA, rDx, rb); is_converged = mpConvergenceCriteria->PreCriteria(BaseType::GetModelPart(), p_builder_and_solver->GetDofSet(), rA, rDx, rb); // Function to perform the building and the solving phase. if (BaseType::mRebuildLevel > 0 || BaseType::mStiffnessMatrixIsBuilt == false) { TSparseSpace::SetToZero(rA); TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildAndSolve(p_scheme, BaseType::GetModelPart(), rA, rDx, rb); } else { TSparseSpace::SetToZero(rDx); //Dx=0.00; TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHSAndSolve(p_scheme, BaseType::GetModelPart(), rA, rDx, rb); } // Debugging info EchoInfo(iteration_number); // Updating the results stored in the database UpdateDatabase(rA, rDx, rb, BaseType::MoveMeshFlag()); p_scheme->FinalizeNonLinIteration(BaseType::GetModelPart(), rA, rDx, rb); if (is_converged) { if (mpConvergenceCriteria->GetActualizeRHSflag()) { TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHS(p_scheme, BaseType::GetModelPart(), rb); } is_converged = mpConvergenceCriteria->PostCriteria(BaseType::GetModelPart(), p_builder_and_solver->GetDofSet(), rA, rDx, rb); } //Iteration Cycle... performed only for NonLinearProblems while (is_converged == false && iteration_number++ < mMaxIterationNumber) { //setting the number of iteration BaseType::GetModelPart().GetProcessInfo()[NL_ITERATION_NUMBER] = iteration_number; p_scheme->InitializeNonLinIteration(BaseType::GetModelPart(), rA, rDx, rb); is_converged = mpConvergenceCriteria->PreCriteria(BaseType::GetModelPart(), p_builder_and_solver->GetDofSet(), rA, rDx, rb); //call the linear system solver to find the correction mDx for the //it is not called if there is no system to solve if (SparseSpaceType::Size(rDx) != 0) { if (BaseType::mRebuildLevel > 1 || BaseType::mStiffnessMatrixIsBuilt == false) { if (GetKeepSystemConstantDuringIterations() == false) { //A = 0.00; TSparseSpace::SetToZero(rA); TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildAndSolve(p_scheme, BaseType::GetModelPart(), rA, rDx, rb); } else { TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHSAndSolve(p_scheme, BaseType::GetModelPart(), rA, rDx, rb); } } else { TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHSAndSolve(p_scheme, BaseType::GetModelPart(), rA, rDx, rb); } } else { KRATOS_WARNING("NO DOFS") << "ATTENTION: no free DOFs!! " << std::endl; } // Debugging info EchoInfo(iteration_number); // Updating the results stored in the database UpdateDatabase(rA, rDx, rb, BaseType::MoveMeshFlag()); p_scheme->FinalizeNonLinIteration(BaseType::GetModelPart(), rA, rDx, rb); residual_is_updated = false; if (is_converged == true) { if (mpConvergenceCriteria->GetActualizeRHSflag() == true) { TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHS(p_scheme, BaseType::GetModelPart(), rb); residual_is_updated = true; } is_converged = mpConvergenceCriteria->PostCriteria(BaseType::GetModelPart(), p_builder_and_solver->GetDofSet(), rA, rDx, rb); } } //plots a warning if the maximum number of iterations is exceeded if (iteration_number >= mMaxIterationNumber && BaseType::GetModelPart().GetCommunicator().MyPID() == 0) MaxIterationsExceeded(); //recalculate residual if needed //(note that some convergence criteria need it to be recalculated) if (residual_is_updated == false) { // NOTE: // The following part will be commented because it is time consuming // and there is no obvious reason to be here. If someone need this // part please notify the community via mailing list before uncommenting it. // Pooyan. // TSparseSpace::SetToZero(mb); // p_builder_and_solver->BuildRHS(p_scheme, BaseType::GetModelPart(), mb); } //calculate reactions if required if (mCalculateReactionsFlag == true) p_builder_and_solver->CalculateReactions(p_scheme, BaseType::GetModelPart(), rA, rDx, rb); return is_converged; } /** * @brief Function to perform expensive checks. * @details It is designed to be called ONCE to verify that the input is correct. */ int Check() override { KRATOS_TRY BaseType::Check(); GetBuilderAndSolver()->Check(BaseType::GetModelPart()); GetScheme()->Check(BaseType::GetModelPart()); mpConvergenceCriteria->Check(BaseType::GetModelPart()); return 0; KRATOS_CATCH("") } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ ///@} ///@name Access ///@{ /** * @brief This method returns the LHS matrix * @return The LHS matrix */ TSystemMatrixType &GetSystemMatrix() { TSystemMatrixType &mA = *mpA; return mA; } /** * @brief This method returns the RHS vector * @return The RHS vector */ TSystemVectorType& GetSystemVector() { TSystemVectorType& mb = *mpb; return mb; } /** * @brief This method returns the solution vector * @return The Dx vector */ TSystemVectorType& GetSolutionVector() { TSystemVectorType& mDx = *mpDx; return mDx; } /** * @brief Set method for the flag mKeepSystemConstantDuringIterations * @param Value If we consider constant the system of equations during the iterations */ void SetKeepSystemConstantDuringIterations(bool Value) { mKeepSystemConstantDuringIterations = Value; } /** * @brief Get method for the flag mKeepSystemConstantDuringIterations * @return True if we consider constant the system of equations during the iterations, false otherwise */ bool GetKeepSystemConstantDuringIterations() { return mKeepSystemConstantDuringIterations; } ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualBasedNewtonRaphsonStrategy"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << Info(); } ///@} ///@name Friends ///@{ ///@} private: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} protected: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ typename TLinearSolver::Pointer mpLinearSolver; /// The pointer to the linear solver considered typename TSchemeType::Pointer mpScheme; /// The pointer to the time scheme employed typename TBuilderAndSolverType::Pointer mpBuilderAndSolver; /// The pointer to the builder and solver employed typename TConvergenceCriteriaType::Pointer mpConvergenceCriteria; /// The pointer to the convergence criteria employed TSystemVectorPointerType mpDx; /// The incremement in the solution TSystemVectorPointerType mpb; /// The RHS vector of the system of equations TSystemMatrixPointerType mpA; /// The LHS matrix of the system of equations /** * @brief Flag telling if it is needed to reform the DofSet at each solution step or if it is possible to form it just once * @details Default = false - true : Reforme at each time step - false : Form just one (more efficient) */ bool mReformDofSetAtEachStep; /** * @brief Flag telling if it is needed or not to compute the reactions * @details default = true */ bool mCalculateReactionsFlag; bool mSolutionStepIsInitialized; /// Flag to set as initialized the solution step unsigned int mMaxIterationNumber; /// The maximum number of iterations, 30 by default bool mInitializeWasPerformed; /// Flag to set as initialized the strategy bool mKeepSystemConstantDuringIterations; // Flag to allow keeping system matrix constant during iterations ///@} ///@name Private Operators ///@{ /** * @brief Here the database is updated * @param A The LHS matrix of the system of equations * @param Dx The incremement in the solution * @param b The RHS vector of the system of equations * @param MoveMesh The flag that allows to move the mesh */ virtual void UpdateDatabase( TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb, const bool MoveMesh) { typename TSchemeType::Pointer p_scheme = GetScheme(); typename TBuilderAndSolverType::Pointer p_builder_and_solver = GetBuilderAndSolver(); p_scheme->Update(BaseType::GetModelPart(), p_builder_and_solver->GetDofSet(), rA, rDx, rb); // Move the mesh if needed if (MoveMesh == true) BaseType::MoveMesh(); } /** * @brief This method returns the components of the system of equations depending of the echo level * @param IterationNumber The non linear iteration in the solution loop */ virtual void EchoInfo(const unsigned int IterationNumber) { TSystemMatrixType& rA = *mpA; TSystemVectorType& rDx = *mpDx; TSystemVectorType& rb = *mpb; if (this->GetEchoLevel() == 2) //if it is needed to print the debug info { KRATOS_INFO("Dx") << "Solution obtained = " << rDx << std::endl; KRATOS_INFO("RHS") << "RHS = " << rb << std::endl; } else if (this->GetEchoLevel() == 3) //if it is needed to print the debug info { KRATOS_INFO("LHS") << "SystemMatrix = " << rA << std::endl; KRATOS_INFO("Dx") << "Solution obtained = " << rDx << std::endl; KRATOS_INFO("RHS") << "RHS = " << rb << std::endl; } else if (this->GetEchoLevel() == 4) //print to matrix market file { std::stringstream matrix_market_name; matrix_market_name << "A_" << BaseType::GetModelPart().GetProcessInfo()[TIME] << "_" << IterationNumber << ".mm"; TSparseSpace::WriteMatrixMarketMatrix((char *)(matrix_market_name.str()).c_str(), rA, false); std::stringstream matrix_market_vectname; matrix_market_vectname << "b_" << BaseType::GetModelPart().GetProcessInfo()[TIME] << "_" << IterationNumber << ".mm.rhs"; TSparseSpace::WriteMatrixMarketVector((char *)(matrix_market_vectname.str()).c_str(), rb); } } /** * @brief This method prints information after reach the max number of iterations * @todo Replace by logger */ virtual void MaxIterationsExceeded() { if (this->GetEchoLevel() != 0 && BaseType::GetModelPart().GetCommunicator().MyPID() == 0) { std::cout << "***************************************************" << std::endl; std::cout << "******* ATTENTION: max iterations exceeded ********" << std::endl; std::cout << "***************************************************" << std::endl; } } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /** * Copy constructor. */ ResidualBasedNewtonRaphsonStrategy(const ResidualBasedNewtonRaphsonStrategy &Other){}; ///@} }; /* Class ResidualBasedNewtonRaphsonStrategy */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos. */ #endif /* KRATOS_RESIDUALBASED_NEWTON_RAPHSON_STRATEGY defined */
lockarray.c
/* test fine grained locks instead of critical section by Chunhua Liao */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #define LOCKNUM 100 #endif #define SIZE 5000 int main(void) { int a[SIZE]; int i,j,sum,lock_index; #ifdef _OPENMP omp_lock_t lck[LOCKNUM]; for (i=0;i<LOCKNUM;i++) omp_init_lock(&(lck[i])); #endif for (i=0;i<SIZE;i++) a[i]=0; #pragma omp parallel private (i,j,lock_index) { /*critical version*/ #pragma omp for schedule(dynamic,1) for (i=0;i<SIZE;i++) { j=(i*i)%SIZE; #pragma omp critical { a[j]=a[j]+5; } } /* fine grained lock version*/ #pragma omp for schedule(dynamic,1) for (i=0;i<SIZE;i++) { j=(i*i)%SIZE; #ifdef _OPENMP lock_index= j%LOCKNUM; // omp_set_lock(lck[lock_index]); #endif a[j]=a[j]-5; #ifdef _OPENMP // omp_unset_lock(lck[lock_index]); #endif } /*verify the result*/ sum=0; #pragma omp for reduction (+:sum) for (i=0;i<SIZE;i++) { sum+=a[i]; } } /* destroy locks*/ #ifdef _OPENMP for (i=0;i<LOCKNUM;i++) omp_destroy_lock(&(lck[i])); #endif printf("sum of a[] = %d\n",sum); return 0; }
boundary_mask_l1_mex.c
#include <inttypes.h> #include <omp.h> #include "mex.h" #include "boundary_mask_l1_mex.h" void boundary_mask_l1(uint8_t *B, const uint8_t *G, const size_t *sz, const uint8_t l1); #ifdef BOUNDARY_MASK_L1_MEX void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs != 3) || (nlhs > 1)) { mexErrMsgTxt("Usage: boundary_mask_mex(B, G, l1);"); } uint8_t *B = (uint8_t *)mxGetData(prhs[0]); const uint8_t *G = (const uint8_t *)mxGetData(prhs[1]); const uint8_t l1 = (const uint8_t)mxGetScalar(prhs[2]); const size_t *sz = (const size_t *)mxGetDimensions(prhs[0]); boundary_mask_l1(B, G, sz, l1); if (nlhs == 1) { plhs[0] = mxCreateDoubleScalar(1.0); } return; } #endif void mx_boundary_mask_l1(mxArray *mxB, const mxArray *mxG, uint8_t l1) { uint8_t *B = (uint8_t *)mxGetData(mxB); const uint8_t *G = (const uint8_t *)mxGetData(mxG); const size_t *sz = (const size_t *)mxGetDimensions(mxG); boundary_mask_l1(B, G, sz, l1); return; } void boundary_mask_l1(uint8_t *B, const uint8_t *G, const size_t *sz, const uint8_t l1) { size_t i, j, k; size_t l; const size_t nx = sz[0]; const size_t ny = sz[1]; const size_t nz = sz[2]; const size_t nxny = nx*ny; const size_t nxnynz = nx*ny*nz; size_t NX = nx-1; size_t NY = nx*(ny-1); size_t NZ = nxny*(nz-1); uint8_t *GL = (uint8_t *)calloc(nx*ny*nz, sizeof(*G)); #pragma omp parallel for private(i,j,k,l) schedule(static) \ if(nxny*nz > 32*32*32) for(k = 0; k < nxnynz; k += nxny) { for(j = 0; j < nxny; j += nx) { l = j + k; for(i = 0; i < nx; ++i, ++l) { if ((i == 0) || (j == 0) || (k == 0) || (i == NX) || (j == NY) || (k == NZ)) { B[l] = GL[l] = G[l]; } else { B[l] = GL[l] = G[l] && !(G[l-1] && G[l+1] && G[l-nx] && G[l+nx] && G[l-nxny] && G[l+nxny]); } } } } for(size_t L1 = 1; L1 < l1; ++L1) { #pragma omp parallel for private(i,j,k,l) schedule(static) \ if(nxny*nz > 32*32*32) for(k = L1*nxny; k < nxnynz-L1*nxny; k += nxny) { for(j = L1*nx; j < nxny-L1*nx; j += nx) { l = L1 + j + k; for(i = L1; i < nx-L1; ++i, ++l) { if (G[l] && !GL[l] && ((GL[l-1] == L1) || (GL[l+1] == L1) || (GL[l-nx] == L1) || (GL[l+nx] == L1) || (GL[l-nxny] == L1) || (GL[l+nxny] == L1))) { B[l] = 1; GL[l] = L1+1; } } } } } if (NULL != GL) { free(GL); GL = NULL; } return; }
mandel-omp-task-point.c
/* * Sequential Mandelbrot program * * This program computes and displays all or part of the Mandelbrot * set. By default, it examines all points in the complex plane * that have both real and imaginary parts between -2 and 2. * Command-line parameters allow zooming in on a specific part of * this range. * * Usage: * mandel [-i maxiter -c x0 y0 -s size -w windowsize] * where * maxiter denotes the maximum number of iterations at each point -- by default 1000 * x0, y0, and size specify the range to examine (a square * centered at (x0 + iy0) of size 2*size by 2*size -- by default, * a square of size 4 by 4 centered at the origin) * windowsize denotes the size of the image (diplay window) to compute * * Input: none, except the optional command-line arguments * Output: a graphical display as described in Wilkinson & Allen, * displayed using the X Window system, plus text output to * standard output showing the above parameters, plus execution * time in seconds. * * Code based on the original code from Web site for Wilkinson and Allen's * text on parallel programming: * http://www.cs.uncc.edu/~abw/parallel/par_prog/ * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <malloc.h> #if _DISPLAY_ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #endif #include <sys/time.h> double getusec_() { struct timeval time; gettimeofday(&time, NULL); return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec); } #define START_COUNT_TIME stamp = getusec_(); #define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\ stamp = stamp/1e6;\ printf ("%s: %0.6fs\n",(_m), stamp); /* Default values for things. */ #define N 2 /* size of problem space (x, y from -N to N) */ #define NPIXELS 800 /* size of display window in pixels */ int row, col; // variables used to traverse the problem space /* Structure definition for complex numbers */ typedef struct { double real, imag; } complex; #if _DISPLAY_ /* Functions for GUI */ #include "mandelbrot-gui.h" /* has setup(), interact() */ #endif void mandelbrot(int height, int width, double real_min, double imag_min, double scale_real, double scale_imag, int maxiter, #if _DISPLAY_ int setup_return, Display *display, Window win, GC gc, double scale_color, double min_color) #else int ** output) #endif { /* Calculate points and save/display */ //#pragma omp for schedule(runtime) #pragma omp parallel #pragma omp single { for (row = 0; row < height; ++row) { for (col = 0; col < width; ++col) { #pragma omp task firstprivate(row,col) { complex z, c; z.real = z.imag = 0; /* Scale display coordinates to actual region */ c.real = real_min + ((double) col * scale_real); c.imag = imag_min + ((double) (height-1-row) * scale_imag); /* height-1-row so y axis displays * with larger values at top */ /* Calculate z0, z1, .... until divergence or maximum iterations */ int k = 0; double lengthsq, temp; do { temp = z.real*z.real - z.imag*z.imag + c.real; z.imag = 2*z.real*z.imag + c.imag; z.real = temp; lengthsq = z.real*z.real + z.imag*z.imag; ++k; } while (lengthsq < (N*N) && k < maxiter); #if _DISPLAY_ /* Scale color and display point */ long color = (long) ((k-1) * scale_color) + min_color; if (setup_return == EXIT_SUCCESS) { #pragma omp critical { XSetForeground (display, gc, color); XDrawPoint (display, win, gc, col, row); } } #else output[row][col]=k; #endif } } } } } int main(int argc, char *argv[]) { int maxiter = 1000; double real_min; double real_max; double imag_min; double imag_max; int width = NPIXELS; /* dimensions of display window */ int height = NPIXELS; double size=N, x0 = 0, y0 = 0; #if _DISPLAY_ Display *display; Window win; GC gc; int setup_return; long min_color = 0, max_color = 0; double scale_color; #else int ** output; FILE *fp = NULL; #endif double scale_real, scale_imag; /* Process command-line arguments */ for (int i=1; i<argc; i++) { if (strcmp(argv[i], "-i")==0) { maxiter = atoi(argv[++i]); } else if (strcmp(argv[i], "-w")==0) { width = atoi(argv[++i]); height = width; } else if (strcmp(argv[i], "-s")==0) { size = atof(argv[++i]); } #if !_DISPLAY_ else if (strcmp(argv[i], "-o")==0) { if((fp=fopen("mandel.out", "wb"))==NULL) { fprintf(stderr, "Unable to open file\n"); return EXIT_FAILURE; } } #endif else if (strcmp(argv[i], "-c")==0) { x0 = atof(argv[++i]); y0 = atof(argv[++i]); } else { #if _DISPLAY_ fprintf(stderr, "Usage: %s [-i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]); #else fprintf(stderr, "Usage: %s [-o -i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]); fprintf(stderr, " -o to write computed image to disk (default no file generated)\n"); #endif fprintf(stderr, " -i to specify maximum number of iterations at each point (default 1000)\n"); #if _DISPLAY_ fprintf(stderr, " -w to specify the size of the display window (default 800x800 pixels)\n"); #else fprintf(stderr, " -w to specify the size of the image to compute (default 800x800 elements)\n"); #endif fprintf(stderr, " -c to specify the center x0+iy0 of the square to compute (default origin)\n"); fprintf(stderr, " -s to specify the size of the square to compute (default 2, i.e. size 4 by 4)\n"); return EXIT_FAILURE; } } real_min = x0 - size; real_max = x0 + size; imag_min = y0 - size; imag_max = y0 + size; /* Produce text output */ fprintf(stdout, "\n"); fprintf(stdout, "Mandelbrot program\n"); fprintf(stdout, "center = (%g, %g), size = %g\n", (real_max + real_min)/2, (imag_max + imag_min)/2, (real_max - real_min)/2); fprintf(stdout, "maximum iterations = %d\n", maxiter); fprintf(stdout, "\n"); #if _DISPLAY_ /* Initialize for graphical display */ setup_return = setup(width, height, &display, &win, &gc, &min_color, &max_color); if (setup_return != EXIT_SUCCESS) { fprintf(stderr, "Unable to initialize display, continuing\n"); return EXIT_FAILURE; } #else output = malloc(height*sizeof(int *)); for (int row = 0; row < height; ++row) output[row] = malloc(width*sizeof(int)); #endif /* Compute factors to scale computational region to window */ scale_real = (double) (real_max - real_min) / (double) width; scale_imag = (double) (imag_max - imag_min) / (double) height; #if _DISPLAY_ /* Compute factor for color scaling */ scale_color = (double) (max_color - min_color) / (double) (maxiter - 1); #endif /* Start timing */ double stamp; START_COUNT_TIME; #if _DISPLAY_ mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter, setup_return, display, win, gc, scale_color, min_color); #else mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter, output); #endif /* End timing */ STOP_COUNT_TIME("Total execution time"); /* Be sure all output is written */ #if _DISPLAY_ if (setup_return == EXIT_SUCCESS) { XFlush (display); } #else if (fp != NULL) { for (int row = 0; row < height; ++row) if(fwrite(output[row], sizeof(int), width, fp) != width) { fprintf(stderr, "Output file not written correctly\n"); } } #endif #if _DISPLAY_ /* Wait for user response, then exit program */ if (setup_return == EXIT_SUCCESS) { interact(display, &win, width, height, real_min, real_max, imag_min, imag_max); } return EXIT_SUCCESS; #endif }
TemporalReflectionPadding.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/TemporalReflectionPadding.c" #else static void THNN_(TemporalReflectionPadding_updateOutput_frame)( real *input_p, real *output_p, long nslices, long iwidth, long owidth, int pad_l, int pad_r) { int iStartX = fmax(0, -pad_l); int oStartX = fmax(0, pad_l); long k, ip_x; #pragma omp parallel for private(k, ip_x) for (k = 0; k < nslices; k++) { long j; for (j = 0; j < owidth; j++) { if (j < pad_l) { ip_x = pad_l * 2 - j; } else if (j >= pad_l && j < iwidth + pad_l) { ip_x = j; } else { ip_x = (iwidth + pad_l - 1) * 2 - j; } ip_x = ip_x - oStartX + iStartX; /* real *dest_p = output_p + k*owidth*oheight + i * owidth + j; */ real *dest_p = output_p + k*owidth + j; real *src_p = input_p + k*iwidth + ip_x; *dest_p = *src_p; } } } void THNN_(TemporalReflectionPadding_updateOutput)(THNNState *state, THTensor *input, THTensor *output, int pad_l, int pad_r) { int dimw = 1; int dimslices = 0; long nbatch = 1; long nslices; long iwidth; long owidth; real *input_data; real *output_data; THNN_ARGCHECK(!input->is_empty() && (input->dim() == 2 || input->dim() == 3), 2, input, "non-empty 2D or 3D (batch mode) tensor expected for input, but got: %s"); if (input->dim() == 3) { nbatch = input->size(0); dimw++; dimslices++; } /* input size */ nslices = input->size(dimslices); iwidth = input->size(dimw); AT_CHECK(pad_l < iwidth && pad_r < iwidth, "Argument #4: Padding size should be less than the corresponding input dimension, " "but got: padding (", pad_l, ", ", pad_r, ") at dimension ", dimw, " of input ", input->sizes()); /* output size */ owidth = iwidth + pad_l + pad_r; THArgCheck(owidth >= 1 , 2, "input (W: %d)is too small." " Calculated output W: %d", iwidth, owidth); /* get contiguous input */ input = THTensor_(newContiguous)(input); /* resize output */ if (input->dim() == 2) { THTensor_(resize2d)(output, nslices, owidth); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); THNN_(TemporalReflectionPadding_updateOutput_frame)(input_data, output_data, nslices, iwidth, owidth, pad_l, pad_r); } else { long p; THTensor_(resize3d)(output, nbatch, nslices, owidth); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); #pragma omp parallel for private(p) for (p = 0; p < nbatch; p++) { THNN_(TemporalReflectionPadding_updateOutput_frame)( input_data+p*nslices*iwidth, output_data+p*nslices*owidth, nslices, iwidth, owidth, pad_l, pad_r); } } /* cleanup */ THTensor_(free)(input); } static void THNN_(TemporalReflectionPadding_updateGradInput_frame)( real *ginput_p, real *goutput_p, long nslices, long iwidth, long owidth, int pad_l, int pad_r) { int iStartX = fmax(0, -pad_l); int oStartX = fmax(0, pad_l); long k, ip_x; #pragma omp parallel for private(k, ip_x) for (k = 0; k < nslices; k++) { long j; for (j = 0; j < owidth; j++) { if (j < pad_l) { ip_x = pad_l * 2 - j; } else if (j >= pad_l && j < iwidth + pad_l) { ip_x = j; } else { ip_x = (iwidth + pad_l - 1) * 2 - j; } ip_x = ip_x - oStartX + iStartX; real *src_p = goutput_p + k*owidth + j; real *dest_p = ginput_p + k*iwidth + ip_x; *dest_p += *src_p; } } } void THNN_(TemporalReflectionPadding_updateGradInput)(THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, int pad_l, int pad_r) { int dimw = 1; int dimslices = 0; long nbatch = 1; long nslices; long iwidth; long owidth; if (input->dim() == 3) { nbatch = input->size(0); dimw++; dimslices++; } /* sizes */ nslices = input->size(dimslices); iwidth = input->size(dimw); owidth = iwidth + pad_l + pad_r; THArgCheck(owidth == THTensor_(size)(gradOutput, dimw), 3, "gradOutput width unexpected. Expected: %d, Got: %d", owidth, THTensor_(size)(gradOutput, dimw)); /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); /* backprop */ if (input->dim() == 2) { THNN_(TemporalReflectionPadding_updateGradInput_frame)( THTensor_(data)(gradInput), THTensor_(data)(gradOutput), nslices, iwidth, owidth, pad_l, pad_r); } else { long p; #pragma omp parallel for private(p) for (p = 0; p < nbatch; p++) { THNN_(TemporalReflectionPadding_updateGradInput_frame)( THTensor_(data)(gradInput) + p * nslices * iwidth, THTensor_(data)(gradOutput) + p * nslices * owidth, nslices, iwidth, owidth, pad_l, pad_r); } } /* cleanup */ THTensor_(free)(gradOutput); } #endif
lock-unrelated.c
/* * lock-unrelated.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run-race | FileCheck %s #include <omp.h> #include <stdio.h> int main(int argc, char *argv[]) { int var = 0; omp_lock_t lock; omp_init_lock(&lock); #pragma omp parallel num_threads(2) shared(var) { omp_set_lock(&lock); // Dummy locking. omp_unset_lock(&lock); var++; } omp_destroy_lock(&lock); int error = (var != 2); fprintf(stderr, "DONE\n"); return error; } // CHECK: WARNING: ThreadSanitizer: data race // CHECK-NEXT: {{(Write|Read)}} of size 4 // CHECK-NEXT: #0 {{.*}}lock-unrelated.c:31 // CHECK: Previous write of size 4 // CHECK-NEXT: #0 {{.*}}lock-unrelated.c:31 // CHECK: DONE // CHECK: ThreadSanitizer: reported 1 warnings
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 16; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. 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 ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=2*Nt-2;t1++) { lbp=ceild(t1+2,2); ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-4,8),ceild(4*t2-Nz-3,16));t3<=min(min(floord(4*Nt+Ny-9,16),floord(2*t1+Ny-3,16)),floord(4*t2+Ny-9,16));t3++) { for (t4=max(max(ceild(t1-124,128),ceild(4*t2-Nz-243,256)),ceild(16*t3-Ny-243,256));t4<=min(min(min(floord(4*Nt+Nx-9,256),floord(2*t1+Nx-3,256)),floord(4*t2+Nx-9,256)),floord(16*t3+Nx+3,256));t4++) { for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(256*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) { for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(256*t4,4*t5+4); ubv=min(256*t4+255,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
update_c99.c
#ifdef __ICC #include <omp.h> #endif /** * Recommended reference for multi-dimensional array handling in C99 * by Jeff Hammond: * * https://github.com/jeffhammond/HPCInfo/blob/master/c99/array3d.c */ void update_c99(double *data_new, const double *data_old, int dim_x, int dim_y, int dim_z) { // cast types here to maintain a C++-compatible signature: double (* const restrict grid_old)[dim_y][dim_x] = (double (* const)[dim_y][dim_x])data_old; double (* restrict grid_new)[dim_y][dim_x] = (double (* )[dim_y][dim_x])data_new; #pragma omp parallel for schedule(static) for (int z = 1; z < (dim_z - 1); ++z) { for (int y = 1; y < (dim_y - 1); ++y) { #ifdef __ICC #pragma vector always nontemporal #endif for (int x = 1; x < (dim_x - 1); ++x) { grid_new[z][y][x] = (grid_old[z - 1][y ][x ] + grid_old[z ][y - 1][x ] + grid_old[z ][y ][x - 1] + grid_old[z ][y ][x + 1] + grid_old[z ][y + 1][x ] + grid_old[z + 1][y ][x ]) * (1.0 / 6.0); } } } }
duplex.c
/* * compute the duplex structure of two RNA strands, * allowing only inter-strand base pairs. * see cofold() for computing hybrid structures without * restriction. * * Ivo Hofacker * Vienna RNA package */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/fold.h" #include "ViennaRNA/pair_mat.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/alifold.h" #include "ViennaRNA/subopt.h" #include "ViennaRNA/loops/all.h" #include "ViennaRNA/duplex.h" #ifdef _OPENMP #include <omp.h> #endif #define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */ #define NEW_NINIO 1 /* new asymetry penalty */ #define MAXSECTORS 500 /* dimension for a backtrack array */ #define LOCALITY 0. /* locality parameter for base-pairs */ #define UNIT 100 #define MINPSCORE -2 * UNIT #define NONE -10000 /* score for forbidden pairs */ /* ################################# # GLOBAL VARIABLES # ################################# */ /* ################################# # PRIVATE VARIABLES # ################################# */ PRIVATE vrna_param_t *P = NULL; PRIVATE int **c = NULL; /* energy array, given that i-j pair */ PRIVATE short *S1 = NULL, *SS1 = NULL, *S2 = NULL, *SS2 = NULL; PRIVATE int n1, n2; /* sequence lengths */ #ifdef _OPENMP /* NOTE: all variables are assumed to be uninitialized if they are declared as threadprivate */ #pragma omp threadprivate(P, c, S1, SS1, S2, SS2, n1, n2) #endif /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE duplexT duplexfold_cu(const char *s1, const char *s2, int clean_up); PRIVATE duplexT aliduplexfold_cu(const char *s1[], const char *s2[], int clean_up); PRIVATE char * backtrack(int i, int j); PRIVATE char * alibacktrack(int i, int j, const short **S1, const short **S2); PRIVATE int compare(const void *sub1, const void *sub2); PRIVATE int covscore(const int *types, int n_seq); /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC duplexT duplexfold(const char *s1, const char *s2) { return duplexfold_cu(s1, s2, 1); } PRIVATE duplexT duplexfold_cu(const char *s1, const char *s2, int clean_up) { int i, j, Emin = INF, i_min = 0, j_min = 0; char *struc; duplexT mfe; vrna_md_t md; n1 = (int)strlen(s1); n2 = (int)strlen(s2); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } c = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); for (i = 1; i <= n1; i++) c[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); S1 = encode_sequence(s1, 0); S2 = encode_sequence(s2, 0); SS1 = encode_sequence(s1, 1); SS2 = encode_sequence(s2, 1); for (i = 1; i <= n1; i++) { for (j = n2; j > 0; j--) { int type, type2, E, k, l; type = pair[S1[i]][S2[j]]; c[i][j] = type ? P->DuplexInit : INF; if (!type) continue; c[i][j] += E_ExtLoop(type, (i > 1) ? SS1[i - 1] : -1, (j < n2) ? SS2[j + 1] : -1, P); for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) { for (l = j + 1; l <= n2; l++) { if (i - k + l - j - 2 > MAXLOOP) break; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; E = E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type], SS1[k + 1], SS2[l - 1], SS1[i - 1], SS2[j + 1], P); c[i][j] = MIN2(c[i][j], c[k][l] + E); } } E = c[i][j]; E += E_ExtLoop(rtype[type], (j > 1) ? SS2[j - 1] : -1, (i < n1) ? SS1[i + 1] : -1, P); if (E < Emin) { Emin = E; i_min = i; j_min = j; } } } struc = backtrack(i_min, j_min); if (i_min < n1) i_min++; if (j_min > 1) j_min--; mfe.i = i_min; mfe.j = j_min; mfe.energy = (float)Emin / 100.; mfe.structure = struc; if (clean_up) { for (i = 1; i <= n1; i++) free(c[i]); free(c); free(S1); free(S2); free(SS1); free(SS2); } return mfe; } PUBLIC duplexT * duplex_subopt(const char *s1, const char *s2, int delta, int w) { int i, j, n1, n2, thresh, E, n_subopt = 0, n_max; char *struc; duplexT mfe; duplexT *subopt; n_max = 16; subopt = (duplexT *)vrna_alloc(n_max * sizeof(duplexT)); mfe = duplexfold_cu(s1, s2, 0); free(mfe.structure); thresh = (int)mfe.energy * 100 + 0.1 + delta; n1 = strlen(s1); n2 = strlen(s2); for (i = n1; i > 0; i--) { for (j = 1; j <= n2; j++) { int type, ii, jj, Ed; type = pair[S2[j]][S1[i]]; if (!type) continue; E = Ed = c[i][j]; Ed += E_ExtLoop(type, (j > 1) ? SS2[j - 1] : -1, (i < n1) ? SS1[i + 1] : -1, P); if (Ed > thresh) continue; /* too keep output small, remove hits that are dominated by a * better one close (w) by. For simplicity we do test without * adding dangles, which is slightly inaccurate. */ for (ii = MAX2(i - w, 1); (ii <= MIN2(i + w, n1)) && type; ii++) { for (jj = MAX2(j - w, 1); jj <= MIN2(j + w, n2); jj++) if (c[ii][jj] < E) { type = 0; break; } } if (!type) continue; struc = backtrack(i, j); vrna_message_info(stderr, "%d %d %d", i, j, E); if (n_subopt + 1 >= n_max) { n_max *= 2; subopt = (duplexT *)vrna_realloc(subopt, n_max * sizeof(duplexT)); } subopt[n_subopt].i = MIN2(i + 1, n1); subopt[n_subopt].j = MAX2(j - 1, 1); subopt[n_subopt].energy = Ed * 0.01; subopt[n_subopt++].structure = struc; } } /* free all static globals */ for (i = 1; i <= n1; i++) free(c[i]); free(c); free(S1); free(S2); free(SS1); free(SS2); if (subopt_sorted) qsort(subopt, n_subopt, sizeof(duplexT), compare); subopt[n_subopt].i = 0; subopt[n_subopt].j = 0; subopt[n_subopt].structure = NULL; return subopt; } PRIVATE char * backtrack(int i, int j) { /* backtrack structure going backwards from i, and forwards from j * return structure in bracket notation with & as separator */ int k, l, type, type2, E, traced, i0, j0; char *st1, *st2, *struc; st1 = (char *)vrna_alloc(sizeof(char) * (n1 + 1)); st2 = (char *)vrna_alloc(sizeof(char) * (n2 + 1)); i0 = MIN2(i + 1, n1); j0 = MAX2(j - 1, 1); while (i > 0 && j <= n2) { E = c[i][j]; traced = 0; st1[i - 1] = '('; st2[j - 1] = ')'; type = pair[S1[i]][S2[j]]; if (!type) vrna_message_error("backtrack failed in fold duplex"); for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) { for (l = j + 1; l <= n2; l++) { int LE; if (i - k + l - j - 2 > MAXLOOP) break; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; LE = E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type], SS1[k + 1], SS2[l - 1], SS1[i - 1], SS2[j + 1], P); if (E == c[k][l] + LE) { traced = 1; i = k; j = l; break; } } if (traced) break; } if (!traced) { E -= E_ExtLoop(type, (i > 1) ? SS1[i - 1] : -1, (j < n2) ? SS2[j + 1] : -1, P); if (E != P->DuplexInit) vrna_message_error("backtrack failed in fold duplex"); else break; } } if (i > 1) i--; if (j < n2) j++; struc = (char *)vrna_alloc(i0 - i + 1 + j - j0 + 1 + 2); for (k = MAX2(i, 1); k <= i0; k++) if (!st1[k - 1]) st1[k - 1] = '.'; for (k = j0; k <= j; k++) if (!st2[k - 1]) st2[k - 1] = '.'; strcpy(struc, st1 + MAX2(i - 1, 0)); strcat(struc, "&"); strcat(struc, st2 + j0 - 1); /* printf("%s %3d,%-3d : %3d,%-3d\n", struc, i,i0,j0,j); */ free(st1); free(st2); return struc; } /*------------------------------------------------------------------------*/ PRIVATE int compare(const void *sub1, const void *sub2) { int d; if (((duplexT *)sub1)->energy > ((duplexT *)sub2)->energy) return 1; if (((duplexT *)sub1)->energy < ((duplexT *)sub2)->energy) return -1; d = ((duplexT *)sub1)->i - ((duplexT *)sub2)->i; if (d != 0) return d; return ((duplexT *)sub1)->j - ((duplexT *)sub2)->j; } /*---------------------------------------------------------------------------*/ PUBLIC duplexT aliduplexfold(const char *s1[], const char *s2[]) { return aliduplexfold_cu(s1, s2, 1); } PRIVATE duplexT aliduplexfold_cu(const char *s1[], const char *s2[], int clean_up) { int i, j, s, n_seq, Emin = INF, i_min = 0, j_min = 0; char *struc; duplexT mfe; short **S1, **S2; int *type; vrna_md_t md; n1 = (int)strlen(s1[0]); n2 = (int)strlen(s2[0]); for (s = 0; s1[s] != NULL; s++) ; n_seq = s; for (s = 0; s2[s] != NULL; s++) ; if (n_seq != s) vrna_message_error("unequal number of sequences in aliduplexfold()\n"); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } c = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); for (i = 1; i <= n1; i++) c[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); S1 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); S2 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); for (s = 0; s < n_seq; s++) { if (strlen(s1[s]) != n1) vrna_message_error("uneqal seqence lengths"); if (strlen(s2[s]) != n2) vrna_message_error("uneqal seqence lengths"); S1[s] = encode_sequence(s1[s], 0); S2[s] = encode_sequence(s2[s], 0); } type = (int *)vrna_alloc(n_seq * sizeof(int)); for (i = 1; i <= n1; i++) { for (j = n2; j > 0; j--) { int k, l, E, psc; for (s = 0; s < n_seq; s++) type[s] = pair[S1[s][i]][S2[s][j]]; psc = covscore(type, n_seq); for (s = 0; s < n_seq; s++) if (type[s] == 0) type[s] = 7; c[i][j] = (psc >= MINPSCORE) ? (n_seq * P->DuplexInit) : INF; if (psc < MINPSCORE) continue; for (s = 0; s < n_seq; s++) c[i][j] += E_ExtLoop(type[s], (i > 1) ? S1[s][i - 1] : -1, (j < n2) ? S2[s][j + 1] : -1, P); for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) { for (l = j + 1; l <= n2; l++) { int type2; if (i - k + l - j - 2 > MAXLOOP) break; if (c[k][l] > INF / 2) continue; for (E = s = 0; s < n_seq; s++) { type2 = pair[S1[s][k]][S2[s][l]]; if (type2 == 0) type2 = 7; E += E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type[s]], S1[s][k + 1], S2[s][l - 1], S1[s][i - 1], S2[s][j + 1], P); } c[i][j] = MIN2(c[i][j], c[k][l] + E); } } c[i][j] -= psc; E = c[i][j]; for (s = 0; s < n_seq; s++) E += E_ExtLoop(rtype[type[s]], (j > 1) ? S2[s][j - 1] : -1, (i < n1) ? S1[s][i + 1] : -1, P); if (E < Emin) { Emin = E; i_min = i; j_min = j; } } } struc = alibacktrack(i_min, j_min, (const short **)S1, (const short **)S2); if (i_min < n1) i_min++; if (j_min > 1) j_min--; mfe.i = i_min; mfe.j = j_min; mfe.energy = (float)(Emin / (100. * n_seq)); mfe.structure = struc; if (clean_up) { for (i = 1; i <= n1; i++) free(c[i]); free(c); } for (s = 0; s < n_seq; s++) { free(S1[s]); free(S2[s]); } free(S1); free(S2); free(type); return mfe; } PUBLIC duplexT * aliduplex_subopt(const char *s1[], const char *s2[], int delta, int w) { int i, j, n1, n2, thresh, E, n_subopt = 0, n_max, s, n_seq, *type; char *struc; duplexT mfe; duplexT *subopt; short **S1, **S2; n_max = 16; subopt = (duplexT *)vrna_alloc(n_max * sizeof(duplexT)); mfe = aliduplexfold_cu(s1, s2, 0); free(mfe.structure); for (s = 0; s1[s] != NULL; s++) ; n_seq = s; thresh = (int)((mfe.energy * 100. + delta) * n_seq + 0.1); n1 = strlen(s1[0]); n2 = strlen(s2[0]); S1 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); S2 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); for (s = 0; s < n_seq; s++) { if (strlen(s1[s]) != n1) vrna_message_error("uneqal seqence lengths"); if (strlen(s2[s]) != n2) vrna_message_error("uneqal seqence lengths"); S1[s] = encode_sequence(s1[s], 0); S2[s] = encode_sequence(s2[s], 0); } type = (int *)vrna_alloc(n_seq * sizeof(int)); for (i = n1; i > 0; i--) { for (j = 1; j <= n2; j++) { int ii, jj, skip, Ed, psc; for (s = 0; s < n_seq; s++) type[s] = pair[S2[s][j]][S1[s][i]]; psc = covscore(type, n_seq); for (s = 0; s < n_seq; s++) if (type[s] == 0) type[s] = 7; if (psc < MINPSCORE) continue; E = Ed = c[i][j]; for (s = 0; s < n_seq; s++) Ed += E_ExtLoop(type[s], (j > 1) ? S2[s][j - 1] : -1, (i < n1) ? S1[s][i + 1] : -1, P); if (Ed > thresh) continue; /* too keep output small, skip hits that are dominated by a * better one close (w) by. For simplicity we don't take dangels * into account here, thus the heuristic is somewhat inaccurate. */ for (skip = 0, ii = MAX2(i - w, 1); (ii <= MIN2(i + w, n1)) && type; ii++) { for (jj = MAX2(j - w, 1); jj <= MIN2(j + w, n2); jj++) if (c[ii][jj] < E) { skip = 1; break; } } if (skip) continue; struc = alibacktrack(i, j, (const short **)S1, (const short **)S2); vrna_message_info(stderr, "%d %d %d", i, j, E); if (n_subopt + 1 >= n_max) { n_max *= 2; subopt = (duplexT *)vrna_realloc(subopt, n_max * sizeof(duplexT)); } subopt[n_subopt].i = MIN2(i + 1, n1); subopt[n_subopt].j = MAX2(j - 1, 1); subopt[n_subopt].energy = Ed * 0.01 / n_seq; subopt[n_subopt++].structure = struc; } } for (i = 1; i <= n1; i++) free(c[i]); free(c); for (s = 0; s < n_seq; s++) { free(S1[s]); free(S2[s]); } free(S1); free(S2); free(type); if (subopt_sorted) qsort(subopt, n_subopt, sizeof(duplexT), compare); subopt[n_subopt].i = 0; subopt[n_subopt].j = 0; subopt[n_subopt].structure = NULL; return subopt; } PRIVATE char * alibacktrack(int i, int j, const short **S1, const short **S2) { /* backtrack structure going backwards from i, and forwards from j * return structure in bracket notation with & as separator */ int k, l, *type, type2, E, traced, i0, j0, s, n_seq; char *st1, *st2, *struc; n1 = (int)S1[0][0]; n2 = (int)S2[0][0]; for (s = 0; S1[s] != NULL; s++) ; n_seq = s; for (s = 0; S2[s] != NULL; s++) ; if (n_seq != s) vrna_message_error("unequal number of sequences in alibacktrack()\n"); st1 = (char *)vrna_alloc(sizeof(char) * (n1 + 1)); st2 = (char *)vrna_alloc(sizeof(char) * (n2 + 1)); type = (int *)vrna_alloc(n_seq * sizeof(int)); i0 = MIN2(i + 1, n1); j0 = MAX2(j - 1, 1); while (i > 0 && j <= n2) { int psc; E = c[i][j]; traced = 0; st1[i - 1] = '('; st2[j - 1] = ')'; for (s = 0; s < n_seq; s++) type[s] = pair[S1[s][i]][S2[s][j]]; psc = covscore(type, n_seq); for (s = 0; s < n_seq; s++) if (type[s] == 0) type[s] = 7; E += psc; for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) { for (l = j + 1; l <= n2; l++) { int LE; if (i - k + l - j - 2 > MAXLOOP) break; if (c[k][l] > INF / 2) continue; for (s = LE = 0; s < n_seq; s++) { type2 = pair[S1[s][k]][S2[s][l]]; if (type2 == 0) type2 = 7; LE += E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type[s]], S1[s][k + 1], S2[s][l - 1], S1[s][i - 1], S2[s][j + 1], P); } if (E == c[k][l] + LE) { traced = 1; i = k; j = l; break; } } if (traced) break; } if (!traced) { for (s = 0; s < n_seq; s++) E -= E_ExtLoop(type[s], (i > 1) ? S1[s][i - 1] : -1, (j < n2) ? S2[s][j + 1] : -1, P); if (E != n_seq * P->DuplexInit) vrna_message_error("backtrack failed in aliduplex"); else break; } } if (i > 1) i--; if (j < n2) j++; struc = (char *)vrna_alloc(i0 - i + 1 + j - j0 + 1 + 2); for (k = MAX2(i, 1); k <= i0; k++) if (!st1[k - 1]) st1[k - 1] = '.'; for (k = j0; k <= j; k++) if (!st2[k - 1]) st2[k - 1] = '.'; strcpy(struc, st1 + MAX2(i - 1, 0)); strcat(struc, "&"); strcat(struc, st2 + j0 - 1); /* printf("%s %3d,%-3d : %3d,%-3d\n", struc, i,i0,j0,j); */ free(st1); free(st2); free(type); return struc; } PRIVATE int covscore(const int *types, int n_seq) { /* calculate co-variance bonus for a pair depending on */ /* compensatory/consistent mutations and incompatible seqs */ /* should be 0 for conserved pairs, >0 for good pairs */ int k, l, s, score, pscore; int dm[7][7] = { { 0, 0, 0, 0, 0, 0, 0 }, /* hamming distance between pairs */ { 0, 0, 2, 2, 1, 2, 2 } /* CG */, { 0, 2, 0, 1, 2, 2, 2 } /* GC */, { 0, 2, 1, 0, 2, 1, 2 } /* GU */, { 0, 1, 2, 2, 0, 2, 1 } /* UG */, { 0, 2, 2, 1, 2, 0, 2 } /* AU */, { 0, 2, 2, 2, 1, 2, 0 } /* UA */ }; int pfreq[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; for (s = 0; s < n_seq; s++) pfreq[types[s]]++; if (pfreq[0] * 2 > n_seq) return NONE; for (k = 1, score = 0; k <= 6; k++) /* ignore pairtype 7 (gap-gap) */ for (l = k + 1; l <= 6; l++) /* scores for replacements between pairtypes */ /* consistent or compensatory mutations score 1 or 2 */ score += pfreq[k] * pfreq[l] * dm[k][l]; /* counter examples score -1, gap-gap scores -0.25 */ pscore = cv_fact * ((UNIT * score) / n_seq - nc_fact * UNIT * (pfreq[0] + pfreq[7] * 0.25)); return pscore; }
omp_init_lock.c
// RUN: %libomp-compile-and-run // REQUIRES: dummy #include "omp_testsuite.h" #include <stdio.h> // This should be slightly less than KMP_I_LOCK_CHUNK, which is 1024 #define LOCKS_PER_ITER 1000 #define ITERATIONS (REPETITIONS + 1) // This tests concurrently using locks on one thread while initializing new // ones on another thread. This exercises the global lock pool. int test_omp_init_lock() { int i; omp_lock_t lcks[ITERATIONS * LOCKS_PER_ITER]; #pragma omp parallel for schedule(static) num_threads(NUM_TASKS) for (i = 0; i < ITERATIONS; i++) { int j; omp_lock_t *my_lcks = &lcks[i * LOCKS_PER_ITER]; for (j = 0; j < LOCKS_PER_ITER; j++) { omp_init_lock(&my_lcks[j]); } for (j = 0; j < LOCKS_PER_ITER * 100; j++) { omp_set_lock(&my_lcks[j % LOCKS_PER_ITER]); omp_unset_lock(&my_lcks[j % LOCKS_PER_ITER]); } } // Wait until all repititions are done. The test is exercising growth of // the global lock pool, which does not shrink when no locks are allocated. { int j; for (j = 0; j < ITERATIONS * LOCKS_PER_ITER; j++) { omp_destroy_lock(&lcks[j]); } } return 0; } int main() { // No use repeating this test, since it's exercising a private global pool // which is not reset between test iterations. return test_omp_init_lock(); }
opencl_7z_fmt_plug.c
/* * This software is Copyright (c) 2015 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. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_sevenzip; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_sevenzip); #else #include <string.h> #include "aes.h" #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "common.h" #include "misc.h" #include "common-opencl.h" #include "options.h" #include "crc32.h" #include "stdint.h" #include "unicode.h" #include "dyna_salt.h" #include "memdbg.h" #define FORMAT_LABEL "7z-opencl" #define FORMAT_NAME "7-Zip" #define FORMAT_TAG "$7z$" #define TAG_LENGTH (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "SHA256 OPENCL AES" #define BENCHMARK_COMMENT " (512K iterations)" #define BENCHMARK_LENGTH 0 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define PLAINTEXT_LENGTH ((55-8)/2) // 23, rar3 uses 22 #define UNICODE_LENGTH (2 * PLAINTEXT_LENGTH) #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define SALT_SIZE sizeof(struct custom_salt*) #define SALT_ALIGN sizeof(struct custom_salt*) typedef struct { uint32_t length; uint16_t v[PLAINTEXT_LENGTH]; } sevenzip_password; typedef struct { uint round; uint8_t key[32]; } sevenzip_hash; typedef struct { uint32_t length; uint32_t iterations; uint8_t salt[16]; } sevenzip_salt; typedef struct { cl_uint total[2]; cl_uint state[8]; cl_uchar buffer[64]; } SHA256_CTX; typedef struct { cl_ulong t; SHA256_CTX ctx; cl_uint len; cl_ushort buffer[PLAINTEXT_LENGTH]; } sevenzip_state; static int *cracked; static int any_cracked; static int new_keys; static struct custom_salt { dyna_salt dsalt; size_t length; /* used in decryption */ size_t unpacksize; /* used in CRC calculation */ int NumCyclesPower; int SaltSize; int ivSize; int type; unsigned char iv[16]; unsigned char salt[16]; unsigned int crc; unsigned char data[1]; } *cur_salt; static struct fmt_tests sevenzip_tests[] = { /* CRC checks passes for these hashes */ {"$7z$0$19$0$1122$8$d1f50227759415890000000000000000$1412385885$112$112$5e5b8b734adf52a64c541a5a5369023d7cccb78bd910c0092535dfb013a5df84ac692c5311d2e7bbdc580f5b867f7b5dd43830f7b4f37e41c7277e228fb92a6dd854a31646ad117654182253706dae0c069d3f4ce46121d52b6f20741a0bb39fc61113ce14d22f9184adafd6b5333fb1", "password"}, {"$7z$0$19$0$1122$8$a264c94f2cd72bec0000000000000000$725883103$112$108$64749c0963e20c74602379ca740165b9511204619859d1914819bc427b7e5f0f8fc67f53a0b53c114f6fcf4542a28e4a9d3914b4bc76baaa616d6a7ec9efc3f051cb330b682691193e6fa48159208329460c3025fb273232b82450645f2c12a9ea38b53a2331a1d0858813c8bf25a831", "openwall"}, /* padding check passes for these hashes */ {"$7z$0$19$0$1122$8$732b59fd26896e410000000000000000$2955316379$192$183$7544a3a7ec3eb99a33d80e57907e28fb8d0e140ec85123cf90740900429136dcc8ba0692b7e356a4d4e30062da546a66b92ec04c64c0e85b22e3c9a823abef0b57e8d7b8564760611442ecceb2ca723033766d9f7c848e5d234ca6c7863a2683f38d4605322320765938049305655f7fb0ad44d8781fec1bf7a2cb3843f269c6aca757e509577b5592b60b8977577c20aef4f990d2cb665de948004f16da9bf5507bf27b60805f16a9fcc4983208297d3affc4455ca44f9947221216f58c337f", "password"}, /* not supported hashes, will require validFolder check */ // {"$7z$0$19$0$1122$8$5fdbec1569ff58060000000000000000$2465353234$112$112$58ba7606aafc7918e3db7f6e0920f410f61f01e9c1533c40850992fee4c5e5215bc6b4ea145313d0ac065b8ec5b47d9fb895bb7f97609be46107d71e219544cfd24b52c2ecd65477f72c466915dcd71b80782b1ac46678ab7f437fd9f7b8e9d9fad54281d252de2a7ae386a65fc69eda", "password"}, #if DEBUG {"$7z$0$19$0$1122$8$94fb9024fdd3e6c40000000000000000$3965424295$112$99$1127828817ff126bc45ff3c5225d9d0c5d00a52094909674e6ed3dc431546d9a672738f2fa07556340d604d2efd2901b9d2ac2c0686c25af9c520c137b16c50c54df8703fd0b0606fa721ad70aafb9c4e3b288ef49864e6034021969b4ce11e3b8e269a92090ccf593c6a0da06262116", ""}, {"$7z$0$19$0$1122$8$6fd059d516d5490f0000000000000000$460747259$112$99$af163eb5532c557efca78fbb448aa04f348cd258c94233e6669f4e5025f220274c244d4f2347a7512571d9b6015a1e1a90e281983b743da957437b33092eddb55a5bc76f3ab6c7dbabb001578d1043285f5fa791fd94dd9779b461e44cbfe869f891007335b766774ccee3813ec8cd57", "&"}, {"$7z$0$19$0$1122$8$6d4a12af68d83bfe0000000000000000$993697592$112$99$7c308faa36b667599ee4418435ab621884c5c115ee3b70be454fe99236422f4f2d5cd9c8fcfbe6b6b0805ee602ce8488a08f7ea14a4f5c0c060fc685bff187720a402b23a5cfe3c9c5a5ae07f91209031b8f9804ac10459e15a0158031f6c58e507401ec6e1e6de8f64d94201159432b", "&'"}, {"$7z$0$19$0$1122$8$7527d758a59181830000000000000000$3917710544$112$99$61a9ca9e835bd0f2dc474b34d5d89bcf8cd1bb071a984ee1dcf224174a60bcee140fcf2fde8927fe4f3f4eb4a2cc39faff73f1898ae25cc92bd02939f4317ebb173bf3b6f01eef183163ddd533ad5c076f87341bd8b86d8460c68fc390aa8df89fc4076bdfd24e157f6c07e105c07612", "&'("}, {"$7z$0$19$0$1122$8$68928bade860a2b80000000000000000$3235890186$112$99$4b685a569c3aed78d217bae9ec64fa06b614df55c1cb0d160563d87efe38813accb38dd7037f86cebc91751c2488769c7398dfefaf491c024f2d640dcb388a56404cd5ac475ba16b5f8206fa45d5923b3a0c8dd0f24460ccee0d93bea03ad58b8a8db502a55ba1775560b3d194f342f7", "&'()"}, {"$7z$0$19$0$1122$8$81931b9ba0b069820000000000000000$3094344848$112$99$fdbb2622143d25b13992b1467ce9edce4e3df8ca07535735b76e8abcb0791e384a1d5547483e19c3bd6e5a0742d29c403cfc8b3a003b285e80b350ea9157600eb91c49b329903de9ec9b17d1c95b0e136b579e165a6e80550464fa99830bfd9ee58fc14516b614ff9f84ec80e6880a36", "&'()*"}, {"$7z$0$19$0$1122$8$ccf696913989510d0000000000000000$1238556212$112$99$647264fbc665e73ecfe3ef7055fef0d91cb86833d6df08b2f7a3c1c89cf7cdaa09a802c8bfb2e5c6b55143a315df74d841b349fc8b43613d0f87cc90325fd56fc17ee08df7ce76cdc9cda61bd4d5632e20af3db16e921c755174f291c0aa6581844def4547380e2dd4a574435d17e1e8", "&'()*+"}, {"$7z$0$19$0$1122$8$d618bd3ec8bafd800000000000000000$1349785$112$99$6514e2e7468e6f0ed63796cfc0588ac2d75f024c4a0fa03778bd252d316d03e48a08ffcc0011725ad4f867e9a9666630dff4f352c59bcbadb94b9d0e2c42d653b80f480005ce868a0b1a075b2e00abd743de0867d69cdc8b56c7f9770537d50e6bb11eb0d2d7d8b6af5dd8ecb50ab553", "&'()*+,"}, {"$7z$0$19$0$1122$8$1c1586d191f190890000000000000000$642253888$112$99$f55cf9ab802b10a83471abe9319711ae79906cd6921365167c389470a3a8a72b0d877379daae2c24ea2258e8586f12d5036aff9ddc8e26861467b0843ffb72e4410c2be76ec111d37f875c81b244ed172f1f4765a220d830a9615787e9d07f8582146556e9c566b64897a47d18a82b36", "&'()*+,-"}, {"$7z$0$19$0$1122$8$0df03cbdbc73e22a0000000000000000$3194757927$112$99$df53e9d8b4e02cf2962ad87912021508a36910c399a7abc4a3a5423fa2184816af7172418eb4763924ec8b099b7ca95abdc6faac9aaa6e181ffa60b7e8bdb2bf576536ca69152e3b6b97302c796bbc9dec78db6ba7a4a58e68f8ee28f27dea26bd4f848dc3a3315e97e1463b5c171ce5", "&'()*+,-."}, {"$7z$0$19$0$1122$8$7785351cf9fe5dfa0000000000000000$1304801610$112$99$7b35280384726da8521fee0786ef43e0aa621394a6f015b65cbd7f1329f43c4543b8a451a0007c03a3ce3f61e639c54ede3e580600b113777822b6d562390d14ed236e5bac3d3af63ae23015148a95e7ccbc9eea653b52c606ca09ec51fd2b0c4cfc2b760fccc1fe0ccdd9ee3fcb8129", "&'()*+,-./"}, {"$7z$0$19$0$1122$8$70eb7f4b821cf5310000000000000000$3381356868$112$99$c26db2cb89df1237f323d92044726d03cfc7ba83115e789243c3b2570ae674d8356a23e004b103638b1ea9fe6ff5db844a1ddcaaed8a71a8d8e343f73868b4acafd34d493345439b0e0be87d2cf52eb4cceaafcff0dfaf9cf25080693ede267460320e1282b869a5f0b6c8789e769640", "&'()*+,-./0"}, {"$7z$0$19$0$1122$8$2ac0f1307794d8e10000000000000000$2871514580$112$99$4783d91fa72c377310654e961120e71ecdd27ec2e67366e83291daefcea03514ca9ecea031fcbd25c0759c1f242219e673cee093ef361664f18dacf85ca0620fd7092477ceeff7c548df0a475ce93278a564fe4ddb4ee2e4695cbe417a792e822204390ca5a530208a8ed51bc01f79e6", "&'()*+,-./01"}, {"$7z$0$19$0$1122$8$5bc4988c71cba8b70000000000000000$2815498089$112$99$0e4368dde66925e2bfac9a450291f8f817beaa891f08c4d2735d20b3147df581e2f3c53abfe2b0971186ac39280eb354ca5989f9043ad0288302d0ac59a3c8fa99d26c9619b81d22996f24eec1dba361afdd5e50060c2599a40a00c83c4ee0bc4ebe6e3126a64a743af95d9b22ee5867", "&'()*+,-./012"}, {"$7z$0$19$0$1122$8$33ab0ad513b7d6910000000000000000$107430285$112$99$f9f1195a4210eadc5b23f046f81c8cfaec3b90d8b6b67893f10bd9bedd0d859d0695bca5ce315cecbc2910dce27e4c1a1416675d841901c8d84846360b1919ebcba91143713c6b755758d3db64d39344da18222341818220cc43f3ee3a91cbc288f1aafe377b53def310d3b83d32aee3", "&'()*+,-./0123"}, {"$7z$0$19$0$1122$8$dd490a165c1b90f90000000000000000$2897354864$112$99$51efe41b67875503acebe2e199cb542a279520b468a61ba67b54612e317a84e95879a34eaad82124798f32c19f9c0786e8faaac768da5f6b2c91e3ba9f97a03a992c18b5b9b21a5f2b67ae9daeef37ec115f44bfb8b10ac3cb7862b6c024413a2ee801aa674df05e8b56bd8654f279f5", "&'()*+,-./01234"}, {"$7z$0$19$0$1122$8$9077cb191a5969b40000000000000000$3637063426$112$99$1e74746c59bdfe6b3f3d957493c9d5b92ba358f97e19d30e20443cb2fbac0501e07a162344ac7cf7cfa727c70a2bcf52593accc5c2c070c2331863ac76da5ad2f5de374292a87c6af67ab561f9cf71ae472ed1267d481c250f5b4d82d0ec0b2b8531db1fe4637c3f4e3a08de1b9b5418", "&'()*+,-./012345"}, {"$7z$0$19$0$1122$8$adc090d27b0343d30000000000000000$1147570982$112$99$ac14b9dc3751cfe6c1c719ceef3d73946fff2b0f924e06cd3177883df770e5505551bcf5598277801f46584a4f41530f50007c776d2bb91fd160148042275dfe4e420ff72244409f59c687a5bb2d0fc1bb29138689094fe40bb0f22785c63c631cd05abf4f7f3c9b6832e192e103d2f1", "&'()*+,-./0123456"}, {"$7z$0$19$0$1122$8$8dee69dc35517a2a0000000000000000$87427823$112$99$ea36cf8b577a0b5f31115f8550987f05f174b347a8a6433a08c013ecd816c8ecaad163c62db9bae6c57ace3c2a6ce0b36f78ad4723328cc022906400eed55e0e3685a5e8e6b369df780ee72f3d25ccd49d7f40d013052e080723dd4c0b1c75302c884ea956e3b6fd27261eb8c49dea51", "&'()*+,-./01234567"}, {"$7z$0$19$0$1122$8$200ce603d6f355f10000000000000000$3012105149$112$99$0ae42342f52172ad921178a25df3666e34e5a217d0afb3655088806f821d374bf522c197e59b131dbc574d4c936472f59f8892f69e47724ea52ecc5dc7d3ed734c557c9698a6f01519039714c065ad25008003c93cb7f694ee07267d5fcdebab5d149d5404023a0112faec2264d33ff6", "&'()*+,-./012345678"}, {"$7z$0$19$0$1122$8$a5007fc77fa5cc0b0000000000000000$1082728565$112$99$32c404c9633e9c61b76556e169695248008c51ca8f7f0f79c4a271ac6eb1d905a2622132f2f6988f9f3f5e375c592ec63d92d7b183b5801b149595ed440b23a083633de9f1cb5b6ac3238b7523b23141e686e6cbe9d4d3a28fc6489e902c17aeff6cd4cb516bef5cd5c6def78cb88ad4", "&'()*+,-./0123456789"}, {"$7z$0$19$0$1122$8$fd531c4e580be9a60000000000000000$1843420503$112$99$704289830b1add1c8ee6fd622ecf5b8da01988580bdb52f6269cc61c21838849d3a04299eaee15e0cae0eff9f6c3c82f71e434b3aa1c0ca824b90438c1c983130218acd128d9186e5dc2d19a8db602a0382cb60dadb4641b46fe532b799d29a4b882beaa9217f48ddccc99578617f8a0", "&'()*+,-./0123456789:"}, {"$7z$0$19$0$1122$8$7f94a95f71c1b0df0000000000000000$141406606$112$99$1a510a6fda9788b4f4b2274ea929044c00b61b23946bc417ead90ad64dcc9a55378f9ab74f7d693a5dcf455c00f82f6c2a885b664f4ab10c9969026714ce2773030f1c5872ca3948cd612e21b321826c2a561104d57a3ba2055f03aa9cc264821544ec4bccc41f4ac76aab97accb8f9c", "&'()*+,-./0123456789:;"}, {"$7z$0$19$0$1122$8$e24e93c7a9ebde080000000000000000$718561925$112$99$580bf36388526c932c22e3227b51774b6963a9c5b96fc8e2ac70a4302864fa88f50e7c00d9a79e0bca0f07a236e51200dc23435b7680e6fa99b19d790ac093af615a972f8b232686c21279234a2582f9714c5a1a2d326084158eba3e81b4f8ad40784d84baa8ddbed19f1c6603156d2c", "&'()*+,-./0123456789:;<"}, #if PLAINTEXT_LENGTH > 23 {"$7z$0$19$0$1122$8$6fbd519735b131710000000000000000$1248418560$112$99$cc9e3c97073d7fd37f04d4e6983b386e3ac00f6292dedb0f566dccf22cdbbb55fee8669edade383e96aa0a740e2b42aa7fddbe5831cac10828c624ee03a1a256c6e777c3d714c55296cb815c509a252b9426fe8d4566c944efe3fac5ea94910e55a390aef2c729a031e832c406049810", "&'()*+,-./0123456789:;<="}, {"$7z$0$19$0$1122$8$3ce1b899fc03d9c30000000000000000$1452122600$112$99$d4be60d5ab390713c7189f0dd808227c01f15f71fcf4bbccce6cb9238d6418c115eff59784d96ff8944575710a5799c7bcb761e8f1bfb7646a0e8fac3728ba4cca44fb82e5dd9f87bb26828566af64374b512fa094d35af8d743bded88b6257ec98a99b50dd225d4608b283bf035ac08", "&'()*+,-./0123456789:;<=>"}, {"$7z$0$19$0$1122$8$656e2285aabed25b0000000000000000$3885982465$112$99$77f2871e556e7f5278a9e896e91cd386ca8935128957d31fdce0603ea0e71c08b908a4c2d9f2d279757ced848be9482067c9d7935c88e5233aaa94a101d29908f7f015646758029d2078d25d0886bb9f0cdc0dd5136d72e90ceeea678564b199866dd8c9e5fe927102ee2dcf1cd4167f", "&'()*+,-./0123456789:;<=>?"}, {"$7z$0$19$0$1122$8$44ffefa48fa5a5b00000000000000000$1011653568$112$99$5d2504a1eb819218b9ad552e377d37e811ffccb64a554f404d982d209edfafb893b679cc881bbcbc606e67ffa055f712d7f140b554769511bc00321765830ea7c5db810fa2000ae7f4250b74aa61d881db66ae6f30e4c8e71887960c117b268d9934b8b5d52d4abdcb42b0e4ff40b805", "&'()*+,-./0123456789:;<=>?@"}, {"$7z$0$19$0$1122$8$b6e089dd0c52b6b80000000000000000$1229766981$112$99$49a8334d64d9cc7d710fe3b9c35f5d7cb0ec44d5db8a90966fbee93f85fdeeeca859c55519addb20c4628c9204dd24d1169b34dc53a2a685440fae7ed6748c172a8e9dcc42c8dffe60196818ad17a6f9314fcfd4d97cab3c18cf279df344e00fd04eaff32f29cbfcdb6832cfb69fe351", "&'()*+,-./0123456789:;<=>?@A"}, #endif /* PLAINTEXT_LENGTH > 23 */ #endif /* DEBUG */ {NULL} }; static sevenzip_password *inbuffer; static sevenzip_hash *outbuffer; static sevenzip_salt currentsalt; static cl_mem mem_in, mem_out, mem_salt; static cl_kernel sevenzip_init, sevenzip_final; #define insize (sizeof(sevenzip_password) * global_work_size) #define outsize (sizeof(sevenzip_hash) * global_work_size) #define statesize (sizeof(sevenzip_state) * global_work_size) #define saltsize (sizeof(sevenzip_salt)) #define cracked_size (sizeof(*cracked) * global_work_size) static struct fmt_main *self; #define HASH_LOOPS 0x4000 #define LOOP_COUNT ((1 << currentsalt.iterations) / HASH_LOOPS) #define STEP 0 #define SEED 16 static int split_events[] = { 2, -1, -1 }; static const char *warn[] = { "xfer: ", ", init: ", ", crypt: ", ", final: ", ", xfer: " }; // This file contains auto-tuning routine(s). It has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { size_t s; s = autotune_get_task_max_work_group_size(FALSE, 0, sevenzip_init); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel)); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, sevenzip_final)); return s; } static void create_clobj(size_t global_work_size, struct fmt_main *self) { cl_int cl_error; inbuffer = (sevenzip_password*) mem_calloc(1, insize); outbuffer = (sevenzip_hash*) mem_alloc(outsize); cracked = mem_calloc(1, cracked_size); // Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, saltsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem salt"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(sevenzip_init, 0, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(sevenzip_final, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(sevenzip_final, 1, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(sevenzip_final, 2, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); } static void release_clobj(void) { if (cracked) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_salt), "Release mem salt"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(cracked); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(sevenzip_init), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(sevenzip_final), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { CRC32_t crc; self = _self; opencl_prepare_dev(gpu_id); CRC32_Init(&crc); if (options.target_enc == UTF_8) self->params.plaintext_length = MIN(125, 3 * PLAINTEXT_LENGTH); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; cl_int cl_error; snprintf(build_opts, sizeof(build_opts), "-DPLAINTEXT_LENGTH=%d -DHASH_LOOPS=%d", PLAINTEXT_LENGTH, HASH_LOOPS); opencl_init("$JOHN/kernels/7z_kernel.cl", gpu_id, build_opts); sevenzip_init = clCreateKernel(program[gpu_id], "sevenzip_init", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); crypt_kernel = clCreateKernel(program[gpu_id], "sevenzip_loop", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); sevenzip_final = clCreateKernel(program[gpu_id], "sevenzip_final", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, HASH_LOOPS, split_events, warn, 2, self, create_clobj, release_clobj, sizeof(sevenzip_state), 0, db); // Auto tune execution from shared/included code. autotune_run(self, 1 << 19, 0, 15000000000ULL); } } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr, *p; int len, NumCyclesPower; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += TAG_LENGTH; if ((p = strtokm(ctcopy, "$")) == NULL) goto err; if (strlen(p) > 1 || '0' != *p) /* p must be "0" */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* NumCyclesPower */ goto err; if (strlen(p) > 2) goto err; if (!isdec(p)) goto err; NumCyclesPower = atoi(p); if (NumCyclesPower > 24 || NumCyclesPower < 1) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* salt length */ goto err; if (!isdec(p)) goto err; len = atoi(p); if (len > 16) /* salt length */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* salt */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* iv length */ goto err; if (strlen(p) > 2) goto err; if (!isdec(p)) goto err; len = atoi(p); if (len > 16) /* iv length */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* iv */ goto err; if (!ishexlc(p)) goto err; if (strlen(p) / 2 > len && strcmp(p+len*2, "0000000000000000")) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* crc */ goto err; if (!isdecu(p)) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* data length */ goto err; if(!isdec(p)) goto err; len = atoi(p); if ((p = strtokm(NULL, "$")) == NULL) /* unpacksize */ goto err; if (!isdec(p)) /* no way to validate, other than atoi() works for it */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* data */ goto err; if (strlen(p) / 2 != len) /* validates data_len atoi() */ goto err; if (!ishexlc(p)) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { struct custom_salt cs; struct custom_salt *psalt; static void *ptr; char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; if (!ptr) ptr = mem_alloc_tiny(sizeof(struct custom_salt*), sizeof(struct custom_salt*)); memset(&cs, 0, sizeof(cs)); ctcopy += TAG_LENGTH; p = strtokm(ctcopy, "$"); cs.type = atoi(p); p = strtokm(NULL, "$"); cs.NumCyclesPower = atoi(p); p = strtokm(NULL, "$"); cs.SaltSize = atoi(p); p = strtokm(NULL, "$"); /* salt */ p = strtokm(NULL, "$"); cs.ivSize = atoi(p); p = strtokm(NULL, "$"); /* iv */ for (i = 0; i < cs.ivSize; i++) cs.iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); /* crc */ cs.crc = atou(p); /* unsigned function */ p = strtokm(NULL, "$"); cs.length = atoll(p); psalt = malloc(sizeof(struct custom_salt) + cs.length - 1); memcpy(psalt, &cs, sizeof(cs)); p = strtokm(NULL, "$"); psalt->unpacksize = atoll(p); p = strtokm(NULL, "$"); /* data */ for (i = 0; i < psalt->length; i++) psalt->data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); psalt->dsalt.salt_cmp_offset = SALT_CMP_OFF(struct custom_salt, length); psalt->dsalt.salt_cmp_size = SALT_CMP_SIZE(struct custom_salt, length, data, psalt->length); psalt->dsalt.salt_alloc_needs_free = 1; memcpy(ptr, &psalt, sizeof(void*)); return ptr; } static void set_salt(void *salt) { cur_salt = *((struct custom_salt **)salt); memcpy((char*)currentsalt.salt, cur_salt->salt, cur_salt->SaltSize); if (currentsalt.iterations != cur_salt->NumCyclesPower) new_keys = 1; currentsalt.length = cur_salt->SaltSize; currentsalt.iterations = cur_salt->NumCyclesPower; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, saltsize, &currentsalt, 0, NULL, NULL), "Transfer salt to gpu"); } static void clear_keys(void) { memset(inbuffer, 0, insize); } static void sevenzip_set_key(char *key, int index) { UTF16 c_key[PLAINTEXT_LENGTH + 1]; int length = strlen(key); /* Convert password to utf-16-le format (--encoding aware) */ length = enc_to_utf16(c_key, PLAINTEXT_LENGTH, (UTF8*)key, length); if (length <= 0) length = strlen16(c_key); length *= 2; inbuffer[index].length = length; memcpy(inbuffer[index].v, c_key, length); new_keys = 1; } static char *get_key(int index) { UTF16 c_key[PLAINTEXT_LENGTH + 1]; int length = inbuffer[index].length; memcpy(c_key, inbuffer[index].v, length); c_key[length / 2] = 0; return (char*)utf16_to_enc(c_key); } static int salt_compare(const void *x, const void *y) { int c; const struct custom_salt *s1 = *((struct custom_salt**)x); const struct custom_salt *s2 = *((struct custom_salt**)y); // we had to make the salt order deterministic, so that intersalt-restore works if (s1->NumCyclesPower != s2->NumCyclesPower) return (s1->NumCyclesPower - s2->NumCyclesPower); c = memcmp(s1->salt, s2->salt, 16); if (c) return c; return memcmp(s1->iv, s2->iv, 16); } // XXX port Python code to C *OR* use code from LZMA SDK static int validFolder(unsigned char *data) { // int numcoders = self._read64Bit(file) return 0; } static int sevenzip_decrypt(unsigned char *derived_key, unsigned char *data) { unsigned char out[cur_salt->length]; AES_KEY akey; unsigned char iv[16]; union { unsigned char crcc[4]; unsigned int crci; } _crc_out; unsigned char *crc_out = _crc_out.crcc; unsigned int ccrc; CRC32_t crc; int i; int nbytes, margin; memcpy(iv, cur_salt->iv, 16); if(AES_set_decrypt_key(derived_key, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n"); } AES_cbc_encrypt(cur_salt->data, out, cur_salt->length, &akey, iv, AES_DECRYPT); /* various verifications tests */ // test 0, padding check, bad hack :-( margin = nbytes = cur_salt->length - cur_salt->unpacksize; i = cur_salt->length - 1; while (nbytes > 0) { if (out[i] != 0) return -1; nbytes--; i--; } if (margin > 7) { // printf("valid padding test ;-)\n"); // print_hex(out, cur_salt->length); return 0; } // test 1, CRC test CRC32_Init(&crc); CRC32_Update(&crc, out, cur_salt->unpacksize); CRC32_Final(crc_out, crc); ccrc = _crc_out.crci; // computed CRC if (ccrc == cur_salt->crc) return 0; // XXX don't be too eager! // XXX test 2, "well-formed folder" test if (validFolder(out)) { printf("validFolder check ;-)\n"); return 0; } return -1; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; //fprintf(stderr, "%s(%d) lws %zu gws %zu\n", __FUNCTION__, count, local_work_size, global_work_size); if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } if (ocl_autotune_running || new_keys) { int i; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); // Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); // Run 1st kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], sevenzip_init, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run init kernel"); // Run loop kernel for (i = 0; i < (ocl_autotune_running ? 1 : LOOP_COUNT); i++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[2]), "Run loop kernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } // Run final kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], sevenzip_final, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[3]), "Run final kernel"); // Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[4]), "Copy result back"); } new_keys = 0; if (!ocl_autotune_running) { #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { /* decrypt and check */ if(sevenzip_decrypt(outbuffer[index].key, cur_salt->data) == 0) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } } return count; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int)(1 << my_salt->NumCyclesPower); } struct fmt_main fmt_opencl_sevenzip = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT | FMT_UNICODE | FMT_UTF8 | FMT_DYNA_SALT, { "iteration count", }, { FORMAT_TAG }, sevenzip_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, salt_compare, set_salt, sevenzip_set_key, get_key, clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
GB_binop__plus_fc32.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__plus_fc32) // A.*B function (eWiseMult): GB (_AemultB_08__plus_fc32) // A.*B function (eWiseMult): GB (_AemultB_02__plus_fc32) // A.*B function (eWiseMult): GB (_AemultB_04__plus_fc32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__plus_fc32) // A*D function (colscale): GB (_AxD__plus_fc32) // D*A function (rowscale): GB (_DxB__plus_fc32) // C+=B function (dense accum): GB (_Cdense_accumB__plus_fc32) // C+=b function (dense accum): GB (_Cdense_accumb__plus_fc32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__plus_fc32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__plus_fc32) // C=scalar+B GB (_bind1st__plus_fc32) // C=scalar+B' GB (_bind1st_tran__plus_fc32) // C=A+scalar GB (_bind2nd__plus_fc32) // C=A'+scalar GB (_bind2nd_tran__plus_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_add (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_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_FC32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ GxB_FC32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_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_FC32_add (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_PLUS || GxB_NO_FC32 || GxB_NO_PLUS_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__plus_fc32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__plus_fc32) ( 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__plus_fc32) ( 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__plus_fc32) ( 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_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_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__plus_fc32) ( 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 GxB_FC32_t *restrict Cx = (GxB_FC32_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__plus_fc32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *restrict Cx = (GxB_FC32_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__plus_fc32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__plus_fc32) ( 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__plus_fc32) ( 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__plus_fc32) ( 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__plus_fc32) ( 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__plus_fc32) ( 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_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_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_FC32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_FC32_add (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__plus_fc32) ( 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_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_FC32_add (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_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC32_add (x, aij) ; \ } GrB_Info GB (_bind1st_tran__plus_fc32) ( 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_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_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_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC32_add (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__plus_fc32) ( 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_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__lnot_fp64_uint64.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__lnot_fp64_uint64 // op(A') function: GB_tran__lnot_fp64_uint64 // C type: double // A type: uint64_t // cast: double cij = (double) aij // unaryop: cij = !(aij != 0) #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 != 0) ; // casting #define GB_CASTING(z, aij) \ double z = (double) 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_LNOT || GxB_NO_FP64 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp64_uint64 ( double *Cx, // Cx and Ax may be aliased uint64_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__lnot_fp64_uint64 ( 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
mc_pi_omp.c
// ******************************************************************* #pragma GCC optimize("O3","unroll-loops","omit-frame-pointer","inline", "unsafe-math-optimizations") #pragma GCC option("arch=native","tune=native","no-zero-upper") //************************************************************ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <limits.h> #include <omp.h> #define SEED 1053608 #define N 5000000000000 unsigned int seed = 676767676 ; //Random number generator with linear congruential generator double randUint( long i ){ seed = seed * 1103515245 + 123456; return seed / (double)UINT_MAX ; } int main() { long count=0; double pi; //Init Parallelazation with reduction techinue #pragma omp parallel for reduction(+: count) for (long i=0; i<N; i++) { //Getting the coordinates y,x ε [0,1] double x,y; x = randUint(i); y = randUint(i); //Checking if in unit circle if (x*x+y*y <= 1) count = count + 1; } //Calcuting the ratio and as a result the pi pi=((double)count/(double)N) * 4.0; printf("OpenMP : # of trials = %14ld , estimate of pi is %1.16f AND an absolute error of %g\n",N,pi,fabs(pi - M_PI)); return 0; }
data.c
#include "data.h" #include "utils.h" #include "image.h" #include "cuda.h" #include <stdio.h> #include <stdlib.h> #include <string.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; list *get_paths(char *filename) { char *path; FILE *file = fopen(filename, "r"); if(!file) file_error(filename); list *lines = make_list(); while((path=fgetl(file))){ list_insert(lines, path); } fclose(file); return lines; } /* char **get_random_paths_indexes(char **paths, int n, int m, int *indexes) { char **random_paths = calloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); for(i = 0; i < n; ++i){ int index = rand()%m; indexes[i] = index; random_paths[i] = paths[index]; if(i == 0) printf("%s\n", paths[index]); } pthread_mutex_unlock(&mutex); return random_paths; } */ char **get_random_paths(char **paths, int n, int m) { char **random_paths = calloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); for(i = 0; i < n; ++i){ int index = rand()%m; random_paths[i] = paths[index]; //if(i == 0) printf("%s\n", paths[index]); } pthread_mutex_unlock(&mutex); return random_paths; } char **find_replace_paths(char **paths, int n, char *find, char *replace) { char **replace_paths = calloc(n, sizeof(char*)); int i; for(i = 0; i < n; ++i){ char replaced[4096]; find_replace(paths[i], find, replace, replaced); replace_paths[i] = copy_string(replaced); } return replace_paths; } matrix load_image_paths_gray(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = calloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image(paths[i], w, h, 3); image gray = grayscale_image(im); free_image(im); im = gray; X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_paths(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = calloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], w, h); X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_augment_paths(char **paths, int n, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure, int center) { int i; matrix X; X.rows = n; X.vals = calloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], 0, 0); image crop; if(center){ crop = center_crop_image(im, size, size); } else { crop = random_augment_image(im, angle, aspect, min, max, size, size); } int flip = rand()%2; if (flip) flip_image(crop); random_distort_image(crop, hue, saturation, exposure); /* show_image(im, "orig"); show_image(crop, "crop"); cvWaitKey(0); */ free_image(im); X.vals[i] = crop.data; X.cols = crop.h*crop.w*crop.c; } return X; } box_label *read_boxes(char *filename, int *n) { FILE *file = fopen(filename, "r"); if(!file) file_error(filename); float x, y, h, w; int id; int count = 0; int size = 64; box_label *boxes = calloc(size, sizeof(box_label)); while(fscanf(file, "%d %f %f %f %f", &id, &x, &y, &w, &h) == 5){ if(count == size) { size = size * 2; boxes = realloc(boxes, size*sizeof(box_label)); } boxes[count].id = id; boxes[count].x = x; boxes[count].y = y; boxes[count].h = h; boxes[count].w = w; boxes[count].left = x - w/2; boxes[count].right = x + w/2; boxes[count].top = y - h/2; boxes[count].bottom = y + h/2; ++count; } fclose(file); *n = count; return boxes; } void randomize_boxes(box_label *b, int n) { int i; for(i = 0; i < n; ++i){ box_label swap = b[i]; int index = rand()%n; b[i] = b[index]; b[index] = swap; } } void correct_boxes(box_label *boxes, int n, float dx, float dy, float sx, float sy, int flip) { int i; for(i = 0; i < n; ++i){ if(boxes[i].x == 0 && boxes[i].y == 0) { boxes[i].x = 999999; boxes[i].y = 999999; boxes[i].w = 999999; boxes[i].h = 999999; continue; } boxes[i].left = boxes[i].left * sx - dx; boxes[i].right = boxes[i].right * sx - dx; boxes[i].top = boxes[i].top * sy - dy; boxes[i].bottom = boxes[i].bottom* sy - dy; if(flip){ float swap = boxes[i].left; boxes[i].left = 1. - boxes[i].right; boxes[i].right = 1. - swap; } boxes[i].left = constrain(0, 1, boxes[i].left); boxes[i].right = constrain(0, 1, boxes[i].right); boxes[i].top = constrain(0, 1, boxes[i].top); boxes[i].bottom = constrain(0, 1, boxes[i].bottom); boxes[i].x = (boxes[i].left+boxes[i].right)/2; boxes[i].y = (boxes[i].top+boxes[i].bottom)/2; boxes[i].w = (boxes[i].right - boxes[i].left); boxes[i].h = (boxes[i].bottom - boxes[i].top); boxes[i].w = constrain(0, 1, boxes[i].w); boxes[i].h = constrain(0, 1, boxes[i].h); } } void fill_truth_swag(char *path, float *truth, int classes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count && i < 30; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .0 || h < .0) continue; int index = (4+classes) * i; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; if (id < classes) truth[index+id] = 1; } free(boxes); } void fill_truth_region(char *path, float *truth, int classes, int num_boxes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".png", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .005 || h < .005) continue; int col = (int)(x*num_boxes); int row = (int)(y*num_boxes); x = x*num_boxes - col; y = y*num_boxes - row; int index = (col+row*num_boxes)*(5+classes); if (truth[index]) continue; truth[index++] = 1; if (id < classes) truth[index+id] = 1; index += classes; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; } free(boxes); } void load_rle(image im, int *rle, int n) { int count = 0; int curr = 0; int i,j; for(i = 0; i < n; ++i){ for(j = 0; j < rle[i]; ++j){ im.data[count++] = curr; } curr = 1 - curr; } for(; count < im.h*im.w*im.c; ++count){ im.data[count] = curr; } } void or_image(image src, image dest, int c) { int i; for(i = 0; i < src.w*src.h; ++i){ if(src.data[i]) dest.data[dest.w*dest.h*c + i] = 1; } } void exclusive_image(image src) { int k, j, i; int s = src.w*src.h; for(k = 0; k < src.c-1; ++k){ for(i = 0; i < s; ++i){ if (src.data[k*s + i]){ for(j = k+1; j < src.c; ++j){ src.data[j*s + i] = 0; } } } } } box bound_image(image im) { int x,y; int minx = im.w; int miny = im.h; int maxx = 0; int maxy = 0; for(y = 0; y < im.h; ++y){ for(x = 0; x < im.w; ++x){ if(im.data[y*im.w + x]){ minx = (x < minx) ? x : minx; miny = (y < miny) ? y : miny; maxx = (x > maxx) ? x : maxx; maxy = (y > maxy) ? y : maxy; } } } box b = {minx, miny, maxx-minx + 1, maxy-miny + 1}; //printf("%f %f %f %f\n", b.x, b.y, b.w, b.h); return b; } void fill_truth_iseg(char *path, int num_boxes, float *truth, int classes, int w, int h, augment_args aug, int flip, int mw, int mh) { char labelpath[4096]; find_replace(path, "images", "mask", labelpath); find_replace(labelpath, "JPEGImages", "mask", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); FILE *file = fopen(labelpath, "r"); if(!file) file_error(labelpath); char buff[32788]; int id; int i = 0; image part = make_image(w, h, 1); while((fscanf(file, "%d %s", &id, buff) == 2) && i < num_boxes){ int n = 0; int *rle = read_intlist(buff, &n, 0); load_rle(part, rle, n); image sized = rotate_crop_image(part, aug.rad, aug.scale, aug.w, aug.h, aug.dx, aug.dy, aug.aspect); if(flip) flip_image(sized); box b = bound_image(sized); if(b.w > 0){ image crop = crop_image(sized, b.x, b.y, b.w, b.h); image mask = resize_image(crop, mw, mh); truth[i*(4 + mw*mh + 1) + 0] = (b.x + b.w/2.)/sized.w; truth[i*(4 + mw*mh + 1) + 1] = (b.y + b.h/2.)/sized.h; truth[i*(4 + mw*mh + 1) + 2] = b.w/sized.w; truth[i*(4 + mw*mh + 1) + 3] = b.h/sized.h; int j; for(j = 0; j < mw*mh; ++j){ truth[i*(4 + mw*mh + 1) + 4 + j] = mask.data[j]; } truth[i*(4 + mw*mh + 1) + 4 + mw*mh] = id; free_image(crop); free_image(mask); ++i; } free_image(sized); free(rle); } fclose(file); free_image(part); } void fill_truth_detection(char *path, int num_boxes, float *truth, int classes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, "raw", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".png", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); if(count > num_boxes) count = num_boxes; float x,y,w,h; int id; int i; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if ((w < .001 || h < .001)) continue; truth[i*5+0] = x; truth[i*5+1] = y; truth[i*5+2] = w; truth[i*5+3] = h; truth[i*5+4] = id; } free(boxes); } #define NUMCHARS 37 void print_letters(float *pred, int n) { int i; for(i = 0; i < n; ++i){ int index = max_index(pred+i*NUMCHARS, NUMCHARS); printf("%c", int_to_alphanum(index)); } printf("\n"); } void fill_truth_captcha(char *path, int n, float *truth) { char *begin = strrchr(path, '/'); ++begin; int i; for(i = 0; i < strlen(begin) && i < n && begin[i] != '.'; ++i){ int index = alphanum_to_int(begin[i]); if(index > 35) printf("Bad %c\n", begin[i]); truth[i*NUMCHARS+index] = 1; } for(;i < n; ++i){ truth[i*NUMCHARS + NUMCHARS-1] = 1; } } data load_data_captcha(char **paths, int n, int m, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = make_matrix(n, k*NUMCHARS); int i; for(i = 0; i < n; ++i){ fill_truth_captcha(paths[i], k, d.y.vals[i]); } if(m) free(paths); return d; } data load_data_captcha_encode(char **paths, int n, int m, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.X.cols = 17100; d.y = d.X; if(m) free(paths); return d; } void fill_truth(char *path, char **labels, int k, float *truth) { int i; memset(truth, 0, k*sizeof(float)); int count = 0; for(i = 0; i < k; ++i){ if(strstr(path, labels[i])){ truth[i] = 1; ++count; } } if(count != 1 && (k != 1 || count != 0)) printf("Too many or too few labels: %d, %s\n", count, path); } void fill_hierarchy(float *truth, int k, tree *hierarchy) { int j; for(j = 0; j < k; ++j){ if(truth[j]){ int parent = hierarchy->parent[j]; while(parent >= 0){ truth[parent] = 1; parent = hierarchy->parent[parent]; } } } int i; int count = 0; for(j = 0; j < hierarchy->groups; ++j){ //printf("%d\n", count); int mask = 1; for(i = 0; i < hierarchy->group_size[j]; ++i){ if(truth[count + i]){ mask = 0; break; } } if (mask) { for(i = 0; i < hierarchy->group_size[j]; ++i){ truth[count + i] = SECRET_NUM; } } count += hierarchy->group_size[j]; } } matrix load_regression_labels_paths(char **paths, int n) { matrix y = make_matrix(n, 1); int i; for(i = 0; i < n; ++i){ char labelpath[4096]; find_replace(paths[i], "images", "targets", labelpath); find_replace(labelpath, "JPEGImages", "targets", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".png", ".txt", labelpath); FILE *file = fopen(labelpath, "r"); fscanf(file, "%f", &(y.vals[i][0])); fclose(file); } return y; } matrix load_labels_paths(char **paths, int n, char **labels, int k, tree *hierarchy) { matrix y = make_matrix(n, k); int i; for(i = 0; i < n && labels; ++i){ fill_truth(paths[i], labels, k, y.vals[i]); if(hierarchy){ fill_hierarchy(y.vals[i], k, hierarchy); } } return y; } matrix load_tags_paths(char **paths, int n, int k) { matrix y = make_matrix(n, k); int i; int count = 0; for(i = 0; i < n; ++i){ char label[4096]; find_replace(paths[i], "imgs", "labels", label); find_replace(label, "_iconl.jpeg", ".txt", label); FILE *file = fopen(label, "r"); if(!file){ find_replace(label, "labels", "labels2", label); file = fopen(label, "r"); if(!file) continue; } ++count; int tag; while(fscanf(file, "%d", &tag) == 1){ if(tag < k){ y.vals[i][tag] = 1; } } fclose(file); } printf("%d/%d\n", count, n); return y; } char **get_labels(char *filename) { list *plist = get_paths(filename); char **labels = (char **)list_to_array(plist); free_list(plist); return labels; } void free_data(data d) { if(!d.shallow){ free_matrix(d.X); free_matrix(d.y); }else{ free(d.X.vals); free(d.y.vals); } } image get_segmentation_image(char *path, int w, int h, int classes) { char labelpath[4096]; find_replace(path, "images", "mask", labelpath); find_replace(labelpath, "JPEGImages", "mask", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); image mask = make_image(w, h, classes); FILE *file = fopen(labelpath, "r"); if(!file) file_error(labelpath); char buff[32788]; int id; image part = make_image(w, h, 1); while(fscanf(file, "%d %s", &id, buff) == 2){ int n = 0; int *rle = read_intlist(buff, &n, 0); load_rle(part, rle, n); or_image(part, mask, id); free(rle); } //exclusive_image(mask); fclose(file); free_image(part); return mask; } image get_segmentation_image2(char *path, int w, int h, int classes) { char labelpath[4096]; find_replace(path, "images", "mask", labelpath); find_replace(labelpath, "JPEGImages", "mask", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPG", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); image mask = make_image(w, h, classes+1); int i; for(i = 0; i < w*h; ++i){ mask.data[w*h*classes + i] = 1; } FILE *file = fopen(labelpath, "r"); if(!file) file_error(labelpath); char buff[32788]; int id; image part = make_image(w, h, 1); while(fscanf(file, "%d %s", &id, buff) == 2){ int n = 0; int *rle = read_intlist(buff, &n, 0); load_rle(part, rle, n); or_image(part, mask, id); for(i = 0; i < w*h; ++i){ if(part.data[i]) mask.data[w*h*classes + i] = 0; } free(rle); } //exclusive_image(mask); fclose(file); free_image(part); return mask; } data load_data_seg(int n, char **paths, int m, int w, int h, int classes, int min, int max, float angle, float aspect, float hue, float saturation, float exposure, int div) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; d.y.rows = n; d.y.cols = h*w*classes/div/div; d.y.vals = calloc(d.X.rows, sizeof(float*)); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); augment_args a = random_augment_args(orig, angle, aspect, min, max, w, h); image sized = rotate_crop_image(orig, a.rad, a.scale, a.w, a.h, a.dx, a.dy, a.aspect); int flip = rand()%2; if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; image mask = get_segmentation_image(random_paths[i], orig.w, orig.h, classes); //image mask = make_image(orig.w, orig.h, classes+1); image sized_m = rotate_crop_image(mask, a.rad, a.scale/div, a.w/div, a.h/div, a.dx/div, a.dy/div, a.aspect); if(flip) flip_image(sized_m); d.y.vals[i] = sized_m.data; free_image(orig); free_image(mask); /* image rgb = mask_to_rgb(sized_m, classes); show_image(rgb, "part"); show_image(sized, "orig"); cvWaitKey(0); free_image(rgb); */ } free(random_paths); return d; } data load_data_iseg(int n, char **paths, int m, int w, int h, int classes, int boxes, int coords, int min, int max, float angle, float aspect, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; d.y = make_matrix(n, (coords+1)*boxes); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); augment_args a = random_augment_args(orig, angle, aspect, min, max, w, h); image sized = rotate_crop_image(orig, a.rad, a.scale, a.w, a.h, a.dx, a.dy, a.aspect); int flip = rand()%2; if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; //show_image(sized, "image"); fill_truth_iseg(random_paths[i], boxes, d.y.vals[i], classes, orig.w, orig.h, a, flip, 14, 14); free_image(orig); /* image rgb = mask_to_rgb(sized_m, classes); show_image(rgb, "part"); show_image(sized, "orig"); cvWaitKey(0); free_image(rgb); */ } free(random_paths); return d; } data load_data_region(int n, char **paths, int m, int w, int h, int size, int classes, float jitter, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = size*size*(5+classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); int oh = orig.h; int ow = orig.w; int dw = (ow*jitter); int dh = (oh*jitter); int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; int flip = rand()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/ow)/sx; float dy = ((float)ptop /oh)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; fill_truth_region(random_paths[i], d.y.vals[i], classes, size, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); } free(random_paths); return d; } data load_data_compare(int n, char **paths, int m, int classes, int w, int h) { if(m) paths = get_random_paths(paths, 2*n, m); int i,j; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*6; int k = 2*(classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image im1 = load_image_color(paths[i*2], w, h); image im2 = load_image_color(paths[i*2+1], w, h); d.X.vals[i] = calloc(d.X.cols, sizeof(float)); memcpy(d.X.vals[i], im1.data, h*w*3*sizeof(float)); memcpy(d.X.vals[i] + h*w*3, im2.data, h*w*3*sizeof(float)); int id; float iou; char imlabel1[4096]; char imlabel2[4096]; find_replace(paths[i*2], "imgs", "labels", imlabel1); find_replace(imlabel1, "jpg", "txt", imlabel1); FILE *fp1 = fopen(imlabel1, "r"); while(fscanf(fp1, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id] < iou) d.y.vals[i][2*id] = iou; } find_replace(paths[i*2+1], "imgs", "labels", imlabel2); find_replace(imlabel2, "jpg", "txt", imlabel2); FILE *fp2 = fopen(imlabel2, "r"); while(fscanf(fp2, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id + 1] < iou) d.y.vals[i][2*id + 1] = iou; } for (j = 0; j < classes; ++j){ if (d.y.vals[i][2*j] > .5 && d.y.vals[i][2*j+1] < .5){ d.y.vals[i][2*j] = 1; d.y.vals[i][2*j+1] = 0; } else if (d.y.vals[i][2*j] < .5 && d.y.vals[i][2*j+1] > .5){ d.y.vals[i][2*j] = 0; d.y.vals[i][2*j+1] = 1; } else { d.y.vals[i][2*j] = SECRET_NUM; d.y.vals[i][2*j+1] = SECRET_NUM; } } fclose(fp1); fclose(fp2); free_image(im1); free_image(im2); } if(m) free(paths); return d; } data load_data_swag(char **paths, int n, int classes, float jitter) { int index = rand()%n; char *random_path = paths[index]; image orig = load_image_color(random_path, 0, 0); int h = orig.h; int w = orig.w; data d = {0}; d.shallow = 0; d.w = w; d.h = h; d.X.rows = 1; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = (4+classes)*30; d.y = make_matrix(1, k); int dw = w*jitter; int dh = h*jitter; int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = w - pleft - pright; int sheight = h - ptop - pbot; float sx = (float)swidth / w; float sy = (float)sheight / h; int flip = rand()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/w)/sx; float dy = ((float)ptop /h)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); d.X.vals[0] = sized.data; fill_truth_swag(random_path, d.y.vals[0], classes, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); return d; } data load_data_detection(int n, char **paths, int m, int w, int h, int boxes, int classes, float jitter, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; d.y = make_matrix(n, 5*boxes); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); image sized = make_image(w, h, orig.c); fill_image(sized, .5); float dw = jitter * orig.w; float dh = jitter * orig.h; float new_ar = (orig.w + rand_uniform(-dw, dw)) / (orig.h + rand_uniform(-dh, dh)); float scale = rand_uniform(.25, 2); float nw, nh; if(new_ar < 1){ nh = scale * h; nw = nh * new_ar; } else { nw = scale * w; nh = nw / new_ar; } float dx = rand_uniform(0, w - nw); float dy = rand_uniform(0, h - nh); place_image(orig, nw, nh, dx, dy, sized); random_distort_image(sized, hue, saturation, exposure); int flip = rand()%2; if(flip) flip_image(sized); d.X.vals[i] = sized.data; fill_truth_detection(random_paths[i], boxes, d.y.vals[i], classes, flip, -dx/w, -dy/h, nw/w, nh/h); free_image(orig); } free(random_paths); return d; } void *load_thread(void *ptr) { //printf("Loading data: %d\n", rand()); load_args a = *(struct load_args*)ptr; if(a.exposure == 0) a.exposure = 1; if(a.saturation == 0) a.saturation = 1; if(a.aspect == 0) a.aspect = 1; if (a.type == OLD_CLASSIFICATION_DATA){ *a.d = load_data_old(a.paths, a.n, a.m, a.labels, a.classes, a.w, a.h); } else if (a.type == REGRESSION_DATA){ *a.d = load_data_regression(a.paths, a.n, a.m, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } else if (a.type == CLASSIFICATION_DATA){ *a.d = load_data_augment(a.paths, a.n, a.m, a.labels, a.classes, a.hierarchy, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.center); } else if (a.type == SUPER_DATA){ *a.d = load_data_super(a.paths, a.n, a.m, a.w, a.h, a.scale); } else if (a.type == WRITING_DATA){ *a.d = load_data_writing(a.paths, a.n, a.m, a.w, a.h, a.out_w, a.out_h); } else if (a.type == INSTANCE_DATA){ *a.d = load_data_iseg(a.n, a.paths, a.m, a.w, a.h, a.classes, a.num_boxes, a.coords, a.min, a.max, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } else if (a.type == SEGMENTATION_DATA){ *a.d = load_data_seg(a.n, a.paths, a.m, a.w, a.h, a.classes, a.min, a.max, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.scale); } else if (a.type == REGION_DATA){ *a.d = load_data_region(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure); } else if (a.type == DETECTION_DATA){ *a.d = load_data_detection(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure); } else if (a.type == SWAG_DATA){ *a.d = load_data_swag(a.paths, a.n, a.classes, a.jitter); } else if (a.type == COMPARE_DATA){ *a.d = load_data_compare(a.n, a.paths, a.m, a.classes, a.w, a.h); } else if (a.type == IMAGE_DATA){ *(a.im) = load_image_color(a.path, 0, 0); *(a.resized) = resize_image(*(a.im), a.w, a.h); } else if (a.type == LETTERBOX_DATA){ *(a.im) = load_image_color(a.path, 0, 0); *(a.resized) = letterbox_image(*(a.im), a.w, a.h); } else if (a.type == TAG_DATA){ *a.d = load_data_tag(a.paths, a.n, a.m, a.classes, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } free(ptr); return 0; } pthread_t load_data_in_thread(load_args args) { pthread_t thread; struct load_args *ptr = calloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_thread, ptr)) error("Thread creation failed"); return thread; } void *load_threads(void *ptr) { int i; load_args args = *(load_args *)ptr; if (args.threads == 0) args.threads = 1; data *out = args.d; int total = args.n; free(ptr); data *buffers = calloc(args.threads, sizeof(data)); pthread_t *threads = calloc(args.threads, sizeof(pthread_t)); for(i = 0; i < args.threads; ++i){ args.d = buffers + i; args.n = (i+1) * total/args.threads - i * total/args.threads; threads[i] = load_data_in_thread(args); } for(i = 0; i < args.threads; ++i){ pthread_join(threads[i], 0); } *out = concat_datas(buffers, args.threads); out->shallow = 0; for(i = 0; i < args.threads; ++i){ buffers[i].shallow = 1; free_data(buffers[i]); } free(buffers); free(threads); return 0; } void load_data_blocking(load_args args) { struct load_args *ptr = calloc(1, sizeof(struct load_args)); *ptr = args; load_thread(ptr); } pthread_t load_data(load_args args) { pthread_t thread; struct load_args *ptr = calloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_threads, ptr)) error("Thread creation failed"); return thread; } data load_data_writing(char **paths, int n, int m, int w, int h, int out_w, int out_h) { if(m) paths = get_random_paths(paths, n, m); char **replace_paths = find_replace_paths(paths, n, ".png", "-label.png"); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_image_paths_gray(replace_paths, n, out_w, out_h); if(m) free(paths); int i; for(i = 0; i < n; ++i) free(replace_paths[i]); free(replace_paths); return d; } data load_data_old(char **paths, int n, int m, char **labels, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_labels_paths(paths, n, labels, k, 0); if(m) free(paths); return d; } /* data load_data_study(char **paths, int n, int m, char **labels, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { data d = {0}; d.indexes = calloc(n, sizeof(int)); if(m) paths = get_random_paths_indexes(paths, n, m, d.indexes); d.shallow = 0; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure); d.y = load_labels_paths(paths, n, labels, k); if(m) free(paths); return d; } */ data load_data_super(char **paths, int n, int m, int w, int h, int scale) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; int i; d.X.rows = n; d.X.vals = calloc(n, sizeof(float*)); d.X.cols = w*h*3; d.y.rows = n; d.y.vals = calloc(n, sizeof(float*)); d.y.cols = w*scale * h*scale * 3; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], 0, 0); image crop = random_crop_image(im, w*scale, h*scale); int flip = rand()%2; if (flip) flip_image(crop); image resize = resize_image(crop, w, h); d.X.vals[i] = resize.data; d.y.vals[i] = crop.data; free_image(im); } if(m) free(paths); return d; } data load_data_regression(char **paths, int n, int m, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, 0); d.y = load_regression_labels_paths(paths, n); if(m) free(paths); return d; } data select_data(data *orig, int *inds) { data d = {0}; d.shallow = 1; d.w = orig[0].w; d.h = orig[0].h; d.X.rows = orig[0].X.rows; d.y.rows = orig[0].X.rows; d.X.cols = orig[0].X.cols; d.y.cols = orig[0].y.cols; d.X.vals = calloc(orig[0].X.rows, sizeof(float *)); d.y.vals = calloc(orig[0].y.rows, sizeof(float *)); int i; for(i = 0; i < d.X.rows; ++i){ d.X.vals[i] = orig[inds[i]].X.vals[i]; d.y.vals[i] = orig[inds[i]].y.vals[i]; } return d; } data *tile_data(data orig, int divs, int size) { data *ds = calloc(divs*divs, sizeof(data)); int i, j; #pragma omp parallel for for(i = 0; i < divs*divs; ++i){ data d; d.shallow = 0; d.w = orig.w/divs * size; d.h = orig.h/divs * size; d.X.rows = orig.X.rows; d.X.cols = d.w*d.h*3; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.y = copy_matrix(orig.y); #pragma omp parallel for for(j = 0; j < orig.X.rows; ++j){ int x = (i%divs) * orig.w / divs - (d.w - orig.w/divs)/2; int y = (i/divs) * orig.h / divs - (d.h - orig.h/divs)/2; image im = float_to_image(orig.w, orig.h, 3, orig.X.vals[j]); d.X.vals[j] = crop_image(im, x, y, d.w, d.h).data; } ds[i] = d; } return ds; } data resize_data(data orig, int w, int h) { data d = {0}; d.shallow = 0; d.w = w; d.h = h; int i; d.X.rows = orig.X.rows; d.X.cols = w*h*3; d.X.vals = calloc(d.X.rows, sizeof(float*)); d.y = copy_matrix(orig.y); #pragma omp parallel for for(i = 0; i < orig.X.rows; ++i){ image im = float_to_image(orig.w, orig.h, 3, orig.X.vals[i]); d.X.vals[i] = resize_image(im, w, h).data; } return d; } data load_data_augment(char **paths, int n, int m, char **labels, int k, tree *hierarchy, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure, int center) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.w=size; d.h=size; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, center); d.y = load_labels_paths(paths, n, labels, k, hierarchy); if(m) free(paths); return d; } data load_data_tag(char **paths, int n, int m, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.w = size; d.h = size; d.shallow = 0; d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, 0); d.y = load_tags_paths(paths, n, k); if(m) free(paths); return d; } matrix concat_matrix(matrix m1, matrix m2) { int i, count = 0; matrix m; m.cols = m1.cols; m.rows = m1.rows+m2.rows; m.vals = calloc(m1.rows + m2.rows, sizeof(float*)); for(i = 0; i < m1.rows; ++i){ m.vals[count++] = m1.vals[i]; } for(i = 0; i < m2.rows; ++i){ m.vals[count++] = m2.vals[i]; } return m; } data concat_data(data d1, data d2) { data d = {0}; d.shallow = 1; d.X = concat_matrix(d1.X, d2.X); d.y = concat_matrix(d1.y, d2.y); d.w = d1.w; d.h = d1.h; return d; } data concat_datas(data *d, int n) { int i; data out = {0}; for(i = 0; i < n; ++i){ data new = concat_data(d[i], out); free_data(out); out = new; } return out; } data load_categorical_data_csv(char *filename, int target, int k) { data d = {0}; d.shallow = 0; matrix X = csv_to_matrix(filename); float *truth_1d = pop_column(&X, target); float **truth = one_hot_encode(truth_1d, X.rows, k); matrix y; y.rows = X.rows; y.cols = k; y.vals = truth; d.X = X; d.y = y; free(truth_1d); return d; } data load_cifar10_data(char *filename) { data d = {0}; d.shallow = 0; long i,j; matrix X = make_matrix(10000, 3072); matrix y = make_matrix(10000, 10); d.X = X; d.y = y; FILE *fp = fopen(filename, "rb"); if(!fp) file_error(filename); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class = bytes[0]; y.vals[i][class] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i][j] = (double)bytes[j+1]; } } scale_data_rows(d, 1./255); //normalize_data_rows(d); fclose(fp); return d; } void get_random_batch(data d, int n, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = rand()%d.X.rows; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void get_next_batch(data d, int n, int offset, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = offset + j; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); if(y) memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void smooth_data(data d) { int i, j; float scale = 1. / d.y.cols; float eps = .1; for(i = 0; i < d.y.rows; ++i){ for(j = 0; j < d.y.cols; ++j){ d.y.vals[i][j] = eps * scale + (1-eps) * d.y.vals[i][j]; } } } data load_all_cifar10() { data d = {0}; d.shallow = 0; int i,j,b; matrix X = make_matrix(50000, 3072); matrix y = make_matrix(50000, 10); d.X = X; d.y = y; for(b = 0; b < 5; ++b){ char buff[256]; sprintf(buff, "data/cifar/cifar-10-batches-bin/data_batch_%d.bin", b+1); FILE *fp = fopen(buff, "rb"); if(!fp) file_error(buff); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class = bytes[0]; y.vals[i+b*10000][class] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i+b*10000][j] = (double)bytes[j+1]; } } fclose(fp); } //normalize_data_rows(d); scale_data_rows(d, 1./255); smooth_data(d); return d; } data load_go(char *filename) { FILE *fp = fopen(filename, "rb"); matrix X = make_matrix(3363059, 361); matrix y = make_matrix(3363059, 361); int row, col; if(!fp) file_error(filename); char *label; int count = 0; while((label = fgetl(fp))){ int i; if(count == X.rows){ X = resize_matrix(X, count*2); y = resize_matrix(y, count*2); } sscanf(label, "%d %d", &row, &col); char *board = fgetl(fp); int index = row*19 + col; y.vals[count][index] = 1; for(i = 0; i < 19*19; ++i){ float val = 0; if(board[i] == '1') val = 1; else if(board[i] == '2') val = -1; X.vals[count][i] = val; } ++count; free(label); free(board); } X = resize_matrix(X, count); y = resize_matrix(y, count); data d = {0}; d.shallow = 0; d.X = X; d.y = y; fclose(fp); return d; } void randomize_data(data d) { int i; for(i = d.X.rows-1; i > 0; --i){ int index = rand()%i; float *swap = d.X.vals[index]; d.X.vals[index] = d.X.vals[i]; d.X.vals[i] = swap; swap = d.y.vals[index]; d.y.vals[index] = d.y.vals[i]; d.y.vals[i] = swap; } } void scale_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ scale_array(d.X.vals[i], d.X.cols, s); } } void translate_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ translate_array(d.X.vals[i], d.X.cols, s); } } data copy_data(data d) { data c = {0}; c.w = d.w; c.h = d.h; c.shallow = 0; c.num_boxes = d.num_boxes; c.boxes = d.boxes; c.X = copy_matrix(d.X); c.y = copy_matrix(d.y); return c; } void normalize_data_rows(data d) { int i; for(i = 0; i < d.X.rows; ++i){ normalize_array(d.X.vals[i], d.X.cols); } } data get_data_part(data d, int part, int total) { data p = {0}; p.shallow = 1; p.X.rows = d.X.rows * (part + 1) / total - d.X.rows * part / total; p.y.rows = d.y.rows * (part + 1) / total - d.y.rows * part / total; p.X.cols = d.X.cols; p.y.cols = d.y.cols; p.X.vals = d.X.vals + d.X.rows * part / total; p.y.vals = d.y.vals + d.y.rows * part / total; return p; } data get_random_data(data d, int num) { data r = {0}; r.shallow = 1; r.X.rows = num; r.y.rows = num; r.X.cols = d.X.cols; r.y.cols = d.y.cols; r.X.vals = calloc(num, sizeof(float *)); r.y.vals = calloc(num, sizeof(float *)); int i; for(i = 0; i < num; ++i){ int index = rand()%d.X.rows; r.X.vals[i] = d.X.vals[index]; r.y.vals[i] = d.y.vals[index]; } return r; } data *split_data(data d, int part, int total) { data *split = calloc(2, sizeof(data)); int i; int start = part*d.X.rows/total; int end = (part+1)*d.X.rows/total; data train; data test; train.shallow = test.shallow = 1; test.X.rows = test.y.rows = end-start; train.X.rows = train.y.rows = d.X.rows - (end-start); train.X.cols = test.X.cols = d.X.cols; train.y.cols = test.y.cols = d.y.cols; train.X.vals = calloc(train.X.rows, sizeof(float*)); test.X.vals = calloc(test.X.rows, sizeof(float*)); train.y.vals = calloc(train.y.rows, sizeof(float*)); test.y.vals = calloc(test.y.rows, sizeof(float*)); for(i = 0; i < start; ++i){ train.X.vals[i] = d.X.vals[i]; train.y.vals[i] = d.y.vals[i]; } for(i = start; i < end; ++i){ test.X.vals[i-start] = d.X.vals[i]; test.y.vals[i-start] = d.y.vals[i]; } for(i = end; i < d.X.rows; ++i){ train.X.vals[i-(end-start)] = d.X.vals[i]; train.y.vals[i-(end-start)] = d.y.vals[i]; } split[0] = train; split[1] = test; return split; }
multiplications.c
/* This source file is part of the Geophysical Fluids Modeling Framework (GAME), which is released under the MIT license. Github repository: https://github.com/OpenNWP/GAME */ /* In this file, algebraic multiplications of fields are collected. */ #include <stdio.h> #include "../game_types.h" #include "spatial_operators.h" #include "../thermodynamics/thermodynamics.h" int scalar_times_scalar(Scalar_field in_field_0, Scalar_field in_field_1, Scalar_field out_field) { #pragma omp parallel for for (int i = 0; i < NO_OF_SCALARS; ++i) { out_field[i] = in_field_0[i]*in_field_1[i]; } return 0; } int vector_times_vector(Vector_field in_field_0, Vector_field in_field_1, Vector_field out_field) { #pragma omp parallel for for (int i = 0; i < NO_OF_VECTORS; ++i) { out_field[i] = in_field_0[i]*in_field_1[i]; } return 0; } int scalar_times_vector(Scalar_field scalar_field, Vector_field vector_field, Vector_field out_field, Grid *grid) { /* This function multiplies the vector field vector_field by the scalar field scalar_field. */ scalar_times_vector_h(scalar_field, vector_field, out_field, grid); scalar_times_vector_v(scalar_field, vector_field, out_field, grid); return 0; } int scalar_times_vector_h(Scalar_field in_field_h, Vector_field vector_field, Vector_field out_field, Grid *grid) { int vector_index; double scalar_value; #pragma omp parallel for private (vector_index, scalar_value) for (int h_index = 0; h_index < NO_OF_VECTORS_H; ++h_index) { for (int layer_index = 0; layer_index < NO_OF_LAYERS; ++layer_index) { vector_index = NO_OF_SCALARS_H + layer_index*NO_OF_VECTORS_PER_LAYER + h_index; scalar_value = 0.5*( in_field_h[grid -> to_index[h_index] + layer_index*NO_OF_SCALARS_H] + in_field_h[grid -> from_index[h_index] + layer_index*NO_OF_SCALARS_H]); out_field[vector_index] = scalar_value*vector_field[vector_index]; } } return 0; } int scalar_times_vector_v(Scalar_field in_field_v, Vector_field vector_field, Vector_field out_field, Grid *grid) { int i, lower_index, upper_index; double scalar_value; #pragma omp parallel for private (i, lower_index, upper_index, scalar_value) for (int h_index = 0; h_index < NO_OF_SCALARS_H; ++h_index) { for (int layer_index = 1; layer_index < NO_OF_LAYERS; ++layer_index) { i = layer_index*NO_OF_VECTORS_PER_LAYER + h_index; lower_index = h_index + layer_index*NO_OF_SCALARS_H; upper_index = h_index + (layer_index - 1)*NO_OF_SCALARS_H; scalar_value = 0.5*( in_field_v[upper_index] + in_field_v[lower_index]); out_field[i] = scalar_value*vector_field[i]; } } return 0; }
shortcut_layer.c
#include "shortcut_layer.h" #include "dark_cuda.h" #include "blas.h" #include <stdio.h> #include <assert.h> layer make_shortcut_layer(int batch, int index, int w, int h, int c, int w2, int h2, int c2) { fprintf(stderr,"Shortcut Layer: %d\n", index); layer l = { (LAYER_TYPE)0 }; l.type = SHORTCUT; l.batch = batch; l.w = w2; l.h = h2; l.c = c2; l.out_w = w; l.out_h = h; l.out_c = c; l.outputs = w*h*c; l.inputs = l.outputs; l.index = index; l.delta = (float*)calloc(l.outputs * batch, sizeof(float)); l.output = (float*)calloc(l.outputs * batch, sizeof(float)); l.forward = forward_shortcut_layer; l.backward = backward_shortcut_layer; #ifdef GPU l.forward_gpu = forward_shortcut_layer_gpu; l.backward_gpu = backward_shortcut_layer_gpu; l.delta_gpu = cuda_make_array(l.delta, l.outputs*batch); l.output_gpu = cuda_make_array(l.output, l.outputs*batch); #endif return l; } void resize_shortcut_layer(layer *l, int w, int h) { //assert(l->w == l->out_w); //assert(l->h == l->out_h); l->w = l->out_w = w; l->h = l->out_h = h; l->outputs = w*h*l->out_c; l->inputs = l->outputs; l->delta = (float*)realloc(l->delta, l->outputs * l->batch * sizeof(float)); l->output = (float*)realloc(l->output, l->outputs * l->batch * sizeof(float)); #ifdef GPU cuda_free(l->output_gpu); cuda_free(l->delta_gpu); l->output_gpu = cuda_make_array(l->output, l->outputs*l->batch); l->delta_gpu = cuda_make_array(l->delta, l->outputs*l->batch); #endif } void forward_shortcut_layer(const layer l, network_state state) { if (l.w == l.out_w && l.h == l.out_h && l.c == l.out_c) { int size = l.batch * l.w * l.h * l.c; int i; #pragma omp parallel for for(i = 0; i < size; ++i) l.output[i] = state.input[i] + state.net.layers[l.index].output[i]; } else { copy_cpu(l.outputs*l.batch, state.input, 1, l.output, 1); shortcut_cpu(l.batch, l.w, l.h, l.c, state.net.layers[l.index].output, l.out_w, l.out_h, l.out_c, l.output); } activate_array(l.output, l.outputs*l.batch, l.activation); } void backward_shortcut_layer(const layer l, network_state state) { gradient_array(l.output, l.outputs*l.batch, l.activation, l.delta); axpy_cpu(l.outputs*l.batch, 1, l.delta, 1, state.delta, 1); shortcut_cpu(l.batch, l.out_w, l.out_h, l.out_c, l.delta, l.w, l.h, l.c, state.net.layers[l.index].delta); } #ifdef GPU void forward_shortcut_layer_gpu(const layer l, network_state state) { //copy_ongpu(l.outputs*l.batch, state.input, 1, l.output_gpu, 1); //simple_copy_ongpu(l.outputs*l.batch, state.input, l.output_gpu); //shortcut_gpu(l.batch, l.w, l.h, l.c, state.net.layers[l.index].output_gpu, l.out_w, l.out_h, l.out_c, l.output_gpu); input_shortcut_gpu(state.input, l.batch, l.w, l.h, l.c, state.net.layers[l.index].output_gpu, l.out_w, l.out_h, l.out_c, l.output_gpu); activate_array_ongpu(l.output_gpu, l.outputs*l.batch, l.activation); } void backward_shortcut_layer_gpu(const layer l, network_state state) { gradient_array_ongpu(l.output_gpu, l.outputs*l.batch, l.activation, l.delta_gpu); axpy_ongpu(l.outputs*l.batch, 1, l.delta_gpu, 1, state.delta, 1); shortcut_gpu(l.batch, l.out_w, l.out_h, l.out_c, l.delta_gpu, l.w, l.h, l.c, state.net.layers[l.index].delta_gpu); } #endif
gather_ref.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: jxyang@openailab.com * Update: hhchen@openailab.com */ #include <math.h> #include "sys_port.h" #include "module.h" #include "tengine_errno.h" #include "tengine_log.h" #include "tengine_ir.h" #include "../../cpu_node_ops.h" #include "tengine_op.h" #include "gather_param.h" typedef struct { int* in_shape; // the dim of the input int axis; int indices_num; int dim_size; int is_onnx; } gather_param_t; static int ref_gather_fp32(float* input, int* input_indices, float* output, gather_param_t* param, int num_thread) { float* out_ptr = output; float* in_ptr = input; int axis = param->axis; int outer_size = 1; int inner_size = 1; int axis_size = param->in_shape[axis]; for (int i = 0; i < axis; i++) { outer_size *= param->in_shape[i]; } for (int i = axis + 1; i < param->dim_size; i++) { inner_size *= param->in_shape[i]; // printf("inner_size size: %d %d \n", inner_size, param->in_shape[i]); } // #pragma omp parallel for num_threads(num_thread) if(param->is_onnx){ for (int outer = 0; outer < outer_size; ++outer) { memcpy(out_ptr + (outer * param->indices_num ) * inner_size, in_ptr + (outer* axis_size + param->indices_num) * inner_size, inner_size* sizeof(float)); } } else { for (int outer = 0; outer < outer_size; ++outer) { for (int i = 0; i < param->indices_num; i++) { memcpy(out_ptr + (outer * param->indices_num + i) * inner_size, in_ptr + (outer * axis_size + ( int )input_indices[i]) * inner_size, inner_size * sizeof(float)); } } } return 0; } static int ref_gather_uint8(uint8_t* input, int* input_indices, uint8_t* output, gather_param_t* param, int num_thread) { uint8_t* out_ptr = output; uint8_t* in_ptr = input; int axis = param->axis; int outer_size = 1; int inner_size = 1; int axis_size = param->in_shape[axis]; for (int i = 0; i < axis; i++) { outer_size *= param->in_shape[i]; } for (int i = axis + 1; i < param->dim_size; i++) { inner_size *= param->in_shape[i]; } // #pragma omp parallel for num_threads(num_thread) for (int outer = 0; outer < outer_size; ++outer) { for (int i = 0; i < param->indices_num; i++) { memcpy(out_ptr + (outer * param->indices_num + i) * inner_size, in_ptr + (outer * axis_size + ( int )input_indices[i]) * inner_size, inner_size); } } return 0; } static int prerun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; struct ir_graph* ir_graph = ir_node->graph; struct gather_param* gather_param = ( struct gather_param* )ir_node->op.param_mem; gather_param_t* op_priv_info = ( gather_param_t* )exec_node->ops_priv; struct ir_tensor* input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); op_priv_info->axis = gather_param->axis; op_priv_info->indices_num = gather_param->indices_num; op_priv_info->is_onnx = gather_param->is_onnx; op_priv_info->in_shape = (int*)sys_malloc(input_tensor->dim_num*sizeof(int)); /* prerun now */ return 0; } static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; struct ir_graph* ir_graph = ir_node->graph; struct ir_tensor* input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); struct ir_tensor* output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); struct ir_tensor* indices_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[1]); gather_param_t* op_priv_info = ( gather_param_t* )exec_node->ops_priv; int out_size = input_tensor->elem_num; // auto in_dim = input_tensor->GetShape().GetDim(); void* input = input_tensor->data; void* indices_data = indices_tensor->data; op_priv_info->dim_size = input_tensor->dim_num; for (int i = 0; i < op_priv_info->dim_size; i++) { op_priv_info->in_shape[i] = input_tensor->dims[i]; } // printf("in shape: %d %d %d %d\n", op_priv_info->in_shape[0], op_priv_info->in_shape[1], op_priv_info->in_shape[3], op_priv_info->in_shape[3]); // int indices_num = op_param.indices_num; void* output = output_tensor->data; int ret = -1; if (input_tensor->data_type == TENGINE_DT_FP32) ret = ref_gather_fp32(input, indices_data, output, op_priv_info, exec_graph->num_thread); else if(input_tensor->data_type == TENGINE_DT_UINT8) ret = ref_gather_uint8(input, indices_data, output, op_priv_info, exec_graph->num_thread); return ret; } static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; struct ir_graph* ir_graph = ir_node->graph; gather_param_t* op_priv_info = ( gather_param_t* )sys_malloc(sizeof(gather_param_t)); if (op_priv_info == NULL) { set_tengine_errno(ENOMEM); return -1; } memset(op_priv_info, 0, sizeof(gather_param_t)); exec_node->ops_priv = op_priv_info; return 0; } static int postrun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; gather_param_t* op_param = ( gather_param_t* )exec_node->ops_priv; sys_free(op_param->in_shape); return 0; } static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { gather_param_t* op_priv_info = ( gather_param_t* )exec_node->ops_priv; sys_free(op_priv_info); exec_node->ops_priv = NULL; return 0; } static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct ir_node* exec_node) { return OPS_SCORE_BEST; } static struct node_ops gather_node_ops = {.prerun = prerun, .run = run, .reshape = NULL, .postrun = NULL, .init_node = init_node, .release_node = release_node, .score = score}; static int reg_gather_ops(void* arg) { return register_builtin_node_ops(OP_GATHER, &gather_node_ops); } static int unreg_gather_ops(void* arg) { return unregister_builtin_node_ops(OP_GATHER, &gather_node_ops); } AUTO_REGISTER_OPS(reg_gather_ops); AUTO_UNREGISTER_OPS(unreg_gather_ops);
ParallelAlgorithms.c
/* ============================================================================ Author : Roberto Diaz Morales ============================================================================ Copyright (c) 2016 Roberto Díaz Morales 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. ============================================================================ */ /** * @brief Functions to perform some parallel linear algebra tasks. * * Parallel procedures to solve linear systems, cholesky factorization, * matrix products or triangular matrix inversion. * * @file ParallelAlgorithms.c * @author Roberto Diaz Morales * @date 23 Aug 2016 * @see ParallelAlgorithms.h */ #include "ParallelAlgorithms.h" #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> /** * @cond */ extern void dgemm_(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc ); extern void dpotrs_(char *uplo, int *n, int *nrhs, double *A, int *lda, double *B, int *ldb, int *info); extern void dtrtri_(char *uplo, char *diag, int *n, double *a, int *lda, int *info); extern void dpotrf_(char *uplo, int *n, double *A, int *lda, int *info); extern void dsyrk_(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c, int *ldc); extern void dtrmm_(char *side, char *uplo, char *transA, char *diag, int *m, int *n, double *alpha, double *A, int *ldA, double *B, int *ldB); /** @brief Auxiliar memory to perform temporal results in the parallel algebra operations. */ double **auxmemory1; /** @brief Auxiliar memory to perform temporal results in the parallel algebra operations. */ double **auxmemory2; /** @brief Auxiliar memory to perform temporal results in the parallel algebra operations. */ double **auxmemory3; /** * @brief Function to allocate auxiliar memory to be used in the algebra operations. * * * The parallel lineal algebra functions of this module require some memory for every thead to * allocate temporal results. This function must be called before any other function. * * @param Threads The number of threads to parallelize the linear algebra functions. * @param size The size of the dimensions of the matrices that will be handle. If a matrix has a rows and b columns, then n=max(a,b). * @see updateMemory() */ void initMemory(int Threads, int size){ auxmemory1=(double **) calloc(Threads,sizeof(double*)); auxmemory2=(double **) calloc(Threads,sizeof(double*)); auxmemory3=(double **) calloc(Threads,sizeof(double*)); int i; for(i=0;i<Threads;i++){ auxmemory1[i]=(double *) calloc(pow(ceil(1.0*(size)),2),sizeof(double)); auxmemory2[i]=(double *) calloc(pow(ceil(1.0*(size)),2),sizeof(double)); auxmemory3[i]=(double *) calloc(pow(ceil(1.0*(size)),2),sizeof(double)); } } /** * @brief Function to free auxiliar memory to be used in the algebra operations. * * * The parallel lineal algebra functions of this module require some memory for every thead to * allocate temporal results. This function must be called after any other function. * * @param Threads The number of threads to parallelize the linear algebra functions. * @see updateMemory() */ void freeMemory(int Threads){ int i; for(i=0;i<Threads;i++){ free(auxmemory1[i]); free(auxmemory2[i]); free(auxmemory3[i]); } free(auxmemory1); free(auxmemory2); free(auxmemory3); } /** * @brief Function to update auxiliar memory to be used in the algebra operations. * * The parallel lineal algebra functions of this module require some memory for every thead to * allocate temporal results. This function must be called if we allocated the memory using the function initMemory and we are going to work with bigger matrices. * * @param Threads The number of threads to parallelize the linear algebra functions. * @param size The size of the dimensions of the matrices that will be handle. If a matrix has a rows and b columns, then n=max(a,b). * @see initMemory() */ void updateMemory(int Threads, int size){ int i; for(i=0;i<Threads;i++){ auxmemory1[i]=realloc(auxmemory1[i],pow(ceil(1.0*(size)),2)*sizeof(double)); auxmemory2[i]=realloc(auxmemory2[i],pow(ceil(1.0*(size)),2)*sizeof(double)); auxmemory3[i]=realloc(auxmemory3[i],pow(ceil(1.0*(size)),2)*sizeof(double)); } } /** * @brief This function saves a piece of a matrix in the auxiliar memory. * * This is an auxiliry function of the linear algebra funtions. It is used to save a submatrix of * a matrix given as a parameter in the auxiliar memory. * * @param matrix The original matrix. * @param size1 The number of rows fo the original matrix. * @param size2 The number of columns of the original matrix. * @param O1 The row where the submatrix starts. * @param O2 The column where the submatrix starts. * @param A The pointer where the submatrix will be storaged. * @param size3 Number of rows of the submatrix to storage. * @param size4 Number of columns of the submatrix to storage. * @param nCores Number of threads to perform this task. */ void getSubMatrix(double *matrix,int size1,int size2,int O1,int O2,double *A, int size3,int size4,int nCores){ int j; for(j=0;j<size4;j++){ memcpy(&A[j*size3],&matrix[(j+O2)*size1+O1],size3*sizeof(double)); } } /** * @brief This function loads a piece of a matrix in the auxiliar memory and storage it in a matrix. * * This is an auxiliry function of the linear algebra funtions. It is used to load a matrix from * the auxiliar memory and storage it as a submatrix of another matrix. * * @param matrix The original matrix where the submatrix will be allocated. * @param size1 The number of rows fo the original matrix. * @param size2 The number of columns of the original matrix. * @param O1 The row of the original matrix where the submatrix starts. * @param O2 The column of the original matrix where the submatrix starts. * @param A The pointer where the submatrix is storaged. * @param size3 Number of rows of the submatrix that is storaged. * @param size4 Number of columns of the submatrix that is storaged. * @param nCores Number of threads to perform this task. */ void putSubMatrix(double *matrix,int size1,int size2,int O1,int O2,double *A, int size3,int size4,int nCores){ int j; for(j=0;j<size4;j++){ memcpy(&matrix[(j+O2)*size1+O1],&A[j*size3],size3*sizeof(double)); } } /** * @brief Main function that performs a parallel cholesky factorization. * * This function performs a parallel cholesky factorization on a sqaure submatrix * of a matrix recived as an argument. It uses openmp to create to parallelize the task using * different threads and every one of them performs a subtask using the function Chol. * @param matrix The matrix to perform the cholesky factorization. * @param r The number of rows of matrix * @param c The number of columns of matrix. * @param ro The row where the submatrix starts. * @param co The column where the submatrix starts. * @param n The order of the square submatrix * @param nCores The number of threads to perform the task. * @param deep It is a recursive function, this parameter tell the recursion deep to use. * @see Chol() */ void ParallelChol(double *matrix,int r,int c, int ro, int co, int n,int nCores, int deep){ double *memaux = (double *)calloc(2*pow(ceil(0.5*n),2),sizeof(double)); int blockSize = pow(ceil(0.5*n),2)/nCores; int i; #pragma omp parallel default(shared) private(i) { #pragma omp for schedule(static) for (i=0;i<nCores;i++){ Chol(matrix,r,c,ro,co,n,nCores,i,deep,0,memaux,blockSize); } } free(memaux); } /** * @brief Auxiliar function to perform a parallel cholesky factorization. * * This function is called by ParallelChol, that creates different threads and call this function * on each one using its thread index and the total number of threads as parameters. * * This is a recursive function where every thread finally find out the part of the matrix that need * and the linear algebra operations that it has to do. * * @param matrix The matrix to perform the cholesky factorization. * @param r The number of rows of matrix * @param c The number of columns of matrix. * @param ro The row where the submatrix starts. * @param co The column where the submatrix starts. * @param n The order of the square submatrix * @param nCores The number of threads to perform the task. * @param numTh Thread identifier. * @param posIni Variable to know what task to do by this thread. * @param memaux The auxiliar memory. * @param blockSize The size of its memory to save temporal results. * @param deep It is a recursive function, this parameter tell the recursion deep to use. * @see ParallelChol() * @see initMemory() * @see updateMemory() */ void Chol(double *matrix,int r,int c, int ro, int co, int n,int nCores,int numTh, int deep,int posIni,double *memaux, int blockSize){ if(deep<=1 | n < 8){ if(numTh==posIni & n>0){ double *m=auxmemory1[numTh]; getSubMatrix(matrix,r,c,ro,co,m, n,n,1); int info; char s='L'; dpotrf_(&s,&n, m, &n,&info); if(info != 0 & posIni==2){ printf("Error en dpotrf %d ------------------------------\n",info); exit(0); } int i,j; for(i=1;i<n;i++){ for(j=0;j<i;j++){ m[i*n+j]=0.0; } } putSubMatrix(matrix,r,c,ro,co,m, n,n,1); } }else{ int size1=ceil(0.5*n); int size2=n-size1; Chol(matrix,r,c,ro,co,size1,nCores,numTh,deep-1,posIni,memaux,blockSize); #pragma omp barrier MoveMatrix(matrix,r,ro,c,co,&memaux[posIni*blockSize],size1,0,size1,0,size1,size1, nCores,posIni,numTh); #pragma omp barrier TriangleInversion(&memaux[posIni*blockSize],size1, size1, 0, 0, size1, nCores,posIni,numTh,&memaux[size1*size1],blockSize); #pragma omp barrier MoveMatrix(matrix,r,ro+size1,c,co,&memaux[posIni*blockSize+size1*size1],size2,0,size1,0,size2,size1, nCores,posIni,numTh); #pragma omp barrier NLTProduct(&memaux[posIni*blockSize],size1,0,size1,0,&memaux[posIni*blockSize+size1*size1],size2,0,size1,0,size1,size2,1.0,matrix,r,ro+size1,c, co, nCores,posIni,numTh); #pragma omp barrier AATProduct(matrix,r,ro+size1,c,co,size2,size1,-1.0,1.0,matrix,r,ro+size1,c, co+size1, nCores,posIni,numTh); #pragma omp barrier if(numTh==posIni){ double *Zeroes = (double *) malloc(size1*size2*sizeof(double)); putSubMatrix(matrix,r,c,ro,co+size1,Zeroes, size1,size2,1); free(Zeroes); } #pragma omp barrier Chol(matrix,r,c,ro+size1,co+size1,size2,nCores,numTh,deep-1,posIni,memaux,blockSize); #pragma omp barrier } } /** * @brief Main function to solve a linear system in parallel. * * This function solves a linear system of two submatrices of matrix1 and matrix2. * It uses openmp to create different threads and every one of them performs a subtask * using the function LinearSystem. * If submatrix1 is the submatrix of matrix1 and submatrix2 is the submatrix of matrix2 then * it performs (submatrix1)^-1*submatrix2. * * @param matrix1 The first matrix. * @param r1 The number of rows of matrix1. * @param c1 The number of columns of matrix1. * @param ro1 The row where the submatrix starts. * @param co1 The column where the submatrix starts. * @param matrix2 The second matrix. * @param r2 The number of rows of matrix2. * @param c2 The number of columns of matrix2. * @param ro2 The row where the second submatrix starts. * @param co2 The column where the second submatrix starts. * @param n The number of rows of the submatrix1 * @param m The number of columns of the submatrix2. * @param result The matrix where the result should be storaged. * @param rr The number of rows of matrix result. * @param cr The number of columns of matrix result. * @param ror The row where the result submatrix starts. * @param cor The column where the result submatrix starts. * @param nCores The number of threads to launch to solve the task. */ void ParallelLinearSystem(double *matrix1,int r1,int c1, int ro1, int co1,double *matrix2,int r2,int c2, int ro2, int co2,int n, int m,double *result,int rr,int cr, int ror, int cor, int nCores){ if(n>nCores){ double *memaux = (double *)calloc(2*pow(ceil(0.5*n),2),sizeof(double)); int blockSize = pow(ceil(0.5*n),2)/nCores; int i; #pragma omp parallel default(shared) private(i) { #pragma omp for schedule(static) for (i=0;i<nCores;i++){ LinearSystem(matrix1,r1,c1,ro1,co1,matrix2,r2,c2,ro2,co2,n,m,result,rr,cr,ror,cor,nCores,i,0,memaux,blockSize); } } free(memaux); }else{ int info; char s='L'; int cols=1; dpotrf_(&s,&n, matrix1, &n,&info); memcpy(result,matrix2,n*sizeof(double)); dpotrs_(&s,&n,&cols, matrix1, &n, result,&n,&info); } } /** * @brief This function is called by ParallelLinearSystems, that creates different threads and call this function * on each one using its thread index and the total number of threads as parameters. * * This is a recursive function where every thread finally find out the part of the matrix that need * and the linear algebra operations that it has to do. * * @param matrix1 The first matrix. * @param r1 The number of rows of matrix1. * @param c1 The number of columns of matrix1. * @param ro1 The row where the submatrix starts. * @param co1 The column where the submatrix starts. * @param matrix2 The second matrix. * @param r2 The number of rows of matrix2. * @param c2 The number of columns of matrix2. * @param ro2 The row where the second submatrix starts. * @param co2 The column where the second submatrix starts. * @param n The number of rows of the submatrix1 * @param m The number of columns of the submatrix2. * @param result The matrix where the result should be storaged. * @param rr The number of rows of matrix result. * @param cr The number of columns of matrix result. * @param ror The row where the result submatrix starts. * @param cor The column where the result submatrix starts. * @param nCores The number of threads to launch to solve the task. * @param numTh Thread identifier. * @param posIni Variable to know what task to do by this thread. * @param memaux The auxiliar memory. * @param blockSize The size of its memory to save temporal results. * @see ParallelLinearSystem() */ void LinearSystem(double *matrix1,int r1,int c1, int ro1, int co1,double *matrix2,int r2,int c2, int ro2, int co2,int n, int m,double *result,int rr,int cr, int ror, int cor, int nCores, int numTh,int posIni,double *memaux, int blockSize){ int deep=2; Chol(matrix1,r1,c1,ro1,co1,n,nCores,numTh,deep,posIni,memaux,blockSize); #pragma omp barrier int info; char s='L'; int ncols = 1; int j,k; for(j=0;j<n;j++){ for(k=0;k<j;k++){ matrix1[j*n+k]=0.0; } } if(numTh==0){ memcpy(&result[0],&matrix2[0],n*sizeof(double)); dpotrs_(&s,&n,&ncols, &matrix1[0], &n, &result[0],&n,&info); } } /** * @brief This function performs a lower triangular matrix inverse in parallel of a submatrix. * * This function performs a lower triangular matrix inverse in parallel. It is used by the * ParallelLinearSystem function to solve the linear system using Cholesky Factorization. * * It makes use of the functions DiagInversion, InversionNLProducts and InversionLNProducts * to tell every thread the operations that they must do. * * * @param matrix The matrix. * @param r The number of rows of matrix. * @param c The number of columns of matrix. * @param ro The row where the submatrix starts. * @param co The column where the submatrix starts. * @param n The order of the submatrix. * @param nCores The number of threads to perform the matrix inversion. * @param posIni Variable to know what task to do by this thread. * @param numTh Thread identifier. * @param memaux The auxiliar memory. * @param blockSize The size of its memory to save temporal results. * @see DiagInversion() * @see InversionNLProducts() * @see InversionLNProducts() */ void TriangleInversion(double *matrix,int r, int c, int ro, int co, int n,int nCores,int posIni, int numTh,double *memaux,int blockSize){ #pragma omp barrier DiagInversion(matrix,r,c,ro,co,n,nCores,posIni,numTh); #pragma omp barrier int deep=log(nCores)/log(2); int o; #pragma omp barrier for (o=deep;o>=1;o--){ InversionNLProducts(matrix,r,c,ro,co,n,nCores,posIni,o,numTh,memaux,blockSize); #pragma omp barrier InversionLNProducts(matrix,r,c,ro,co,n,nCores,posIni,o,numTh,memaux,blockSize); #pragma omp barrier } } /** * @brief This function is an auxiliar function TriangleInversion. * * This function is an auxiliar function of TriangleInversion and is in charge of small matrix * inversions of the submtrices that has a portion of the diagonal. * * @param matrix The matrix. * @param r The number of rows of matrix. * @param c The number of columns of matrix. * @param ro The row where the submatrix starts. * @param co The column where the submatrix starts. * @param n The order of the submatrix. * @param nCores The number of threads to perform the matrix inversion. * @param posIni Variable to know what task to do by this thread. * @param numTh Thread identifier. * @see TriangleInversion() */ void DiagInversion(double *matrix,int r, int c, int ro, int co, int n,int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n>0){ double *m=auxmemory1[numTh]; getSubMatrix(matrix,r,c,ro,co,m, n,n,1); int info; char s1='L'; char s2='N'; dtrtri_(&s1,&s2,&n, m, &n,&info); if(info != 0){printf("Error en dtrtri %d ------------------------------\n",info);} putSubMatrix(matrix,r,c,ro,co,m, n,n,1); } }else{ int size1=ceil(0.5*n); int size2=n-size1; if(numTh<posIni+nCores/2) DiagInversion(matrix,r,c,ro,co,size1,nCores/2,posIni,numTh); else DiagInversion(matrix,r,c,ro+size1,co+size1, size2,nCores/2,posIni+nCores/2,numTh); } } /** * @brief This function is an auxiliar function TriangleInversion. * * This function is an auxiliar function of TriangleInversion and is in charge of products * of matrices and lower triangular matrices (previously storaged in the auxiliar memory) that * are portions of the original matrix. * * @param matrix The matrix. * @param r The number of rows of matrix. * @param c The number of columns of matrix. * @param ro The row where the submatrix starts. * @param co The column where the submatrix starts. * @param n The order of the submatrix. * @param nCores The number of threads to perform the matrix inversion. * @param posIni Variable to know what task to do by this thread. * @param deep The deep of the recursion. * @param numTh Thread identifier. * @param memaux The auxiliar memory for this task. * @param blockSize The size of its memory to save temporal results. * @see TriangleInversion() */ void InversionNLProducts(double *matrix,int r, int c, int ro, int co, int n,int nCores,int posIni,int deep,int numTh, double *memaux, int blockSize){ int size1=ceil(0.5*n); int size2=n-size1; if(deep==1){ double *C1=&memaux[posIni*blockSize]; NLProduct(matrix,r,ro,c,co,matrix,r,ro+size1,c,co,size1,size2,-1.0,C1,size2,0,size1,0, nCores,posIni,numTh); }else{ if(numTh<posIni+nCores/2) InversionNLProducts(matrix,r,c,ro,co,size1,nCores/2,posIni,deep-1,numTh,memaux,blockSize); else InversionNLProducts(matrix,r,c,ro+size1,co+size1,size2,nCores/2,posIni+nCores/2,deep-1,numTh,memaux,blockSize); } } /** * @brief This function is an auxiliar function TriangleInversion. * * This function is an auxiliar function of TriangleInversion and is in charge of products * of lower triangular matrices (previously storaged in the auxiliar memory) and matrices that * are portions of the original matrix. * * @param matrix The matrix. * @param r The number of rows of matrix. * @param c The number of columns of matrix. * @param ro The row where the submatrix starts. * @param co The column where the submatrix starts. * @param n The order of the submatrix. * @param nCores The number of threads to perform the matrix inversion. * @param posIni Variable to know what task to do by this thread. * @param deep The deep of the recursion. * @param numTh Thread identifier. * @param memaux The auxiliar memory for this task. * @param blockSize The size of its memory to save temporal results. * @see TriangleInversion() */ void InversionLNProducts(double *matrix,int r, int c, int ro, int co, int n,int nCores,int posIni,int deep,int numTh, double *memaux, int blockSize){ int size1=ceil(0.5*n); int size2=n-size1; if(deep==1){ double *C1=&memaux[posIni*blockSize]; LNProduct(matrix,r,ro+size1,c,co+size1,C1,size2,0,size1,0,size2,size1,1.0,matrix,r,ro+size1,c,co, nCores,posIni,numTh); }else{ if(numTh<posIni+nCores/2) InversionLNProducts(matrix,r,c,ro,co,size1,nCores/2,posIni,deep-1,numTh,memaux,blockSize); else InversionLNProducts(matrix,r,c,ro+size1,co+size1,size2,nCores/2,posIni+nCores/2,deep-1,numTh,memaux,blockSize); } } /** * @brief An auxiliar function of used to perform parallel matrix products. * * This is an auxiliar function that takes subm1 (a sub matrix of matrix m1), subm2 (a submatrix of matrix m2) and performs the following operation on subresult (a sub matrix * of matrix result): subresult = K1*subm1*subm2+K2*subresult * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param m2 The second matrix. * @param r2 The number of rows of matrix. * @param c2 The number of columns of matrix. * @param ro2 The row where the submatrix starts. * @param co2 The column where the submatrix starts. * @param n1 The number of rows of the subm1. * @param n2 The number of columns of the subm1. * @param n3 The number of columns of the subm2. * @param K1 The first constant of the formula. * @param K2 The second constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. * @param orientation Auxiliar variable to know the next task to perform. */ void NNProduct(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2,int n1,int n2,int n3,double K1,double K2,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh,int orientation){ if(nCores <= 1){ if(n1 >0 & n3>0){ double *mresultT=auxmemory2[numTh]; getSubMatrix(result,rr,cr,ror,cor,mresultT, n1,n3,nCores); if(n2 > 0){ double *m1T=auxmemory1[numTh]; double *m2T=auxmemory3[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n2,nCores); getSubMatrix(m2,r2,c2,ro2,co2,m2T, n2,n3,nCores); char transN = 'N'; char transY = 'N'; dgemm_(&transN, &transY, &(n1), &(n3), &(n2),&(K1), m1T, &(n1), m2T, &(n2), &(K2), mresultT, &(n1)); //cblas_dgemm (CblasColMajor, CblasNoTrans, CblasNoTrans, n1,n3,n2,K1, m1T, n1, m2T, n2, K2, mresultT, n1); }else{ int i; for(i=0;i<n2*n3;i++) mresultT[i]=K2*mresultT[i]; } putSubMatrix(result,rr,cr,ror,cor,mresultT, n1,n3,nCores); //free(mresultT); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n2); int cols1B=n2-cols1A; int rows2A=ceil(0.5*n2); int rows2B=n2-rows2A; int cols2A=ceil(0.5*n3); int cols2B=n3-cols2A; if(numTh<posIni+nCores/2){ NNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,cols1A,cols2A,K1,K2,result,rr,ror,cr,cor, nCores/2,posIni,numTh,orientation); NNProduct(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2,rows1A,cols1B,cols2A,K1,1.0,result,rr,ror,cr,cor, nCores/2,posIni,numTh,orientation); if(orientation==1){ NNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2,c2,co2,rows1B,cols1A,cols2A,K1,K2,result,rr,ror+rows1A,cr,cor,nCores/2,posIni,numTh,orientation); NNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2,rows1B,cols1B,cols2A,K1,1.0,result,rr,ror+rows1A,cr,cor, nCores/2,posIni,numTh,orientation); }else{ NNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2+cols2A,rows1A,cols1A,cols2B,K1,K2,result,rr,ror,cr,cor+cols2A, nCores/2,posIni,numTh,orientation); NNProduct(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1A,cols1B,cols2B,K1,1.0,result,rr,ror,cr,cor+cols2A, nCores/2,posIni,numTh,orientation); } }else{ if(orientation==2){ NNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2,c2,co2,rows1B,cols1A,cols2A,K1,K2,result,rr,ror+rows1A,cr,cor,nCores/2,posIni+nCores/2,numTh,orientation); NNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2,rows1B,cols1B,cols2A,K1,1.0,result,rr,ror+rows1A,cr,cor, nCores/2,posIni+nCores/2,numTh,orientation); }else{ NNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2+cols2A,rows1A,cols1A,cols2B,K1,K2,result,rr,ror,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh,orientation); NNProduct(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1A,cols1B,cols2B,K1,1.0,result,rr,ror,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh,orientation); } NNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2,c2,co2+cols2A,rows1B,cols1A,cols2B,K1,K2,result,rr,ror+rows1A,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh,orientation); NNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,cols1B,cols2B,K1,1.0,result,rr,ror+rows1A,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh,orientation); } } } /** * @brief It moves a submatrix from matrix m1 to matrix m2. * * This function takes a submatrix form matrix m2 and allocated it in another submatrix of matrix m2. * @param m1 The matrix origin. * @param r1 The number of rows of the origin matrix. * @param c1 The number of columns of the origin matrix. * @param ro1 The row of the origin matrix where the submatrix starts. * @param co1 The column of the origin where the submatrix starts. * @param m2 The destination matrix. * @param r2 The number of rows of the destination matrix. * @param c2 The number of columns of the destination matrix. * @param ro2 The row of the destination matrix where the submatrix starts. * @param co2 The column of the destination matrix where the submatrix starts. * @param n1 The number of rows of the submatrix. * @param n2 The number of columns of the submatrix. * @param numTh The thread identifier. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. */ void MoveMatrix(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2, int n1, int n2, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n1 >0 & n2>0){ double *mmv=auxmemory2[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,mmv, n1,n2,nCores); putSubMatrix(m2,r2,c2,ro2,co2,mmv, n1,n2,nCores); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n2); int cols1B=n2-cols1A; if(numTh<posIni+nCores/2){ MoveMatrix(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,cols1A,nCores/2,posIni,numTh); MoveMatrix(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2+rows1A,c2,co2,rows1B,cols1A,nCores/2,posIni,numTh); }else{ MoveMatrix(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2,c2,co2+cols1A,rows1A,cols1B,nCores/2,posIni+nCores/2,numTh); MoveMatrix(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows1A,c2,co2+cols1A,rows1B,cols1B,nCores/2,posIni+nCores/2,numTh); } } } /** * @brief An auxiliar function of used to perform parallel matrix products. * * This is an auxiliar function that takes subm1 (a sub matrix of matrix of the transpose matrix of m1), subm2 (a submatrix of matrix m2 * and performs the following operation on subresult (a sub matrix of matrix result): subresult = K1*subm1*subm2+K2*subresult * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param m2 The second matrix. * @param r2 The number of rows of matrix. * @param c2 The number of columns of matrix. * @param ro2 The row where the submatrix starts. * @param co2 The column where the submatrix starts. * @param n1 The number of rows of the subm1. * @param n2 The number of columns of the subm1. * @param n3 The number of columns of the subm2. * @param K1 The first constant of the formula. * @param K2 The second constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. */ void TNNProduct(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2,int n1,int n2,int n3,double K1,double K2,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n2 >0 & n3>0){ double *mresultT=auxmemory2[numTh]; getSubMatrix(result,rr,cr,ror,cor,mresultT, n2,n3,nCores); if(n1 >0){ double *m1T=auxmemory1[numTh]; double *m2T=auxmemory3[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n2,nCores); getSubMatrix(m2,r2,c2,ro2,co2,m2T, n1,n3,nCores); char transN = 'N'; char transY = 'N'; dgemm_(&transN, &transY, &(n2), &(n3), &(n1),&(K1), m1T, &(n1), m2T, &(n1), &(K2), mresultT, &(n2)); //cblas_dgemm (CblasColMajor, CblasTrans, CblasNoTrans, n2,n3,n1,K1, m1T, n1, m2T, n1, K2, mresultT, n2); }else{ int i; for(i=0;i<n2*n3;i++) mresultT[i]=K2*mresultT[i]; } putSubMatrix(result,rr,cr,ror,cor,mresultT, n2,n3,nCores); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n2); int cols1B=n2-cols1A; int rows2A=ceil(0.5*n1); int rows2B=n1-rows1A; int cols2A=ceil(0.5*n3); int cols2B=n3-cols2A; if(numTh<posIni+nCores/2){ TNNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,cols1A,cols2A,K1,K2,result,rr,ror,cr,cor, nCores/2,posIni,numTh); TNNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2+rows2A,c2,co2,rows1B,cols1A,cols2A,K1,1.0,result,rr,ror,cr,cor, nCores/2,posIni,numTh); TNNProduct(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2,c2,co2,rows1A,cols1B,cols2A,K1,K2,result,rr,ror+cols1A,cr,cor,nCores/2,posIni,numTh); TNNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2,rows1B,cols1B,cols2A,K1,1.0,result,rr,ror+cols1A,cr,cor, nCores/2,posIni,numTh); }else{ TNNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2+cols2A,rows1A,cols1A,cols2B,K1,K2,result,rr,ror,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); TNNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,cols1A,cols2B,K1,1.0,result,rr,ror,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); TNNProduct(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2,c2,co2+cols2A,rows1A,cols1B,cols2B,K1,K2,result,rr,ror+cols1A,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); TNNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,cols1B,cols2B,K1,1.0,result,rr,ror+cols1A,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); } } } /** * @brief An auxiliar function of used to perform parallel matrix products. * * This is an auxiliar function that takes subm1 (a sub matrix of matrix of m1), subm2 (a submatrix of the transpose matrix of m2 * and performs the following operation on subresult (a sub matrix of matrix result): subresult = K1*subm1*subm2+K2*subresult * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param m2 The second matrix. * @param r2 The number of rows of matrix. * @param c2 The number of columns of matrix. * @param ro2 The row where the submatrix starts. * @param co2 The column where the submatrix starts. * @param n1 The number of rows of the subm1. * @param n2 The number of columns of the subm1. * @param n3 The number of columns of the subm2. * @param K1 The first constant of the formula. * @param K2 The second constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. */ void NNTProduct(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2,int n1,int n2,int n3,double K1,double K2,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n1 >0 & n3>0){ double *mresultT=auxmemory2[numTh]; getSubMatrix(result,rr,cr,ror,cor,mresultT, n1,n3,nCores); if(n2 > 0){ double *m1T=auxmemory1[numTh]; double *m2T=auxmemory3[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n2,nCores); getSubMatrix(m2,r2,c2,ro2,co2,m2T, n3,n2,nCores); char transN = 'N'; char transY = 'T'; dgemm_(&transN, &transY, &(n1), &(n3), &(n2),&(K1), m1T, &(n1), m2T, &(n3), &(K2), mresultT, &(n1)); //cblas_dgemm (CblasColMajor, CblasNoTrans, CblasTrans, n1,n3,n2,K1, m1T, n1, m2T, n3, K2, mresultT, n1); }else{ int i; for(i=0;i<n1*n3;i++) mresultT[i]=K2*mresultT[i]; } putSubMatrix(result,rr,cr,ror,cor,mresultT, n1,n3,nCores); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n2); int cols1B=n2-cols1A; int rows2A=ceil(0.5*n3); int rows2B=n3-rows2A; int cols2A=ceil(0.5*n2); int cols2B=n2-cols2A; if(numTh<posIni+nCores/2){ NNTProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,cols1A,rows2A,K1,K2,result,rr,ror,cr,cor, nCores/2,posIni,numTh); NNTProduct(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2,c2,co2+cols2A,rows1A,cols1B,rows2A,K1,1.0,result,rr,ror,cr,cor, nCores/2,posIni,numTh); NNTProduct(m1,r1,ro1,c1,co1,m2,r2,ro2+rows2A,c2,co2,rows1A,cols1A,rows2B,K1,K2,result,rr,ror,cr,cor+rows2A, nCores/2,posIni,numTh); NNTProduct(m1,r1,ro1,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1A,cols1B,rows2B,K1,1.0,result,rr,ror,cr,cor+rows2A, nCores/2,posIni,numTh); }else{ NNTProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2+rows2A,c2,co2,rows1B,cols1A,rows2B,K1,K2,result,rr,ror+rows1A,cr,cor+rows2A, nCores/2,posIni+nCores/2,numTh); NNTProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,cols1B,rows2B,K1,1.0,result,rr,ror+rows1A,cr,cor+rows2A, nCores/2,posIni+nCores/2,numTh); NNTProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2,c2,co2,rows1B,cols1A,rows2A,K1,K2,result,rr,ror+rows1A,cr,cor,nCores/2,posIni+nCores/2,numTh); NNTProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2,c2,co2+cols2A,rows1B,cols1B,rows2A,K1,1.0,result,rr,ror+rows1A,cr,cor, nCores/2,posIni+nCores/2,numTh); } } } /** * @brief An auxiliar function of used to perform parallel matrix products. * * This is an auxiliar function that takes subm1 (a sub matrix of matrix of m1) and performs the following operation * on subresult (a sub matrix of matrix result): subresult = K1*subm1*subm1^T+K2*subresult * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param n1 The number of rows of the subm1. * @param n2 The number of columns of the subm1. * @param K1 The first constant of the formula. * @param K2 The second constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. */ void AATProduct(double *m1,int r1,int ro1,int c1, int co1,int n1,int n2,double K1,double K2,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n1 >0 & n2>0){ double *m1T = (double *) malloc(n1*n2*sizeof(double)); double *mresultT = (double *) malloc(n1*n1*sizeof(double)); getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n2,nCores); getSubMatrix(result,rr,cr,ror,cor,mresultT, n1,n1,nCores); char transN = 'L'; char transY = 'N'; dsyrk_(&transN, &transY, &(n1), &(n2), &(K1), m1T, &(n1), &(K2), mresultT, &(n1)); //cblas_dsyrk (CblasColMajor, CblasLower, CblasNoTrans, n1,n2,K1, m1T, n1, K2, mresultT, n1); int i,j; for(i=0;i<n1;i++){ for(j=i;j<n1;j++){ mresultT[j*n1+i]=mresultT[i*n1+j]; } } putSubMatrix(result,rr,cr,ror,cor,mresultT, n1,n1,nCores); free(m1T); free(mresultT); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n2); int cols1B=n2-cols1A; if(numTh<posIni+nCores/2){ AATProduct(m1,r1,ro1,c1,co1,rows1A,cols1A,K1,K2,result,rr,ror,cr,cor, nCores/2,posIni,numTh); AATProduct(m1,r1,ro1,c1,co1+cols1A,rows1A,cols1B,K1,1.0,result,rr,ror,cr,cor, nCores/2,posIni,numTh); }else{ AATProduct(m1,r1,ro1+rows1A,c1,co1,rows1B,cols1A,K1,K2,result,rr,ror+rows1A,cr,cor+rows1A, nCores/2,posIni+nCores/2,numTh); AATProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,rows1B,cols1B,K1,1.0,result,rr,ror+rows1A,cr,cor+rows1A, nCores/2,posIni+nCores/2,numTh); } NNTProduct(m1,r1,ro1+rows1A,c1,co1,m1,r1,ro1,c1,co1,rows1B,cols1A,rows1A,K1,K2,result,rr,ror+rows1A,cr,cor,nCores,posIni,numTh); NNTProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m1,r1,ro1,c1,co1+cols1A,rows1B,cols1B,rows1A,K1,1.0,result,rr,ror+rows1A,cr,cor, nCores,posIni,numTh); } } /** * @brief This function performs a product of a lower triangular submatrix of matrix m1 * and a submatrix of m2 in parallel. * * Begin subm1 a lower triangular submatrix of matrix m1 and subm2 a submatrix of m2, * this funtion execute K1(subm1*subm2) and saves the result in a different matrix. * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param m2 The second matrix. * @param r2 The number of rows of matrix. * @param c2 The number of columns of matrix. * @param ro2 The row where the submatrix starts. * @param co2 The column where the submatrix starts. * @param n1 The number of rows of the submatrix1. * @param n2 The number of columns of the submatrix2. * @param K1 The constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. */ void LNProduct(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2,int n1,int n2,double K1,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n1 >0 & n2>0){ double *m1T=auxmemory2[numTh]; double *mresultT=auxmemory1[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n1,nCores); getSubMatrix(m2,r2,c2,ro2,co2,mresultT, n1,n2,nCores); char side = 'L'; char uplo = 'L'; char transa = 'N'; char diag = 'N'; dtrmm_(&side, &uplo, &transa, &diag, &(n1), &(n2), &(K1), m1T, &(n1), mresultT, &(n1)); //cblas_dtrmm (CblasColMajor, CblasLeft,CblasLower,CblasNoTrans,CblasNonUnit,n1,n2,K1, m1T, n1, mresultT, n1); putSubMatrix(result,rr,cr,ror,cor,mresultT, n1,n2,nCores); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n1); int cols1B=n1-cols1A; int rows2A=ceil(0.5*n1); int rows2B=n1-cols1A; int cols2A=ceil(0.5*n2); int cols2B=n2-cols2A; if(numTh<posIni+nCores/2){ LNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,cols2A,K1,result,rr,ror,cr,cor, nCores/2,posIni,numTh); LNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2,rows1B,cols2A,K1,result,rr,ror+rows1A,cr,cor, nCores/2,posIni,numTh); NNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2,c2,co2,rows1B,cols1A,cols2A,K1,1.0,result,rr,ror+rows1A,cr,cor,nCores/2,posIni,numTh,1); }else{ LNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2+cols2A,rows1A,cols2B,K1,result,rr,ror,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); LNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,cols2B,K1,result,rr,ror+rows1A,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); NNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2,c2,co2+cols2A,rows1B,cols1A,cols2B,K1,1,result,rr,ror+rows1A,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh,1); } } } /** * @brief This function performs a product of a lower triangular submatrix of the transpose of matrix m1 * and a submatrix of m2 in parallel. * * Begin subm1 a lower triangular submatrix of the transpose of matrix m1 and subm2 a submatrix of m2, * this funtion execute K1(subm1*subm2) and saves the result in a different matrix. * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param m2 The second matrix. * @param r2 The number of rows of matrix. * @param c2 The number of columns of matrix. * @param ro2 The row where the submatrix starts. * @param co2 The column where the submatrix starts. * @param n1 The number of rows of the submatrix1. * @param n2 The number of columns of the submatrix2. * @param K1 The constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. */ void LTNProduct(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2,int n1,int n2,double K1,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n1 >0 & n2>0){ int in; double *m1T=auxmemory1[numTh]; double *m2T=auxmemory2[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n1,1); getSubMatrix(result,rr,cr,ror,cor,m2T, n1,n2,1); char side = 'L'; char uplo = 'L'; char transa = 'T'; char diag = 'N'; dtrmm_(&side, &uplo, &transa, &diag, &(n1), &(n2), &(K1), m1T, &(n1), m2T, &(n1)); //cblas_dtrmm (CblasColMajor, CblasLeft,CblasLower,CblasTrans,CblasNonUnit,n1,n2,K1, m1T, n1, m2T, n1); putSubMatrix(result,rr,cr,ror,cor,m2T, n1,n2,1); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n1); int cols1B=n1-cols1A; int rows2A=ceil(0.5*n1); int rows2B=n1-cols1A; int cols2A=ceil(0.5*n2); int cols2B=n2-cols2A; if(numTh<posIni+nCores/2){ LTNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2,rows1B,cols2A,K1,result,rr,ror+cols1A,cr,cor, nCores/2,posIni,numTh); LTNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,cols2A,K1,result,rr,ror,cr,cor, nCores/2,posIni,numTh); TNNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2+rows2A,c2,co2,rows1B,cols1A,cols2A,K1,1.0,result,rr,ror,cr,cor,nCores/2,posIni,numTh); }else{ LTNProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,cols2B,K1,result,rr,ror+cols1A,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); LTNProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2+cols2A,rows1A,cols2B,K1,result,rr,ror,cr,cor+cols2A, nCores/2,posIni+nCores/2,numTh); TNNProduct(m1,r1,ro1+rows1A,c1,co1,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,cols1A,cols2B,K1,1.0,result,rr,ror,cr,cor+cols2A,nCores/2,posIni+nCores/2,numTh); } } } /** * @brief This function performs a product of a submatrix of matrix m1 and a triangular submatrix * of m2 in parallel. * * Begin subm1 a submatrix of m1 and subm2 a triangular submatrix of m2, * this funtion execute K1(subm1*subm2) and saves the result in a different matrix. * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param m2 The second matrix. * @param r2 The number of rows of matrix. * @param c2 The number of columns of matrix. * @param ro2 The row where the submatrix starts. * @param co2 The column where the submatrix starts. * @param n1 The number of rows of the submatrix1. * @param n2 The number of columns of the submatrix1 (and rows and columns of submatrix2). * @param K1 The constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. */ void NLProduct(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2,int n1,int n2,double K1,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n1 >0 & n2>0){ double *m1T=auxmemory1[numTh]; double *mresultT=auxmemory2[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n1,nCores); getSubMatrix(m2,r2,c2,ro2,co2,mresultT, n2,n1,nCores); char side = 'R'; char uplo = 'L'; char transa = 'N'; char diag = 'N'; dtrmm_(&side, &uplo, &transa, &diag, &(n2), &(n1), &(K1), m1T, &(n1), mresultT, &(n2)); //cblas_dtrmm (CblasColMajor, CblasRight,CblasLower,CblasNoTrans,CblasNonUnit,n2,n1,K1, m1T, n1, mresultT, n2); putSubMatrix(result,rr,cr,ror,cor,mresultT, n2,n1,nCores); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n1); int cols1B=n1-cols1A; int rows2A=ceil(0.5*n2); int rows2B=n2-rows2A; int cols2A=ceil(0.5*n1); int cols2B=n1-cols2A; if(numTh<posIni+nCores/2){ NLProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,rows2A,K1,result,rr,ror,cr,cor, nCores/2,posIni,numTh); NNProduct(m2,r2,ro2,c2,co2+cols2A,m1,r1,ro1+rows1A,c1,co1,rows2A,cols2B,cols1A,K1,1,result,rr,ror,cr,cor, nCores/2,posIni,numTh,2); NLProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2,c2,co2+cols2A,rows1B,rows2A,K1,result,rr,ror,cr,cor+cols1A, nCores/2,posIni,numTh); }else{ NLProduct(m1,r1,ro1,c1,co1,m2,r2,ro2+rows2A,c2,co2,rows1A,rows2B,K1,result,rr,ror+rows2A,cr,cor,nCores/2,posIni+nCores/2,numTh); NNProduct(m2,r2,ro2+rows2A,c2,co2+cols2A,m1,r1,ro1+rows1A,c1,co1,rows2B,cols2B,cols1A,K1,1,result,rr,ror+rows2A,cr,cor, nCores/2,posIni+nCores/2,numTh,2); NLProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,rows2B,K1,result,rr,ror+rows2A,cr,cor+cols1A, nCores/2,posIni+nCores/2,numTh); } } } /** * @brief This function performs a product of a submatrix of matrix m1 and a triangular submatrix * of the transpose of m2 in parallel. * * Begin subm1 a submatrix of m1 and subm2 a triangular submatrix of the transpose of m2, * this funtion execute K1(subm1*subm2) and saves the result in a different matrix. * * @param m1 The first matrix. * @param r1 The number of rows of the first matrix. * @param c1 The number of columns of the first matrix. * @param ro1 The row where the submatrix of m1 starts. * @param co1 The column where the submatrix of m1 starts. * @param m2 The second matrix. * @param r2 The number of rows of matrix. * @param c2 The number of columns of matrix. * @param ro2 The row where the submatrix starts. * @param co2 The column where the submatrix starts. * @param n1 The number of rows of the submatrix1. * @param n2 The number of columns of the submatrix1 (and rows and columns of submatrix2). * @param K1 The constant of the formula. * @param result The matrix to storage the result. * @param rr The number of rows of result. * @param cr The number of columns of result. * @param ror The row where the submatrix of result starts. * @param cor The column where the submatrix of result starts. * @param nCores The total number of threads. * @param posIni Variable to know what task to do by this thread. * @param numTh The thread identifier. */ void NLTProduct(double *m1,int r1,int ro1,int c1, int co1,double *m2,int r2,int ro2,int c2, int co2,int n1,int n2,double K1,double *result,int rr,int ror,int cr, int cor, int nCores,int posIni,int numTh){ if(nCores <= 1){ if(n1 >0 & n2>0){ double *m1T=auxmemory1[numTh]; double *m2T=auxmemory2[numTh]; getSubMatrix(m1,r1,c1,ro1,co1,m1T, n1,n1,nCores); getSubMatrix(m2,r2,c2,ro2,co2,m2T, n2,n1,nCores); char side = 'R'; char uplo = 'L'; char transa = 'T'; char diag = 'N'; dtrmm_(&side, &uplo, &transa, &diag, &(n2), &(n1), &(K1), m1T, &(n1), m2T, &(n2)); //cblas_dtrmm (CblasColMajor, CblasRight,CblasLower,CblasTrans,CblasNonUnit,n2,n1,K1, m1T, n1, m2T, n2); putSubMatrix(result,rr,cr,ror,cor,m2T, n2,n1,nCores); } }else{ int rows1A=ceil(0.5*n1); int rows1B=n1-rows1A; int cols1A=ceil(0.5*n1); int cols1B=n1-cols1A; int rows2A=ceil(0.5*n2); int rows2B=n2-rows2A; int cols2A=ceil(0.5*n1); int cols2B=n1-cols2A; if(numTh<posIni+nCores/2){ NLTProduct(m1,r1,ro1,c1,co1,m2,r2,ro2,c2,co2,rows1A,rows2A,K1,result,rr,ror,cr,cor,nCores/2,posIni,numTh); NLTProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2,c2,co2+cols2A,rows1B,rows2A,K1,result,rr,ror,cr,cor+rows1A,nCores/2,posIni,numTh); NNTProduct(m2,r2,ro2,c2,co2,m1,r1,ro1+rows1A,c1,co1,rows2A,cols2A,rows1B,K1,1.0,result,rr,ror,cr,cor+rows1A,nCores/2,posIni,numTh); }else{ NLTProduct(m1,r1,ro1,c1,co1,m2,r2,ro2+rows2A,c2,co2,rows1A,rows2B,K1,result,rr,ror+rows2A,cr,cor, nCores/2,posIni+nCores/2,numTh); NLTProduct(m1,r1,ro1+rows1A,c1,co1+cols1A,m2,r2,ro2+rows2A,c2,co2+cols2A,rows1B,rows2B,K1,result,rr,ror+rows2A,cr,cor+rows1A, nCores/2,posIni+nCores/2,numTh); NNTProduct(m2,r2,ro2+rows2A,c2,co2,m1,r1,ro1+rows1A,c1,co1,rows2B,cols2A,rows1B,K1,1.0,result,rr,ror+rows2A,cr,cor+rows1A, nCores/2,posIni+nCores/2,numTh); } } } /** * @brief This function performs a product of a vector and the transpose of a square matrix in parallel. * * This function performs a product of a vector and the transpose of a matrix in parallel. * * @param m1 The vector. * @param size The length of the vector and the order of the square matrix. * @param m2 The square matrix. * @param result The matrix to storage the result. * @param numThreads Number of threads to pefrom this task. */ void ParallelVectorMatrixT(double *m1,int size,double *m2,double *result, int numThreads){ int i; char transN = 'N'; char transY = 'T'; int aux=1; double aux2=0; double factor=1.0; #pragma omp parallel default(shared) private(i) { #pragma omp for schedule(static) for (i=0;i<numThreads;i++){ int InitCol=round(i*size/numThreads); int FinalCol=round((i+1)*size/numThreads)-1; int lenghtCol=FinalCol-InitCol+1; if(lenghtCol>0){ dgemm_(&transN, &transN, &(lenghtCol), &(aux), &(size),&factor, &m2[InitCol], &(size), m1, &size, &aux2, &result[InitCol], &(size)); } } } } /** * @brief This function performs a product of a vector and a square matrix in parallel. * * This function performs a product of a vector and a matrix in parallel. * * This function performs a vector matrix product in parallel. * @param m1 The vector. * @param size The length of the vector and the order of the square matrix. * @param m2 The square matrix. * @param result The matrix to storage the result. * @param numThreads Number of threads to pefrom this task. */ void ParallelVectorMatrix(double *m1,int size,double *m2,double *result, int numThreads){ int i; char transN = 'N'; char transY = 'N'; int aux=1; double aux2=0; double factor=1.0; #pragma omp parallel default(shared) private(i) { #pragma omp for schedule(static) for (i=0;i<numThreads;i++){ int InitCol=round(i*size/numThreads); int FinalCol=round((i+1)*size/numThreads)-1; int lenghtCol=FinalCol-InitCol+1; if(lenghtCol>0){ dgemm_(&transN, &transY, &aux, &(lenghtCol), &(size),&factor, m1, &aux, &m2[size*InitCol], &size, &aux2, &result[InitCol], &aux); } } } } /** * @endcond */
entrega-malloc.c
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <omp.h> #include "ctimer.h" void add (int A[], int B[], int C[], int N) { int i, carry, sum; carry = 0; for (i=0; i<N; i++) { sum = A[i] + B[i] + carry; if (sum >= 10) { carry = 1; sum -= 10; } else carry = 0; C[i] = sum; } } void multiply_one_digit (int A[], int B[], int n, int N) { int i, carry; carry = 0; for (i=0; i<N; i++) { B[i] = n * A[i]; B[i] += carry; if (B[i] >= 10) { carry = B[i] / 10; B[i] %= 10; } else carry = 0; } } void shift_left (int A[], int n, int N) { int i; for (i=N-1; i>=n; i--) A[i] = A[i-n]; while (i >= 0) A[i--] = 0; } void multiply (int A[], int B[], int C[], int N) { int i, j, P[N]; for (i=0; i<N; i++) { multiply_one_digit (B, P, A[i], N); shift_left (P, i, N); add (C, P, C, N); } } main(int argc, char**argv) { // DECLARACION DE VARIABLES double t1,t2,tucpu,tscpu; int len1 = strlen(argv[1]); int len2 = strlen(argv[2]); int N = len1+len2; int A[N], B[N], C[N]; for(int i=0;i < N; i++){ A[i] = 0; B[i] = 0; C[i] = 0; } // RELLENADO DE MATRICES char k[len1]; strcpy(k, argv[1]); for(int i=0;i < len1; i++){ A[i] = k[len1-1-i] - '0'; } char l[len2]; strcpy(l, argv[2]); for(int i=0;i < len2; i++){ B[i] = l[len2-1-i] - '0'; } // SECUENCIAL ctimer(&t1,&tucpu,&tscpu); multiply(A,B,C,N); ctimer(&t2,&tucpu,&tscpu); printf("---SECUENCIAL---\n"); printf("A [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", A[loop]); printf("]\n"); printf("B [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", B[loop]); printf("]\nC [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", C[loop]); printf("]\n"); printf(" ------- \n"); printf("Tiempo %f segundos \n",(float) (t2-t1)); printf(" ------- \n"); // PARALELO printf("---PARALELO---\n"); omp_set_num_threads(4); int D[4*N]; int n, i, carry,j,sum, P[N], tid, nthreads; int E[N]; for(int i=0;i < N; i++) E[i] = 0; ctimer(&t1,&tucpu,&tscpu); #pragma omp parallel shared (B,A) private(i,n, carry, j, sum, P, tid) { nthreads = omp_get_num_threads(); for(i=0;i < N*nthreads; i++){ D[i] = 0; } #pragma omp barrier tid = omp_get_thread_num(); for (i=tid; i<len1; i=i+nthreads) { n = A[i]; carry = 0; for (j=0; j<N; j++) { P[j] = n * B[j]; P[j] += carry; if (P[j] >= 10) { carry = P[j] / 10; P[j] %= 10; } else carry = 0; } // SHIFT for (j=N-1; j>=i; j--) P[j] = P[j-i]; while (j >= 0) P[j--] = 0; // SUMA Y ACUMULACION EN D carry = 0; sum = 0; for (j=0; j<N; j++) { sum = D[tid*N+j] + P[j] + carry; if (sum >= 10) { carry = 1; sum -= 10; } else carry = 0; D[tid*N+j] = sum; } } #pragma omp barrier // TRANSFERENCIA A E SUMANDO PARCIALES if(tid==0){ for(int k=0; k<nthreads;k++){ carry = 0; sum = 0; for (j=0; j<N; j++) { sum = E[j] + D[k*N+j] + carry; if (sum >= 10) { carry = 1; sum -= 10; } else carry = 0; E[j] = sum; } } } } ctimer(&t2,&tucpu,&tscpu); printf("A [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", A[loop]); printf("]\n"); printf("B [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", B[loop]); printf("]\n"); printf("C [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", E[loop]); printf("]\n"); printf(" ------- \n"); printf("Tiempo %f segundos \n",(float) (t2-t1)); printf(" ------- \n"); }
task-dependency.c
/* Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Simone Atzeni (simone@cs.utah.edu), Joachim Protze (joachim.protze@tu-dresden.de), Jonas Hahnfeld (hahnfeld@itc.rwth-aachen.de), Ganesh Gopalakrishnan, Zvonimir Rakamaric, Dong H. Ahn, Gregory L. Lee, Ignacio Laguna, and Martin Schulz. LLNL-CODE-773957 All rights reserved. This file is part of Archer. For details, see https://pruners.github.io/archer. Please also read https://github.com/PRUNERS/archer/blob/master/LICENSE. 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. */ // RUN: %libarcher-compile-and-run | FileCheck %s #include <omp.h> #include <stdio.h> #include <unistd.h> int main(int argc, char* argv[]) { int var = 0; #pragma omp parallel num_threads(2) shared(var) #pragma omp master { #pragma omp task shared(var) depend(out: var) { var++; } #pragma omp task depend(in: var) { // FIXME: This is ugly to make the worker task sleep and let the master // thread execute the second task incrementing var... sleep(2); } #pragma omp task shared(var) depend(in: var) { var++; } // Give other thread time to steal the task. sleep(1); } fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK: DONE
GB_unop__identity_int8_uint16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int8_uint16) // op(A') function: GB (_unop_tran__identity_int8_uint16) // C type: int8_t // A type: uint16_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ int8_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_CAST(z, aij) \ int8_t z = (int8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = (int8_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int8_uint16) ( int8_t *Cx, // Cx and Ax may be aliased const uint16_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++) { uint16_t aij = Ax [p] ; int8_t z = (int8_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint16_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_uint16) ( 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
DRB002-antidep1-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. */ /* A loop with loop-carried anti-dependence. Data race pair: a[i+1]@67:10 vs. a[i]@67:5 */ #include <stdlib.h> int main(int argc, char* argv[]) { int i; int len = 1000; if (argc>1) len = atoi(argv[1]); int a[len]; for (i=0; i<len; i++) a[i]= i; #pragma omp parallel for schedule(dynamic) for (i=0;i< len -1 ;i++) a[i]=a[i+1]+1; return 0; }
munit.c
/* Copyright (c) 2013-2018 Evan Nemerson <evan@nemerson.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. */ /*** Configuration ***/ /* This is just where the output from the test goes. It's really just * meant to let you choose stdout or stderr, but if anyone really want * to direct it to a file let me know, it would be fairly easy to * support. */ #if !defined(MUNIT_OUTPUT_FILE) # define MUNIT_OUTPUT_FILE stdout #endif /* This is a bit more useful; it tells µnit how to format the seconds in * timed tests. If your tests run for longer you might want to reduce * it, and if your computer is really fast and your tests are tiny you * can increase it. */ #if !defined(MUNIT_TEST_TIME_FORMAT) # define MUNIT_TEST_TIME_FORMAT "0.8f" #endif /* If you have long test names you might want to consider bumping * this. The result information takes 43 characters. */ #if !defined(MUNIT_TEST_NAME_LEN) # define MUNIT_TEST_NAME_LEN 37 #endif /* If you don't like the timing information, you can disable it by * defining MUNIT_DISABLE_TIMING. */ #if !defined(MUNIT_DISABLE_TIMING) # define MUNIT_ENABLE_TIMING #endif /*** End configuration ***/ #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE < 200809L) # undef _POSIX_C_SOURCE #endif #if !defined(_POSIX_C_SOURCE) # define _POSIX_C_SOURCE 200809L #endif /* Solaris freaks out if you try to use a POSIX or SUS standard without * the "right" C standard. */ #if defined(_XOPEN_SOURCE) # undef _XOPEN_SOURCE #endif #if defined(__STDC_VERSION__) # if __STDC_VERSION__ >= 201112L # define _XOPEN_SOURCE 700 # elif __STDC_VERSION__ >= 199901L # define _XOPEN_SOURCE 600 # endif #endif /* Because, according to Microsoft, POSIX is deprecated. You've got * to appreciate the chutzpah. */ #if defined(_MSC_VER) && !defined(_CRT_NONSTDC_NO_DEPRECATE) # define _CRT_NONSTDC_NO_DEPRECATE #endif #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # include <stdbool.h> #elif defined(_WIN32) /* https://msdn.microsoft.com/en-us/library/tf4dy80a.aspx */ #endif #include <limits.h> #include <time.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #if !defined(MUNIT_NO_NL_LANGINFO) && !defined(_WIN32) #define MUNIT_NL_LANGINFO #include <locale.h> #include <langinfo.h> #include <strings.h> #endif #if !defined(_WIN32) # include <unistd.h> # include <sys/types.h> # include <sys/wait.h> #else # include <windows.h> # include <io.h> # include <fcntl.h> # if !defined(STDERR_FILENO) # define STDERR_FILENO _fileno(stderr) # endif #endif #include "munit.h" #define MUNIT_STRINGIFY(x) #x #define MUNIT_XSTRINGIFY(x) MUNIT_STRINGIFY(x) #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) # define MUNIT_THREAD_LOCAL __thread #elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) || defined(_Thread_local) # define MUNIT_THREAD_LOCAL _Thread_local #elif defined(_WIN32) # define MUNIT_THREAD_LOCAL __declspec(thread) #endif /* MSVC 12.0 will emit a warning at /W4 for code like 'do { ... } * while (0)', or 'do { ... } while (1)'. I'm pretty sure nobody * at Microsoft compiles with /W4. */ #if defined(_MSC_VER) && (_MSC_VER <= 1800) #pragma warning(disable: 4127) #endif #if defined(_WIN32) || defined(__EMSCRIPTEN__) # define MUNIT_NO_FORK #endif #if defined(__EMSCRIPTEN__) # define MUNIT_NO_BUFFER #endif /*** Logging ***/ static MunitLogLevel munit_log_level_visible = MUNIT_LOG_INFO; static MunitLogLevel munit_log_level_fatal = MUNIT_LOG_ERROR; #if defined(MUNIT_THREAD_LOCAL) static MUNIT_THREAD_LOCAL munit_bool munit_error_jmp_buf_valid = 0; static MUNIT_THREAD_LOCAL jmp_buf munit_error_jmp_buf; #endif /* At certain warning levels, mingw will trigger warnings about * suggesting the format attribute, which we've explicity *not* set * because it will then choke on our attempts to use the MS-specific * I64 modifier for size_t (which we have to use since MSVC doesn't * support the C99 z modifier). */ #if defined(__MINGW32__) || defined(__MINGW64__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wsuggest-attribute=format" #endif MUNIT_PRINTF(5,0) static void munit_logf_exv(MunitLogLevel level, FILE* fp, const char* filename, int line, const char* format, va_list ap) { if (level < munit_log_level_visible) return; switch (level) { case MUNIT_LOG_DEBUG: fputs("Debug", fp); break; case MUNIT_LOG_INFO: fputs("Info", fp); break; case MUNIT_LOG_WARNING: fputs("Warning", fp); break; case MUNIT_LOG_ERROR: fputs("Error", fp); break; default: munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Invalid log level (%d)", level); return; } fputs(": ", fp); if (filename != NULL) fprintf(fp, "%s:%d: ", filename, line); vfprintf(fp, format, ap); fputc('\n', fp); } MUNIT_PRINTF(3,4) static void munit_logf_internal(MunitLogLevel level, FILE* fp, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, fp, NULL, 0, format, ap); va_end(ap); } static void munit_log_internal(MunitLogLevel level, FILE* fp, const char* message) { munit_logf_internal(level, fp, "%s", message); } void munit_logf_ex(MunitLogLevel level, const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, stderr, filename, line, format, ap); va_end(ap); if (level >= munit_log_level_fatal) { #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } } void munit_errorf_ex(const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(MUNIT_LOG_ERROR, stderr, filename, line, format, ap); va_end(ap); #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } #if defined(__MINGW32__) || defined(__MINGW64__) #pragma GCC diagnostic pop #endif #if !defined(MUNIT_STRERROR_LEN) # define MUNIT_STRERROR_LEN 80 #endif static void munit_log_errno(MunitLogLevel level, FILE* fp, const char* msg) { #if defined(MUNIT_NO_STRERROR_R) || (defined(__MINGW32__) && !defined(MINGW_HAS_SECURE_API)) munit_logf_internal(level, fp, "%s: %s (%d)", msg, strerror(errno), errno); #else char munit_error_str[MUNIT_STRERROR_LEN]; munit_error_str[0] = '\0'; #if !defined(_WIN32) strerror_r(errno, munit_error_str, MUNIT_STRERROR_LEN); #else strerror_s(munit_error_str, MUNIT_STRERROR_LEN, errno); #endif munit_logf_internal(level, fp, "%s: %s (%d)", msg, munit_error_str, errno); #endif } /*** Memory allocation ***/ void* munit_malloc_ex(const char* filename, int line, size_t size) { void* ptr; if (size == 0) return NULL; ptr = calloc(1, size); if (MUNIT_UNLIKELY(ptr == NULL)) { munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Failed to allocate %" MUNIT_SIZE_MODIFIER "u bytes.", size); } return ptr; } /*** Timer code ***/ #if defined(MUNIT_ENABLE_TIMING) #define psnip_uint64_t munit_uint64_t #define psnip_uint32_t munit_uint32_t /* Code copied from portable-snippets * <https://github.com/nemequ/portable-snippets/>. If you need to * change something, please do it there so we can keep the code in * sync. */ /* Clocks (v1) * Portable Snippets - https://gitub.com/nemequ/portable-snippets * Created by Evan Nemerson <evan@nemerson.com> * * To the extent possible under law, the authors have waived all * copyright and related or neighboring rights to this code. For * details, see the Creative Commons Zero 1.0 Universal license at * https://creativecommons.org/publicdomain/zero/1.0/ */ #if !defined(PSNIP_CLOCK_H) #define PSNIP_CLOCK_H #if !defined(psnip_uint64_t) # include "../exact-int/exact-int.h" #endif #if !defined(PSNIP_CLOCK_STATIC_INLINE) # if defined(__GNUC__) # define PSNIP_CLOCK__COMPILER_ATTRIBUTES __attribute__((__unused__)) # else # define PSNIP_CLOCK__COMPILER_ATTRIBUTES # endif # define PSNIP_CLOCK__FUNCTION PSNIP_CLOCK__COMPILER_ATTRIBUTES static #endif enum PsnipClockType { /* This clock provides the current time, in units since 1970-01-01 * 00:00:00 UTC not including leap seconds. In other words, UNIX * time. Keep in mind that this clock doesn't account for leap * seconds, and can go backwards (think NTP adjustments). */ PSNIP_CLOCK_TYPE_WALL = 1, /* The CPU time is a clock which increases only when the current * process is active (i.e., it doesn't increment while blocking on * I/O). */ PSNIP_CLOCK_TYPE_CPU = 2, /* Monotonic time is always running (unlike CPU time), but it only ever moves forward unless you reboot the system. Things like NTP adjustments have no effect on this clock. */ PSNIP_CLOCK_TYPE_MONOTONIC = 3 }; struct PsnipClockTimespec { psnip_uint64_t seconds; psnip_uint64_t nanoseconds; }; /* Methods we support: */ #define PSNIP_CLOCK_METHOD_CLOCK_GETTIME 1 #define PSNIP_CLOCK_METHOD_TIME 2 #define PSNIP_CLOCK_METHOD_GETTIMEOFDAY 3 #define PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER 4 #define PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME 5 #define PSNIP_CLOCK_METHOD_CLOCK 6 #define PSNIP_CLOCK_METHOD_GETPROCESSTIMES 7 #define PSNIP_CLOCK_METHOD_GETRUSAGE 8 #define PSNIP_CLOCK_METHOD_GETSYSTEMTIMEPRECISEASFILETIME 9 #define PSNIP_CLOCK_METHOD_GETTICKCOUNT64 10 #include <assert.h> #if defined(HEDLEY_UNREACHABLE) # define PSNIP_CLOCK_UNREACHABLE() HEDLEY_UNREACHABLE() #else # define PSNIP_CLOCK_UNREACHABLE() assert(0) #endif /* Choose an implementation */ /* #undef PSNIP_CLOCK_WALL_METHOD */ /* #undef PSNIP_CLOCK_CPU_METHOD */ /* #undef PSNIP_CLOCK_MONOTONIC_METHOD */ /* We want to be able to detect the libc implementation, so we include <limits.h> (<features.h> isn't available everywhere). */ #if defined(__unix__) || defined(__unix) || defined(__linux__) # include <limits.h> # include <unistd.h> #endif #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) /* These are known to work without librt. If you know of others * please let us know so we can add them. */ # if \ (defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17))) || \ (defined(__FreeBSD__)) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # elif !defined(PSNIP_CLOCK_NO_LIBRT) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # endif #endif #if defined(_WIN32) # if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_GETPROCESSTIMES # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER # endif #endif #if defined(__MACH__) && !defined(__gnu_hurd__) # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME # endif #endif #if defined(PSNIP_CLOCK_HAVE_CLOCK_GETTIME) # include <time.h> # if !defined(PSNIP_CLOCK_WALL_METHOD) # if defined(CLOCK_REALTIME_PRECISE) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME_PRECISE # elif !defined(__sun) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME # endif # endif # if !defined(PSNIP_CLOCK_CPU_METHOD) # if defined(_POSIX_CPUTIME) || defined(CLOCK_PROCESS_CPUTIME_ID) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_PROCESS_CPUTIME_ID # elif defined(CLOCK_VIRTUAL) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_VIRTUAL # endif # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # if defined(CLOCK_MONOTONIC_RAW) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # elif defined(CLOCK_MONOTONIC_PRECISE) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC_PRECISE # elif defined(_POSIX_MONOTONIC_CLOCK) || defined(CLOCK_MONOTONIC) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # endif # endif #endif #if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 200112L) # if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_GETTIMEOFDAY # endif #endif #if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_TIME #endif #if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK #endif /* Primarily here for testing. */ #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) && defined(PSNIP_CLOCK_REQUIRE_MONOTONIC) # error No monotonic clock found. #endif /* Implementations */ #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_TIME)) # include <time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) # include <sys/time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) # include <windows.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) # include <sys/time.h> # include <sys/resource.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) # include <CoreServices/CoreServices.h> # include <mach/mach.h> # include <mach/mach_time.h> #endif /*** Implementations ***/ #define PSNIP_CLOCK_NSEC_PER_SEC ((psnip_uint32_t) (1000000000ULL)) #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock__clock_getres (clockid_t clk_id) { struct timespec res; int r; r = clock_getres(clk_id, &res); if (r != 0) return 0; return (psnip_uint32_t) (PSNIP_CLOCK_NSEC_PER_SEC / res.tv_nsec); } PSNIP_CLOCK__FUNCTION int psnip_clock__clock_gettime (clockid_t clk_id, struct PsnipClockTimespec* res) { struct timespec ts; if (clock_gettime(clk_id, &ts) != 0) return -10; res->seconds = (psnip_uint64_t) (ts.tv_sec); res->nanoseconds = (psnip_uint64_t) (ts.tv_nsec); return 0; } #endif PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_wall_get_precision (void) { #if !defined(PSNIP_CLOCK_WALL_METHOD) return 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_WALL); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY return 1000000; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME return 1; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_wall_get_time (struct PsnipClockTimespec* res) { (void) res; #if !defined(PSNIP_CLOCK_WALL_METHOD) return -2; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_WALL, res); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME res->seconds = time(NULL); res->nanoseconds = 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY struct timeval tv; if (gettimeofday(&tv, NULL) != 0) return -6; res->seconds = tv.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_cpu_get_precision (void) { #if !defined(PSNIP_CLOCK_CPU_METHOD) return 0; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_CPU); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK return CLOCKS_PER_SEC; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES return PSNIP_CLOCK_NSEC_PER_SEC / 100; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_cpu_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_CPU_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_CPU, res); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK clock_t t = clock(); if (t == ((clock_t) -1)) return -5; res->seconds = t / CLOCKS_PER_SEC; res->nanoseconds = (t % CLOCKS_PER_SEC) * (PSNIP_CLOCK_NSEC_PER_SEC / CLOCKS_PER_SEC); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES FILETIME CreationTime, ExitTime, KernelTime, UserTime; LARGE_INTEGER date, adjust; if (!GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime)) return -7; /* http://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/ */ date.HighPart = UserTime.dwHighDateTime; date.LowPart = UserTime.dwLowDateTime; adjust.QuadPart = 11644473600000 * 10000; date.QuadPart -= adjust.QuadPart; res->seconds = date.QuadPart / 10000000; res->nanoseconds = (date.QuadPart % 10000000) * (PSNIP_CLOCK_NSEC_PER_SEC / 100); #elif PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE struct rusage usage; if (getrusage(RUSAGE_SELF, &usage) != 0) return -8; res->seconds = usage.ru_utime.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else (void) res; return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_monotonic_get_precision (void) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) return 0; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); return (psnip_uint32_t) (tbi.numer / tbi.denom); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 return 1000; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER Frequency; QueryPerformanceFrequency(&Frequency); return (psnip_uint32_t) ((Frequency.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) ? PSNIP_CLOCK_NSEC_PER_SEC : Frequency.QuadPart); #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_monotonic_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC, res); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME psnip_uint64_t nsec = mach_absolute_time(); static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); nsec *= ((psnip_uint64_t) tbi.numer) / ((psnip_uint64_t) tbi.denom); res->seconds = nsec / PSNIP_CLOCK_NSEC_PER_SEC; res->nanoseconds = nsec % PSNIP_CLOCK_NSEC_PER_SEC; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER t, f; if (QueryPerformanceCounter(&t) == 0) return -12; QueryPerformanceFrequency(&f); res->seconds = t.QuadPart / f.QuadPart; res->nanoseconds = t.QuadPart % f.QuadPart; if (f.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) res->nanoseconds /= f.QuadPart / PSNIP_CLOCK_NSEC_PER_SEC; else res->nanoseconds *= PSNIP_CLOCK_NSEC_PER_SEC / f.QuadPart; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 const ULONGLONG msec = GetTickCount64(); res->seconds = msec / 1000; res->nanoseconds = sec % 1000; #else return -2; #endif return 0; } /* Returns the number of ticks per second for the specified clock. * For example, a clock with millisecond precision would return 1000, * and a clock with 1 second (such as the time() function) would * return 1. * * If the requested clock isn't available, it will return 0. * Hopefully this will be rare, but if it happens to you please let us * know so we can work on finding a way to support your system. * * Note that different clocks on the same system often have a * different precisions. */ PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_get_precision (enum PsnipClockType clock_type) { switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_precision (); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_precision (); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_precision (); } PSNIP_CLOCK_UNREACHABLE(); return 0; } /* Set the provided timespec to the requested time. Returns 0 on * success, or a negative value on failure. */ PSNIP_CLOCK__FUNCTION int psnip_clock_get_time (enum PsnipClockType clock_type, struct PsnipClockTimespec* res) { assert(res != NULL); switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_time (res); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_time (res); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_time (res); } return -1; } #endif /* !defined(PSNIP_CLOCK_H) */ static psnip_uint64_t munit_clock_get_elapsed(struct PsnipClockTimespec* start, struct PsnipClockTimespec* end) { psnip_uint64_t r = (end->seconds - start->seconds) * PSNIP_CLOCK_NSEC_PER_SEC; if (end->nanoseconds < start->nanoseconds) { r -= (start->nanoseconds - end->nanoseconds); } else { r += (end->nanoseconds - start->nanoseconds); } return r; } #else # include <time.h> #endif /* defined(MUNIT_ENABLE_TIMING) */ /*** PRNG stuff ***/ /* This is (unless I screwed up, which is entirely possible) the * version of PCG with 32-bit state. It was chosen because it has a * small enough state that we should reliably be able to use CAS * instead of requiring a lock for thread-safety. * * If I did screw up, I probably will not bother changing it unless * there is a significant bias. It's really not important this be * particularly strong, as long as it is fairly random it's much more * important that it be reproducible, so bug reports have a better * chance of being reproducible. */ #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) && !defined(__EMSCRIPTEN__) && (!defined(__GNUC_MINOR__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ > 8)) # define HAVE_STDATOMIC #elif defined(__clang__) # if __has_extension(c_atomic) # define HAVE_CLANG_ATOMICS # endif #endif /* Workaround for http://llvm.org/bugs/show_bug.cgi?id=26911 */ #if defined(__clang__) && defined(_WIN32) # undef HAVE_STDATOMIC # if defined(__c2__) # undef HAVE_CLANG_ATOMICS # endif #endif #if defined(_OPENMP) # define ATOMIC_UINT32_T uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(HAVE_STDATOMIC) # include <stdatomic.h> # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) ATOMIC_VAR_INIT(x) #elif defined(HAVE_CLANG_ATOMICS) # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(_WIN32) # define ATOMIC_UINT32_T volatile LONG # define ATOMIC_UINT32_INIT(x) (x) #else # define ATOMIC_UINT32_T volatile uint32_t # define ATOMIC_UINT32_INIT(x) (x) #endif static ATOMIC_UINT32_T munit_rand_state = ATOMIC_UINT32_INIT(42); #if defined(_OPENMP) static inline void munit_atomic_store(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T value) { #pragma omp critical (munit_atomics) *dest = value; } static inline uint32_t munit_atomic_load(ATOMIC_UINT32_T* src) { int ret; #pragma omp critical (munit_atomics) ret = *src; return ret; } static inline uint32_t munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { munit_bool ret; #pragma omp critical (munit_atomics) { if (*dest == *expected) { *dest = desired; ret = 1; } else { ret = 0; } } return ret; } #elif defined(HAVE_STDATOMIC) # define munit_atomic_store(dest, value) atomic_store(dest, value) # define munit_atomic_load(src) atomic_load(src) # define munit_atomic_cas(dest, expected, value) atomic_compare_exchange_weak(dest, expected, value) #elif defined(HAVE_CLANG_ATOMICS) # define munit_atomic_store(dest, value) __c11_atomic_store(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __c11_atomic_load(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __c11_atomic_compare_exchange_weak(dest, expected, value, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) # define munit_atomic_store(dest, value) __atomic_store_n(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __atomic_load_n(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __atomic_compare_exchange_n(dest, expected, value, 1, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ >= 4) # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) __sync_bool_compare_and_swap(dest, *expected, value) #elif defined(_WIN32) /* Untested */ # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) InterlockedCompareExchange((dest), (value), *(expected)) #else # warning No atomic implementation, PRNG will not be thread-safe # define munit_atomic_store(dest, value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) static inline munit_bool munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { if (*dest == *expected) { *dest = desired; return 1; } else { return 0; } } #endif #define MUNIT_PRNG_MULTIPLIER (747796405U) #define MUNIT_PRNG_INCREMENT (1729U) static munit_uint32_t munit_rand_next_state(munit_uint32_t state) { return state * MUNIT_PRNG_MULTIPLIER + MUNIT_PRNG_INCREMENT; } static munit_uint32_t munit_rand_from_state(munit_uint32_t state) { munit_uint32_t res = ((state >> ((state >> 28) + 4)) ^ state) * (277803737U); res ^= res >> 22; return res; } void munit_rand_seed(munit_uint32_t seed) { munit_uint32_t state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); munit_atomic_store(&munit_rand_state, state); } static munit_uint32_t munit_rand_generate_seed(void) { munit_uint32_t seed, state; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wc = { 0, }; psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wc); seed = (munit_uint32_t) wc.nanoseconds; #else seed = (munit_uint32_t) time(NULL); #endif state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); return munit_rand_from_state(state); } static munit_uint32_t munit_rand_state_uint32(munit_uint32_t* state) { const munit_uint32_t old = *state; *state = munit_rand_next_state(old); return munit_rand_from_state(old); } munit_uint32_t munit_rand_uint32(void) { munit_uint32_t old, state; do { old = munit_atomic_load(&munit_rand_state); state = munit_rand_next_state(old); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return munit_rand_from_state(old); } static void munit_rand_state_memory(munit_uint32_t* state, size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { size_t members_remaining = size / sizeof(munit_uint32_t); size_t bytes_remaining = size % sizeof(munit_uint32_t); munit_uint8_t* b = data; munit_uint32_t rv; while (members_remaining-- > 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, sizeof(munit_uint32_t)); b += sizeof(munit_uint32_t); } if (bytes_remaining != 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, bytes_remaining); } } void munit_rand_memory(size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { munit_uint32_t old, state; do { state = old = munit_atomic_load(&munit_rand_state); munit_rand_state_memory(&state, size, data); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); } static munit_uint32_t munit_rand_state_at_most(munit_uint32_t* state, munit_uint32_t salt, munit_uint32_t max) { /* We want (UINT32_MAX + 1) % max, which in unsigned arithmetic is the same * as (UINT32_MAX + 1 - max) % max = -max % max. We compute -max using not * to avoid compiler warnings. */ const munit_uint32_t min = (~max + 1U) % max; munit_uint32_t x; if (max == (~((munit_uint32_t) 0U))) return munit_rand_state_uint32(state) ^ salt; max++; do { x = munit_rand_state_uint32(state) ^ salt; } while (x < min); return x % max; } static munit_uint32_t munit_rand_at_most(munit_uint32_t salt, munit_uint32_t max) { munit_uint32_t old, state; munit_uint32_t retval; do { state = old = munit_atomic_load(&munit_rand_state); retval = munit_rand_state_at_most(&state, salt, max); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } int munit_rand_int_range(int min, int max) { munit_uint64_t range = (munit_uint64_t) max - (munit_uint64_t) min; if (min > max) return munit_rand_int_range(max, min); if (range > (~((munit_uint32_t) 0U))) range = (~((munit_uint32_t) 0U)); return min + munit_rand_at_most(0, (munit_uint32_t) range); } double munit_rand_double(void) { munit_uint32_t old, state; double retval = 0.0; do { state = old = munit_atomic_load(&munit_rand_state); /* See http://mumble.net/~campbell/tmp/random_real.c for how to do * this right. Patches welcome if you feel that this is too * biased. */ retval = munit_rand_state_uint32(&state) / ((~((munit_uint32_t) 0U)) + 1.0); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } /*** Test suite handling ***/ typedef struct { unsigned int successful; unsigned int skipped; unsigned int failed; unsigned int errored; #if defined(MUNIT_ENABLE_TIMING) munit_uint64_t cpu_clock; munit_uint64_t wall_clock; #endif } MunitReport; typedef struct { const char* prefix; const MunitSuite* suite; const char** tests; munit_uint32_t seed; unsigned int iterations; MunitParameter* parameters; munit_bool single_parameter_mode; void* user_data; MunitReport report; munit_bool colorize; munit_bool fork; munit_bool show_stderr; munit_bool fatal_failures; } MunitTestRunner; const char* munit_parameters_get(const MunitParameter params[], const char* key) { const MunitParameter* param; for (param = params ; param != NULL && param->name != NULL ; param++) if (strcmp(param->name, key) == 0) return param->value; return NULL; } #if defined(MUNIT_ENABLE_TIMING) static void munit_print_time(FILE* fp, munit_uint64_t nanoseconds) { fprintf(fp, "%" MUNIT_TEST_TIME_FORMAT, ((double) nanoseconds) / ((double) PSNIP_CLOCK_NSEC_PER_SEC)); } #endif /* Add a paramter to an array of parameters. */ static MunitResult munit_parameters_add(size_t* params_size, MunitParameter* params[MUNIT_ARRAY_PARAM(*params_size)], char* name, char* value) { *params = (MunitParameter*)realloc(*params, sizeof(MunitParameter) * (*params_size + 2)); if (*params == NULL) return MUNIT_ERROR; (*params)[*params_size].name = name; (*params)[*params_size].value = value; (*params_size)++; (*params)[*params_size].name = NULL; (*params)[*params_size].value = NULL; return MUNIT_OK; } /* Concatenate two strings, but just return one of the components * unaltered if the other is NULL or "". */ static char* munit_maybe_concat(size_t* len, char* prefix, char* suffix) { char* res; size_t res_l; const size_t prefix_l = prefix != NULL ? strlen(prefix) : 0; const size_t suffix_l = suffix != NULL ? strlen(suffix) : 0; if (prefix_l == 0 && suffix_l == 0) { res = NULL; res_l = 0; } else if (prefix_l == 0 && suffix_l != 0) { res = suffix; res_l = suffix_l; } else if (prefix_l != 0 && suffix_l == 0) { res = prefix; res_l = prefix_l; } else { res_l = prefix_l + suffix_l; res = (char*)malloc(res_l + 1); memcpy(res, prefix, prefix_l); memcpy(res + prefix_l, suffix, suffix_l); res[res_l] = 0; } if (len != NULL) *len = res_l; return res; } /* Possbily free a string returned by munit_maybe_concat. */ static void munit_maybe_free_concat(char* s, const char* prefix, const char* suffix) { if (prefix != s && suffix != s) free(s); } /* Cheap string hash function, just used to salt the PRNG. */ static munit_uint32_t munit_str_hash(const char* name) { const char *p; munit_uint32_t h = 5381U; for (p = name; *p != '\0'; p++) h = (h << 5) + h + *p; return h; } static void munit_splice(int from, int to) { munit_uint8_t buf[1024]; #if !defined(_WIN32) ssize_t len; ssize_t bytes_written; ssize_t write_res; #else int len; int bytes_written; int write_res; #endif do { len = read(from, buf, sizeof(buf)); if (len > 0) { bytes_written = 0; do { write_res = write(to, buf + bytes_written, len - bytes_written); if (write_res < 0) break; bytes_written += write_res; } while (bytes_written < len); } else break; } while (1); } /* This is the part that should be handled in the child process */ static MunitResult munit_test_runner_exec(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[], MunitReport* report) { unsigned int iterations = runner->iterations; MunitResult result = MUNIT_FAIL; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wall_clock_begin = { 0, }, wall_clock_end = { 0, }; struct PsnipClockTimespec cpu_clock_begin = { 0, }, cpu_clock_end = { 0, }; #endif unsigned int i = 0; if ((test->options & MUNIT_TEST_OPTION_SINGLE_ITERATION) == MUNIT_TEST_OPTION_SINGLE_ITERATION) iterations = 1; else if (iterations == 0) iterations = runner->suite->iterations; munit_rand_seed(runner->seed); do { void* data = (test->setup == NULL) ? runner->user_data : test->setup(params, runner->user_data); #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_begin); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_begin); #endif result = test->test(params, data); #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_end); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_end); #endif if (test->tear_down != NULL) test->tear_down(data); if (MUNIT_LIKELY(result == MUNIT_OK)) { report->successful++; #if defined(MUNIT_ENABLE_TIMING) report->wall_clock += munit_clock_get_elapsed(&wall_clock_begin, &wall_clock_end); report->cpu_clock += munit_clock_get_elapsed(&cpu_clock_begin, &cpu_clock_end); #endif } else { switch ((int) result) { case MUNIT_SKIP: report->skipped++; break; case MUNIT_FAIL: report->failed++; break; case MUNIT_ERROR: report->errored++; break; default: break; } break; } } while (++i < iterations); return result; } #if defined(MUNIT_EMOTICON) # define MUNIT_RESULT_STRING_OK ":)" # define MUNIT_RESULT_STRING_SKIP ":|" # define MUNIT_RESULT_STRING_FAIL ":(" # define MUNIT_RESULT_STRING_ERROR ":o" # define MUNIT_RESULT_STRING_TODO ":/" #else # define MUNIT_RESULT_STRING_OK "OK " # define MUNIT_RESULT_STRING_SKIP "SKIP " # define MUNIT_RESULT_STRING_FAIL "FAIL " # define MUNIT_RESULT_STRING_ERROR "ERROR" # define MUNIT_RESULT_STRING_TODO "TODO " #endif static void munit_test_runner_print_color(const MunitTestRunner* runner, const char* string, char color) { if (runner->colorize) fprintf(MUNIT_OUTPUT_FILE, "\x1b[3%cm%s\x1b[39m", color, string); else fputs(string, MUNIT_OUTPUT_FILE); } #if !defined(MUNIT_NO_BUFFER) static int munit_replace_stderr(FILE* stderr_buf) { if (stderr_buf != NULL) { const int orig_stderr = dup(STDERR_FILENO); int errfd = fileno(stderr_buf); if (MUNIT_UNLIKELY(errfd == -1)) { exit(EXIT_FAILURE); } dup2(errfd, STDERR_FILENO); return orig_stderr; } return -1; } static void munit_restore_stderr(int orig_stderr) { if (orig_stderr != -1) { dup2(orig_stderr, STDERR_FILENO); close(orig_stderr); } } #endif /* !defined(MUNIT_NO_BUFFER) */ /* Run a test with the specified parameters. */ static void munit_test_runner_run_test_with_params(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[]) { MunitResult result = MUNIT_OK; MunitReport report = { 0, 0, 0, 0, #if defined(MUNIT_ENABLE_TIMING) 0, 0 #endif }; unsigned int output_l; munit_bool first; const MunitParameter* param; FILE* stderr_buf; #if !defined(MUNIT_NO_FORK) int pipefd[2]; pid_t fork_pid; int orig_stderr; ssize_t bytes_written = 0; ssize_t write_res; ssize_t bytes_read = 0; ssize_t read_res; int status = 0; pid_t changed_pid; #endif if (params != NULL) { output_l = 2; fputs(" ", MUNIT_OUTPUT_FILE); first = 1; for (param = params ; param != NULL && param->name != NULL ; param++) { if (!first) { fputs(", ", MUNIT_OUTPUT_FILE); output_l += 2; } else { first = 0; } output_l += fprintf(MUNIT_OUTPUT_FILE, "%s=%s", param->name, param->value); } while (output_l++ < MUNIT_TEST_NAME_LEN) { fputc(' ', MUNIT_OUTPUT_FILE); } } fflush(MUNIT_OUTPUT_FILE); stderr_buf = NULL; #if !defined(_WIN32) || defined(__MINGW32__) stderr_buf = tmpfile(); #else tmpfile_s(&stderr_buf); #endif if (stderr_buf == NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create buffer for stderr"); result = MUNIT_ERROR; goto print_result; } #if !defined(MUNIT_NO_FORK) if (runner->fork) { pipefd[0] = -1; pipefd[1] = -1; if (pipe(pipefd) != 0) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create pipe"); result = MUNIT_ERROR; goto print_result; } fork_pid = fork(); if (fork_pid == 0) { close(pipefd[0]); orig_stderr = munit_replace_stderr(stderr_buf); munit_test_runner_exec(runner, test, params, &report); /* Note that we don't restore stderr. This is so we can buffer * things written to stderr later on (such as by * asan/tsan/ubsan, valgrind, etc.) */ close(orig_stderr); do { write_res = write(pipefd[1], ((munit_uint8_t*) (&report)) + bytes_written, sizeof(report) - bytes_written); if (write_res < 0) { if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to write to pipe"); } exit(EXIT_FAILURE); } bytes_written += write_res; } while ((size_t) bytes_written < sizeof(report)); if (stderr_buf != NULL) fclose(stderr_buf); close(pipefd[1]); exit(EXIT_SUCCESS); } else if (fork_pid == -1) { close(pipefd[0]); close(pipefd[1]); if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to fork"); } report.errored++; result = MUNIT_ERROR; } else { close(pipefd[1]); do { read_res = read(pipefd[0], ((munit_uint8_t*) (&report)) + bytes_read, sizeof(report) - bytes_read); if (read_res < 1) break; bytes_read += read_res; } while (bytes_read < (ssize_t) sizeof(report)); changed_pid = waitpid(fork_pid, &status, 0); if (MUNIT_LIKELY(changed_pid == fork_pid) && MUNIT_LIKELY(WIFEXITED(status))) { if (bytes_read != sizeof(report)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited unexpectedly with status %d", WEXITSTATUS(status)); report.errored++; } else if (WEXITSTATUS(status) != EXIT_SUCCESS) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited with status %d", WEXITSTATUS(status)); report.errored++; } } else { if (WIFSIGNALED(status)) { #if defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700) munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d (%s)", WTERMSIG(status), strsignal(WTERMSIG(status))); #else munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d", WTERMSIG(status)); #endif } else if (WIFSTOPPED(status)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child stopped by signal %d", WSTOPSIG(status)); } report.errored++; } close(pipefd[0]); waitpid(fork_pid, NULL, 0); } } else #endif { #if !defined(MUNIT_NO_BUFFER) const volatile int orig_stderr = munit_replace_stderr(stderr_buf); #endif #if defined(MUNIT_THREAD_LOCAL) if (MUNIT_UNLIKELY(setjmp(munit_error_jmp_buf) != 0)) { result = MUNIT_FAIL; report.failed++; } else { munit_error_jmp_buf_valid = 1; result = munit_test_runner_exec(runner, test, params, &report); } #else result = munit_test_runner_exec(runner, test, params, &report); #endif #if !defined(MUNIT_NO_BUFFER) munit_restore_stderr(orig_stderr); #endif /* Here just so that the label is used on Windows and we don't get * a warning */ goto print_result; } print_result: fputs("[ ", MUNIT_OUTPUT_FILE); if ((test->options & MUNIT_TEST_OPTION_TODO) == MUNIT_TEST_OPTION_TODO) { if (report.failed != 0 || report.errored != 0 || report.skipped != 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_TODO, '3'); result = MUNIT_OK; } else { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); if (MUNIT_LIKELY(stderr_buf != NULL)) munit_log_internal(MUNIT_LOG_ERROR, stderr_buf, "Test marked TODO, but was successful."); runner->report.failed++; result = MUNIT_ERROR; } } else if (report.failed > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_FAIL, '1'); runner->report.failed++; result = MUNIT_FAIL; } else if (report.errored > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); runner->report.errored++; result = MUNIT_ERROR; } else if (report.skipped > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_SKIP, '3'); runner->report.skipped++; result = MUNIT_SKIP; } else if (report.successful > 1) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock / report.successful); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock / report.successful); fprintf(MUNIT_OUTPUT_FILE, " CPU ]\n %-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s Total: [ ", ""); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } else if (report.successful > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } fputs(" ]\n", MUNIT_OUTPUT_FILE); if (stderr_buf != NULL) { if (result == MUNIT_FAIL || result == MUNIT_ERROR || runner->show_stderr) { fflush(MUNIT_OUTPUT_FILE); rewind(stderr_buf); munit_splice(fileno(stderr_buf), STDERR_FILENO); fflush(stderr); } fclose(stderr_buf); } } static void munit_test_runner_run_test_wild(MunitTestRunner* runner, const MunitTest* test, const char* test_name, MunitParameter* params, MunitParameter* p) { const MunitParameterEnum* pe; char** values; MunitParameter* next; for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { if (p->name == pe->name) break; } if (pe == NULL) return; for (values = pe->values ; *values != NULL ; values++) { next = p + 1; p->value = *values; if (next->name == NULL) { munit_test_runner_run_test_with_params(runner, test, params); } else { munit_test_runner_run_test_wild(runner, test, test_name, params, next); } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) break; } } /* Run a single test, with every combination of parameters * requested. */ static void munit_test_runner_run_test(MunitTestRunner* runner, const MunitTest* test, const char* prefix) { char* test_name = munit_maybe_concat(NULL, (char*) prefix, (char*) test->name); /* The array of parameters to pass to * munit_test_runner_run_test_with_params */ MunitParameter* params = NULL; size_t params_l = 0; /* Wildcard parameters are parameters which have possible values * specified in the test, but no specific value was passed to the * CLI. That means we want to run the test once for every * possible combination of parameter values or, if --single was * passed to the CLI, a single time with a random set of * parameters. */ MunitParameter* wild_params = NULL; size_t wild_params_l = 0; const MunitParameterEnum* pe; const MunitParameter* cli_p; munit_bool filled; unsigned int possible; char** vals; size_t first_wild; const MunitParameter* wp; int pidx; munit_rand_seed(runner->seed); fprintf(MUNIT_OUTPUT_FILE, "%-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s", test_name); if (test->parameters == NULL) { /* No parameters. Simple, nice. */ munit_test_runner_run_test_with_params(runner, test, NULL); } else { fputc('\n', MUNIT_OUTPUT_FILE); for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { /* Did we received a value for this parameter from the CLI? */ filled = 0; for (cli_p = runner->parameters ; cli_p != NULL && cli_p->name != NULL ; cli_p++) { if (strcmp(cli_p->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, cli_p->value) != MUNIT_OK)) goto cleanup; filled = 1; break; } } if (filled) continue; /* Nothing from CLI, is the enum NULL/empty? We're not a * fuzzer… */ if (pe->values == NULL || pe->values[0] == NULL) continue; /* If --single was passed to the CLI, choose a value from the * list of possibilities randomly. */ if (runner->single_parameter_mode) { possible = 0; for (vals = pe->values ; *vals != NULL ; vals++) possible++; /* We want the tests to be reproducible, even if you're only * running a single test, but we don't want every test with * the same number of parameters to choose the same parameter * number, so use the test name as a primitive salt. */ pidx = munit_rand_at_most(munit_str_hash(test_name), possible - 1); if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[pidx]) != MUNIT_OK)) goto cleanup; } else { /* We want to try every permutation. Put in a placeholder * entry, we'll iterate through them later. */ if (MUNIT_UNLIKELY(munit_parameters_add(&wild_params_l, &wild_params, pe->name, NULL) != MUNIT_OK)) goto cleanup; } } if (wild_params_l != 0) { first_wild = params_l; for (wp = wild_params ; wp != NULL && wp->name != NULL ; wp++) { for (pe = test->parameters ; pe != NULL && pe->name != NULL && pe->values != NULL ; pe++) { if (strcmp(wp->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[0]) != MUNIT_OK)) goto cleanup; } } } munit_test_runner_run_test_wild(runner, test, test_name, params, params + first_wild); } else { munit_test_runner_run_test_with_params(runner, test, params); } cleanup: free(params); free(wild_params); } munit_maybe_free_concat(test_name, prefix, test->name); } /* Recurse through the suite and run all the tests. If a list of * tests to run was provied on the command line, run only those * tests. */ static void munit_test_runner_run_suite(MunitTestRunner* runner, const MunitSuite* suite, const char* prefix) { size_t pre_l; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const char** test_name; const MunitSuite* child_suite; /* Run the tests. */ for (test = suite->tests ; test != NULL && test->test != NULL ; test++) { if (runner->tests != NULL) { /* Specific tests were requested on the CLI */ for (test_name = runner->tests ; test_name != NULL && *test_name != NULL ; test_name++) { if ((pre_l == 0 || strncmp(pre, *test_name, pre_l) == 0) && strncmp(test->name, *test_name + pre_l, strlen(*test_name + pre_l)) == 0) { munit_test_runner_run_test(runner, test, pre); if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) goto cleanup; } } } else { /* Run all tests */ munit_test_runner_run_test(runner, test, pre); } } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) goto cleanup; /* Run any child suites. */ for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_test_runner_run_suite(runner, child_suite, pre); } cleanup: munit_maybe_free_concat(pre, prefix, suite->prefix); } static void munit_test_runner_run(MunitTestRunner* runner) { munit_test_runner_run_suite(runner, runner->suite, NULL); } static void munit_print_help(int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)], void* user_data, const MunitArgument arguments[]) { const MunitArgument* arg; (void) argc; printf("USAGE: %s [OPTIONS...] [TEST...]\n\n", argv[0]); puts(" --seed SEED\n" " Value used to seed the PRNG. Must be a 32-bit integer in decimal\n" " notation with no separators (commas, decimals, spaces, etc.), or\n" " hexidecimal prefixed by \"0x\".\n" " --iterations N\n" " Run each test N times. 0 means the default number.\n" " --param name value\n" " A parameter key/value pair which will be passed to any test with\n" " takes a parameter of that name. If not provided, the test will be\n" " run once for each possible parameter value.\n" " --list Write a list of all available tests.\n" " --list-params\n" " Write a list of all available tests and their possible parameters.\n" " --single Run each parameterized test in a single configuration instead of\n" " every possible combination\n" " --log-visible debug|info|warning|error\n" " --log-fatal debug|info|warning|error\n" " Set the level at which messages of different severities are visible,\n" " or cause the test to terminate.\n" #if !defined(MUNIT_NO_FORK) " --no-fork Do not execute tests in a child process. If this option is supplied\n" " and a test crashes (including by failing an assertion), no further\n" " tests will be performed.\n" #endif " --fatal-failures\n" " Stop executing tests as soon as a failure is found.\n" " --show-stderr\n" " Show data written to stderr by the tests, even if the test succeeds.\n" " --color auto|always|never\n" " Colorize (or don't) the output.\n" /* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */ " --help Print this help message and exit.\n"); #if defined(MUNIT_NL_LANGINFO) setlocale(LC_ALL, ""); fputs((strcasecmp("UTF-8", nl_langinfo(CODESET)) == 0) ? "µnit" : "munit", stdout); #else puts("munit"); #endif printf(" %d.%d.%d\n" "Full documentation at: https://nemequ.github.io/munit/\n", (MUNIT_CURRENT_VERSION >> 16) & 0xff, (MUNIT_CURRENT_VERSION >> 8) & 0xff, (MUNIT_CURRENT_VERSION >> 0) & 0xff); for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) arg->write_help(arg, user_data); } static const MunitArgument* munit_arguments_find(const MunitArgument arguments[], const char* name) { const MunitArgument* arg; for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) if (strcmp(arg->name, name) == 0) return arg; return NULL; } static void munit_suite_list_tests(const MunitSuite* suite, munit_bool show_params, const char* prefix) { size_t pre_l; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const MunitParameterEnum* params; munit_bool first; char** val; const MunitSuite* child_suite; for (test = suite->tests ; test != NULL && test->name != NULL ; test++) { if (pre != NULL) fputs(pre, stdout); puts(test->name); if (show_params) { for (params = test->parameters ; params != NULL && params->name != NULL ; params++) { fprintf(stdout, " - %s: ", params->name); if (params->values == NULL) { puts("Any"); } else { first = 1; for (val = params->values ; *val != NULL ; val++ ) { if(!first) { fputs(", ", stdout); } else { first = 0; } fputs(*val, stdout); } putc('\n', stdout); } } } } for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_suite_list_tests(child_suite, show_params, pre); } munit_maybe_free_concat(pre, prefix, suite->prefix); } static munit_bool munit_stream_supports_ansi(FILE *stream) { #if !defined(_WIN32) return isatty(fileno(stream)); #else #if !defined(__MINGW32__) size_t ansicon_size = 0; #endif if (isatty(fileno(stream))) { #if !defined(__MINGW32__) getenv_s(&ansicon_size, NULL, 0, "ANSICON"); return ansicon_size != 0; #else return getenv("ANSICON") != NULL; #endif } return 0; #endif } int munit_suite_main_custom(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)], const MunitArgument arguments[]) { int result = EXIT_FAILURE; MunitTestRunner runner; size_t parameters_size = 0; size_t tests_size = 0; int arg; char* envptr; unsigned long ts; char* endptr; unsigned long long iterations; MunitLogLevel level; const MunitArgument* argument; const char** runner_tests; unsigned int tests_run; unsigned int tests_total; runner.prefix = NULL; runner.suite = NULL; runner.tests = NULL; runner.seed = 0; runner.iterations = 0; runner.parameters = NULL; runner.single_parameter_mode = 0; runner.user_data = NULL; runner.report.successful = 0; runner.report.skipped = 0; runner.report.failed = 0; runner.report.errored = 0; #if defined(MUNIT_ENABLE_TIMING) runner.report.cpu_clock = 0; runner.report.wall_clock = 0; #endif runner.colorize = 0; #if !defined(_WIN32) runner.fork = 1; #else runner.fork = 0; #endif runner.show_stderr = 0; runner.fatal_failures = 0; runner.suite = suite; runner.user_data = user_data; runner.seed = munit_rand_generate_seed(); runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); for (arg = 1 ; arg < argc ; arg++) { if (strncmp("--", argv[arg], 2) == 0) { if (strcmp("seed", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } envptr = argv[arg + 1]; ts = strtoul(argv[arg + 1], &envptr, 0); if (*envptr != '\0' || ts > (~((munit_uint32_t) 0U))) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.seed = (munit_uint32_t) ts; arg++; } else if (strcmp("iterations", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } endptr = argv[arg + 1]; iterations = strtoul(argv[arg + 1], &endptr, 0); if (*endptr != '\0' || iterations > UINT_MAX) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.iterations = (unsigned int) iterations; arg++; } else if (strcmp("param", argv[arg] + 2) == 0) { if (arg + 2 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires two arguments", argv[arg]); goto cleanup; } runner.parameters = (MunitParameter*)realloc(runner.parameters, sizeof(MunitParameter) * (parameters_size + 2)); if (runner.parameters == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.parameters[parameters_size].name = (char*) argv[arg + 1]; runner.parameters[parameters_size].value = (char*) argv[arg + 2]; parameters_size++; runner.parameters[parameters_size].name = NULL; runner.parameters[parameters_size].value = NULL; arg += 2; } else if (strcmp("color", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "always") == 0) runner.colorize = 1; else if (strcmp(argv[arg + 1], "never") == 0) runner.colorize = 0; else if (strcmp(argv[arg + 1], "auto") == 0) runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } arg++; } else if (strcmp("help", argv[arg] + 2) == 0) { munit_print_help(argc, argv, user_data, arguments); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("single", argv[arg] + 2) == 0) { runner.single_parameter_mode = 1; } else if (strcmp("show-stderr", argv[arg] + 2) == 0) { runner.show_stderr = 1; #if !defined(_WIN32) } else if (strcmp("no-fork", argv[arg] + 2) == 0) { runner.fork = 0; #endif } else if (strcmp("fatal-failures", argv[arg] + 2) == 0) { runner.fatal_failures = 1; } else if (strcmp("log-visible", argv[arg] + 2) == 0 || strcmp("log-fatal", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "debug") == 0) level = MUNIT_LOG_DEBUG; else if (strcmp(argv[arg + 1], "info") == 0) level = MUNIT_LOG_INFO; else if (strcmp(argv[arg + 1], "warning") == 0) level = MUNIT_LOG_WARNING; else if (strcmp(argv[arg + 1], "error") == 0) level = MUNIT_LOG_ERROR; else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } if (strcmp("log-visible", argv[arg] + 2) == 0) munit_log_level_visible = level; else munit_log_level_fatal = level; arg++; } else if (strcmp("list", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, 0, NULL); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("list-params", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, 1, NULL); result = EXIT_SUCCESS; goto cleanup; } else { argument = munit_arguments_find(arguments, argv[arg] + 2); if (argument == NULL) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "unknown argument ('%s')", argv[arg]); goto cleanup; } if (!argument->parse_argument(suite, user_data, &arg, argc, argv)) goto cleanup; } } else { runner_tests = (const char**)realloc((void*) runner.tests, sizeof(char*) * (tests_size + 2)); if (runner_tests == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.tests = runner_tests; runner.tests[tests_size++] = argv[arg]; runner.tests[tests_size] = NULL; } } fflush(stderr); fprintf(MUNIT_OUTPUT_FILE, "Running test suite with seed %08x ...\n", runner.seed); munit_test_runner_run(&runner); tests_run = runner.report.successful + runner.report.failed + runner.report.errored; tests_total = tests_run + runner.report.skipped; if (tests_run == 0) { fprintf(stderr, "No tests run, %d (100%%) skipped.\n", runner.report.skipped); } else { fprintf(MUNIT_OUTPUT_FILE, "%d of %d (%0.0f%%) tests successful, %d (%0.0f%%) test skipped.\n", runner.report.successful, tests_run, (((double) runner.report.successful) / ((double) tests_run)) * 100.0, runner.report.skipped, (((double) runner.report.skipped) / ((double) tests_total)) * 100.0); } if (runner.report.failed == 0 && runner.report.errored == 0) { result = EXIT_SUCCESS; } cleanup: free(runner.parameters); free((void*) runner.tests); return result; } int munit_suite_main(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)]) { return munit_suite_main_custom(suite, user_data, argc, argv, NULL); }
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 16; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. 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 ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-2,4),ceild(8*t2-Nz-3,16));t3<=min(floord(4*Nt+Ny-9,16),floord(4*t1+Ny-1,16));t3++) { for (t4=max(max(ceild(t1-254,256),ceild(8*t2-Nz-1011,1024)),ceild(16*t3-Ny-1011,1024));t4<=min(min(floord(4*Nt+Nx-9,1024),floord(4*t1+Nx-1,1024)),floord(16*t3+Nx+3,1024));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4)),t1);t5<=min(min(min(Nt-1,t1+1),4*t3+2),256*t4+254);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(1024*t4,4*t5+4); ubv=min(1024*t4+1023,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
SlicedC02BasedTraversal.h
/** * @file SlicedC02BasedTraversal.h * * @date 24 May 2020 * @author fischerv */ #pragma once #include <algorithm> #include "autopas/containers/cellPairTraversals/SlicedBasedTraversal.h" #include "autopas/utils/DataLayoutConverter.h" #include "autopas/utils/ThreeDimensionalMapping.h" #include "autopas/utils/WrapOpenMP.h" namespace autopas { /** * This class provides the colored sliced traversal. * * The traversal finds the longest dimension of the simulation domain and cuts * the domain into as many slices as possible along this dimension. Unlike the regular * sliced traversal, this version uses a 2-coloring to prevent race conditions, instead of * locking the starting layers. This could also be describes as a c02-traversal. This class * is however not derived from CBasedTraversal, as that would not allow varying slice thicknesses, * and would prevent us from selecting the dimension in which we cut the slices. * * @tparam ParticleCell The type of cells. * @tparam PairwiseFunctor The functor that defines the interaction of two particles. * @tparam dataLayout * @tparam useNewton3 * @tparam spaciallyForward Whether the base step only covers neigboring cells tha are spacially forward (for example * c08) */ template <class ParticleCell, class PairwiseFunctor, DataLayoutOption::Value dataLayout, bool useNewton3, bool spaciallyForward> class SlicedC02BasedTraversal : public SlicedBasedTraversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3, spaciallyForward> { public: /** * Constructor of the colored sliced traversal. * @param dims The dimensions of the cellblock, i.e. the number of cells in x, * y and z direction. * @param pairwiseFunctor The functor that defines the interaction of two particles. * @param interactionLength Interaction length (cutoff + skin). * @param cellLength cell length. */ explicit SlicedC02BasedTraversal(const std::array<unsigned long, 3> &dims, PairwiseFunctor *pairwiseFunctor, const double interactionLength, const std::array<double, 3> &cellLength) : SlicedBasedTraversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3, spaciallyForward>( dims, pairwiseFunctor, interactionLength, cellLength) {} /** * The main traversal of the colored sliced traversal. * This provides the structure of the loops and its parallelization. * * @copydetails C01BasedTraversal::c01Traversal() * */ template <typename LoopBody> inline void cSlicedTraversal(LoopBody &&loopBody); /** * Checks if the traversal is applicable to the current state of the domain. * @return true iff the traversal can be applied. */ [[nodiscard]] bool isApplicable() const override { return this->_cellsPerDimension[this->_dimsPerLength[0]] >= this->_overlapLongestAxis; } /** * Load Data Layouts and sets up slice thicknesses. */ void initTraversal() override { this->loadDataLayout(); // split domain across its longest dimension auto minSliceThickness = this->_overlapLongestAxis; this->initSliceThickness(minSliceThickness); } }; template <class ParticleCell, class PairwiseFunctor, DataLayoutOption::Value dataLayout, bool useNewton3, bool spaciallyForward> template <typename LoopBody> void SlicedC02BasedTraversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3, spaciallyForward>::cSlicedTraversal( LoopBody &&loopBody) { using std::array; auto numSlices = this->_sliceThickness.size(); // check if applicable std::array<size_t, 2> overLapps23{this->_overlap[this->_dimsPerLength[1]], this->_overlap[this->_dimsPerLength[2]]}; if (not spaciallyForward) { overLapps23 = {0ul, 0ul}; } for (size_t offset = 0; offset < 2; offset++) { #ifdef AUTOPAS_OPENMP // although every thread gets exactly one iteration (=slice) this is faster than a normal parallel region #pragma omp parallel for schedule(dynamic, 1) #endif for (size_t slice = offset; slice < numSlices; slice += 2) { array<unsigned long, 3> myStartArray{0, 0, 0}; for (size_t i = 0; i < slice; ++i) { myStartArray[this->_dimsPerLength[0]] += this->_sliceThickness[i]; } const auto lastLayer = myStartArray[this->_dimsPerLength[0]] + this->_sliceThickness[slice]; for (unsigned long dimSlice = myStartArray[this->_dimsPerLength[0]]; dimSlice < lastLayer; ++dimSlice) { for (unsigned long dimMedium = 0; dimMedium < this->_cellsPerDimension[this->_dimsPerLength[1]] - overLapps23[0]; ++dimMedium) { for (unsigned long dimShort = 0; dimShort < this->_cellsPerDimension[this->_dimsPerLength[2]] - overLapps23[1]; ++dimShort) { array<unsigned long, 3> idArray = {}; idArray[this->_dimsPerLength[0]] = dimSlice; idArray[this->_dimsPerLength[1]] = dimMedium; idArray[this->_dimsPerLength[2]] = dimShort; loopBody(idArray[0], idArray[1], idArray[2]); } } } } } } } // namespace autopas
vector.h
/* Copyright 2016 Waizung Taam 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. - 2016-08-12 - ======== tensor::Vector ======== - namespace tensor - struct Random - class Vector - Declaration - type - constructors, etc - shape - iterators - accessors - modifiers - arithmetic - comparisons - io - helper functions - private data member - Implementation - Same order as declared - namespace internal before - random constructors - arithmetic - comparisons - class VectorException */ #ifndef TENSOR_VECTOR_H_ #define TENSOR_VECTOR_H_ #include <algorithm> #include <cmath> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <random> #include <string> #include <type_traits> #include <utility> #include <vector> #include <omp.h> #include <x86intrin.h> namespace tensor { struct Random { enum Generator { default_random_engine, minstd_rand0, minstd_rand, mt19937, mt19937_64, ranlux24_base, ranlux48_base, ranlux24, ranlux48, knuth_b }; enum Distribution { uniform_int, uniform_real, bernoulli, binomial, negative_binomial, geometric, poisson, exponential, gamma, weibull, extreme_value, normal, lognormal, chi_squared, cauchy, fisher_f, student_t }; }; class VectorException; template <typename T> class Vector { public: // ======== Types ======== typedef T value_type; typedef typename std::vector<T>::size_type size_type; typedef typename std::make_signed<size_type>::type index_type; typedef typename std::vector<T>::difference_type difference_type; typedef typename std::vector<T>::iterator iterator; typedef typename std::vector<T>::const_iterator const_iterator; typedef typename std::vector<T>::reverse_iterator reverse_iterator; typedef typename std::vector<T>::const_reverse_iterator const const_reverse_iterator; // ======== Constructors, etc ======== Vector(); explicit Vector(const size_type& size_init); Vector(const size_type& size_init, const T& val_init); template <typename OtherT> Vector(const size_type& size_init, const OtherT& val_cast); Vector(const Vector& vec_init); template <typename OtherT> Vector(const Vector<OtherT>& vec_cast); Vector(Vector&& vec_init); template <typename OtherT> Vector(Vector<OtherT>&& vec_cast); /*explicit */Vector(const std::vector<T>& stdvec_init); template <typename OtherT> /*explicit */Vector(const std::vector<OtherT>& stdvec_cast); /*explicit */Vector(const std::initializer_list<T>& il_init); template <typename OtherT> /*explicit */Vector(const std::initializer_list<OtherT>& il_cast); /* TODO */ template <typename ParamT1, typename ParamT2> Vector(const size_type& size_init, Random::Generator gen, Random::Distribution dis, const ParamT1& param1, const ParamT2& param2); /* TODO */ template <typename ParamT> Vector(const size_type& size_init, Random::Generator gen, Random::Distribution dis, const ParamT& param); template <typename ParamT1, typename ParamT2> Vector(const size_type& size_init, Random::Distribution dis, const ParamT1& param1, const ParamT2& param2); template <typename ParamT> Vector(const size_type& size_init, Random::Distribution dis, const ParamT& param); Vector& operator=(const T& val_assign); template <typename OtherT> Vector& operator=(const OtherT& val_cast); Vector& operator=(const Vector& vec_copy); template <typename OtherT> Vector& operator=(const Vector<OtherT>& vec_cast); Vector& operator=(Vector&& vec_move); template <typename OtherT> Vector& operator=(Vector<OtherT>&& vec_cast); Vector& operator=(const std::vector<T>& stdvec_assign); template <typename OtherT> Vector& operator=(const std::vector<OtherT>& stdvec_cast); Vector& operator=(const std::initializer_list<T>& il_assign); template <typename OtherT> Vector& operator=(const std::initializer_list<OtherT>& il_cast); ~Vector(); // ======== Shape ======== Vector<size_type> shape() const; void clear(); bool empty() const; // ======== Iterators ======== iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; reverse_iterator rbegin(); reverse_iterator rend(); const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; const_reverse_iterator crbegin() const; const_reverse_iterator crend() const; // ======== Accessors ======== T& operator[](const index_type& index); const T& operator[](const index_type& index) const; Vector operator()(const index_type& index) const; Vector operator()(const const_iterator& cit) const; Vector operator()(const index_type& idx_begin, const index_type& idx_end) const; Vector operator()(const const_iterator& cit_begin, const const_iterator& cit_end) const; // ======== Modifiers ======== Vector insert(const T& val_insert, const index_type& index) const; Vector insert(const T& val_insert, const const_iterator& cit) const; Vector insert(const Vector& vec_insert, const index_type& index) const; Vector insert(const Vector& vec_insert, const const_iterator& cit) const; Vector remove(const index_type& index) const; Vector remove(const const_iterator& cit) const; Vector remove(const index_type& idx_begin, const index_type& idx_end) const; Vector remove(const const_iterator& cit_begin, const const_iterator& cit_end) const; Vector replace(const T& val_replace, const index_type& index) const; Vector replace(const T& val_replace, const const_iterator& cit) const; Vector replace(const Vector& vec_replace, const index_type& index) const; Vector replace(const Vector& vec_replace, const const_iterator& cit) const; Vector reshape(const size_type& size) const; Vector reverse() const; Vector shuffle() const; // ======== Arithmetic ======== template <typename AriT> friend Vector<AriT> operator+(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs); template <typename AriT> friend Vector<AriT> operator+(const Vector<AriT>& vec_lhs, const AriT& val_rhs); template <typename AriT> friend Vector<AriT> operator+(const AriT& val_lhs, const Vector<AriT>& vec_rhs); template <typename AriT> friend Vector<AriT> operator-(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs); template <typename AriT> friend Vector<AriT> operator-(const Vector<AriT>& vec_lhs, const AriT& val_rhs); template <typename AriT> friend Vector<AriT> operator-(const AriT& val_lhs, const Vector<AriT>& vec_rhs); template <typename AriT> friend Vector<AriT> operator*(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs); template <typename AriT> friend Vector<AriT> operator*(const Vector<AriT>& vec_lhs, const AriT& val_rhs); template <typename AriT> friend Vector<AriT> operator*(const AriT& val_lhs, const Vector<AriT>& vec_rhs); template <typename AriT> friend Vector<AriT> operator/(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs); template <typename AriT> friend Vector<AriT> operator/(const Vector<AriT>& vec_lhs, const AriT& val_rhs); template <typename AriT> friend Vector<AriT> operator/(const AriT& val_lhs, const Vector<AriT>& vec_rhs); void operator+=(const Vector& vec_rhs); void operator+=(const T& val_rhs); void operator-=(const Vector& vec_rhs); void operator-=(const T& val_rhs); void operator*=(const Vector& vec_rhs); void operator*=(const T& val_rhs); void operator/=(const Vector& vec_rhs); void operator/=(const T& val_rhs); T sum() const; // ======== Comparisons ======== template <typename CmpT> friend Vector<CmpT> operator==(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator==(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs); template <typename CmpT> friend Vector<CmpT> operator==(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator!=(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator!=(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs); template <typename CmpT> friend Vector<CmpT> operator!=(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator<(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator<(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs); template <typename CmpT> friend Vector<CmpT> operator<(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator<=(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator<=(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs); template <typename CmpT> friend Vector<CmpT> operator<=(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator>(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator>(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs); template <typename CmpT> friend Vector<CmpT> operator>(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator>=(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs); template <typename CmpT> friend Vector<CmpT> operator>=(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs); template <typename CmpT> friend Vector<CmpT> operator>=(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs); bool equal(const Vector& vec_rhs, std::size_t ulp = 1); bool nequal(const Vector& vec_rhs, std::size_t ulp = 1); T max() const; T min() const; // ======== IO ======== template <typename VecT, typename CharT, typename Traits> friend std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const Vector<VecT>& vec); template <typename VecT, typename CharT, typename Traits> friend std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, Vector<VecT>& vec); private: // ======== Helper Functions ======== static bool fequal_(const T& x, const T& y, std::size_t ulp = 1); static index_type to_positive_index_(const size_type& size, const index_type& index); static void exclusive_range_check_(const size_type& size, const index_type& index); static void exclusive_range_check_(const iterator& it_begin, const iterator& it_end, const iterator& it); static void exclusive_range_check_(const const_iterator& cit_begin, const const_iterator& cit_end, const const_iterator& cit); static void inclusive_range_check_(const size_type& size, const index_type& index); static void inclusive_range_check_(const iterator& it_begin, const iterator& it_end, const iterator& it); static void inclusive_range_check_(const const_iterator& cit_begin, const const_iterator& cit_end, const const_iterator& cit); static void shape_consistence_check_(const Vector<size_type>& shape_lhs, const Vector<size_type>& shape_rhs); static void index_order_check_(const size_type& size, const index_type& idx_begin, const index_type& idx_end); index_type to_positive_index_(const index_type& index) const; void exclusive_range_check_(const index_type& index) const; void exclusive_range_check_(const iterator& it); void exclusive_range_check_(const const_iterator& cit) const; void inclusive_range_check_(const index_type& index) const; void inclusive_range_check_(const iterator& it); void inclusive_range_check_(const const_iterator& cit) const; void index_order_check_(const index_type& idx_begin, const index_type& idx_end) const; void iterator_order_check_(const iterator& it_begin, const iterator& it_end); void const_iterator_order_check_(const const_iterator& cit_begin, const const_iterator& cit_end) const; // ======== Private Data Member ======== std::vector<T> vec_; }; // ======== Constructors, etc ======== template <typename T> Vector<T>::Vector() {} template <typename T> Vector<T>::Vector(const size_type& size_init) : vec_(std::vector<T>(size_init, T())) {} template <typename T> Vector<T>::Vector(const size_type& size_init, const T& val_init) : vec_(std::vector<T>(size_init, val_init)) {} template <typename T> template <typename OtherT> Vector<T>::Vector(const size_type& size_init, const OtherT& val_cast) : vec_(std::vector<T>(size_init, static_cast<T>(val_cast))) {} template <typename T> Vector<T>::Vector(const Vector& vec_init) : vec_(vec_init.vec_) {} template <typename T> template <typename OtherT> Vector<T>::Vector(const Vector<OtherT>& vec_cast) { vec_.resize(vec_cast.shape()[0]); for (size_type idx = 0; idx < vec_.size(); ++idx) { vec_[idx] = static_cast<T>(vec_cast[idx]); } } template <typename T> Vector<T>::Vector(Vector&& vec_init) : vec_(std::move(vec_init.vec_)) {} template <typename T> template <typename OtherT> Vector<T>::Vector(Vector<OtherT>&& vec_cast) { vec_.resize(vec_cast.shape()[0]); Vector<OtherT> vec_cache = std::move(vec_cast); for (size_type idx = 0; idx < vec_.size(); ++idx) { vec_[idx] = static_cast<T>(vec_cache[idx]); } } template <typename T> Vector<T>::Vector(const std::vector<T>& stdvec_init) : vec_(stdvec_init) {} template <typename T> template <typename OtherT> Vector<T>::Vector(const std::vector<OtherT>& stdvec_cast) { vec_.resize(stdvec_cast.size()); for (size_type idx = 0; idx < vec_.size(); ++idx) { vec_[idx] = static_cast<T>(stdvec_cast[idx]); } } template <typename T> Vector<T>::Vector(const std::initializer_list<T>& il_init) : vec_(il_init) {} template <typename T> template <typename OtherT> Vector<T>::Vector(const std::initializer_list<OtherT>& il_cast) { vec_.resize(il_cast.size()); for (size_type idx = 0; idx < vec_.size(); ++idx) { vec_[idx] = static_cast<T>(*(il_cast.begin() + idx)); } } // namespace internal namespace internal { struct RandomNumberGenerator { #define RNG(NAME) \ static std::NAME NAME(std::NAME::result_type seed) { \ return std::NAME(seed); \ } RNG(default_random_engine) RNG(minstd_rand0) RNG(minstd_rand) RNG(mt19937) RNG(mt19937_64) RNG(ranlux24_base) RNG(ranlux48_base) RNG(ranlux24) RNG(ranlux48) RNG(knuth_b) #undef RNG }; template <typename T> struct RandomDistribution { #define DIS_2_PARAM_INTEGRAL(NAME) \ template <typename Tp = T, typename ParamT1, typename ParamT2> \ static std::NAME##_distribution< typename \ std::enable_if<std::is_integral<Tp>::value, Tp>::type> \ NAME(const ParamT1& param1, const ParamT2& param2) { \ return std::NAME##_distribution<Tp>(param1, param2); \ } \ template <typename Tp = T, typename ParamT1, typename ParamT2> \ static std::NAME##_distribution< typename \ std::enable_if<!std::is_integral<Tp>::value, int>::type> \ NAME(const ParamT1& param1, const ParamT2& param2) { \ return std::NAME##_distribution<int>(param1, param2); \ } #define DIS_2_PARAM_FLOATING(NAME) \ template <typename Tp = T, typename ParamT1, typename ParamT2> \ static std::NAME##_distribution< typename \ std::enable_if<std::is_floating_point<Tp>::value, Tp>::type> \ NAME(const ParamT1& param1, const ParamT2& param2) { \ return std::NAME##_distribution<Tp>(param1, param2); \ } \ template <typename Tp = T, typename ParamT1, typename ParamT2> \ static std::NAME##_distribution< typename \ std::enable_if<!std::is_floating_point<Tp>::value, double>::type> \ NAME(const ParamT1& param1, const ParamT2& param2) { \ return std::NAME##_distribution<double>(param1, param2); \ } #define DIS_1_PARAM_INTEGRAL(NAME) \ template <typename Tp = T, typename ParamT> \ static std::NAME##_distribution< typename \ std::enable_if<std::is_integral<Tp>::value, Tp>::type> \ NAME(const ParamT& param) { \ return std::NAME##_distribution<Tp>(param); \ } \ template <typename Tp = T, typename ParamT> \ static std::NAME##_distribution< typename \ std::enable_if<!std::is_integral<Tp>::value, int>::type> \ NAME(const ParamT& param) { \ return std::NAME##_distribution<int>(param); \ } #define DIS_1_PARAM_FLOATING(NAME) \ template <typename Tp = T, typename ParamT> \ static std::NAME##_distribution< typename \ std::enable_if<std::is_floating_point<Tp>::value, Tp>::type> \ NAME(const ParamT& param) { \ return std::NAME##_distribution<Tp>(param); \ } \ template <typename Tp = T, typename ParamT> \ static std::NAME##_distribution< typename \ std::enable_if<!std::is_floating_point<Tp>::value, double>::type> \ NAME(const ParamT& param) { \ return std::NAME##_distribution<double>(param); \ } DIS_2_PARAM_INTEGRAL(uniform_int) DIS_2_PARAM_FLOATING(uniform_real) DIS_2_PARAM_INTEGRAL(binomial) DIS_2_PARAM_INTEGRAL(negative_binomial) DIS_1_PARAM_INTEGRAL(geometric) DIS_1_PARAM_INTEGRAL(poisson) DIS_1_PARAM_FLOATING(exponential) DIS_2_PARAM_FLOATING(gamma) DIS_2_PARAM_FLOATING(weibull) DIS_2_PARAM_FLOATING(extreme_value) DIS_2_PARAM_FLOATING(normal) DIS_2_PARAM_FLOATING(lognormal) DIS_1_PARAM_FLOATING(chi_squared) DIS_2_PARAM_FLOATING(cauchy) DIS_2_PARAM_FLOATING(fisher_f) DIS_1_PARAM_FLOATING(student_t) #undef DIS_2_PARAM_INTEGRAL #undef DIS_2_PARAM_FLOATING #undef DIS_1_PARAM_INTEGRAL #undef DIS_1_PARAM_FLOATING template <typename ParamT> static std::bernoulli_distribution bernoulli(const ParamT& param) { return std::bernoulli_distribution(param); } }; } // namespace internal // Random Constructor template <typename T> template <typename ParamT1, typename ParamT2> Vector<T>::Vector(const size_type& size_init, Random::Generator gen, Random::Distribution dis, const ParamT1& param1, const ParamT2& param2) { /* TODO */ } template <typename T> template <typename ParamT> Vector<T>::Vector(const size_type& size_init, Random::Generator gen, Random::Distribution dis, const ParamT& param) { /* TODO */ } template <typename T> template <typename ParamT1, typename ParamT2> Vector<T>::Vector(const size_type& size_init, Random::Distribution dis, const ParamT1& param1, const ParamT2& param2) { vec_.resize(size_init); auto gen = internal::RandomNumberGenerator::default_random_engine( std::random_device()()); switch (dis) { case Random::Distribution::uniform_int: { if(!std::is_integral<T>::value) { throw VectorException( "Result type of uniform_int should be a integral type."); } auto dis = internal::RandomDistribution<T>::uniform_int(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::uniform_real: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of uniform_real should be a floating point type."); } auto dis = internal::RandomDistribution<T>::uniform_real(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::binomial: { if(!std::is_integral<T>::value) { throw VectorException( "Result type of binomial should be a integral type."); } auto dis = internal::RandomDistribution<T>::binomial(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::negative_binomial: { if(!std::is_integral<T>::value) { throw VectorException( "Result type of negative_binomial should be a integral type."); } auto dis = internal::RandomDistribution<T>::negative_binomial( param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::gamma: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of gamma should be a floating point type."); } auto dis = internal::RandomDistribution<T>::gamma(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::weibull: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of weibull should be a floating point type."); } auto dis = internal::RandomDistribution<T>::weibull(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::extreme_value: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of extreme_value should be a floating point type."); } auto dis = internal::RandomDistribution<T>::extreme_value( param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::normal: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of normal should be a floating point type."); } auto dis = internal::RandomDistribution<T>::normal(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::lognormal: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of lognormal should be a floating point type."); } auto dis = internal::RandomDistribution<T>::lognormal(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::cauchy: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of cauchy should be a floating point type."); } auto dis = internal::RandomDistribution<T>::cauchy(param1, param2); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::fisher_f: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of fisher_f should be a floating point type."); } auto dis = internal::RandomDistribution<T>::fisher_f(param1, param2); for (T& element : vec_) element = dis(gen); break; } default: throw VectorException("Unsupported random distribution type."); } } template <typename T> template <typename ParamT> Vector<T>::Vector(const size_type& size_init, Random::Distribution dis, const ParamT& param) { vec_.resize(size_init); auto gen = internal::RandomNumberGenerator::default_random_engine( std::random_device()()); switch (dis) { case Random::Distribution::bernoulli: { auto dis = internal::RandomDistribution<T>::bernoulli(param); for (T& element : vec_) element = static_cast<T>(dis(gen)); break; } case Random::Distribution::geometric: { if(!std::is_integral<T>::value) { throw VectorException( "Result type of geometric should be a integral type."); } auto dis = internal::RandomDistribution<T>::geometric(param); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::poisson: { if(!std::is_integral<T>::value) { throw VectorException( "Result type of poisson should be a integral type."); } auto dis = internal::RandomDistribution<T>::poisson(param); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::exponential: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of exponential should be a floating point type."); } auto dis = internal::RandomDistribution<T>::exponential(param); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::chi_squared: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of chi_squared should be a floating point type."); } auto dis = internal::RandomDistribution<T>::chi_squared(param); for (T& element : vec_) element = dis(gen); break; } case Random::Distribution::student_t: { if(!std::is_floating_point<T>::value) { throw VectorException( "Result type of student_t should be a floating point type."); } auto dis = internal::RandomDistribution<T>::student_t(param); for (T& element : vec_) element = dis(gen); break; } default: throw VectorException("Unsupported random distribution type."); } } template <typename T> Vector<T>& Vector<T>::operator=(const T& val_assign) { vec_ = std::vector<T>(vec_.size(), val_assign); return *this; } template <typename T> template <typename OtherT> Vector<T>& Vector<T>::operator=(const OtherT& val_cast) { T value = static_cast<T>(val_cast); vec_ = std::vector<T>(vec_.size(), value); return *this; } template <typename T> Vector<T>& Vector<T>::operator=(const Vector& vec_copy) { vec_ = vec_copy.vec_; return *this; } template <typename T> template <typename OtherT> Vector<T>& Vector<T>::operator=(const Vector<OtherT>& vec_cast) { vec_ = Vector<T>(vec_cast).vec_; return *this; } template <typename T> Vector<T>& Vector<T>::operator=(Vector&& vec_move) { vec_ = std::move(vec_move.vec_); return *this; } template <typename T> template <typename OtherT> Vector<T>& Vector<T>::operator=(Vector<OtherT>&& vec_cast) { vec_ = Vector<T>(vec_cast).vec_; return *this; } template <typename T> Vector<T>& Vector<T>::operator=(const std::vector<T>& stdvec_assign) { vec_ = stdvec_assign; return *this; } template <typename T> template <typename OtherT> Vector<T>& Vector<T>::operator=(const std::vector<OtherT>& stdvec_cast) { vec_ = Vector<T>(stdvec_cast).vec_; return *this; } template <typename T> Vector<T>& Vector<T>::operator=(const std::initializer_list<T>& il_assign) { vec_ = il_assign; return *this; } template <typename T> template <typename OtherT> Vector<T>& Vector<T>::operator=(const std::initializer_list<OtherT>& il_cast) { vec_ = Vector<T>(il_cast).vec_; return *this; } template <typename T> Vector<T>::~Vector() {} // ======== Shape ======== template <typename T> Vector<typename Vector<T>::size_type> Vector<T>::shape() const { return Vector<size_type>(1, vec_.size()); } template <typename T> void Vector<T>::clear() { vec_.clear(); } template <typename T> bool Vector<T>::empty() const { return vec_.size() == 0; } // ======== Iterators ======== template <typename T> typename Vector<T>::iterator Vector<T>::begin() { return vec_.begin(); } template <typename T> typename Vector<T>::iterator Vector<T>::end() { return vec_.end(); } template <typename T> typename Vector<T>::const_iterator Vector<T>::begin() const { return vec_.cbegin(); } template <typename T> typename Vector<T>::const_iterator Vector<T>::end() const { return vec_.cend(); } template <typename T> typename Vector<T>::const_iterator Vector<T>::cbegin() const { return vec_.cbegin(); } template <typename T> typename Vector<T>::const_iterator Vector<T>::cend() const { return vec_.cend(); } template <typename T> typename Vector<T>::reverse_iterator Vector<T>::rbegin() { return vec_.rbegin(); } template <typename T> typename Vector<T>::reverse_iterator Vector<T>::rend() { return vec_.rend(); } template <typename T> typename Vector<T>::const_reverse_iterator Vector<T>::rbegin() const { return vec_.crbegin(); } template <typename T> typename Vector<T>::const_reverse_iterator Vector<T>::rend() const { return vec_.crend(); } template <typename T> typename Vector<T>::const_reverse_iterator Vector<T>::crbegin() const { return vec_.crbegin(); } template <typename T> typename Vector<T>::const_reverse_iterator Vector<T>::crend() const { return vec_.crend(); } // ======== Accessors ======== template <typename T> T& Vector<T>::operator[](const index_type& index) { exclusive_range_check_(index); return vec_.at(to_positive_index_(index)); } template <typename T> const T& Vector<T>::operator[](const index_type& index) const { exclusive_range_check_(index); return vec_.at(to_positive_index_(index)); } template <typename T> Vector<T> Vector<T>::operator()(const index_type& index) const { exclusive_range_check_(index); return Vector(1, vec_.at(to_positive_index_(index))); } template <typename T> Vector<T> Vector<T>::operator()(const const_iterator& cit) const { exclusive_range_check_(cit); return Vector(1, *cit); } template <typename T> Vector<T> Vector<T>::operator()(const index_type& idx_begin, const index_type& idx_end) const { exclusive_range_check_(idx_begin); inclusive_range_check_(idx_end); index_order_check_(idx_begin, idx_end); return Vector(std::vector<T>(vec_.begin() + to_positive_index_(idx_begin), vec_.begin() + to_positive_index_(idx_end))); } template <typename T> Vector<T> Vector<T>::operator()(const const_iterator& cit_begin, const const_iterator& cit_end) const { exclusive_range_check_(cit_begin); inclusive_range_check_(cit_end); const_iterator_order_check_(cit_begin, cit_end); return Vector(std::vector<T>(cit_begin, cit_end)); } // ======== Modifiers ======== template <typename T> Vector<T> Vector<T>::insert(const T& val_insert, const index_type& index) const { inclusive_range_check_(index); Vector vec_inserted = *this; vec_inserted.vec_.insert( vec_inserted.vec_.begin() + to_positive_index_(index), val_insert); return vec_inserted; } template <typename T> Vector<T> Vector<T>::insert(const T& val_insert, const const_iterator& cit) const { inclusive_range_check_(cit); return insert(val_insert, static_cast<index_type>(cit - vec_.cbegin())); } template <typename T> Vector<T> Vector<T>::insert(const Vector& vec_insert, const index_type& index) const { inclusive_range_check_(index); Vector vec_inserted = *this; vec_inserted.vec_.insert( vec_inserted.vec_.begin() + to_positive_index_(index), vec_insert.vec_.begin(), vec_insert.vec_.end()); return vec_inserted; } template <typename T> Vector<T> Vector<T>::insert(const Vector& vec_insert, const const_iterator& cit) const { inclusive_range_check_(cit); return insert(vec_insert, static_cast<index_type>(cit - vec_.cbegin())); } template <typename T> Vector<T> Vector<T>::remove(const index_type& index) const { exclusive_range_check_(index); Vector vec_removed = *this; vec_removed.vec_.erase(vec_removed.vec_.begin() + to_positive_index_(index)); return vec_removed; } template <typename T> Vector<T> Vector<T>::remove(const const_iterator& cit) const { exclusive_range_check_(cit); return remove(static_cast<size_type>(cit - vec_.cbegin())); } template <typename T> Vector<T> Vector<T>::remove(const index_type& idx_begin, const index_type& idx_end) const { exclusive_range_check_(idx_begin); inclusive_range_check_(idx_end); index_order_check_(idx_begin, idx_end); Vector vec_removed = *this; vec_removed.vec_.erase( vec_removed.vec_.begin() + to_positive_index_(idx_begin), vec_removed.vec_.begin() + to_positive_index_(idx_end)); return vec_removed; } template <typename T> Vector<T> Vector<T>::remove(const const_iterator& cit_begin, const const_iterator& cit_end) const { exclusive_range_check_(cit_begin); inclusive_range_check_(cit_end); const_iterator_order_check_(cit_begin, cit_end); return remove(static_cast<index_type>(cit_begin - vec_.cbegin()), static_cast<index_type>(cit_end - vec_.cbegin())); } template <typename T> Vector<T> Vector<T>::replace(const T& val_replace, const index_type& index) const { exclusive_range_check_(index); Vector vec_replaced = *this; vec_replaced.vec_.at(to_positive_index_(index)) = val_replace; return vec_replaced; } template <typename T> Vector<T> Vector<T>::replace(const T& val_replace, const const_iterator& cit) const { exclusive_range_check_(cit); return replace(val_replace, static_cast<index_type>(cit - vec_.cbegin())); } template <typename T> Vector<T> Vector<T>::replace(const Vector& vec_replace, const index_type& index) const { exclusive_range_check_(index); index_type pos_index = to_positive_index_(index); Vector vec_replaced = *this; for (index_type idx_rep = 0; idx_rep < vec_replace.vec_.size() && pos_index + idx_rep < vec_replaced.vec_.size(); ++idx_rep) { vec_replaced.vec_.at(pos_index + idx_rep) = vec_replace.vec_.at(idx_rep); } return vec_replaced; } template <typename T> Vector<T> Vector<T>::replace(const Vector& vec_replace, const const_iterator& cit) const { exclusive_range_check_(cit); return replace(vec_replace, static_cast<index_type>(cit - vec_.cbegin())); } template <typename T> Vector<T> Vector<T>::reshape(const size_type& size) const { std::vector<T> vec_cache = vec_; vec_cache.resize(size); return Vector(vec_cache); } template <typename T> Vector<T> Vector<T>::reverse() const { return Vector(std::vector<T>(vec_.crbegin(), vec_.crend())); } template <typename T> Vector<T> Vector<T>::shuffle() const { std::random_device rd; std::default_random_engine gen(rd()); Vector vec_shuffled = *this; std::shuffle(vec_shuffled.vec_.begin(), vec_shuffled.vec_.end(), gen); return vec_shuffled; } // ======== Arithmetic ======== // namespace internal namespace internal { #define OMP_FOR_3_PTR \ _Pragma("omp parallel for shared(ptr_lhs, ptr_rhs, ptr_ans) schedule(auto)") #define OMP_FOR_2_PTR_L_ANS \ _Pragma("omp parallel for shared(ptr_lhs, rhs, ptr_ans) schedule(auto)") #define OMP_FOR_2_PTR_R_ANS \ _Pragma("omp parallel for shared(lhs, ptr_rhs, ptr_ans) schedule(auto)") #define ARITHMETIC_VEC_VEC(OPERATION, OPERATOR) \ template <typename T> \ void OPERATION(const Vector<T>& lhs, const Vector<T>& rhs, \ Vector<T>& ans) { \ const typename Vector<T>::size_type size = ans.shape()[0]; \ const T* ptr_lhs = &lhs[0]; \ const T* ptr_rhs = &rhs[0]; \ T* ptr_ans = &ans[0]; \ for (typename Vector<T>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = ptr_lhs[idx] OPERATOR ptr_rhs[idx]; \ } \ } ARITHMETIC_VEC_VEC(add, +) ARITHMETIC_VEC_VEC(sub, -) ARITHMETIC_VEC_VEC(mul, *) ARITHMETIC_VEC_VEC(div, /) #undef ARITHMETIC_VEC_VEC #define ARITHMETIC_DOUBLE_VEC_VEC(OPERATION, OPERATOR, SSE_OPERATION) \ template <> \ void OPERATION<double>(const Vector<double>& lhs, const Vector<double>& rhs, \ Vector<double>& ans) { \ const Vector<double>::size_type size_c_to_c_omp_sse = 476; \ const Vector<double>::size_type size = ans.shape()[0]; \ const double* ptr_lhs = &lhs[0]; \ const double* ptr_rhs = &rhs[0]; \ double* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp_sse) { \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = ptr_lhs[idx] OPERATOR ptr_rhs[idx]; \ } \ } else { \ OMP_FOR_3_PTR \ for (Vector<double>::size_type idx = 0; idx < size / 2; ++idx) { \ _mm_store_pd(ptr_ans + 2 * idx, SSE_OPERATION( \ _mm_load_pd(ptr_lhs + 2 * idx), _mm_load_pd(ptr_rhs + 2 * idx))); \ } \ if (size % 2 != 0) { \ ptr_ans[size - 1] = ptr_lhs[size - 1] + ptr_rhs[size - 1]; \ } \ } \ } ARITHMETIC_DOUBLE_VEC_VEC(add, +, _mm_add_pd) ARITHMETIC_DOUBLE_VEC_VEC(sub, -, _mm_sub_pd) ARITHMETIC_DOUBLE_VEC_VEC(mul, *, _mm_mul_pd) ARITHMETIC_DOUBLE_VEC_VEC(div, /, _mm_div_pd) #undef ARITHMETIC_DOUBLE_VEC_VEC #define ARITHMETIC_FLOAT_VEC_VEC(OPERATION, OPERATOR, SSE_OPERATION) \ template <> \ void OPERATION<float>(const Vector<float>& lhs, const Vector<float>& rhs, \ Vector<float>& ans) { \ const Vector<float>::size_type size_c_sse_to_c_omp_sse = 826; \ const Vector<float>::size_type size = ans.shape()[0]; \ const float* ptr_lhs = &lhs[0]; \ const float* ptr_rhs = &rhs[0]; \ float* ptr_ans = &ans[0]; \ if (size < size_c_sse_to_c_omp_sse) { \ for (Vector<float>::size_type idx = 0; idx < size / 4; ++idx) { \ _mm_store_ps(ptr_ans + 4 * idx, SSE_OPERATION( \ _mm_load_ps(ptr_lhs + 4 * idx), _mm_load_ps(ptr_rhs + 4 * idx))); \ } \ } else { \ OMP_FOR_3_PTR \ for (Vector<float>::size_type idx = 0; idx < size / 4; ++idx) { \ _mm_store_ps(ptr_ans + 4 * idx, SSE_OPERATION( \ _mm_load_ps(ptr_lhs + 4 * idx), _mm_load_ps(ptr_rhs + 4 * idx))); \ } \ } \ if (size % 4 == 1) { \ ptr_ans[size - 1] = ptr_lhs[size - 1] OPERATOR ptr_rhs[size - 1]; \ } else if (size % 4 == 2) { \ ptr_ans[size - 2] = ptr_lhs[size - 2] OPERATOR ptr_rhs[size - 2]; \ ptr_ans[size - 1] = ptr_lhs[size - 1] OPERATOR ptr_rhs[size - 1]; \ } else if (size % 4 == 3) { \ ptr_ans[size - 3] = ptr_lhs[size - 3] OPERATOR ptr_rhs[size - 3]; \ ptr_ans[size - 2] = ptr_lhs[size - 2] OPERATOR ptr_rhs[size - 2]; \ ptr_ans[size - 1] = ptr_lhs[size - 1] OPERATOR ptr_rhs[size - 1]; \ } \ } ARITHMETIC_FLOAT_VEC_VEC(add, +, _mm_add_ps) ARITHMETIC_FLOAT_VEC_VEC(sub, -, _mm_sub_ps) ARITHMETIC_FLOAT_VEC_VEC(mul, *, _mm_mul_ps) ARITHMETIC_FLOAT_VEC_VEC(div, /, _mm_div_ps) #undef ARITHMETIC_FLOAT_VEC_VEC #define ARITHMETIC_VEC_SCA(OPERATION, OPERATOR) \ template <typename T> \ void OPERATION(const Vector<T>& lhs, const T& rhs, \ Vector<T>& ans) { \ const typename Vector<T>::size_type size = ans.shape()[0]; \ const T* ptr_lhs = &lhs[0]; \ T* ptr_ans = &ans[0]; \ for (typename Vector<T>::index_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = ptr_lhs[idx] OPERATOR rhs; \ } \ } ARITHMETIC_VEC_SCA(add, +) ARITHMETIC_VEC_SCA(sub, -) ARITHMETIC_VEC_SCA(mul, *) ARITHMETIC_VEC_SCA(div, /) #undef ARITHMETIC_VEC_SCA #define ARITHMETIC_DOUBLE_VEC_SCA(OPERATION, OPERATOR, SSE_OPERATION) \ template <> \ void OPERATION<double>(const Vector<double>& lhs, const double& rhs, \ Vector<double>& ans) { \ const Vector<double>::size_type size_c_to_c_omp = 595; \ const Vector<double>::size_type size_c_omp_to_c_omp_sse = 6726; \ const Vector<double>::size_type size = ans.shape()[0]; \ const double* ptr_lhs = &lhs[0]; \ double* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp) { \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = ptr_lhs[idx] OPERATOR rhs; \ } \ } else if (size < size_c_omp_to_c_omp_sse) { \ OMP_FOR_2_PTR_L_ANS \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = ptr_lhs[idx] OPERATOR rhs; \ } \ } else { \ const double* ptr_rhs = &rhs; \ OMP_FOR_3_PTR \ for (Vector<double>::size_type idx = 0; idx < size / 2; ++idx) { \ _mm_store_pd(ptr_ans + 2 * idx, SSE_OPERATION( \ _mm_load_pd(ptr_lhs + 2 * idx), _mm_load1_pd(ptr_rhs))); \ } \ if (size % 2 != 0) { \ ptr_ans[size - 1] = ptr_lhs[size - 1] OPERATOR rhs; \ } \ }\ } ARITHMETIC_DOUBLE_VEC_SCA(add, +, _mm_add_pd) ARITHMETIC_DOUBLE_VEC_SCA(sub, -, _mm_sub_pd) ARITHMETIC_DOUBLE_VEC_SCA(mul, *, _mm_mul_pd) ARITHMETIC_DOUBLE_VEC_SCA(div, /, _mm_div_pd) #undef ARITHMETIC_DOUBLE_VEC_SCA #define ARITHMETIC_FLOAT_VEC_SCA(OPERATION, OPERATOR, SSE_OPERATION) \ template <> \ void OPERATION<float>(const Vector<float>& lhs, const float& rhs, \ Vector<float>& ans) { \ const Vector<float>::size_type size_c_sse_to_c_omp_sse = 917; \ const Vector<float>::size_type size = ans.shape()[0]; \ const float* ptr_lhs = &lhs[0]; \ const float* ptr_rhs = &rhs; \ float* ptr_ans = &ans[0]; \ if (size < size_c_sse_to_c_omp_sse) { \ for (Vector<float>::size_type idx = 0; idx < size / 4; ++idx) { \ _mm_store_ps(ptr_ans + 4 * idx, SSE_OPERATION( \ _mm_load_ps(ptr_lhs + 4 * idx), _mm_load1_ps(ptr_rhs))); \ } \ } else { \ OMP_FOR_3_PTR \ for (Vector<float>::size_type idx = 0; idx < size / 4; ++idx) { \ _mm_store_ps(ptr_ans + 4 * idx, SSE_OPERATION( \ _mm_load_ps(ptr_lhs + 4 * idx), _mm_load1_ps(ptr_rhs))); \ } \ } \ if (size % 4 == 1) { \ ptr_ans[size - 1] = ptr_lhs[size - 1] OPERATOR rhs; \ } else if (size % 4 == 2) { \ ptr_ans[size - 2] = ptr_lhs[size - 2] OPERATOR rhs; \ ptr_ans[size - 1] = ptr_lhs[size - 1] OPERATOR rhs; \ } else if (size % 4 == 3) { \ ptr_ans[size - 3] = ptr_lhs[size - 3] OPERATOR rhs; \ ptr_ans[size - 2] = ptr_lhs[size - 2] OPERATOR rhs; \ ptr_ans[size - 1] = ptr_lhs[size - 1] OPERATOR rhs; \ } \ } ARITHMETIC_FLOAT_VEC_SCA(add, +, _mm_add_ps) ARITHMETIC_FLOAT_VEC_SCA(sub, -, _mm_sub_ps) ARITHMETIC_FLOAT_VEC_SCA(mul, *, _mm_mul_ps) ARITHMETIC_FLOAT_VEC_SCA(div, /, _mm_div_ps) #undef ARITHMETIC_FLOAT_VEC_SCA #define ARITHMETIC_SCA_VEC(OPERATION, OPERATOR) \ template <typename T> \ void OPERATION(const T& lhs, const Vector<T>& rhs, \ Vector<T>& ans) { \ const typename Vector<T>::size_type size = ans.shape()[0]; \ const T* ptr_rhs = &rhs[0]; \ T* ptr_ans = &ans[0]; \ for (typename Vector<T>::index_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = lhs OPERATOR ptr_rhs[idx]; \ } \ } ARITHMETIC_SCA_VEC(add, +) ARITHMETIC_SCA_VEC(sub, -) ARITHMETIC_SCA_VEC(mul, *) ARITHMETIC_SCA_VEC(div, /) #undef ARITHMETIC_SCA_VEC #define ARITHMETIC_DOUBLE_SCA_VEC(OPERATION, OPERATOR, SSE_OPERATION) \ template <> \ void OPERATION<double>(const double& lhs, const Vector<double>& rhs, \ Vector<double>& ans) { \ const Vector<double>::size_type size_c_to_c_omp = 595; \ const Vector<double>::size_type size_c_omp_to_c_omp_sse = 6726; \ const Vector<double>::size_type size = ans.shape()[0]; \ const double* ptr_rhs = &rhs[0]; \ double* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp) { \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = lhs OPERATOR ptr_rhs[idx]; \ } \ } else if (size < size_c_omp_to_c_omp_sse) { \ OMP_FOR_2_PTR_R_ANS \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = lhs OPERATOR ptr_rhs[idx]; \ } \ } else { \ const double* ptr_lhs = &lhs; \ OMP_FOR_3_PTR \ for (Vector<double>::size_type idx = 0; idx < size / 2; ++idx) { \ _mm_store_pd(ptr_ans + 2 * idx, SSE_OPERATION( \ _mm_load1_pd(ptr_lhs), _mm_load_pd(ptr_rhs + 2 * idx))); \ } \ if (size % 2 != 0) { \ ptr_ans[size - 1] = lhs OPERATOR ptr_rhs[size - 1]; \ } \ }\ } ARITHMETIC_DOUBLE_SCA_VEC(add, +, _mm_add_pd) ARITHMETIC_DOUBLE_SCA_VEC(sub, -, _mm_sub_pd) ARITHMETIC_DOUBLE_SCA_VEC(mul, *, _mm_mul_pd) ARITHMETIC_DOUBLE_SCA_VEC(div, /, _mm_div_pd) #undef ARITHMETIC_DOUBLE_SCA_VEC #define ARITHMETIC_FLOAT_SCA_VEC(OPERATION, OPERATOR, SSE_OPERATION) \ template <> \ void OPERATION<float>(const float& lhs, const Vector<float>& rhs, \ Vector<float>& ans) { \ const Vector<float>::size_type size_c_sse_to_c_omp_sse = 917; \ const Vector<float>::size_type size = ans.shape()[0]; \ const float* ptr_lhs = &lhs; \ const float* ptr_rhs = &rhs[0]; \ float* ptr_ans = &ans[0]; \ if (size < size_c_sse_to_c_omp_sse) { \ for (Vector<float>::size_type idx = 0; idx < size / 4; ++idx) { \ _mm_store_ps(ptr_ans + 4 * idx, SSE_OPERATION( \ _mm_load1_ps(ptr_lhs), _mm_load_ps(ptr_rhs + 4 * idx))); \ } \ } else { \ OMP_FOR_3_PTR \ for (Vector<float>::size_type idx = 0; idx < size / 4; ++idx) { \ _mm_store_ps(ptr_ans + 4 * idx, SSE_OPERATION( \ _mm_load1_ps(ptr_lhs), _mm_load_ps(ptr_rhs + 4 * idx))); \ } \ } \ if (size % 4 == 1) { \ ptr_ans[size - 1] = lhs OPERATOR ptr_rhs[size - 1]; \ } else if (size % 4 == 2) { \ ptr_ans[size - 2] = lhs OPERATOR ptr_rhs[size - 2]; \ ptr_ans[size - 1] = lhs OPERATOR ptr_rhs[size - 1]; \ } else if (size % 4 == 3) { \ ptr_ans[size - 3] = lhs OPERATOR ptr_rhs[size - 3]; \ ptr_ans[size - 2] = lhs OPERATOR ptr_rhs[size - 2]; \ ptr_ans[size - 1] = lhs OPERATOR ptr_rhs[size - 1]; \ } \ } ARITHMETIC_FLOAT_SCA_VEC(add, +, _mm_add_ps) ARITHMETIC_FLOAT_SCA_VEC(sub, -, _mm_sub_ps) ARITHMETIC_FLOAT_SCA_VEC(mul, *, _mm_mul_ps) ARITHMETIC_FLOAT_SCA_VEC(div, /, _mm_div_ps) #undef ARITHMETIC_FLOAT_SCA_VEC template <typename T> void sum(const Vector<T>& v, T& s) { const typename Vector<T>::size_type size = v.shape()[0]; const T* ptr = &v[0]; s = T(); for (typename Vector<T>::size_type idx = 0; idx < size; ++idx) { s = s + ptr[idx]; } } template <> void sum<double>(const Vector<double>& v, double& s) { const Vector<double>::size_type size_c_to_c_sse = 18; const Vector<double>::size_type size_c_sse_to_c_omp = 856; const Vector<double>::size_type size = v.shape()[0]; const double* ptr = &v[0]; s = 0.0; if (size < size_c_to_c_sse) { for (Vector<double>::size_type idx = 0; idx < size; ++idx) { s = s + ptr[idx]; } } else if (size < size_c_sse_to_c_omp) { __m128d s_reg = _mm_set1_pd(0.0); for (Vector<double>::size_type idx = 0; idx < size / 2; ++idx) { s_reg = _mm_add_pd(s_reg, _mm_load_pd(ptr + 2 * idx)); } s_reg = _mm_hadd_pd(s_reg, s_reg); _mm_store_sd(&s, s_reg); if (size % 2 != 0) { s = s + ptr[size - 1]; } } else { #pragma omp parallel for schedule(auto) reduction(+ : s) for (Vector<double>::size_type idx = 0; idx < size; ++idx) { s = s + ptr[idx]; } } } template <> void sum<float>(const Vector<float>& v, float& s) { const Vector<float>::size_type size_c_to_c_sse = 10; const Vector<float>::size_type size = v.shape()[0]; const float* ptr = &v[0]; s = 0.0; if (size < size_c_to_c_sse) { for (Vector<float>::size_type idx = 0; idx < size; ++idx) { s = s + ptr[idx]; } } else { __m128 s_reg = _mm_set1_ps(0.0); for (std::size_t idx = 0; idx < size / 4; ++idx) { s_reg = _mm_add_ps(s_reg, _mm_load_ps(ptr + 4 * idx)); } s_reg = _mm_hadd_ps(s_reg, s_reg); s_reg = _mm_hadd_ps(s_reg, s_reg); _mm_store_ss(&s, s_reg); if (size % 4 == 1) { s = s + ptr[size - 1]; } else if (size % 4 == 2) { s = s + ptr[size - 1] + ptr[size - 2]; } else if (size % 4 == 3) { s = s + ptr[size - 1] + ptr[size - 2] + ptr[size - 3]; } } } } // namespace internal template <typename AriT> Vector<AriT> operator+(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<AriT> vec_sum(vec_lhs.shape()[0]); internal::add(vec_lhs, vec_rhs, vec_sum); return vec_sum; } template <typename AriT> Vector<AriT> operator+(const Vector<AriT>& vec_lhs, const AriT& val_rhs) { Vector<AriT> vec_sum(vec_lhs.shape()[0]); internal::add(vec_lhs, val_rhs, vec_sum); return vec_sum; } template <typename AriT> Vector<AriT> operator+(const AriT& val_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT> vec_sum(vec_rhs.shape()[0]); internal::add(val_lhs, vec_rhs, vec_sum); return vec_sum; } template <typename AriT> Vector<AriT> operator-(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<AriT> vec_diff(vec_lhs.shape()[0]); internal::sub(vec_lhs, vec_rhs, vec_diff); return vec_diff; } template <typename AriT> Vector<AriT> operator-(const Vector<AriT>& vec_lhs, const AriT& val_rhs) { Vector<AriT> vec_diff(vec_lhs.shape()[0]); internal::sub(vec_lhs, val_rhs, vec_diff); return vec_diff; } template <typename AriT> Vector<AriT> operator-(const AriT& val_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT> vec_diff(vec_rhs.shape()[0]); internal::sub(val_lhs, vec_rhs, vec_diff); return vec_diff; } template <typename AriT> Vector<AriT> operator*(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<AriT> vec_prod(vec_lhs.shape()[0]); internal::mul(vec_lhs, vec_rhs, vec_prod); return vec_prod; } template <typename AriT> Vector<AriT> operator*(const Vector<AriT>& vec_lhs, const AriT& val_rhs) { Vector<AriT> vec_prod(vec_lhs.shape()[0]); internal::mul(vec_lhs, val_rhs, vec_prod); return vec_prod; } template <typename AriT> Vector<AriT> operator*(const AriT& val_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT> vec_prod(vec_rhs.shape()[0]); internal::mul(val_lhs, vec_rhs, vec_prod); return vec_prod; } template <typename AriT> Vector<AriT> operator/(const Vector<AriT>& vec_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<AriT> vec_quot(vec_lhs.shape()[0]); internal::div(vec_lhs, vec_rhs, vec_quot); return vec_quot; } template <typename AriT> Vector<AriT> operator/(const Vector<AriT>& vec_lhs, const AriT& val_rhs) { Vector<AriT> vec_quot(vec_lhs.shape()[0]); internal::div(vec_lhs, val_rhs, vec_quot); return vec_quot; } template <typename AriT> Vector<AriT> operator/(const AriT& val_lhs, const Vector<AriT>& vec_rhs) { Vector<AriT> vec_quot(vec_rhs.shape()[0]); internal::div(val_lhs, vec_rhs, vec_quot); return vec_quot; } template <typename T> void Vector<T>::operator+=(const Vector<T>& vec_rhs) { (*this) = (*this) + vec_rhs; } template <typename T> void Vector<T>::operator+=(const T& val_rhs) { (*this) = (*this) + val_rhs; } template <typename T> void Vector<T>::operator-=(const Vector<T>& vec_rhs) { (*this) = (*this) - vec_rhs; } template <typename T> void Vector<T>::operator-=(const T& val_rhs) { (*this) = (*this) - val_rhs; } template <typename T> void Vector<T>::operator*=(const Vector<T>& vec_rhs) { (*this) = (*this) * vec_rhs; } template <typename T> void Vector<T>::operator*=(const T& val_rhs) { (*this) = (*this) * val_rhs; } template <typename T> void Vector<T>::operator/=(const Vector<T>& vec_rhs) { (*this) = (*this) / vec_rhs; } template <typename T> void Vector<T>::operator/=(const T& val_rhs) { (*this) = (*this) / val_rhs; } template <typename T> T Vector<T>::sum() const { T sum_res = T(); internal::sum(*this, sum_res); return sum_res; } // ======== Comparisons ======== // namespace internal namespace internal { #define COMPARISON_VEC_VEC(OPERATION, OPERATOR) \ template <typename T> \ void OPERATION(const Vector<T>& lhs, const Vector<T>& rhs, \ Vector<T>& ans) { \ const typename Vector<T>::size_type size = ans.shape()[0]; \ const T* ptr_lhs = &lhs[0]; \ const T* ptr_rhs = &rhs[0]; \ T* ptr_ans = &ans[0]; \ for (typename Vector<T>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<T>(ptr_lhs[idx] OPERATOR ptr_rhs[idx]); \ } \ } COMPARISON_VEC_VEC(equal, ==) COMPARISON_VEC_VEC(nequal, !=) COMPARISON_VEC_VEC(less, <) COMPARISON_VEC_VEC(leq, <=) COMPARISON_VEC_VEC(greater, >) COMPARISON_VEC_VEC(geq, >=) #undef COMPARISON_VEC_VEC #define COMPARISON_DOUBLE_VEC_VEC(OPERATION, OPERATOR) \ template <> \ void OPERATION<double>(const Vector<double>& lhs, const Vector<double>& rhs, \ Vector<double>& ans) { \ const Vector<double>::size_type size_c_to_c_omp = 550; \ const Vector<double>::size_type size_c_omp_to_c = 3600; \ const Vector<double>::size_type size = ans.shape()[0]; \ const double* ptr_lhs = &lhs[0]; \ const double* ptr_rhs = &rhs[0]; \ double* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp || size >= size_c_omp_to_c) { \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<double>(ptr_lhs[idx] OPERATOR ptr_rhs[idx]); \ } \ } else { \ OMP_FOR_3_PTR \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<double>(ptr_lhs[idx] OPERATOR ptr_rhs[idx]); \ } \ } \ } COMPARISON_DOUBLE_VEC_VEC(equal, ==) COMPARISON_DOUBLE_VEC_VEC(nequal, !=) COMPARISON_DOUBLE_VEC_VEC(less, <) COMPARISON_DOUBLE_VEC_VEC(leq, <=) COMPARISON_DOUBLE_VEC_VEC(greater, >) COMPARISON_DOUBLE_VEC_VEC(geq, >=) #undef COMPARISON_DOUBLE_VEC_VEC #define COMPARISON_FLOAT_VEC_VEC(OPERATION, OPERATOR) \ template <> \ void OPERATION<float>(const Vector<float>& lhs, const Vector<float>& rhs, \ Vector<float>& ans) { \ const Vector<float>::size_type size_c_to_c_omp = 452; \ const Vector<float>::size_type size_c_omp_to_c = 4098; \ const Vector<float>::size_type size = ans.shape()[0]; \ const float* ptr_lhs = &lhs[0]; \ const float* ptr_rhs = &rhs[0]; \ float* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp || size >= size_c_omp_to_c) { \ for (Vector<float>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<float>(ptr_lhs[idx] OPERATOR ptr_rhs[idx]); \ } \ } else { \ OMP_FOR_3_PTR \ for (Vector<float>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<float>(ptr_lhs[idx] OPERATOR ptr_rhs[idx]); \ } \ } \ } COMPARISON_FLOAT_VEC_VEC(equal, ==) COMPARISON_FLOAT_VEC_VEC(nequal, !=) COMPARISON_FLOAT_VEC_VEC(less, <) COMPARISON_FLOAT_VEC_VEC(leq, <=) COMPARISON_FLOAT_VEC_VEC(greater, >) COMPARISON_FLOAT_VEC_VEC(geq, >=) #undef COMPARISON_FLOAT_VEC_VEC #define COMPARISON_VEC_SCA(OPERATION, OPERATOR) \ template <typename T> \ void OPERATION(const Vector<T>& lhs, const T& rhs, Vector<T>& ans) {\ const typename Vector<T>::size_type size = ans.shape()[0]; \ const T* ptr_lhs = &lhs[0]; \ T* ptr_ans = &ans[0]; \ for (typename Vector<T>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<T>(ptr_lhs[idx] OPERATOR rhs); \ } \ } COMPARISON_VEC_SCA(equal, ==) COMPARISON_VEC_SCA(nequal, !=) COMPARISON_VEC_SCA(less, <) COMPARISON_VEC_SCA(leq, <=) COMPARISON_VEC_SCA(greater, >) COMPARISON_VEC_SCA(geq, >=) #undef COMPARISON_VEC_SCA #define COMPARISON_DOUBLE_VEC_SCA(OPERATION, OPERATOR) \ template <> \ void OPERATION<double>(const Vector<double>& lhs, const double& rhs, \ Vector<double>& ans) { \ const Vector<double>::size_type size_c_to_c_omp = 554; \ const Vector<double>::size_type size_c_omp_to_c = 7170; \ const Vector<double>::size_type size = ans.shape()[0]; \ const double* ptr_lhs = &lhs[0]; \ double* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp || size >= size_c_omp_to_c) { \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<double>(ptr_lhs[idx] OPERATOR rhs); \ } \ } else { \ OMP_FOR_2_PTR_L_ANS \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<double>(ptr_lhs[idx] OPERATOR rhs); \ } \ } \ } COMPARISON_DOUBLE_VEC_SCA(equal, ==) COMPARISON_DOUBLE_VEC_SCA(nequal, !=) COMPARISON_DOUBLE_VEC_SCA(less, <) COMPARISON_DOUBLE_VEC_SCA(leq, <=) COMPARISON_DOUBLE_VEC_SCA(greater, >) COMPARISON_DOUBLE_VEC_SCA(geq, >=) #undef COMPARISON_DOUBLE_VEC_SCA #define COMPARISON_FLOAT_VEC_SCA(OPERATION, OPERATOR) \ template <> \ void OPERATION<float>(const Vector<float>& lhs, const float& rhs, \ Vector<float>& ans) { \ const Vector<float>::size_type size_c_to_c_omp = 514; \ const Vector<float>::size_type size_c_omp_to_c = 7243; \ const Vector<float>::size_type size = ans.shape()[0]; \ const float* ptr_lhs = &lhs[0]; \ float* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp || size >= size_c_omp_to_c) { \ for (Vector<float>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<float>(ptr_lhs[idx] OPERATOR rhs); \ } \ } else { \ OMP_FOR_2_PTR_L_ANS \ for (Vector<float>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<float>(ptr_lhs[idx] OPERATOR rhs); \ } \ } \ } COMPARISON_FLOAT_VEC_SCA(equal, ==) COMPARISON_FLOAT_VEC_SCA(nequal, !=) COMPARISON_FLOAT_VEC_SCA(less, <) COMPARISON_FLOAT_VEC_SCA(leq, <=) COMPARISON_FLOAT_VEC_SCA(greater, >) COMPARISON_FLOAT_VEC_SCA(geq, >=) #undef COMPARISON_FLOAT_VEC_SCA #define COMPARISON_SCA_VEC(OPERATION, OPERATOR) \ template <typename T> \ void OPERATION(const T& lhs, const Vector<T>& rhs, Vector<T>& ans) {\ const typename Vector<T>::size_type size = ans.shape()[0]; \ const T* ptr_rhs = &rhs[0]; \ T* ptr_ans = &ans[0]; \ for (typename Vector<T>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<T>(lhs OPERATOR ptr_rhs[idx]); \ } \ } COMPARISON_SCA_VEC(equal, ==) COMPARISON_SCA_VEC(nequal, !=) COMPARISON_SCA_VEC(less, <) COMPARISON_SCA_VEC(leq, <=) COMPARISON_SCA_VEC(greater, >) COMPARISON_SCA_VEC(geq, >=) #undef COMPARISON_SCA_VEC #define COMPARISON_DOUBLE_SCA_VEC(OPERATION, OPERATOR) \ template <> \ void OPERATION<double>(const double& lhs, const Vector<double>& rhs, \ Vector<double>& ans) { \ const Vector<double>::size_type size_c_to_c_omp = 554; \ const Vector<double>::size_type size_c_omp_to_c = 7170; \ const Vector<double>::size_type size = ans.shape()[0]; \ const double* ptr_rhs = &rhs[0]; \ double* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp || size >= size_c_omp_to_c) { \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<double>(lhs OPERATOR ptr_rhs[idx]); \ } \ } else { \ OMP_FOR_2_PTR_R_ANS \ for (Vector<double>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<double>(lhs OPERATOR ptr_rhs[idx]); \ } \ } \ } COMPARISON_DOUBLE_SCA_VEC(equal, ==) COMPARISON_DOUBLE_SCA_VEC(nequal, !=) COMPARISON_DOUBLE_SCA_VEC(less, <) COMPARISON_DOUBLE_SCA_VEC(leq, <=) COMPARISON_DOUBLE_SCA_VEC(greater, >) COMPARISON_DOUBLE_SCA_VEC(geq, >=) #undef COMPARISON_DOUBLE_SCA_VEC #define COMPARISON_FLOAT_SCA_VEC(OPERATION, OPERATOR) \ template <> \ void OPERATION<float>(const float& lhs, const Vector<float>& rhs, \ Vector<float>& ans) { \ const Vector<float>::size_type size_c_to_c_omp = 514; \ const Vector<float>::size_type size_c_omp_to_c = 7243; \ const Vector<float>::size_type size = ans.shape()[0]; \ const float* ptr_rhs = &rhs[0]; \ float* ptr_ans = &ans[0]; \ if (size < size_c_to_c_omp || size >= size_c_omp_to_c) { \ for (Vector<float>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<float>(lhs OPERATOR ptr_rhs[idx]); \ } \ } else { \ OMP_FOR_2_PTR_R_ANS \ for (Vector<float>::size_type idx = 0; idx < size; ++idx) { \ ptr_ans[idx] = static_cast<float>(lhs OPERATOR ptr_rhs[idx]); \ } \ } \ } COMPARISON_FLOAT_SCA_VEC(equal, ==) COMPARISON_FLOAT_SCA_VEC(nequal, !=) COMPARISON_FLOAT_SCA_VEC(less, <) COMPARISON_FLOAT_SCA_VEC(leq, <=) COMPARISON_FLOAT_SCA_VEC(greater, >) COMPARISON_FLOAT_SCA_VEC(geq, >=) #undef COMPARISON_FLOAT_SCA_VEC } // namespace internal template <typename CmpT> Vector<CmpT> operator==(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<CmpT> vec_eq(vec_lhs.shape()[0]); internal::equal(vec_lhs, vec_rhs, vec_eq); return vec_eq; } template <typename CmpT> Vector<CmpT> operator==(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs) { Vector<CmpT> vec_eq(vec_lhs.shape()[0]); internal::equal(vec_lhs, val_rhs, vec_eq); return vec_eq; } template <typename CmpT> Vector<CmpT> operator==(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT> vec_eq(vec_rhs.shape()[0]); internal::equal(val_lhs, vec_rhs, vec_eq); return vec_eq; } template <typename CmpT> Vector<CmpT> operator!=(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<CmpT> vec_neq(vec_lhs.shape()[0]); internal::nequal(vec_lhs, vec_rhs, vec_neq); return vec_neq; } template <typename CmpT> Vector<CmpT> operator!=(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs) { Vector<CmpT> vec_neq(vec_lhs.shape()[0]); internal::nequal(vec_lhs, val_rhs, vec_neq); return vec_neq; } template <typename CmpT> Vector<CmpT> operator!=(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT> vec_neq(vec_rhs.shape()[0]); internal::nequal(val_lhs, vec_rhs, vec_neq); return vec_neq; } template <typename CmpT> Vector<CmpT> operator<(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<CmpT> vec_le(vec_lhs.shape()[0]); internal::less(vec_lhs, vec_rhs, vec_le); return vec_le; } template <typename CmpT> Vector<CmpT> operator<(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs) { Vector<CmpT> vec_le(vec_lhs.shape()[0]); internal::less(vec_lhs, val_rhs, vec_le); return vec_le; } template <typename CmpT> Vector<CmpT> operator<(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT> vec_le(vec_rhs.shape()[0]); internal::less(val_lhs, vec_rhs, vec_le); return vec_le; } template <typename CmpT> Vector<CmpT> operator<=(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<CmpT> vec_leq(vec_lhs.shape()[0]); internal::leq(vec_lhs, vec_rhs, vec_leq); return vec_leq; } template <typename CmpT> Vector<CmpT> operator<=(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs) { Vector<CmpT> vec_leq(vec_lhs.shape()[0]); internal::leq(vec_lhs, val_rhs, vec_leq); return vec_leq; } template <typename CmpT> Vector<CmpT> operator<=(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT> vec_leq(vec_rhs.shape()[0]); internal::leq(val_lhs, vec_rhs, vec_leq); return vec_leq; } template <typename CmpT> Vector<CmpT> operator>(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<CmpT> vec_ge(vec_lhs.shape()[0]); internal::greater(vec_lhs, vec_rhs, vec_ge); return vec_ge; } template <typename CmpT> Vector<CmpT> operator>(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs) { Vector<CmpT> vec_ge(vec_lhs.shape()[0]); internal::greater(vec_lhs, val_rhs, vec_ge); return vec_ge; } template <typename CmpT> Vector<CmpT> operator>(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT> vec_ge(vec_rhs.shape()[0]); internal::greater(val_lhs, vec_rhs, vec_ge); return vec_ge; } template <typename CmpT> Vector<CmpT> operator>=(const Vector<CmpT>& vec_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT>::shape_consistence_check_(vec_lhs.shape(), vec_rhs.shape()); Vector<CmpT> vec_geq(vec_lhs.shape()[0]); internal::geq(vec_lhs, vec_rhs, vec_geq); return vec_geq; } template <typename CmpT> Vector<CmpT> operator>=(const Vector<CmpT>& vec_lhs, const CmpT& val_rhs) { Vector<CmpT> vec_geq(vec_lhs.shape()[0]); internal::geq(vec_lhs, val_rhs, vec_geq); return vec_geq; } template <typename CmpT> Vector<CmpT> operator>=(const CmpT& val_lhs, const Vector<CmpT>& vec_rhs) { Vector<CmpT> vec_geq(vec_rhs.shape()[0]); internal::geq(val_lhs, vec_rhs, vec_geq); return vec_geq; } // namespace internal namespace internal { template <typename T> bool fequal(const T& x, const T& y, std::size_t ulp) { return std::fabs(x - y) <= ulp * std::numeric_limits<T>::epsilon() * std::fabs((x + y) / 2.0) || std::fabs(x - y) <= std::numeric_limits<T>::min(); } template <typename T> bool is_equal(const Vector<T>& vec_lhs, const Vector<T>& vec_rhs, std::size_t ulp = 1) { const typename Vector<T>::size_type size = vec_lhs.shape()[0]; const T* ptr_lhs = &vec_lhs[0]; const T* ptr_rhs = &vec_rhs[0]; if (std::is_floating_point<T>::value) { for (typename Vector<T>::size_type idx = 0; idx < size; ++idx) { if (!fequal(ptr_lhs[idx], ptr_rhs[idx], ulp)) { return false; } } } else { for (typename Vector<T>::size_type idx = 0; idx < size; ++idx) { if (ptr_lhs[idx] != ptr_rhs[idx]) { return false; } } } return true; } } // namespace internal template <typename T> bool Vector<T>::equal(const Vector& vec_rhs, std::size_t ulp) { if (shape()[0] != vec_rhs.shape()[0]) { return false; } if (shape()[0] == 0 && vec_rhs.shape()[0] == 0) { return true; } return internal::is_equal(*this, vec_rhs, ulp); } template <typename T> bool Vector<T>::nequal(const Vector& vec_rhs, std::size_t ulp) { return !equal(vec_rhs, ulp); } // namespace internal namespace internal { template <typename T> void max(const Vector<T>& v, T& m) { typename Vector<T>::size_type size = v.shape()[0]; const T* ptr = &v[0]; m = ptr[0]; for (typename Vector<T>::size_type idx = 1; idx < size; ++idx) { if (ptr[idx] > m) { m = ptr[idx]; } } } template <typename T> void min(const Vector<T>& v, T& m) { typename Vector<T>::size_type size = v.shape()[0]; const T* ptr = &v[0]; m = ptr[0]; for (typename Vector<T>::size_type idx = 1; idx < size; ++idx) { if (ptr[idx] < m) { m = ptr[idx]; } } } } // namespace internal template <typename T> T Vector<T>::max() const { T max_val; internal::max(*this, max_val); return max_val; } template <typename T> T Vector<T>::min() const { T min_val; internal::min(*this, min_val); return min_val; } // ======== IO ======== template <typename VecT, typename CharT, typename Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const Vector<VecT>& vec) { if (vec.shape()[0] == 0) { os << "[]"; return os; } os << "["; for (typename Vector<VecT>::size_type idx = 0; idx < vec.shape()[0] - 1; ++idx) { os << vec[idx] << ", "; } os << vec[vec.shape()[0] - 1] << "]"; return os; } template <typename VecT, typename CharT, typename Traits> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, Vector<VecT>& vec) { if (vec.vec_.size() == 0) { VecT element; while (is >> element) { vec.vec_.push_back(element); } } else { for (VecT& element : vec.vec_) { is >> element; } } return is; } // ======== Helper Functions ======== template <typename T> bool Vector<T>::fequal_(const T& x, const T& y, std::size_t ulp) { // static_assert(std::is_floating_point<T>::value, // "Vector<T>::fequal_ only compares floating point numbers."); return std::fabs(x - y) <= ulp * std::numeric_limits<T>::epsilon() * std::fabs((x + y) / 2.0) || std::fabs(x - y) <= std::numeric_limits<T>::min(); } template <typename T> typename Vector<T>::index_type Vector<T>::to_positive_index_( const size_type& size, const index_type& index) { return index >= 0 ? index : size + index; } template <typename T> void Vector<T>::exclusive_range_check_(const size_type& size, const index_type& index) { size_type pos_index = to_positive_index_(size, index); if (pos_index >= size) { std::string err_msg = "Out-of-Range: index " + std::to_string(index) + " is out of range [0, " + std::to_string(size) + ")."; throw VectorException(err_msg); } } template <typename T> void Vector<T>::exclusive_range_check_(const iterator& it_begin, const iterator& it_end, const iterator& it) { if (it < it_begin || it >= it_end) { std::string err_msg = "Out-of-Range: iterator is out of the range [begin(), end())."; throw VectorException(err_msg); } } template <typename T> void Vector<T>::exclusive_range_check_(const const_iterator& cit_begin, const const_iterator& cit_end, const const_iterator& cit) { if (cit < cit_begin || cit >= cit_end) { std::string err_msg = "Out-of-Range: const_iterator is out of the range [begin(), end())."; throw VectorException(err_msg); } } template <typename T> void Vector<T>::inclusive_range_check_(const size_type& size, const index_type& index) { size_type pos_index = to_positive_index_(size, index); if (pos_index > size) { std::string err_msg = "Out-of-Range: index " + std::to_string(index) + " is out of range [0, " + std::to_string(size) + "]."; throw VectorException(err_msg); } } template <typename T> void Vector<T>::inclusive_range_check_(const iterator& it_begin, const iterator& it_end, const iterator& it) { if (it < it_begin || it > it_end) { std::string err_msg = "Out-of-Range: iterator is out of the range [begin(), end()]."; throw VectorException(err_msg); } } template <typename T> void Vector<T>::inclusive_range_check_(const const_iterator& cit_begin, const const_iterator& cit_end, const const_iterator& cit) { if (cit < cit_begin || cit > cit_end) { std::string err_msg = "Out-of-Range: const_iterator is out of the range [cbegin(), cend()]."; throw VectorException(err_msg); } } template <typename T> void Vector<T>::shape_consistence_check_(const Vector<size_type>& shape_lhs, const Vector<size_type>& shape_rhs) { if (shape_lhs[0] != shape_rhs[0]) { std::string err_msg = "Inconsistent shape: [" + std::to_string(shape_lhs[0]) + "] != [" + std::to_string(shape_rhs[0]) + "]."; throw VectorException(err_msg); } } template <typename T> void Vector<T>::index_order_check_(const size_type& size, const index_type& idx_begin, const index_type& idx_end) { if (to_positive_index_(size, idx_begin) > to_positive_index_(size, idx_end)) { std::string err_msg = "Invalid Index Order: begin " + std::to_string(to_positive_index_(size, idx_begin)) + " > end " + std::to_string(to_positive_index_(size, idx_end)) + "."; throw VectorException(err_msg); } } template <typename T> typename Vector<T>::index_type Vector<T>::to_positive_index_( const index_type& index) const { return to_positive_index_(vec_.size(), index); } template <typename T> void Vector<T>::exclusive_range_check_(const index_type& index) const { exclusive_range_check_(vec_.size(), index); } template <typename T> void Vector<T>::exclusive_range_check_(const iterator& it) { exclusive_range_check_(begin(), end(), it); } template <typename T> void Vector<T>::exclusive_range_check_(const const_iterator& cit) const { exclusive_range_check_(cbegin(), cend(), cit); } template <typename T> void Vector<T>::inclusive_range_check_(const index_type& index) const { inclusive_range_check_(vec_.size(), index); } template <typename T> void Vector<T>::inclusive_range_check_(const iterator& it) { inclusive_range_check_(begin(), end(), it); } template <typename T> void Vector<T>::inclusive_range_check_(const const_iterator& cit) const { inclusive_range_check_(cbegin(), cend(), cit); } template <typename T> void Vector<T>::index_order_check_(const index_type& idx_begin, const index_type& idx_end) const { index_order_check_(vec_.size(), idx_begin, idx_end); } template <typename T> void Vector<T>::iterator_order_check_(const iterator& it_begin, const iterator& it_end) { index_order_check_(vec_.size(), static_cast<index_type>(it_begin - begin()), static_cast<index_type>(it_end - begin())); } template <typename T> void Vector<T>::const_iterator_order_check_( const const_iterator& cit_begin, const const_iterator& cit_end) const { index_order_check_(vec_.size(), static_cast<index_type>(cit_begin - cbegin()), static_cast<index_type>(cit_end - cbegin())); } // ======== End of class Vector ======== class VectorException : public std::exception { public: VectorException() noexcept {}; VectorException(const VectorException& other) noexcept : msg_(other.msg_) {} explicit VectorException(const std::string& message) noexcept : msg_(message) {} explicit VectorException(const char* message) noexcept : msg_(message) {} VectorException& operator=(const VectorException& other) noexcept { msg_ = other.msg_; return *this; } VectorException& operator=(const std::string& msg_copy) noexcept { msg_ = msg_copy; return *this; } VectorException& operator=(const char* msg_copy) noexcept { msg_ = msg_copy; return *this; } ~VectorException() noexcept {}; const char* what() const noexcept { return msg_.c_str(); } protected: std::string msg_; }; } // namespace tensor #endif // TENSOR_VECTOR_H_
rose_lastprivate.c
// an example of output dependence preventing parallelization // x: not live-in, yes live-out // outer scope // loop-carried output-dependence: x=... : accept values based on loop variable; or not. //Solution: Can be parallelized using lastprivate(x) #include <stdio.h> #include "omp.h" void foo() { int i; int x; #pragma omp parallel for private (i) lastprivate (x) for (i = 0; i <= 99; i += 1) { x = i; } printf("x=%d",x); } /* * output dependence, loop carried * 1*1 SCALAR_DEP DATA_DEP; commonlevel = 1 CarryLevel = 0 Scalar dep type OUTPUT_DEP DATA_DEP;SgVarRefExp:x@12:6->SgVarRefExp:x@12:6 == 0;||:: */ // This x should be not lastprivate since it is live-in // x is both live-in and live-out, and written, cannot be reduction // So, the loop cannot be parallelized void foo2() { int a[100]; int i; int x = 10; for (i = 0; i <= 99; i += 1) { a[i] = x; x = i; } printf("x=%d",x); }
mutual_information.h
#pragma once #include "sub_function.h" #include <deform_lib/registration/transform.h> #include <stk/common/assert.h> #include <stk/image/volume.h> #include <stk/math/float3.h> #include <stk/math/int3.h> #include <memory> #include <tuple> #include <vector> std::vector<double> gaussian_kernel(const double sigma); template<typename T> class EntropyTerm { public: /*! * \brief Build an entropy term object. * * This object represents a the contribution of a single voxel to * the entropy of an image. * * \param volume Image. * \param bins Number of bins. * \param sigma Kernel standard deviation. */ EntropyTerm(const stk::VolumeHelper<T>& volume, const int bins, const double sigma) : _bins(bins), _sigma(sigma), _data(bins) { update(volume); } /*! * \brief Compute the entropy on the given volume. * * Entropy is approximated with a first order Taylor polynomial and * the probability distribution is estimated with Parzen KDE, which * in turn is approximated with a smoothed histogram. * * This approximation was introuduced in: * Kim, Junhwan et al. (2003): Visual correspondence using energy * minimization and mutual information, Proceedings of the Ninth * IEEE International Conference on Computer Vision, 1033–1040. * * \param volume Image. */ void update(const stk::VolumeHelper<T>& volume) { stk::find_min_max(volume, _min, _max); T range = _max - _min; _inv_bin_width = static_cast<T>(_bins) / range; dim3 size = volume.size(); // Histogram count std::fill(_data.begin(), _data.end(), 0.0); for (uint32_t z = 0; z < size.z; ++z) { for (uint32_t y = 0; y < size.y; ++y) { for (uint32_t x = 0; x < size.x; ++x) { int i = static_cast<int>(_inv_bin_width * (volume(x, y, z) - _min)); ++at(i); } } } // To probability (term inside the log) const uint32_t N = size.x * size.y * size.z; for (auto& x : _data) { x /= N; } // Approximate PDF of the term inside the log gaussian(); // Log for (auto& x : _data) { x = std::log(x < 1e-8 ? 1e-8 : x); } // Approximate PDF of the term outside the log gaussian(); // To probability (term outside the log) for (auto& x : _data) { x /= N; } } /*! * \brief Retrieve the entropy term for a given intensity. * \param x Intensity. * \return Entropy term. */ double operator()(const T x) const { const int i = bounded(static_cast<int>(_inv_bin_width * (x - _min))); return _data.data()[i]; } private: const int _bins; /*!< Number of bins. */ const double _sigma; /*!< Kernel standard deviation. */ std::vector<double> _data; /*!< Binned data. */ T _min, _max; /*!< Intensity extrema. */ T _inv_bin_width; /*!< Inverse of the bin width. */ /*! * \brief Bound a bin index within a valid range. * \param i Input coordinate. * \return Closest value to `i` in `{0, ..., bins}`. */ int bounded(const int i) const { return std::min<int>(std::max<int>(0, i), _bins - 1); }; /*! * \brief Return a reference to the bin. * \param i Bin index. * \return A reference to the bin. */ double& at(const int i) { return _data.data()[bounded(i)]; } /*! * \brief Gaussian convolution. */ void gaussian(void) { if (_sigma <= 0.0) { return; } // Compute a 1D filter kernel of adaptive size std::vector<double> kernel = gaussian_kernel(_sigma); int r = static_cast<int>(kernel.size() / 2); // Apply the filter std::vector<double> tmp(_bins); #pragma omp parallel for for (int i = 0; i < _bins; ++i) { double val = 0.0; for (int t = -r; t < r + 1; ++t) { val += kernel[t+r] * _data.data()[bounded(i+t)]; } tmp[i] = val; } _data = std::move(tmp); } }; template<typename T> class JointEntropyTerm { public: /*! * \brief Build a joint entropy term object. * * This object represents a the contribution of a single voxel to * the joint entropy of the images. * * \param volume1 First image. * \param volume2 Second image. * \param bins Number of bins on each dimension. * \param sigma Kernel standard deviation. */ JointEntropyTerm(const stk::VolumeHelper<T>& volume1, const stk::VolumeHelper<T>& volume2, const int bins, const double sigma) : _bins(bins), _sigma(sigma), _data(bins * bins) { update(volume1, volume2); } /*! * \brief Compute the joint entropy of two images. * * Joint entropy is approximated with a first order * Taylor polynomial and the probability distribution is estimated * with Parzen KDE, which in turn is approximated with a smoothed * histogram. * * This approximation was introuduced in: * Kim, Junhwan et al. (2003): Visual correspondence using energy * minimization and mutual information, Proceedings of the Ninth * IEEE International Conference on Computer Vision, 1033–1040. * * \param volume1 First image. * \param volume2 Second image. */ void update(const stk::VolumeHelper<T>& volume1, const stk::VolumeHelper<T>& volume2) { stk::find_min_max(volume1, _min1, _max1); stk::find_min_max(volume2, _min2, _max2); T range1 = _max1 - _min1; T range2 = _max2 - _min2; _inv_bin_width_1 = static_cast<T>(_bins) / range1; _inv_bin_width_2 = static_cast<T>(_bins) / range2; dim3 size = volume1.size(); // Joint histogram count std::fill(_data.begin(), _data.end(), 0.0); for (uint32_t z = 0; z < size.z; ++z) { for (uint32_t y = 0; y < size.y; ++y) { for (uint32_t x = 0; x < size.x; ++x) { // [1] -> [world] -> [2] float3 p1 {float(x), float(y), float(z)}; float3 p2 = volume2.point2index(volume1.index2point(p1)); T v1 = volume1(x, y, z); T v2 = volume2.linear_at(p2, stk::Border_Replicate); int i1 = static_cast<int>(_inv_bin_width_1 * (v1 - _min1)); int i2 = static_cast<int>(_inv_bin_width_2 * (v2 - _min2)); ++at(i1, i2); } } } // To probability (term inside the log) const uint32_t N = size.x * size.y * size.z; for (auto& x : _data) { x /= N; } // Approximate PDF of the term inside the log gaussian(); // Log for (auto& x : _data) { x = std::log(x < 1e-8 ? 1e-8 : x); } // Approximate PDF of the term outside the log gaussian(); // To probability (term outside the log) for (auto& x : _data) { x /= N; } } /*! * \brief Retrieve the joint entropy term for a given combination of intensities. * \param x Intensity on the first image. * \param y Intensity on the second image. * \return Joint entropy term. */ double operator()(const T x, const T y) const { const int i = bounded(static_cast<int>(_inv_bin_width_1 * (x - _min1))); const int j = bounded(static_cast<int>(_inv_bin_width_2 * (y - _min2))); return _data.data()[_bins * j + i]; } private: const int _bins; /*!< Number of bins. */ const double _sigma; /*!< Kernel standard deviation. */ std::vector<double> _data; /*!< Binned data. */ T _min1, _max1, _min2, _max2; /*!< Extrema for the two intensities. */ T _inv_bin_width_1, _inv_bin_width_2; /*!< Inverse of the bin widths for each direction. */ /*! * \brief Bound a bin index within a valid range. * \param i Input coordinate. * \return Closest value to `i` in `{0, ..., bins}`. */ int bounded(const int i) const { return std::min<int>(std::max<int>(0, i), _bins - 1); }; /*! * \brief Return a reference to the bin. * \param i First bin coordinate. * \param j Second bin coordinate. * \return A reference to the bin. */ double& at(const int i, const int j) { return _data.data()[_bins * bounded(j) + bounded(i)]; } /*! * \brief Gaussian convolution with decomposed filters. */ void gaussian(void) { if (_sigma <= 0.0) { return; } // Compute a 1D filter kernel of adaptive size std::vector<double> kernel = gaussian_kernel(_sigma); int r = static_cast<int>(kernel.size() / 2); // Apply the filter along the x direction std::vector<double> tmp(_bins * _bins); #pragma omp parallel for for (int i = 0; i < _bins; ++i) { for (int j = 0; j < _bins; ++j) { double val = 0.0; for (int t = -r; t < r + 1; ++t) { val += kernel[t+r] * at(i, j+t); } tmp.data()[_bins * j + i] = val; } } // Apply the filter along the y direction #pragma omp parallel for for (int i = 0; i < _bins; ++i) { for (int j = 0; j < _bins; ++j) { double val = 0.0; for (int t = -r; t < r + 1; ++t) { val += kernel[t+r] * tmp.data()[_bins * j + bounded(i+t)]; } at(i, j) = val; } } } }; template<typename T> struct MIFunction : public SubFunction { MIFunction(const stk::VolumeHelper<T>& fixed, const stk::VolumeHelper<T>& moving, const int bins, const double sigma, const int update_interval, const transform::Interp interpolator) : _fixed(fixed), _moving(moving), _bins(bins), _sigma(sigma), _update_interval(update_interval), _interpolator(interpolator), _voxel_count(fixed.size().x * fixed.size().y * fixed.size().z), _joint_entropy(fixed, moving, bins, sigma), _entropy(moving, bins, sigma) { } virtual ~MIFunction() {} /*! * \brief Contribution of a single voxel to the mutual information. * * Mutual information is broken to a voxel-wise sum thanks to an * approximation of the entropy function based on Taylor polynomia * and Parzen KDE. The formula was introduced in: * Kim, Junhwan et al. (2003): Visual correspondence using energy * minimization and mutual information, Proceedings of the Ninth * IEEE International Conference on Computer Vision, 1033–1040. * * Here, both the joint entropy and the entropy of the moving image * are approximated. The entropy of the fixed image is ignored * since it is constant with respect to the displacement, hence it * has no effect on the optimisation process. */ float cost(const int3& p, const float3& def) { // [fixed] -> [world] -> [moving] const auto moving_p = _moving.point2index(_fixed.index2point(p) + def); // Check whether the point is masked out float mask_value = 1.0f; if (_moving_mask.valid()) { mask_value = _moving_mask.linear_at(moving_p, stk::Border_Constant); if (mask_value <= std::numeric_limits<float>::epsilon()) { return 0.0f; } } const T i1 = _fixed(p); const T i2 = _moving.linear_at(moving_p, stk::Border_Constant); // NOTE: the sign is inverted (minimising negated MI) return mask_value * _voxel_count * static_cast<float>(_entropy(i2) - _joint_entropy(i1, i2)); } /*! * \brief Update the entropy term estimations. * * The entropy terms are approximated with a first order truncated * Taylor polynomial, which is a function of the displacement. The * approximation gets worse as the displacement gets larger. To * compensate for this, resample the moving volume and update the * entropy of the moving image and the joint entropy after each * iteration. */ virtual void pre_iteration_hook(const int iteration, const DisplacementField& df) { if (0 == iteration || 0 == _update_interval || iteration % _update_interval) { return; } auto tmp = transform_volume(_moving, df, _interpolator); _joint_entropy.update(_fixed, tmp); _entropy.update(tmp); } stk::VolumeHelper<T> _fixed; stk::VolumeHelper<T> _moving; const int _bins; const double _sigma; const int _update_interval; const transform::Interp _interpolator; private: const int _voxel_count; JointEntropyTerm<T> _joint_entropy; EntropyTerm<T> _entropy; };
_phono3py.c
/* Copyright (C) 2015 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* * Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* * Neither the name of the phonopy project nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ #include <Python.h> #include <assert.h> #include <math.h> #include <numpy/arrayobject.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include "lapack_wrapper.h" #include "phono3py.h" #include "phonoc_array.h" static PyObject *py_get_interaction(PyObject *self, PyObject *args); static PyObject *py_get_pp_collision(PyObject *self, PyObject *args); static PyObject *py_get_pp_collision_with_sigma(PyObject *self, PyObject *args); static PyObject *py_get_imag_self_energy_with_g(PyObject *self, PyObject *args); static PyObject *py_get_detailed_imag_self_energy_with_g(PyObject *self, PyObject *args); static PyObject *py_get_real_self_energy_at_bands(PyObject *self, PyObject *args); static PyObject *py_get_real_self_energy_at_frequency_point(PyObject *self, PyObject *args); static PyObject *py_get_collision_matrix(PyObject *self, PyObject *args); static PyObject *py_get_reducible_collision_matrix(PyObject *self, PyObject *args); static PyObject *py_symmetrize_collision_matrix(PyObject *self, PyObject *args); static PyObject *py_expand_collision_matrix(PyObject *self, PyObject *args); static PyObject *py_distribute_fc3(PyObject *self, PyObject *args); static PyObject *py_rotate_delta_fc2s(PyObject *self, PyObject *args); static PyObject *py_get_isotope_strength(PyObject *self, PyObject *args); static PyObject *py_get_thm_isotope_strength(PyObject *self, PyObject *args); static PyObject *py_get_permutation_symmetry_fc3(PyObject *self, PyObject *args); static PyObject *py_get_permutation_symmetry_compact_fc3(PyObject *self, PyObject *args); static PyObject *py_transpose_compact_fc3(PyObject *self, PyObject *args); static PyObject *py_get_neighboring_grid_points(PyObject *self, PyObject *args); static PyObject *py_get_thm_integration_weights_at_grid_points(PyObject *self, PyObject *args); static PyObject *py_tpl_get_triplets_reciprocal_mesh_at_q(PyObject *self, PyObject *args); static PyObject *py_tpl_get_BZ_triplets_at_q(PyObject *self, PyObject *args); static PyObject *py_get_triplets_integration_weights(PyObject *self, PyObject *args); static PyObject *py_get_triplets_integration_weights_with_sigma(PyObject *self, PyObject *args); static PyObject *py_get_grid_index_from_address(PyObject *self, PyObject *args); static PyObject *py_get_gr_grid_addresses(PyObject *self, PyObject *args); static PyObject *py_get_reciprocal_rotations(PyObject *self, PyObject *args); static PyObject *py_transform_rotations(PyObject *self, PyObject *args); static PyObject *py_get_snf3x3(PyObject *self, PyObject *args); static PyObject *py_get_ir_grid_map(PyObject *self, PyObject *args); static PyObject *py_get_bz_grid_addresses(PyObject *self, PyObject *args); static PyObject *py_rotate_bz_grid_addresses(PyObject *self, PyObject *args); static PyObject *py_diagonalize_collision_matrix(PyObject *self, PyObject *args); static PyObject *py_pinv_from_eigensolution(PyObject *self, PyObject *args); static PyObject *py_get_default_colmat_solver(PyObject *self, PyObject *args); static void pinv_from_eigensolution(double *data, const double *eigvals, const long size, const double cutoff, const long pinv_method); static void show_colmat_info(const PyArrayObject *collision_matrix_py, const long i_sigma, const long i_temp, const long adrs_shift); static Larray *convert_to_larray(const PyArrayObject *npyary); static Darray *convert_to_darray(const PyArrayObject *npyary); struct module_state { PyObject *error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct module_state *)PyModule_GetState(m)) #else #define GETSTATE(m) (&_state) static struct module_state _state; #endif static PyObject *error_out(PyObject *m) { struct module_state *st = GETSTATE(m); PyErr_SetString(st->error, "something bad happened"); return NULL; } static PyMethodDef _phono3py_methods[] = { {"error_out", (PyCFunction)error_out, METH_NOARGS, NULL}, {"interaction", (PyCFunction)py_get_interaction, METH_VARARGS, "Interaction of triplets"}, {"pp_collision", (PyCFunction)py_get_pp_collision, METH_VARARGS, "Collision and ph-ph calculation"}, {"pp_collision_with_sigma", (PyCFunction)py_get_pp_collision_with_sigma, METH_VARARGS, "Collision and ph-ph calculation for smearing method"}, {"imag_self_energy_with_g", (PyCFunction)py_get_imag_self_energy_with_g, METH_VARARGS, "Imaginary part of self energy at frequency points with g"}, {"detailed_imag_self_energy_with_g", (PyCFunction)py_get_detailed_imag_self_energy_with_g, METH_VARARGS, "Detailed contribution to imaginary part of self energy at frequency " "points with g"}, {"real_self_energy_at_bands", (PyCFunction)py_get_real_self_energy_at_bands, METH_VARARGS, "Real part of self energy from third order force constants"}, {"real_self_energy_at_frequency_point", (PyCFunction)py_get_real_self_energy_at_frequency_point, METH_VARARGS, "Real part of self energy from third order force constants at a frequency " "point"}, {"collision_matrix", (PyCFunction)py_get_collision_matrix, METH_VARARGS, "Collision matrix with g"}, {"reducible_collision_matrix", (PyCFunction)py_get_reducible_collision_matrix, METH_VARARGS, "Collision matrix with g for reducible grid points"}, {"symmetrize_collision_matrix", (PyCFunction)py_symmetrize_collision_matrix, METH_VARARGS, "Symmetrize collision matrix"}, {"expand_collision_matrix", (PyCFunction)py_expand_collision_matrix, METH_VARARGS, "Expand collision matrix"}, {"distribute_fc3", (PyCFunction)py_distribute_fc3, METH_VARARGS, "Distribute least fc3 to full fc3"}, {"rotate_delta_fc2s", (PyCFunction)py_rotate_delta_fc2s, METH_VARARGS, "Rotate delta fc2s"}, {"isotope_strength", (PyCFunction)py_get_isotope_strength, METH_VARARGS, "Isotope scattering strength"}, {"thm_isotope_strength", (PyCFunction)py_get_thm_isotope_strength, METH_VARARGS, "Isotope scattering strength for tetrahedron_method"}, {"permutation_symmetry_fc3", (PyCFunction)py_get_permutation_symmetry_fc3, METH_VARARGS, "Set permutation symmetry for fc3"}, {"permutation_symmetry_compact_fc3", (PyCFunction)py_get_permutation_symmetry_compact_fc3, METH_VARARGS, "Set permutation symmetry for compact-fc3"}, {"transpose_compact_fc3", (PyCFunction)py_transpose_compact_fc3, METH_VARARGS, "Transpose compact fc3"}, {"neighboring_grid_points", (PyCFunction)py_get_neighboring_grid_points, METH_VARARGS, "Neighboring grid points by relative grid addresses"}, {"integration_weights_at_grid_points", (PyCFunction)py_get_thm_integration_weights_at_grid_points, METH_VARARGS, "Integration weights of tetrahedron method at grid points"}, {"triplets_reciprocal_mesh_at_q", (PyCFunction)py_tpl_get_triplets_reciprocal_mesh_at_q, METH_VARARGS, "Triplets on reciprocal mesh points at a specific q-point"}, {"BZ_triplets_at_q", (PyCFunction)py_tpl_get_BZ_triplets_at_q, METH_VARARGS, "Triplets in reciprocal primitive lattice are transformed to those in " "BZ."}, {"triplets_integration_weights", (PyCFunction)py_get_triplets_integration_weights, METH_VARARGS, "Integration weights of tetrahedron method for triplets"}, {"triplets_integration_weights_with_sigma", (PyCFunction)py_get_triplets_integration_weights_with_sigma, METH_VARARGS, "Integration weights of smearing method for triplets"}, {"grid_index_from_address", (PyCFunction)py_get_grid_index_from_address, METH_VARARGS, "Grid index from grid address"}, {"ir_grid_map", (PyCFunction)py_get_ir_grid_map, METH_VARARGS, "Reciprocal mesh points with ir grid mapping table"}, {"gr_grid_addresses", (PyCFunction)py_get_gr_grid_addresses, METH_VARARGS, "Get generalized regular grid addresses"}, {"reciprocal_rotations", (PyCFunction)py_get_reciprocal_rotations, METH_VARARGS, "Return rotation matrices in reciprocal space"}, {"transform_rotations", (PyCFunction)py_transform_rotations, METH_VARARGS, "Transform rotations to those in generalized regular grid"}, {"snf3x3", (PyCFunction)py_get_snf3x3, METH_VARARGS, "Get Smith formal form for 3x3 integer matrix"}, {"bz_grid_addresses", (PyCFunction)py_get_bz_grid_addresses, METH_VARARGS, "Get grid addresses including Brillouin zone surface"}, {"rotate_bz_grid_index", (PyCFunction)py_rotate_bz_grid_addresses, METH_VARARGS, "Rotate grid point considering Brillouin zone surface"}, {"diagonalize_collision_matrix", (PyCFunction)py_diagonalize_collision_matrix, METH_VARARGS, "Diagonalize and optionally pseudo-inverse using Lapack dsyev(d)"}, {"pinv_from_eigensolution", (PyCFunction)py_pinv_from_eigensolution, METH_VARARGS, "Pseudo-inverse from eigensolution"}, {"default_colmat_solver", (PyCFunction)py_get_default_colmat_solver, METH_VARARGS, "Return default collison matrix solver by integer value"}, {NULL, NULL, 0, NULL}}; #if PY_MAJOR_VERSION >= 3 static int _phono3py_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int _phono3py_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_phono3py", NULL, sizeof(struct module_state), _phono3py_methods, NULL, _phono3py_traverse, _phono3py_clear, NULL}; #define INITERROR return NULL PyObject *PyInit__phono3py(void) #else #define INITERROR return void init_phono3py(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module = PyModule_Create(&moduledef); #else PyObject *module = Py_InitModule("_phono3py", _phono3py_methods); #endif struct module_state *st; if (module == NULL) INITERROR; st = GETSTATE(module); st->error = PyErr_NewException("_phono3py.Error", NULL, NULL); if (st->error == NULL) { Py_DECREF(module); INITERROR; } #if PY_MAJOR_VERSION >= 3 return module; #endif } static PyObject *py_get_interaction(PyObject *self, PyObject *args) { PyArrayObject *py_fc3_normal_squared; PyArrayObject *py_g_zero; PyArrayObject *py_frequencies; PyArrayObject *py_eigenvectors; PyArrayObject *py_triplets; PyArrayObject *py_bz_grid_addresses; PyArrayObject *py_D_diag; PyArrayObject *py_Q; PyArrayObject *py_svecs; PyArrayObject *py_multi; PyArrayObject *py_fc3; PyArrayObject *py_masses; PyArrayObject *py_p2s_map; PyArrayObject *py_s2p_map; PyArrayObject *py_band_indices; double cutoff_frequency; long symmetrize_fc3_q; Darray *fc3_normal_squared; Darray *freqs; lapack_complex_double *eigvecs; long(*triplets)[3]; long num_triplets; char *g_zero; long(*bz_grid_addresses)[3]; long *D_diag; long(*Q)[3]; double *fc3; double(*svecs)[3]; long(*multi)[2]; double *masses; long *p2s; long *s2p; long *band_indices; long multi_dims[2]; long i; long is_compact_fc3; if (!PyArg_ParseTuple(args, "OOOOOOOOOOOOOOOld", &py_fc3_normal_squared, &py_g_zero, &py_frequencies, &py_eigenvectors, &py_triplets, &py_bz_grid_addresses, &py_D_diag, &py_Q, &py_fc3, &py_svecs, &py_multi, &py_masses, &py_p2s_map, &py_s2p_map, &py_band_indices, &symmetrize_fc3_q, &cutoff_frequency)) { return NULL; } fc3_normal_squared = convert_to_darray(py_fc3_normal_squared); freqs = convert_to_darray(py_frequencies); /* npy_cdouble and lapack_complex_double may not be compatible. */ /* So eigenvectors should not be used in Python side */ eigvecs = (lapack_complex_double *)PyArray_DATA(py_eigenvectors); triplets = (long(*)[3])PyArray_DATA(py_triplets); num_triplets = (long)PyArray_DIMS(py_triplets)[0]; g_zero = (char *)PyArray_DATA(py_g_zero); bz_grid_addresses = (long(*)[3])PyArray_DATA(py_bz_grid_addresses); D_diag = (long *)PyArray_DATA(py_D_diag); Q = (long(*)[3])PyArray_DATA(py_Q); fc3 = (double *)PyArray_DATA(py_fc3); if (PyArray_DIMS(py_fc3)[0] == PyArray_DIMS(py_fc3)[1]) { is_compact_fc3 = 0; } else { is_compact_fc3 = 1; } svecs = (double(*)[3])PyArray_DATA(py_svecs); for (i = 0; i < 2; i++) { multi_dims[i] = PyArray_DIMS(py_multi)[i]; } multi = (long(*)[2])PyArray_DATA(py_multi); masses = (double *)PyArray_DATA(py_masses); p2s = (long *)PyArray_DATA(py_p2s_map); s2p = (long *)PyArray_DATA(py_s2p_map); band_indices = (long *)PyArray_DATA(py_band_indices); ph3py_get_interaction(fc3_normal_squared, g_zero, freqs, eigvecs, triplets, num_triplets, bz_grid_addresses, D_diag, Q, fc3, is_compact_fc3, svecs, multi_dims, multi, masses, p2s, s2p, band_indices, symmetrize_fc3_q, cutoff_frequency); free(fc3_normal_squared); fc3_normal_squared = NULL; free(freqs); freqs = NULL; Py_RETURN_NONE; } static PyObject *py_get_pp_collision(PyObject *self, PyObject *args) { PyArrayObject *py_gamma; PyArrayObject *py_relative_grid_address; PyArrayObject *py_frequencies; PyArrayObject *py_eigenvectors; PyArrayObject *py_triplets; PyArrayObject *py_triplet_weights; PyArrayObject *py_bz_grid_addresses; PyArrayObject *py_bz_map; PyArrayObject *py_D_diag; PyArrayObject *py_Q; PyArrayObject *py_fc3; PyArrayObject *py_svecs; PyArrayObject *py_multi; PyArrayObject *py_masses; PyArrayObject *py_p2s_map; PyArrayObject *py_s2p_map; PyArrayObject *py_band_indices; PyArrayObject *py_temperatures; double cutoff_frequency; long is_NU; long symmetrize_fc3_q; long bz_grid_type; double *gamma; long(*relative_grid_address)[4][3]; double *frequencies; lapack_complex_double *eigenvectors; long(*triplets)[3]; long num_triplets; long *triplet_weights; long(*bz_grid_addresses)[3]; long *bz_map; long *D_diag; long(*Q)[3]; double *fc3; double(*svecs)[3]; long(*multi)[2]; double *masses; long *p2s; long *s2p; Larray *band_indices; Darray *temperatures; long multi_dims[2]; long i; long is_compact_fc3; if (!PyArg_ParseTuple( args, "OOOOOOOOlOOOOOOOOOOlld", &py_gamma, &py_relative_grid_address, &py_frequencies, &py_eigenvectors, &py_triplets, &py_triplet_weights, &py_bz_grid_addresses, &py_bz_map, &bz_grid_type, &py_D_diag, &py_Q, &py_fc3, &py_svecs, &py_multi, &py_masses, &py_p2s_map, &py_s2p_map, &py_band_indices, &py_temperatures, &is_NU, &symmetrize_fc3_q, &cutoff_frequency)) { return NULL; } gamma = (double *)PyArray_DATA(py_gamma); relative_grid_address = (long(*)[4][3])PyArray_DATA(py_relative_grid_address); frequencies = (double *)PyArray_DATA(py_frequencies); eigenvectors = (lapack_complex_double *)PyArray_DATA(py_eigenvectors); triplets = (long(*)[3])PyArray_DATA(py_triplets); num_triplets = (long)PyArray_DIMS(py_triplets)[0]; triplet_weights = (long *)PyArray_DATA(py_triplet_weights); bz_grid_addresses = (long(*)[3])PyArray_DATA(py_bz_grid_addresses); bz_map = (long *)PyArray_DATA(py_bz_map); D_diag = (long *)PyArray_DATA(py_D_diag); Q = (long(*)[3])PyArray_DATA(py_Q); fc3 = (double *)PyArray_DATA(py_fc3); if (PyArray_DIMS(py_fc3)[0] == PyArray_DIMS(py_fc3)[1]) { is_compact_fc3 = 0; } else { is_compact_fc3 = 1; } svecs = (double(*)[3])PyArray_DATA(py_svecs); for (i = 0; i < 2; i++) { multi_dims[i] = PyArray_DIMS(py_multi)[i]; } multi = (long(*)[2])PyArray_DATA(py_multi); masses = (double *)PyArray_DATA(py_masses); p2s = (long *)PyArray_DATA(py_p2s_map); s2p = (long *)PyArray_DATA(py_s2p_map); band_indices = convert_to_larray(py_band_indices); temperatures = convert_to_darray(py_temperatures); ph3py_get_pp_collision( gamma, relative_grid_address, frequencies, eigenvectors, triplets, num_triplets, triplet_weights, bz_grid_addresses, bz_map, bz_grid_type, D_diag, Q, fc3, is_compact_fc3, svecs, multi_dims, multi, masses, p2s, s2p, band_indices, temperatures, is_NU, symmetrize_fc3_q, cutoff_frequency); free(band_indices); band_indices = NULL; free(temperatures); temperatures = NULL; Py_RETURN_NONE; } static PyObject *py_get_pp_collision_with_sigma(PyObject *self, PyObject *args) { PyArrayObject *py_gamma; PyArrayObject *py_frequencies; PyArrayObject *py_eigenvectors; PyArrayObject *py_triplets; PyArrayObject *py_triplet_weights; PyArrayObject *py_bz_grid_addresses; PyArrayObject *py_D_diag; PyArrayObject *py_Q; PyArrayObject *py_fc3; PyArrayObject *py_svecs; PyArrayObject *py_multi; PyArrayObject *py_masses; PyArrayObject *py_p2s_map; PyArrayObject *py_s2p_map; PyArrayObject *py_band_indices; PyArrayObject *py_temperatures; long is_NU; long symmetrize_fc3_q; double sigma; double sigma_cutoff; double cutoff_frequency; double *gamma; double *frequencies; lapack_complex_double *eigenvectors; long(*triplets)[3]; long num_triplets; long *triplet_weights; long(*bz_grid_addresses)[3]; long *D_diag; long(*Q)[3]; double *fc3; double(*svecs)[3]; long(*multi)[2]; double *masses; long *p2s; long *s2p; Larray *band_indices; Darray *temperatures; long multi_dims[2]; long i; long is_compact_fc3; if (!PyArg_ParseTuple(args, "OddOOOOOOOOOOOOOOOlld", &py_gamma, &sigma, &sigma_cutoff, &py_frequencies, &py_eigenvectors, &py_triplets, &py_triplet_weights, &py_bz_grid_addresses, &py_D_diag, &py_Q, &py_fc3, &py_svecs, &py_multi, &py_masses, &py_p2s_map, &py_s2p_map, &py_band_indices, &py_temperatures, &is_NU, &symmetrize_fc3_q, &cutoff_frequency)) { return NULL; } gamma = (double *)PyArray_DATA(py_gamma); frequencies = (double *)PyArray_DATA(py_frequencies); eigenvectors = (lapack_complex_double *)PyArray_DATA(py_eigenvectors); triplets = (long(*)[3])PyArray_DATA(py_triplets); num_triplets = (long)PyArray_DIMS(py_triplets)[0]; triplet_weights = (long *)PyArray_DATA(py_triplet_weights); bz_grid_addresses = (long(*)[3])PyArray_DATA(py_bz_grid_addresses); D_diag = (long *)PyArray_DATA(py_D_diag); Q = (long(*)[3])PyArray_DATA(py_Q); fc3 = (double *)PyArray_DATA(py_fc3); if (PyArray_DIMS(py_fc3)[0] == PyArray_DIMS(py_fc3)[1]) { is_compact_fc3 = 0; } else { is_compact_fc3 = 1; } svecs = (double(*)[3])PyArray_DATA(py_svecs); for (i = 0; i < 2; i++) { multi_dims[i] = PyArray_DIMS(py_multi)[i]; } multi = (long(*)[2])PyArray_DATA(py_multi); masses = (double *)PyArray_DATA(py_masses); p2s = (long *)PyArray_DATA(py_p2s_map); s2p = (long *)PyArray_DATA(py_s2p_map); band_indices = convert_to_larray(py_band_indices); temperatures = convert_to_darray(py_temperatures); ph3py_get_pp_collision_with_sigma( gamma, sigma, sigma_cutoff, frequencies, eigenvectors, triplets, num_triplets, triplet_weights, bz_grid_addresses, D_diag, Q, fc3, is_compact_fc3, svecs, multi_dims, multi, masses, p2s, s2p, band_indices, temperatures, is_NU, symmetrize_fc3_q, cutoff_frequency); free(band_indices); band_indices = NULL; free(temperatures); temperatures = NULL; Py_RETURN_NONE; } static PyObject *py_get_imag_self_energy_with_g(PyObject *self, PyObject *args) { PyArrayObject *py_gamma; PyArrayObject *py_fc3_normal_squared; PyArrayObject *py_frequencies; PyArrayObject *py_triplets; PyArrayObject *py_triplet_weights; PyArrayObject *py_g; PyArrayObject *py_g_zero; double cutoff_frequency, temperature; long frequency_point_index; Darray *fc3_normal_squared; double *gamma; double *g; char *g_zero; double *frequencies; long(*triplets)[3]; long *triplet_weights; long num_frequency_points; if (!PyArg_ParseTuple(args, "OOOOOdOOdl", &py_gamma, &py_fc3_normal_squared, &py_triplets, &py_triplet_weights, &py_frequencies, &temperature, &py_g, &py_g_zero, &cutoff_frequency, &frequency_point_index)) { return NULL; } fc3_normal_squared = convert_to_darray(py_fc3_normal_squared); gamma = (double *)PyArray_DATA(py_gamma); g = (double *)PyArray_DATA(py_g); g_zero = (char *)PyArray_DATA(py_g_zero); frequencies = (double *)PyArray_DATA(py_frequencies); triplets = (long(*)[3])PyArray_DATA(py_triplets); triplet_weights = (long *)PyArray_DATA(py_triplet_weights); num_frequency_points = (long)PyArray_DIMS(py_g)[2]; ph3py_get_imag_self_energy_at_bands_with_g( gamma, fc3_normal_squared, frequencies, triplets, triplet_weights, g, g_zero, temperature, cutoff_frequency, num_frequency_points, frequency_point_index); free(fc3_normal_squared); fc3_normal_squared = NULL; Py_RETURN_NONE; } static PyObject *py_get_detailed_imag_self_energy_with_g(PyObject *self, PyObject *args) { PyArrayObject *py_gamma_detail; PyArrayObject *py_gamma_N; PyArrayObject *py_gamma_U; PyArrayObject *py_fc3_normal_squared; PyArrayObject *py_frequencies; PyArrayObject *py_triplets; PyArrayObject *py_triplet_weights; PyArrayObject *py_bz_grid_addresses; PyArrayObject *py_g; PyArrayObject *py_g_zero; double cutoff_frequency, temperature; Darray *fc3_normal_squared; double *gamma_detail; double *gamma_N; double *gamma_U; double *g; char *g_zero; double *frequencies; long(*triplets)[3]; long *triplet_weights; long(*bz_grid_addresses)[3]; if (!PyArg_ParseTuple(args, "OOOOOOOOdOOd", &py_gamma_detail, &py_gamma_N, &py_gamma_U, &py_fc3_normal_squared, &py_triplets, &py_triplet_weights, &py_bz_grid_addresses, &py_frequencies, &temperature, &py_g, &py_g_zero, &cutoff_frequency)) { return NULL; } fc3_normal_squared = convert_to_darray(py_fc3_normal_squared); gamma_detail = (double *)PyArray_DATA(py_gamma_detail); gamma_N = (double *)PyArray_DATA(py_gamma_N); gamma_U = (double *)PyArray_DATA(py_gamma_U); g = (double *)PyArray_DATA(py_g); g_zero = (char *)PyArray_DATA(py_g_zero); frequencies = (double *)PyArray_DATA(py_frequencies); triplets = (long(*)[3])PyArray_DATA(py_triplets); triplet_weights = (long *)PyArray_DATA(py_triplet_weights); bz_grid_addresses = (long(*)[3])PyArray_DATA(py_bz_grid_addresses); ph3py_get_detailed_imag_self_energy_at_bands_with_g( gamma_detail, gamma_N, gamma_U, fc3_normal_squared, frequencies, triplets, triplet_weights, bz_grid_addresses, g, g_zero, temperature, cutoff_frequency); free(fc3_normal_squared); fc3_normal_squared = NULL; Py_RETURN_NONE; } static PyObject *py_get_real_self_energy_at_bands(PyObject *self, PyObject *args) { PyArrayObject *py_shift; PyArrayObject *py_fc3_normal_squared; PyArrayObject *py_frequencies; PyArrayObject *py_triplets; PyArrayObject *py_triplet_weights; PyArrayObject *py_band_indices; double epsilon, unit_conversion_factor, cutoff_frequency, temperature; Darray *fc3_normal_squared; double *shift; double *frequencies; long *band_indices; long(*triplets)[3]; long *triplet_weights; if (!PyArg_ParseTuple(args, "OOOOOOdddd", &py_shift, &py_fc3_normal_squared, &py_triplets, &py_triplet_weights, &py_frequencies, &py_band_indices, &temperature, &epsilon, &unit_conversion_factor, &cutoff_frequency)) { return NULL; } fc3_normal_squared = convert_to_darray(py_fc3_normal_squared); shift = (double *)PyArray_DATA(py_shift); frequencies = (double *)PyArray_DATA(py_frequencies); band_indices = (long *)PyArray_DATA(py_band_indices); triplets = (long(*)[3])PyArray_DATA(py_triplets); triplet_weights = (long *)PyArray_DATA(py_triplet_weights); ph3py_get_real_self_energy_at_bands( shift, fc3_normal_squared, band_indices, frequencies, triplets, triplet_weights, epsilon, temperature, unit_conversion_factor, cutoff_frequency); free(fc3_normal_squared); fc3_normal_squared = NULL; Py_RETURN_NONE; } static PyObject *py_get_real_self_energy_at_frequency_point(PyObject *self, PyObject *args) { PyArrayObject *py_shift; PyArrayObject *py_fc3_normal_squared; PyArrayObject *py_frequencies; PyArrayObject *py_triplets; PyArrayObject *py_triplet_weights; PyArrayObject *py_band_indices; double frequency_point, epsilon, unit_conversion_factor, cutoff_frequency; double temperature; Darray *fc3_normal_squared; double *shift; double *frequencies; long *band_indices; long(*triplets)[3]; long *triplet_weights; if (!PyArg_ParseTuple(args, "OdOOOOOdddd", &py_shift, &frequency_point, &py_fc3_normal_squared, &py_triplets, &py_triplet_weights, &py_frequencies, &py_band_indices, &temperature, &epsilon, &unit_conversion_factor, &cutoff_frequency)) { return NULL; } fc3_normal_squared = convert_to_darray(py_fc3_normal_squared); shift = (double *)PyArray_DATA(py_shift); frequencies = (double *)PyArray_DATA(py_frequencies); band_indices = (long *)PyArray_DATA(py_band_indices); triplets = (long(*)[3])PyArray_DATA(py_triplets); triplet_weights = (long *)PyArray_DATA(py_triplet_weights); ph3py_get_real_self_energy_at_frequency_point( shift, frequency_point, fc3_normal_squared, band_indices, frequencies, triplets, triplet_weights, epsilon, temperature, unit_conversion_factor, cutoff_frequency); free(fc3_normal_squared); fc3_normal_squared = NULL; Py_RETURN_NONE; } static PyObject *py_get_collision_matrix(PyObject *self, PyObject *args) { PyArrayObject *py_collision_matrix; PyArrayObject *py_fc3_normal_squared; PyArrayObject *py_frequencies; PyArrayObject *py_triplets; PyArrayObject *py_triplets_map; PyArrayObject *py_map_q; PyArrayObject *py_g; PyArrayObject *py_rotated_grid_points; PyArrayObject *py_rotations_cartesian; double temperature, unit_conversion_factor, cutoff_frequency; Darray *fc3_normal_squared; double *collision_matrix; double *g; double *frequencies; long(*triplets)[3]; long *triplets_map; long *map_q; long *rotated_grid_points; long num_gp, num_ir_gp, num_rot; double *rotations_cartesian; if (!PyArg_ParseTuple( args, "OOOOOOOOOddd", &py_collision_matrix, &py_fc3_normal_squared, &py_frequencies, &py_g, &py_triplets, &py_triplets_map, &py_map_q, &py_rotated_grid_points, &py_rotations_cartesian, &temperature, &unit_conversion_factor, &cutoff_frequency)) { return NULL; } fc3_normal_squared = convert_to_darray(py_fc3_normal_squared); collision_matrix = (double *)PyArray_DATA(py_collision_matrix); g = (double *)PyArray_DATA(py_g); frequencies = (double *)PyArray_DATA(py_frequencies); triplets = (long(*)[3])PyArray_DATA(py_triplets); triplets_map = (long *)PyArray_DATA(py_triplets_map); num_gp = (long)PyArray_DIMS(py_triplets_map)[0]; map_q = (long *)PyArray_DATA(py_map_q); rotated_grid_points = (long *)PyArray_DATA(py_rotated_grid_points); num_ir_gp = (long)PyArray_DIMS(py_rotated_grid_points)[0]; num_rot = (long)PyArray_DIMS(py_rotated_grid_points)[1]; rotations_cartesian = (double *)PyArray_DATA(py_rotations_cartesian); assert(num_rot == PyArray_DIMS(py_rotations_cartesian)[0]); assert(num_gp == PyArray_DIMS(py_frequencies)[0]); ph3py_get_collision_matrix(collision_matrix, fc3_normal_squared, frequencies, triplets, triplets_map, map_q, rotated_grid_points, rotations_cartesian, g, num_ir_gp, num_gp, num_rot, temperature, unit_conversion_factor, cutoff_frequency); free(fc3_normal_squared); fc3_normal_squared = NULL; Py_RETURN_NONE; } static PyObject *py_get_reducible_collision_matrix(PyObject *self, PyObject *args) { PyArrayObject *py_collision_matrix; PyArrayObject *py_fc3_normal_squared; PyArrayObject *py_frequencies; PyArrayObject *py_triplets; PyArrayObject *py_triplets_map; PyArrayObject *py_map_q; PyArrayObject *py_g; double temperature, unit_conversion_factor, cutoff_frequency; Darray *fc3_normal_squared; double *collision_matrix; double *g; double *frequencies; long(*triplets)[3]; long *triplets_map; long num_gp; long *map_q; if (!PyArg_ParseTuple( args, "OOOOOOOddd", &py_collision_matrix, &py_fc3_normal_squared, &py_frequencies, &py_g, &py_triplets, &py_triplets_map, &py_map_q, &temperature, &unit_conversion_factor, &cutoff_frequency)) { return NULL; } fc3_normal_squared = convert_to_darray(py_fc3_normal_squared); collision_matrix = (double *)PyArray_DATA(py_collision_matrix); g = (double *)PyArray_DATA(py_g); frequencies = (double *)PyArray_DATA(py_frequencies); triplets = (long(*)[3])PyArray_DATA(py_triplets); triplets_map = (long *)PyArray_DATA(py_triplets_map); num_gp = (long)PyArray_DIMS(py_triplets_map)[0]; map_q = (long *)PyArray_DATA(py_map_q); ph3py_get_reducible_collision_matrix( collision_matrix, fc3_normal_squared, frequencies, triplets, triplets_map, map_q, g, num_gp, temperature, unit_conversion_factor, cutoff_frequency); free(fc3_normal_squared); fc3_normal_squared = NULL; Py_RETURN_NONE; } static PyObject *py_symmetrize_collision_matrix(PyObject *self, PyObject *args) { PyArrayObject *py_collision_matrix; double *collision_matrix; long num_band, num_grid_points, num_temp, num_sigma; long num_column; if (!PyArg_ParseTuple(args, "O", &py_collision_matrix)) { return NULL; } collision_matrix = (double *)PyArray_DATA(py_collision_matrix); num_sigma = (long)PyArray_DIMS(py_collision_matrix)[0]; num_temp = (long)PyArray_DIMS(py_collision_matrix)[1]; num_grid_points = (long)PyArray_DIMS(py_collision_matrix)[2]; num_band = (long)PyArray_DIMS(py_collision_matrix)[3]; if (PyArray_NDIM(py_collision_matrix) == 8) { num_column = num_grid_points * num_band * 3; } else { num_column = num_grid_points * num_band; } ph3py_symmetrize_collision_matrix(collision_matrix, num_column, num_temp, num_sigma); Py_RETURN_NONE; } static PyObject *py_expand_collision_matrix(PyObject *self, PyObject *args) { PyArrayObject *py_collision_matrix; PyArrayObject *py_ir_grid_points; PyArrayObject *py_rot_grid_points; double *collision_matrix; long *rot_grid_points; long *ir_grid_points; long num_band, num_grid_points, num_temp, num_sigma, num_rot, num_ir_gp; if (!PyArg_ParseTuple(args, "OOO", &py_collision_matrix, &py_ir_grid_points, &py_rot_grid_points)) { return NULL; } collision_matrix = (double *)PyArray_DATA(py_collision_matrix); rot_grid_points = (long *)PyArray_DATA(py_rot_grid_points); ir_grid_points = (long *)PyArray_DATA(py_ir_grid_points); num_sigma = (long)PyArray_DIMS(py_collision_matrix)[0]; num_temp = (long)PyArray_DIMS(py_collision_matrix)[1]; num_grid_points = (long)PyArray_DIMS(py_collision_matrix)[2]; num_band = (long)PyArray_DIMS(py_collision_matrix)[3]; num_rot = (long)PyArray_DIMS(py_rot_grid_points)[0]; num_ir_gp = (long)PyArray_DIMS(py_ir_grid_points)[0]; ph3py_expand_collision_matrix(collision_matrix, rot_grid_points, ir_grid_points, num_ir_gp, num_grid_points, num_rot, num_sigma, num_temp, num_band); Py_RETURN_NONE; } static PyObject *py_get_isotope_strength(PyObject *self, PyObject *args) { PyArrayObject *py_gamma; PyArrayObject *py_frequencies; PyArrayObject *py_eigenvectors; PyArrayObject *py_band_indices; PyArrayObject *py_mass_variances; long grid_point; long num_grid_points; double cutoff_frequency; double sigma; double *gamma; double *frequencies; lapack_complex_double *eigenvectors; long *band_indices; double *mass_variances; long num_band, num_band0; if (!PyArg_ParseTuple(args, "OlOOOOldd", &py_gamma, &grid_point, &py_mass_variances, &py_frequencies, &py_eigenvectors, &py_band_indices, &num_grid_points, &sigma, &cutoff_frequency)) { return NULL; } gamma = (double *)PyArray_DATA(py_gamma); frequencies = (double *)PyArray_DATA(py_frequencies); eigenvectors = (lapack_complex_double *)PyArray_DATA(py_eigenvectors); band_indices = (long *)PyArray_DATA(py_band_indices); mass_variances = (double *)PyArray_DATA(py_mass_variances); num_band = (long)PyArray_DIMS(py_frequencies)[1]; num_band0 = (long)PyArray_DIMS(py_band_indices)[0]; ph3py_get_isotope_scattering_strength( gamma, grid_point, mass_variances, frequencies, eigenvectors, num_grid_points, band_indices, num_band, num_band0, sigma, cutoff_frequency); Py_RETURN_NONE; } static PyObject *py_get_thm_isotope_strength(PyObject *self, PyObject *args) { PyArrayObject *py_gamma; PyArrayObject *py_frequencies; PyArrayObject *py_eigenvectors; PyArrayObject *py_band_indices; PyArrayObject *py_mass_variances; PyArrayObject *py_ir_grid_points; PyArrayObject *py_weights; PyArrayObject *py_integration_weights; long grid_point; double cutoff_frequency; double *gamma; double *frequencies; long *ir_grid_points; long *weights; lapack_complex_double *eigenvectors; long *band_indices; double *mass_variances; long num_band, num_band0, num_ir_grid_points; double *integration_weights; if (!PyArg_ParseTuple(args, "OlOOOOOOOd", &py_gamma, &grid_point, &py_ir_grid_points, &py_weights, &py_mass_variances, &py_frequencies, &py_eigenvectors, &py_band_indices, &py_integration_weights, &cutoff_frequency)) { return NULL; } gamma = (double *)PyArray_DATA(py_gamma); frequencies = (double *)PyArray_DATA(py_frequencies); ir_grid_points = (long *)PyArray_DATA(py_ir_grid_points); weights = (long *)PyArray_DATA(py_weights); eigenvectors = (lapack_complex_double *)PyArray_DATA(py_eigenvectors); band_indices = (long *)PyArray_DATA(py_band_indices); mass_variances = (double *)PyArray_DATA(py_mass_variances); num_band = (long)PyArray_DIMS(py_frequencies)[1]; num_band0 = (long)PyArray_DIMS(py_band_indices)[0]; integration_weights = (double *)PyArray_DATA(py_integration_weights); num_ir_grid_points = (long)PyArray_DIMS(py_ir_grid_points)[0]; ph3py_get_thm_isotope_scattering_strength( gamma, grid_point, ir_grid_points, weights, mass_variances, frequencies, eigenvectors, num_ir_grid_points, band_indices, num_band, num_band0, integration_weights, cutoff_frequency); Py_RETURN_NONE; } static PyObject *py_distribute_fc3(PyObject *self, PyObject *args) { PyArrayObject *force_constants_third; long target; long source; PyArrayObject *rotation_cart_inv; PyArrayObject *atom_mapping_py; double *fc3; double *rot_cart_inv; long *atom_mapping; long num_atom; if (!PyArg_ParseTuple(args, "OllOO", &force_constants_third, &target, &source, &atom_mapping_py, &rotation_cart_inv)) { return NULL; } fc3 = (double *)PyArray_DATA(force_constants_third); rot_cart_inv = (double *)PyArray_DATA(rotation_cart_inv); atom_mapping = (long *)PyArray_DATA(atom_mapping_py); num_atom = (long)PyArray_DIMS(atom_mapping_py)[0]; ph3py_distribute_fc3(fc3, target, source, atom_mapping, num_atom, rot_cart_inv); Py_RETURN_NONE; } static PyObject *py_rotate_delta_fc2s(PyObject *self, PyObject *args) { PyArrayObject *py_fc3; PyArrayObject *py_delta_fc2s; PyArrayObject *py_inv_U; PyArrayObject *py_site_sym_cart; PyArrayObject *py_rot_map_syms; double(*fc3)[3][3][3]; double(*delta_fc2s)[3][3]; double *inv_U; double(*site_sym_cart)[3][3]; long *rot_map_syms; long num_atom, num_disp, num_site_sym; if (!PyArg_ParseTuple(args, "OOOOO", &py_fc3, &py_delta_fc2s, &py_inv_U, &py_site_sym_cart, &py_rot_map_syms)) { return NULL; } /* (num_atom, num_atom, 3, 3, 3) */ fc3 = (double(*)[3][3][3])PyArray_DATA(py_fc3); /* (n_u1, num_atom, num_atom, 3, 3) */ delta_fc2s = (double(*)[3][3])PyArray_DATA(py_delta_fc2s); /* (3, n_u1 * n_sym) */ inv_U = (double *)PyArray_DATA(py_inv_U); /* (n_sym, 3, 3) */ site_sym_cart = (double(*)[3][3])PyArray_DATA(py_site_sym_cart); /* (n_sym, natom) */ rot_map_syms = (long *)PyArray_DATA(py_rot_map_syms); num_atom = (long)PyArray_DIMS(py_fc3)[0]; num_disp = (long)PyArray_DIMS(py_delta_fc2s)[0]; num_site_sym = (long)PyArray_DIMS(py_site_sym_cart)[0]; ph3py_rotate_delta_fc2(fc3, delta_fc2s, inv_U, site_sym_cart, rot_map_syms, num_atom, num_site_sym, num_disp); Py_RETURN_NONE; } static PyObject *py_get_permutation_symmetry_fc3(PyObject *self, PyObject *args) { PyArrayObject *py_fc3; double *fc3; long num_atom; if (!PyArg_ParseTuple(args, "O", &py_fc3)) { return NULL; } fc3 = (double *)PyArray_DATA(py_fc3); num_atom = (long)PyArray_DIMS(py_fc3)[0]; ph3py_get_permutation_symmetry_fc3(fc3, num_atom); Py_RETURN_NONE; } static PyObject *py_get_permutation_symmetry_compact_fc3(PyObject *self, PyObject *args) { PyArrayObject *py_fc3; PyArrayObject *py_permutations; PyArrayObject *py_s2pp_map; PyArrayObject *py_p2s_map; PyArrayObject *py_nsym_list; double *fc3; long *s2pp; long *p2s; long *nsym_list; long *perms; long n_patom, n_satom; if (!PyArg_ParseTuple(args, "OOOOO", &py_fc3, &py_permutations, &py_s2pp_map, &py_p2s_map, &py_nsym_list)) { return NULL; } fc3 = (double *)PyArray_DATA(py_fc3); perms = (long *)PyArray_DATA(py_permutations); s2pp = (long *)PyArray_DATA(py_s2pp_map); p2s = (long *)PyArray_DATA(py_p2s_map); nsym_list = (long *)PyArray_DATA(py_nsym_list); n_patom = (long)PyArray_DIMS(py_fc3)[0]; n_satom = (long)PyArray_DIMS(py_fc3)[1]; ph3py_get_permutation_symmetry_compact_fc3(fc3, p2s, s2pp, nsym_list, perms, n_satom, n_patom); Py_RETURN_NONE; } static PyObject *py_transpose_compact_fc3(PyObject *self, PyObject *args) { PyArrayObject *py_fc3; PyArrayObject *py_permutations; PyArrayObject *py_s2pp_map; PyArrayObject *py_p2s_map; PyArrayObject *py_nsym_list; long t_type; double *fc3; long *s2pp; long *p2s; long *nsym_list; long *perms; long n_patom, n_satom; if (!PyArg_ParseTuple(args, "OOOOOl", &py_fc3, &py_permutations, &py_s2pp_map, &py_p2s_map, &py_nsym_list, &t_type)) { return NULL; } fc3 = (double *)PyArray_DATA(py_fc3); perms = (long *)PyArray_DATA(py_permutations); s2pp = (long *)PyArray_DATA(py_s2pp_map); p2s = (long *)PyArray_DATA(py_p2s_map); nsym_list = (long *)PyArray_DATA(py_nsym_list); n_patom = (long)PyArray_DIMS(py_fc3)[0]; n_satom = (long)PyArray_DIMS(py_fc3)[1]; ph3py_transpose_compact_fc3(fc3, p2s, s2pp, nsym_list, perms, n_satom, n_patom, t_type); Py_RETURN_NONE; } static PyObject *py_get_neighboring_grid_points(PyObject *self, PyObject *args) { PyArrayObject *py_relative_grid_points; PyArrayObject *py_grid_points; PyArrayObject *py_relative_grid_address; PyArrayObject *py_D_diag; PyArrayObject *py_bz_grid_address; PyArrayObject *py_bz_map; long bz_grid_type; long *relative_grid_points; long *grid_points; long num_grid_points, num_relative_grid_address; long(*relative_grid_address)[3]; long *D_diag; long(*bz_grid_address)[3]; long *bz_map; if (!PyArg_ParseTuple(args, "OOOOOOl", &py_relative_grid_points, &py_grid_points, &py_relative_grid_address, &py_D_diag, &py_bz_grid_address, &py_bz_map, &bz_grid_type)) { return NULL; } relative_grid_points = (long *)PyArray_DATA(py_relative_grid_points); grid_points = (long *)PyArray_DATA(py_grid_points); num_grid_points = (long)PyArray_DIMS(py_grid_points)[0]; relative_grid_address = (long(*)[3])PyArray_DATA(py_relative_grid_address); num_relative_grid_address = (long)PyArray_DIMS(py_relative_grid_address)[0]; D_diag = (long *)PyArray_DATA(py_D_diag); bz_grid_address = (long(*)[3])PyArray_DATA(py_bz_grid_address); bz_map = (long *)PyArray_DATA(py_bz_map); ph3py_get_neighboring_gird_points( relative_grid_points, grid_points, relative_grid_address, D_diag, bz_grid_address, bz_map, bz_grid_type, num_grid_points, num_relative_grid_address); Py_RETURN_NONE; } static PyObject *py_get_thm_integration_weights_at_grid_points(PyObject *self, PyObject *args) { PyArrayObject *py_iw; PyArrayObject *py_frequency_points; PyArrayObject *py_relative_grid_address; PyArrayObject *py_D_diag; PyArrayObject *py_grid_points; PyArrayObject *py_frequencies; PyArrayObject *py_bz_grid_address; PyArrayObject *py_gp2irgp_map; PyArrayObject *py_bz_map; long bz_grid_type; char *function; double *iw; double *frequency_points; long num_frequency_points, num_band, num_gp; long(*relative_grid_address)[4][3]; long *D_diag; long *grid_points; long(*bz_grid_address)[3]; long *bz_map; long *gp2irgp_map; double *frequencies; if (!PyArg_ParseTuple(args, "OOOOOOOOOls", &py_iw, &py_frequency_points, &py_relative_grid_address, &py_D_diag, &py_grid_points, &py_frequencies, &py_bz_grid_address, &py_bz_map, &py_gp2irgp_map, &bz_grid_type, &function)) { return NULL; } iw = (double *)PyArray_DATA(py_iw); frequency_points = (double *)PyArray_DATA(py_frequency_points); num_frequency_points = (long)PyArray_DIMS(py_frequency_points)[0]; relative_grid_address = (long(*)[4][3])PyArray_DATA(py_relative_grid_address); D_diag = (long *)PyArray_DATA(py_D_diag); grid_points = (long *)PyArray_DATA(py_grid_points); num_gp = (long)PyArray_DIMS(py_grid_points)[0]; bz_grid_address = (long(*)[3])PyArray_DATA(py_bz_grid_address); bz_map = (long *)PyArray_DATA(py_bz_map); gp2irgp_map = (long *)PyArray_DATA(py_gp2irgp_map); frequencies = (double *)PyArray_DATA(py_frequencies); num_band = (long)PyArray_DIMS(py_frequencies)[1]; ph3py_get_thm_integration_weights_at_grid_points( iw, frequency_points, num_frequency_points, num_band, num_gp, relative_grid_address, D_diag, grid_points, bz_grid_address, bz_map, bz_grid_type, frequencies, gp2irgp_map, function[0]); Py_RETURN_NONE; } static PyObject *py_tpl_get_triplets_reciprocal_mesh_at_q(PyObject *self, PyObject *args) { PyArrayObject *py_map_triplets; PyArrayObject *py_map_q; PyArrayObject *py_D_diag; PyArrayObject *py_rotations; long fixed_grid_number; long is_time_reversal; long swappable; long *map_triplets; long *map_q; long *D_diag; long(*rot)[3][3]; long num_rot; long num_ir; if (!PyArg_ParseTuple(args, "OOlOlOl", &py_map_triplets, &py_map_q, &fixed_grid_number, &py_D_diag, &is_time_reversal, &py_rotations, &swappable)) { return NULL; } map_triplets = (long *)PyArray_DATA(py_map_triplets); map_q = (long *)PyArray_DATA(py_map_q); D_diag = (long *)PyArray_DATA(py_D_diag); rot = (long(*)[3][3])PyArray_DATA(py_rotations); num_rot = (long)PyArray_DIMS(py_rotations)[0]; num_ir = ph3py_get_triplets_reciprocal_mesh_at_q( map_triplets, map_q, fixed_grid_number, D_diag, is_time_reversal, num_rot, rot, swappable); return PyLong_FromLong(num_ir); } static PyObject *py_tpl_get_BZ_triplets_at_q(PyObject *self, PyObject *args) { PyArrayObject *py_triplets; PyArrayObject *py_bz_grid_address; PyArrayObject *py_bz_map; PyArrayObject *py_map_triplets; PyArrayObject *py_D_diag; PyArrayObject *py_Q; long grid_point; long bz_grid_type; long(*triplets)[3]; long(*bz_grid_address)[3]; long *bz_map; long *map_triplets; long num_map_triplets; long *D_diag; long(*Q)[3]; long num_ir; if (!PyArg_ParseTuple(args, "OlOOOOOl", &py_triplets, &grid_point, &py_bz_grid_address, &py_bz_map, &py_map_triplets, &py_D_diag, &py_Q, &bz_grid_type)) { return NULL; } triplets = (long(*)[3])PyArray_DATA(py_triplets); bz_grid_address = (long(*)[3])PyArray_DATA(py_bz_grid_address); bz_map = (long *)PyArray_DATA(py_bz_map); map_triplets = (long *)PyArray_DATA(py_map_triplets); num_map_triplets = (long)PyArray_DIMS(py_map_triplets)[0]; D_diag = (long *)PyArray_DATA(py_D_diag); Q = (long(*)[3])PyArray_DATA(py_Q); num_ir = ph3py_get_BZ_triplets_at_q(triplets, grid_point, bz_grid_address, bz_map, map_triplets, num_map_triplets, D_diag, Q, bz_grid_type); return PyLong_FromLong(num_ir); } static PyObject *py_get_triplets_integration_weights(PyObject *self, PyObject *args) { PyArrayObject *py_iw; PyArrayObject *py_iw_zero; PyArrayObject *py_frequency_points; PyArrayObject *py_relative_grid_address; PyArrayObject *py_D_diag; PyArrayObject *py_triplets; PyArrayObject *py_frequencies1; PyArrayObject *py_frequencies2; PyArrayObject *py_bz_grid_addresses; PyArrayObject *py_bz_map; long bz_grid_type; long tp_type; double *iw; char *iw_zero; double *frequency_points; long(*relative_grid_address)[4][3]; long *D_diag; long(*triplets)[3]; long(*bz_grid_addresses)[3]; long *bz_map; double *frequencies1, *frequencies2; long num_band0, num_band1, num_band2, num_triplets; if (!PyArg_ParseTuple(args, "OOOOOOOOOOll", &py_iw, &py_iw_zero, &py_frequency_points, &py_relative_grid_address, &py_D_diag, &py_triplets, &py_frequencies1, &py_frequencies2, &py_bz_grid_addresses, &py_bz_map, &bz_grid_type, &tp_type)) { return NULL; } iw = (double *)PyArray_DATA(py_iw); iw_zero = (char *)PyArray_DATA(py_iw_zero); frequency_points = (double *)PyArray_DATA(py_frequency_points); num_band0 = (long)PyArray_DIMS(py_frequency_points)[0]; relative_grid_address = (long(*)[4][3])PyArray_DATA(py_relative_grid_address); D_diag = (long *)PyArray_DATA(py_D_diag); triplets = (long(*)[3])PyArray_DATA(py_triplets); num_triplets = (long)PyArray_DIMS(py_triplets)[0]; bz_grid_addresses = (long(*)[3])PyArray_DATA(py_bz_grid_addresses); bz_map = (long *)PyArray_DATA(py_bz_map); frequencies1 = (double *)PyArray_DATA(py_frequencies1); frequencies2 = (double *)PyArray_DATA(py_frequencies2); num_band1 = (long)PyArray_DIMS(py_frequencies1)[1]; num_band2 = (long)PyArray_DIMS(py_frequencies2)[1]; ph3py_get_integration_weight( iw, iw_zero, frequency_points, num_band0, relative_grid_address, D_diag, triplets, num_triplets, bz_grid_addresses, bz_map, bz_grid_type, frequencies1, num_band1, frequencies2, num_band2, tp_type, 1, 0); Py_RETURN_NONE; } static PyObject *py_get_triplets_integration_weights_with_sigma( PyObject *self, PyObject *args) { PyArrayObject *py_iw; PyArrayObject *py_iw_zero; PyArrayObject *py_frequency_points; PyArrayObject *py_triplets; PyArrayObject *py_frequencies; double sigma, sigma_cutoff; double *iw; char *iw_zero; double *frequency_points; long(*triplets)[3]; double *frequencies; long num_band0, num_band, num_iw, num_triplets; if (!PyArg_ParseTuple(args, "OOOOOdd", &py_iw, &py_iw_zero, &py_frequency_points, &py_triplets, &py_frequencies, &sigma, &sigma_cutoff)) { return NULL; } iw = (double *)PyArray_DATA(py_iw); iw_zero = (char *)PyArray_DATA(py_iw_zero); frequency_points = (double *)PyArray_DATA(py_frequency_points); num_band0 = (long)PyArray_DIMS(py_frequency_points)[0]; triplets = (long(*)[3])PyArray_DATA(py_triplets); num_triplets = (long)PyArray_DIMS(py_triplets)[0]; frequencies = (double *)PyArray_DATA(py_frequencies); num_band = (long)PyArray_DIMS(py_frequencies)[1]; num_iw = (long)PyArray_DIMS(py_iw)[0]; ph3py_get_integration_weight_with_sigma( iw, iw_zero, sigma, sigma_cutoff, frequency_points, num_band0, triplets, num_triplets, frequencies, num_band, num_iw); Py_RETURN_NONE; } static PyObject *py_get_grid_index_from_address(PyObject *self, PyObject *args) { PyArrayObject *py_address; PyArrayObject *py_D_diag; long *address; long *D_diag; long gp; if (!PyArg_ParseTuple(args, "OO", &py_address, &py_D_diag)) { return NULL; } address = (long *)PyArray_DATA(py_address); D_diag = (long *)PyArray_DATA(py_D_diag); gp = ph3py_get_grid_index_from_address(address, D_diag); return PyLong_FromLong(gp); } static PyObject *py_get_gr_grid_addresses(PyObject *self, PyObject *args) { PyArrayObject *py_gr_grid_addresses; PyArrayObject *py_D_diag; long(*gr_grid_addresses)[3]; long *D_diag; if (!PyArg_ParseTuple(args, "OO", &py_gr_grid_addresses, &py_D_diag)) { return NULL; } gr_grid_addresses = (long(*)[3])PyArray_DATA(py_gr_grid_addresses); D_diag = (long *)PyArray_DATA(py_D_diag); ph3py_get_gr_grid_addresses(gr_grid_addresses, D_diag); Py_RETURN_NONE; } static PyObject *py_get_reciprocal_rotations(PyObject *self, PyObject *args) { PyArrayObject *py_rec_rotations; PyArrayObject *py_rotations; long is_time_reversal; long(*rec_rotations)[3][3]; long(*rotations)[3][3]; long num_rot, num_rec_rot; if (!PyArg_ParseTuple(args, "OOl", &py_rec_rotations, &py_rotations, &is_time_reversal)) { return NULL; } rec_rotations = (long(*)[3][3])PyArray_DATA(py_rec_rotations); rotations = (long(*)[3][3])PyArray_DATA(py_rotations); num_rot = (long)PyArray_DIMS(py_rotations)[0]; num_rec_rot = ph3py_get_reciprocal_rotations(rec_rotations, rotations, num_rot, is_time_reversal); return PyLong_FromLong(num_rec_rot); } static PyObject *py_transform_rotations(PyObject *self, PyObject *args) { PyArrayObject *py_transformed_rotations; PyArrayObject *py_rotations; PyArrayObject *py_D_diag; PyArrayObject *py_Q; long(*transformed_rotations)[3][3]; long(*rotations)[3][3]; long *D_diag; long(*Q)[3]; long num_rot, succeeded; if (!PyArg_ParseTuple(args, "OOOO", &py_transformed_rotations, &py_rotations, &py_D_diag, &py_Q)) { return NULL; } transformed_rotations = (long(*)[3][3])PyArray_DATA(py_transformed_rotations); rotations = (long(*)[3][3])PyArray_DATA(py_rotations); D_diag = (long *)PyArray_DATA(py_D_diag); Q = (long(*)[3])PyArray_DATA(py_Q); num_rot = (long)PyArray_DIMS(py_transformed_rotations)[0]; succeeded = ph3py_transform_rotations(transformed_rotations, rotations, num_rot, D_diag, Q); if (succeeded) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *py_get_snf3x3(PyObject *self, PyObject *args) { PyArrayObject *py_D_diag; PyArrayObject *py_P; PyArrayObject *py_Q; PyArrayObject *py_A; long *D_diag; long(*P)[3]; long(*Q)[3]; long(*A)[3]; long succeeded; if (!PyArg_ParseTuple(args, "OOOO", &py_D_diag, &py_P, &py_Q, &py_A)) { return NULL; } D_diag = (long *)PyArray_DATA(py_D_diag); P = (long(*)[3])PyArray_DATA(py_P); Q = (long(*)[3])PyArray_DATA(py_Q); A = (long(*)[3])PyArray_DATA(py_A); succeeded = ph3py_get_snf3x3(D_diag, P, Q, A); if (succeeded) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *py_get_ir_grid_map(PyObject *self, PyObject *args) { PyArrayObject *py_grid_mapping_table; PyArrayObject *py_D_diag; PyArrayObject *py_is_shift; PyArrayObject *py_rotations; long *D_diag; long *is_shift; long(*rot)[3][3]; long num_rot; long *grid_mapping_table; long num_ir; if (!PyArg_ParseTuple(args, "OOOO", &py_grid_mapping_table, &py_D_diag, &py_is_shift, &py_rotations)) { return NULL; } D_diag = (long *)PyArray_DATA(py_D_diag); is_shift = (long *)PyArray_DATA(py_is_shift); rot = (long(*)[3][3])PyArray_DATA(py_rotations); num_rot = (long)PyArray_DIMS(py_rotations)[0]; grid_mapping_table = (long *)PyArray_DATA(py_grid_mapping_table); num_ir = ph3py_get_ir_grid_map(grid_mapping_table, D_diag, is_shift, rot, num_rot); return PyLong_FromLong(num_ir); } static PyObject *py_get_bz_grid_addresses(PyObject *self, PyObject *args) { PyArrayObject *py_bz_grid_addresses; PyArrayObject *py_bz_map; PyArrayObject *py_bzg2grg; PyArrayObject *py_D_diag; PyArrayObject *py_Q; PyArrayObject *py_PS; PyArrayObject *py_reciprocal_lattice; long type; long(*bz_grid_addresses)[3]; long *bz_map; long *bzg2grg; long *D_diag; long(*Q)[3]; long *PS; double(*reciprocal_lattice)[3]; long num_total_gp; if (!PyArg_ParseTuple(args, "OOOOOOOl", &py_bz_grid_addresses, &py_bz_map, &py_bzg2grg, &py_D_diag, &py_Q, &py_PS, &py_reciprocal_lattice, &type)) { return NULL; } bz_grid_addresses = (long(*)[3])PyArray_DATA(py_bz_grid_addresses); bz_map = (long *)PyArray_DATA(py_bz_map); bzg2grg = (long *)PyArray_DATA(py_bzg2grg); D_diag = (long *)PyArray_DATA(py_D_diag); Q = (long(*)[3])PyArray_DATA(py_Q); PS = (long *)PyArray_DATA(py_PS); reciprocal_lattice = (double(*)[3])PyArray_DATA(py_reciprocal_lattice); num_total_gp = ph3py_get_bz_grid_addresses(bz_grid_addresses, bz_map, bzg2grg, D_diag, Q, PS, reciprocal_lattice, type); return PyLong_FromLong(num_total_gp); } static PyObject *py_rotate_bz_grid_addresses(PyObject *self, PyObject *args) { PyArrayObject *py_bz_grid_addresses; PyArrayObject *py_rotation; PyArrayObject *py_bz_map; PyArrayObject *py_D_diag; PyArrayObject *py_PS; long bz_grid_index; long type; long(*bz_grid_addresses)[3]; long(*rotation)[3]; long *bz_map; long *D_diag; long *PS; long ret_bz_gp; if (!PyArg_ParseTuple(args, "lOOOOOl", &bz_grid_index, &py_rotation, &py_bz_grid_addresses, &py_bz_map, &py_D_diag, &py_PS, &type)) { return NULL; } bz_grid_addresses = (long(*)[3])PyArray_DATA(py_bz_grid_addresses); rotation = (long(*)[3])PyArray_DATA(py_rotation); bz_map = (long *)PyArray_DATA(py_bz_map); D_diag = (long *)PyArray_DATA(py_D_diag); PS = (long *)PyArray_DATA(py_PS); ret_bz_gp = ph3py_rotate_bz_grid_index( bz_grid_index, rotation, bz_grid_addresses, bz_map, D_diag, PS, type); return PyLong_FromLong(ret_bz_gp); } static PyObject *py_diagonalize_collision_matrix(PyObject *self, PyObject *args) { PyArrayObject *py_collision_matrix; PyArrayObject *py_eigenvalues; double cutoff; long i_sigma, i_temp, is_pinv, solver; double *collision_matrix; double *eigvals; long num_temp, num_grid_point, num_band; long num_column, adrs_shift; long info; if (!PyArg_ParseTuple(args, "OOlldll", &py_collision_matrix, &py_eigenvalues, &i_sigma, &i_temp, &cutoff, &solver, &is_pinv)) { return NULL; } collision_matrix = (double *)PyArray_DATA(py_collision_matrix); eigvals = (double *)PyArray_DATA(py_eigenvalues); if (PyArray_NDIM(py_collision_matrix) == 2) { num_temp = 1; num_column = (long)PyArray_DIM(py_collision_matrix, 1); } else { num_temp = (long)PyArray_DIM(py_collision_matrix, 1); num_grid_point = (long)PyArray_DIM(py_collision_matrix, 2); num_band = (long)PyArray_DIM(py_collision_matrix, 3); if (PyArray_NDIM(py_collision_matrix) == 8) { num_column = num_grid_point * num_band * 3; } else { num_column = num_grid_point * num_band; } } adrs_shift = (i_sigma * num_column * num_column * num_temp + i_temp * num_column * num_column); /* show_colmat_info(py_collision_matrix, i_sigma, i_temp, adrs_shift); */ info = phonopy_dsyev(collision_matrix + adrs_shift, eigvals, num_column, solver); if (is_pinv) { pinv_from_eigensolution(collision_matrix + adrs_shift, eigvals, num_column, cutoff, 0); } return PyLong_FromLong(info); } static PyObject *py_pinv_from_eigensolution(PyObject *self, PyObject *args) { PyArrayObject *py_collision_matrix; PyArrayObject *py_eigenvalues; double cutoff; long i_sigma, i_temp, pinv_method; double *collision_matrix; double *eigvals; long num_temp, num_grid_point, num_band; long num_column, adrs_shift; if (!PyArg_ParseTuple(args, "OOlldl", &py_collision_matrix, &py_eigenvalues, &i_sigma, &i_temp, &cutoff, &pinv_method)) { return NULL; } collision_matrix = (double *)PyArray_DATA(py_collision_matrix); eigvals = (double *)PyArray_DATA(py_eigenvalues); num_temp = (long)PyArray_DIMS(py_collision_matrix)[1]; num_grid_point = (long)PyArray_DIMS(py_collision_matrix)[2]; num_band = (long)PyArray_DIMS(py_collision_matrix)[3]; if (PyArray_NDIM(py_collision_matrix) == 8) { num_column = num_grid_point * num_band * 3; } else { num_column = num_grid_point * num_band; } adrs_shift = (i_sigma * num_column * num_column * num_temp + i_temp * num_column * num_column); /* show_colmat_info(py_collision_matrix, i_sigma, i_temp, adrs_shift); */ pinv_from_eigensolution(collision_matrix + adrs_shift, eigvals, num_column, cutoff, pinv_method); Py_RETURN_NONE; } static PyObject *py_get_default_colmat_solver(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } #if defined(MKL_LAPACKE) || defined(SCIPY_MKL_H) return PyLong_FromLong((long)1); #else return PyLong_FromLong((long)4); #endif } static void pinv_from_eigensolution(double *data, const double *eigvals, const long size, const double cutoff, const long pinv_method) { long i, ib, j, k, max_l, i_s, j_s; double *tmp_data; double e, sum; long *l; l = NULL; tmp_data = NULL; tmp_data = (double *)malloc(sizeof(double) * size * size); #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < size * size; i++) { tmp_data[i] = data[i]; } l = (long *)malloc(sizeof(long) * size); max_l = 0; for (i = 0; i < size; i++) { if (pinv_method == 0) { e = fabs(eigvals[i]); } else { e = eigvals[i]; } if (e > cutoff) { l[max_l] = i; max_l++; } } #ifdef _OPENMP #pragma omp parallel for private(ib, j, k, i_s, j_s, sum) #endif for (i = 0; i < size / 2; i++) { /* from front */ i_s = i * size; for (j = i; j < size; j++) { j_s = j * size; sum = 0; for (k = 0; k < max_l; k++) { sum += tmp_data[i_s + l[k]] * tmp_data[j_s + l[k]] / eigvals[l[k]]; } data[i_s + j] = sum; data[j_s + i] = sum; } /* from back */ ib = size - i - 1; i_s = ib * size; for (j = ib; j < size; j++) { j_s = j * size; sum = 0; for (k = 0; k < max_l; k++) { sum += tmp_data[i_s + l[k]] * tmp_data[j_s + l[k]] / eigvals[l[k]]; } data[i_s + j] = sum; data[j_s + ib] = sum; } } /* when size is odd */ if ((size % 2) == 1) { i = (size - 1) / 2; i_s = i * size; for (j = i; j < size; j++) { j_s = j * size; sum = 0; for (k = 0; k < max_l; k++) { sum += tmp_data[i_s + l[k]] * tmp_data[j_s + l[k]] / eigvals[l[k]]; } data[i_s + j] = sum; data[j_s + i] = sum; } } free(l); l = NULL; free(tmp_data); tmp_data = NULL; } static void show_colmat_info(const PyArrayObject *py_collision_matrix, const long i_sigma, const long i_temp, const long adrs_shift) { long i; printf(" Array_shape:("); for (i = 0; i < PyArray_NDIM(py_collision_matrix); i++) { printf("%d", (int)PyArray_DIM(py_collision_matrix, i)); if (i < PyArray_NDIM(py_collision_matrix) - 1) { printf(","); } else { printf("), "); } } printf("Data shift:%lu [%lu, %lu]\n", adrs_shift, i_sigma, i_temp); } static Larray *convert_to_larray(const PyArrayObject *npyary) { long i; Larray *ary; ary = (Larray *)malloc(sizeof(Larray)); for (i = 0; i < PyArray_NDIM(npyary); i++) { ary->dims[i] = PyArray_DIMS(npyary)[i]; } ary->data = (long *)PyArray_DATA(npyary); return ary; } static Darray *convert_to_darray(const PyArrayObject *npyary) { int i; Darray *ary; ary = (Darray *)malloc(sizeof(Darray)); for (i = 0; i < PyArray_NDIM(npyary); i++) { ary->dims[i] = PyArray_DIMS(npyary)[i]; } ary->data = (double *)PyArray_DATA(npyary); return ary; }
irbuilder_nested_openmp_parallel_empty.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -x c++ -emit-llvm %s -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -o - | FileCheck %s --check-prefixes=ALL,IRBUILDER // %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o /tmp/t1 %s // %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -debug-info-kind=limited -std=c++11 -include-pch /tmp/t1 -verify %s -emit-llvm -o - | FileCheck --check-prefixes=ALL-DEBUG,IRBUILDER-DEBUG %s // expected-no-diagnostics // TODO: Teach the update script to check new functions too. #ifndef HEADER #define HEADER // ALL-LABEL: @_Z17nested_parallel_0v( // ALL-NEXT: entry: // ALL-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]]) // ALL-NEXT: br label [[OMP_PARALLEL:%.*]] // ALL: omp_parallel: // ALL-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* @_Z17nested_parallel_0v..omp_par.1 to void (i32*, i32*, ...)*)) // ALL-NEXT: br label [[OMP_PAR_OUTLINED_EXIT12:%.*]] // ALL: omp.par.outlined.exit12: // ALL-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // ALL: omp.par.exit.split: // ALL-NEXT: ret void // void nested_parallel_0(void) { #pragma omp parallel { #pragma omp parallel { } } } // ALL-LABEL: @_Z17nested_parallel_1Pfid( // ALL-NEXT: entry: // ALL-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // ALL-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // ALL-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // ALL-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // ALL-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // ALL-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // ALL-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // ALL-NEXT: br label [[OMP_PARALLEL:%.*]] // ALL: omp_parallel: // ALL-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i32*, double*, float**)* @_Z17nested_parallel_1Pfid..omp_par.2 to void (i32*, i32*, ...)*), i32* [[A_ADDR]], double* [[B_ADDR]], float** [[R_ADDR]]) // ALL-NEXT: br label [[OMP_PAR_OUTLINED_EXIT13:%.*]] // ALL: omp.par.outlined.exit13: // ALL-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // ALL: omp.par.exit.split: // ALL-NEXT: ret void // void nested_parallel_1(float *r, int a, double b) { #pragma omp parallel { #pragma omp parallel { *r = a + b; } } } // ALL-LABEL: @_Z17nested_parallel_2Pfid( // ALL-NEXT: entry: // ALL-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // ALL-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // ALL-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // ALL-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // ALL-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // ALL-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // ALL-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // ALL-NEXT: br label [[OMP_PARALLEL:%.*]] // ALL: omp_parallel: // ALL-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i32*, double*, float**)* @_Z17nested_parallel_2Pfid..omp_par.5 to void (i32*, i32*, ...)*), i32* [[A_ADDR]], double* [[B_ADDR]], float** [[R_ADDR]]) // ALL-NEXT: br label [[OMP_PAR_OUTLINED_EXIT55:%.*]] // ALL: omp.par.outlined.exit55: // ALL-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // ALL: omp.par.exit.split: // ALL-NEXT: [[TMP0:%.*]] = load i32, i32* [[A_ADDR]], align 4 // ALL-NEXT: [[CONV56:%.*]] = sitofp i32 [[TMP0]] to double // ALL-NEXT: [[TMP1:%.*]] = load double, double* [[B_ADDR]], align 8 // ALL-NEXT: [[ADD57:%.*]] = fadd double [[CONV56]], [[TMP1]] // ALL-NEXT: [[CONV58:%.*]] = fptrunc double [[ADD57]] to float // ALL-NEXT: [[TMP2:%.*]] = load float*, float** [[R_ADDR]], align 8 // ALL-NEXT: store float [[CONV58]], float* [[TMP2]], align 4 // ALL-NEXT: ret void // void nested_parallel_2(float *r, int a, double b) { #pragma omp parallel { *r = a + b; #pragma omp parallel { *r = a + b; #pragma omp parallel { *r = a + b; } *r = a + b; #pragma omp parallel { *r = a + b; } *r = a + b; } *r = a + b; } *r = a + b; } #endif
common.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #pragma once #ifndef COMMON_H #define COMMON_H // Since we call cblas_dgemm in openmp for loop, // we call "extension" APIs for setting the number of threads. #ifdef USE_INTEL_MKL #include <mkl.h> #if INTEL_MKL_VERSION < 20170000 // Will throw an error at development time in non-standard settings PLEASE DONOT COMPILE SHARED LIBRARIES WITH OLDER MKL VERSIONS #endif #include <mkl_service.h> extern "C" void mkl_set_num_threads(int numThreads); #else #include <cblas.h> extern "C" void openblas_set_num_threads(int numThreads); #endif template<class FP> size_t computeNNZ(FP* arr, int limit) { size_t nnz = 0; #ifndef USE_INTEL_MKL #pragma omp parallel for reduction(+: nnz) #endif for(int i=0; i<limit; i++) nnz += (arr[i]!=0) ? 1 : 0; return nnz; } static int SYSDS_CURRENT_NUM_THREADS = -1; static void setNumThreadsForBLAS(int numThreads) { if (SYSDS_CURRENT_NUM_THREADS != numThreads) { #ifdef USE_OPEN_BLAS openblas_set_num_threads(numThreads); #else mkl_set_num_threads(numThreads); #endif SYSDS_CURRENT_NUM_THREADS = numThreads; } } #endif // COMMON_H
atomic_utilities.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // Denis Demidov // #if !defined(KRATOS_ATOMIC_UTILITIES_H_INCLUDED ) #define KRATOS_ATOMIC_UTILITIES_H_INCLUDED // System includes // External includes #ifdef KRATOS_SMP_OPENMP #include <omp.h> #endif // Project includes #include "includes/define.h" namespace Kratos { ///@addtogroup KratosCore /** * collection of utilities for atomic updates of simple types. (essentially mimics the omp atomic) */ /** @param target variable being atomically updated by doing target += value * @param value value being added */ template<class TDataType> inline void AtomicAdd(TDataType& target, const TDataType& value ) { #pragma omp atomic target += value; } /** @param target vector variable being atomically updated by doing target += value * @param value vector value being added * Note that the update is not really atomic, but rather is done component by component */ template<class TVectorType1, class TVectorType2> inline void AtomicAdd(TVectorType1& target, const TVectorType2& value ) { KRATOS_DEBUG_ERROR_IF(target.size() != value.size()) << "vector size mismatch in vector AtomicAdd- Sizes are: " << target.size() << " for target and " << value.size() << " for value " <<std::endl; for(unsigned int i=0; i<target.size(); ++i){ AtomicAdd(target[i], value[i]); } } /** @param target vector variable being atomically updated by doing target -= value * @param value vector value being subtracted * Note that the update is not really atomic, but rather is done component by component */ template<class TDataType> inline void AtomicSub(TDataType& target, const TDataType& value ) { #pragma omp atomic target -= value; } /** @param target vector variable being atomically updated by doing target -= value * @param value vector value being subtracted * Note that the update is not really atomic, but rather is done component by component */ template<class TVectorType1, class TVectorType2> inline void AtomicSub(TVectorType1& target, const TVectorType2& value ) { KRATOS_DEBUG_ERROR_IF(target.size() != value.size()) << "vector size mismatch in vector AtomicSub- Sizes are: " << target.size() << " for target and " << value.size() << " for value " <<std::endl; for(unsigned int i=0; i<target.size(); ++i){ AtomicSub(target[i], value[i]); } } } // namespace Kratos. #endif // KRATOS_ATOMIC_UTILITIES_H_INCLUDED defined
PosTransformer.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: // // File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. ////////////////////////////////////////////////////////////////////////////////////// // -*- C++ -*- /** @file VectorOperators.h * @brief Support funtions to handle position type data manged by soa */ #ifndef QMCPLUSPLUS_SOA_FAST_PARTICLE_OPERATORS_H #define QMCPLUSPLUS_SOA_FAST_PARTICLE_OPERATORS_H #include <simd/blas1.hpp> namespace qmcplusplus { //Need to reorg #if 0 /** Dummy template class to be specialized * * - T1 the datatype to be transformed * - D dimension */ template<class T1, unsigned D> struct PosTransformer { }; /** Specialized PosTransformer<T,3,true> using only the diagonal elements */ template<class T> struct PosTransformer<T,3> { using Array_t=VectorSoaContainer<T,3>; using Transformer_t=Tensor<T,3>; inline static void apply(const Array_t& pin, const Transformer_t& X, Array_t& pout, int first, int last) { const int n=last-first; register T x00=X[0],x01=X[1],x02=X[2], x10=X[3],x11=X[4],x12=X[5], x20=X[6],x21=X[7],x22=X[8]; const T* restrict x_in=pin.data(0)+first; ASSUME_ALIGNED(x_in); const T* restrict y_in=pin.data(1)+first; ASSUME_ALIGNED(y_in); const T* restrict z_in=pin.data(2)+first; ASSUME_ALIGNED(z_in); T* restrict x_out=pout.data(0)+first; ASSUME_ALIGNED(x_out); T* restrict y_out=pout.data(1)+first; ASSUME_ALIGNED(y_out); T* restrict z_out=pout.data(2)+first; ASSUME_ALIGNED(z_out); #pragma ivdep for(int i=0; i<n; i++) { x_out[i]=x_in[i]*x00+y_in[i]*x10+z_in[i]*x20; y_out[i]=x_in[i]*x01+y_in[i]*x11+z_in[i]*x21; z_out[i]=x_in[i]*x02+y_in[i]*x12+z_in[i]*x22; } } inline static void apply(const Transformer_t& X, const Array_t& pin, Array_t& pout, int first, int last) { ::apply(pin,X,pout,first,last); } inline static void apply(Array_t& pinout, const Transformer_t& X,int first, int last) { const int n=last-first; register T x00=X[0],x01=X[1],x02=X[2], x10=X[3],x11=X[4],x12=X[5], x20=X[6],x21=X[7],x22=X[8]; T* restrict x_inout=pinout.data(0)+first; ASSUME_ALIGNED(x_inout); T* restrict y_inout=pinout.data(1)+first; ASSUME_ALIGNED(y_inout); T* restrict z_inout=pinout.data(2)+first; ASSUME_ALIGNED(z_inout); #pragma ivdep for(int i=0; i<n; i++) { T x=x_inout[i]*x00+y_inout[i]*x10+z_inout[i]*x20; T y=x_inout[i]*x01+y_inout[i]*x11+z_inout[i]*x21; T z=x_inout[i]*x02+y_inout[i]*x12+z_inout[i]*x22; x_inout[i]=x; y_inout[i]=y; z_inout[i]=z; } } inline static void apply(const Transformer_t& X, Array_t& pinout, int first, int last) { ::apply(X,pinout,first,last); } }; #endif /** General conversion function from AoS[nrows][ncols] to SoA[ncols][ldb] * @param nrows the first dimension * @param ncols the second dimension * @param iptr input pointer * @param lda stride of iptr * @param out output pointer * @param lda strided of out * * Modeled after blas/lapack for lda/ldb */ template<typename T1, typename T2> void PosAoS2SoA(int nrows, int ncols, const T1* restrict iptr, int lda, T2* restrict out, int ldb) { T2* restrict x = out; T2* restrict y = out + ldb; T2* restrict z = out + 2 * ldb; #if !defined(__ibmxl__) #pragma omp simd aligned(x, y, z) #endif for (int i = 0; i < nrows; ++i) { x[i] = iptr[i * ncols]; //x[i]=in[i][0]; y[i] = iptr[i * ncols + 1]; //y[i]=in[i][1]; z[i] = iptr[i * ncols + 2]; //z[i]=in[i][2]; } } /** General conversion function from SoA[ncols][ldb] to AoS[nrows][ncols] * @param nrows the first dimension * @param ncols the second dimension * @param iptr input pointer * @param lda stride of iptr * @param out output pointer * @param lda strided of out * * Modeled after blas/lapack for lda/ldb */ template<typename T1, typename T2> void PosSoA2AoS(int nrows, int ncols, const T1* restrict iptr, int lda, T2* restrict out, int ldb) { const T1* restrict x = iptr; const T1* restrict y = iptr + lda; const T1* restrict z = iptr + 2 * lda; #if !defined(__ibmxl__) #pragma omp simd aligned(x, y, z) #endif for (int i = 0; i < nrows; ++i) { out[i * ldb] = x[i]; //out[i][0]=x[i]; out[i * ldb + 1] = y[i]; //out[i][1]=y[i]; out[i * ldb + 2] = z[i]; //out[i][2]=z[i]; } } #if 0 //#if defined(HAVE_MKL) ///specialization for double AoS2SoA template<> void PosAoS2SoA(int nrows, int ncols, const double* restrict in, int lda, double* restrict out, int ldb) { const double zone={1.0}; mkl_domatcopy('R','T',nrows,ncols,zone,in,lda,out,ldb); } ///specialization for float AoS2SoA template<> void PosAoS2SoA(int nrows, int ncols, const float* restrict in, int lda, float* restrict out, int ldb) { const float zone={1.0f}; mkl_somatcopy('R','T',nrows,ncols,zone,in,lda,out,ldb); } ///specialization for double SoA2AoS template<> void PosSoA2AoS(int nrows, int ncols, const double* restrict in, int lda, double* restrict out, int ldb) { const double zone={1.0}; mkl_domatcopy('R','T',nrows,ncols,zone,in,lda,out,ldb); } ///specialization for float SoA2AoS template<> void PosSoA2AoS(int nrows, int ncols, const float* restrict in, int lda, float* restrict out, int ldb) { const float zone={1.0f}; mkl_somatcopy('R','T',nrows,ncols,zone,in,lda,out,ldb); } #endif } // namespace qmcplusplus #endif
SpatialClassNLLCriterion.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "THNN/generic/SpatialClassNLLCriterion.c" #else #define INITIAL_CHECK \ THArgCheck(THIndexTensor_(nDimensionLegacyAll)(target) == 3, 3, \ "only batches of spatial targets supported (3D tensors)" \ " but got targets of dimension: %d", \ THIndexTensor_(nDimensionLegacyAll)(target)); \ THArgCheck(THTensor_(nDimensionLegacyAll)(input) == 4, 2, \ "only batches of spatial inputs supported (4D tensors), " \ "but got input of dimension: %d", THTensor_(nDimensionLegacyAll)(input)); \ if (weights && THTensor_(nElement)(weights) != THTensor_(size)(input, 1)) { \ THError("weight tensor should be defined either for all or no classes"); \ } \ \ { \ int64_t input0 = THTensor_(size)(input, 0); \ int64_t input1 = THTensor_(size)(input, 1); \ int64_t input2 = THTensor_(size)(input, 2); \ int64_t input3 = THTensor_(size)(input, 3); \ int64_t target0 = THIndexTensor_(size)(target, 0); \ int64_t target1 = THIndexTensor_(size)(target, 1); \ int64_t target2 = THIndexTensor_(size)(target, 2); \ THAssertMsg(input0 == target0 && input2 == target1 && input3 == target2, \ "size mismatch (got input: %ldx%ldx%ldx%ld, target: %ldx%ldx%ld)", \ input0, input1, input2, input3, target0, target1, target2); \ } #define GRADOUTPUT_SHAPE_CHECK \ THArgCheck(THTensor_(nDimensionLegacyAll)(gradOutput) == 3, 3, \ "gradOutput must have same dimension as target (3)" \ " but got dimension: %d", \ THTensor_(nDimensionLegacyAll)(gradOutput)); \ { \ int64_t gradOutput0 = THTensor_(size)(gradOutput, 0); \ int64_t gradOutput1 = THTensor_(size)(gradOutput, 1); \ int64_t gradOutput2 = THTensor_(size)(gradOutput, 2); \ int64_t target0 = THIndexTensor_(size)(target, 0); \ int64_t target1 = THIndexTensor_(size)(target, 1); \ int64_t target2 = THIndexTensor_(size)(target, 2); \ THAssertMsg( \ gradOutput0 == target0 && gradOutput1 == target1 && gradOutput2 == target2, \ "size mismatch (got gradOutput: %ldx%ldx%ld, target: %ldx%ldx%ld)", \ gradOutput0, gradOutput1, gradOutput2, target0, target1, target2); \ } void THNN_(SpatialClassNLLCriterion_updateOutput)( THNNState *state, THTensor *input, THIndexTensor *target, THTensor *output, int64_t reduction, THTensor *weights, THTensor *total_weight, int64_t ignore_index) { INITIAL_CHECK; THTensor_(resize1d)(output, 1); THTensor_(resize1d)(total_weight, 1); if (reduction == Reduction::None) { int64_t batch_size = THTensor_(size)(input, 0); int64_t H = THTensor_(size)(input, 2); int64_t W = THTensor_(size)(input, 3); THTensor_(resize3d)(output, batch_size, H, W); int64_t b, h, w; #pragma omp parallel for private(b, h, w) for (b = 0; b < batch_size; b++) { for (h = 0; h < H; h++) { for (w = 0; w < W; w++) { int64_t cur_target = (int64_t)THIndexTensor_(get3d)(target, b, h, w); if (cur_target == ignore_index) { THTensor_(fastSet3d)(output, b, h, w, 0.0f); continue; } scalar_t value = THTensor_(fastGet4d)(input, b, cur_target, h, w); scalar_t weight = weights ? THTensor_(fastGetLegacy1dNoScalars)(weights, cur_target) : 1.0f; THTensor_(fastSet3d)(output, b, h, w, -value * weight); } } } return; } input = THTensor_(newContiguous)(input); target = THIndexTensor_(newContiguous)(target); weights = weights ? THTensor_(newContiguous)(weights) : NULL; scalar_t *input_data = input->data<scalar_t>(); THIndex_t *target_data = THIndexTensor_(data)(target); scalar_t *weights_data = weights ? weights->data<scalar_t>() : NULL; scalar_t *output_data = output->data<scalar_t>(); scalar_t *total_weight_data = total_weight->data<scalar_t>(); int64_t batch_size = THTensor_(size)(input, 0); int64_t n_classes = THTensor_(size)(input, 1); int64_t map_size = THTensor_(size)(input, 2) * THTensor_(size)(input, 3); int64_t sample_size = map_size * n_classes; scalar_t total_weight_acc = 0; scalar_t output_acc = 0; for (int b = 0; b < batch_size; b++) { for (int elem = 0; elem < map_size; elem++) { int cur_target = target_data[b * map_size + elem]; if (cur_target == ignore_index) continue; THAssert(cur_target >= 0 && cur_target < n_classes); scalar_t cur_weight = weights ? weights_data[cur_target] : 1.0f; total_weight_acc += cur_weight; output_acc -= input_data[b * sample_size + cur_target * map_size + elem] * cur_weight; } } *total_weight_data = total_weight_acc; *output_data = output_acc; if (reduction == Reduction::Mean && *total_weight_data) *output_data /= *total_weight_data; c10::raw::intrusive_ptr::decref(input); THIndexTensor_(free)(target); if (weights) c10::raw::intrusive_ptr::decref(weights); } void THNN_(SpatialClassNLLCriterion_updateGradInput)( THNNState *state, THTensor *input, THIndexTensor *target, THTensor *gradOutput, THTensor *gradInput, int64_t reduction, THTensor *weights, THTensor *total_weight, int64_t ignore_index) { INITIAL_CHECK; THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); THArgCheck(THTensor_(isContiguous)(gradInput), 4, "gradInput must be contiguous"); THNN_CHECK_SHAPE(input, gradInput); if (reduction == Reduction::None) { GRADOUTPUT_SHAPE_CHECK; int64_t batch_size = THTensor_(size)(input, 0); int64_t H = THTensor_(size)(input, 2); int64_t W = THTensor_(size)(input, 3); int64_t b, h, w; #pragma omp parallel for private(b, h, w) for (b = 0; b < batch_size; b++) { for (h = 0; h < H; h++) { for (w = 0; w < W; w++) { int64_t cur_target = (int64_t)THIndexTensor_(get3d)(target, b, h, w); if (cur_target == ignore_index) { continue; } scalar_t value = -(weights ? THTensor_(fastGetLegacy1dNoScalars)(weights, cur_target) : 1.0f); scalar_t gradOutput_value = THTensor_(fastGet3d)(gradOutput, b, h, w); THTensor_(fastSet4d)(gradInput, b, cur_target, h, w, value * gradOutput_value); } } } return; } THNN_CHECK_DIM_SIZE(gradOutput, 1, 0, 1); scalar_t *total_weight_data = total_weight->data<scalar_t>(); if (*total_weight_data <= 0) return; target = THIndexTensor_(newContiguous)(target); weights = weights ? THTensor_(newContiguous)(weights) : NULL; THIndex_t *target_data = THIndexTensor_(data)(target); scalar_t *weights_data = weights ? weights->data<scalar_t>() : NULL; scalar_t *gradInput_data = gradInput->data<scalar_t>(); int64_t batch_size = THTensor_(size)(input, 0); int64_t n_classes = THTensor_(size)(input, 1); int64_t map_size = THTensor_(size)(input, 2) * THTensor_(size)(input, 3); int64_t sample_size = map_size * n_classes; scalar_t normalize = (reduction == Reduction::Mean) ? *total_weight_data : 1.0f; int b; #pragma omp parallel for for (b = 0; b < batch_size; b++) { int elem; for (elem = 0; elem < map_size; elem++) { int cur_target = target_data[b * map_size + elem]; if (cur_target == ignore_index) continue; THAssert(cur_target >= 0 && cur_target < n_classes); int index = b * sample_size + cur_target * map_size + elem; gradInput_data[index] = -(weights ? weights_data[cur_target] : 1.0f) / normalize * THTensor_(fastGetLegacy1dNoScalars)(gradOutput, 0); } } THIndexTensor_(free)(target); if (weights) c10::raw::intrusive_ptr::decref(weights); } #undef INITIAL_CHECK #endif
StomOmpc_02.c
/* poe -rmpool 1 -procs 1 mpcc_r -qsmp=noauto:omp:explicit -O3 -qarch=pwr3 -qtune=pwr3 ompc_02.c bind.o -lm -o ompc_02 */ #define FLT double #define INT int #include "mpi.h" #include <stdlib.h> #include <stdio.h> #include <time.h> #include <math.h> #if macintosh #include <console.h> #endif FLT **matrix(INT nrl,INT nrh,INT ncl,INT nch); FLT *vector(INT nl, INT nh); INT *ivector(INT nl, INT nh); INT mint(FLT x); FLT walltime(); void bc(FLT ** psi,INT i1,INT i2,INT j1,INT j2); void do_jacobi(FLT ** psi,FLT ** new_psi,FLT *diff,INT i1,INT i2,INT j1,INT j2); void write_grid(FLT ** psi,INT i1,INT i2,INT j1,INT j2); void do_transfer(FLT ** psi,INT i1,INT i2,INT j1,INT j2); void do_force (INT i1,INT i2,INT j1,INT j2); void do_transfer(FLT ** psi,INT i1,INT i2,INT j1,INT j2); char* unique(char *name); FLT force(FLT y); #define pi 3.141592653589793239 FLT **the_for; FLT dx,dy,a1,a2,a3,a4,a5,a6; INT nx,ny; FLT alpha; FLT *svec1,*svec2,*rvec1,*rvec2; INT numnodes,myid,mpi_err; #define mpi_master 0 INT myrow,mycol; INT nrow,ncol; INT myrow,mycol; INT myid_col,myid_row,nodes_row,nodes_col; MPI_Status status; MPI_Comm ROW_COMM,COL_COMM; INT mytop,mybot,myleft,myright; int main(int argc, char **argv) { FLT lx,ly,beta,gamma; INT steps; FLT t1,t2; /*FLT t3,t4,dt; */ /* FLT diff */ FLT mydiff,diff; FLT dx2,dy2,bottom; FLT di,dj; FLT **psi; /* our calculation grid */ FLT **new_psi; /* temp storage for the grid */ INT i,j,i1,i2,j1,j2; INT iout; #if macintosh argc=ccommand(&argv); #endif mpi_err=MPI_Init(&argc,&argv); mpi_err=MPI_Comm_size(MPI_COMM_WORLD,&numnodes); mpi_err=MPI_Comm_rank(MPI_COMM_WORLD,&myid); #pragma omp parallel #pragma omp critical { thread_bind(); } /* ! find a reasonable grid topology based on the number ! of processors */ nrow=mint(sqrt((FLT)(numnodes))); ncol=numnodes/nrow; while (nrow*ncol != numnodes) { nrow=nrow+1; ncol=numnodes/nrow; } if(nrow > ncol){ i=ncol; ncol=nrow; nrow=i; } myrow=myid/ncol+1; mycol=myid - (myrow-1)*ncol + 1; if(myid == mpi_master) printf(" nrow= %d ncol= %d\n",nrow ,ncol); /* ! make the row and col communicators ! all processors with the same row will be in the same ROW_COMM */ mpi_err=MPI_Comm_split(MPI_COMM_WORLD,myrow,mycol,&ROW_COMM); mpi_err=MPI_Comm_rank( ROW_COMM, &myid_row); mpi_err=MPI_Comm_size( ROW_COMM, &nodes_row); /* ! all processors with the same col will be in the same COL_COMM */ mpi_err=MPI_Comm_split(MPI_COMM_WORLD,mycol,myrow,&COL_COMM); mpi_err=MPI_Comm_rank( COL_COMM, &myid_col); mpi_err=MPI_Comm_size( COL_COMM,& nodes_col); /* ! find id of neighbors using the communicators created above */ mytop = myid_col-1;if( mytop < 0 )mytop = MPI_PROC_NULL; mybot = myid_col+1;if( mybot == nodes_col)mybot = MPI_PROC_NULL; myleft = myid_row-1;if( myleft < 0 )myleft = MPI_PROC_NULL; myright = myid_row+1;if( myright == nodes_row)myright = MPI_PROC_NULL; if(myid == mpi_master) { scanf("%d %d",&nx,&ny); scanf("%lg %lg",&lx,&ly); scanf("%lg %lg %lg",&alpha,&beta,&gamma); scanf("%d",&steps); printf("%d %d\n",nx,ny); printf("%g %g\n",lx,ly); printf("%g %g %g\n",alpha,beta,gamma); printf("%d\n",steps); } mpi_err=MPI_Bcast(&nx, 1,MPI_INT, mpi_master,MPI_COMM_WORLD); mpi_err=MPI_Bcast(&ny, 1,MPI_INT, mpi_master,MPI_COMM_WORLD); mpi_err=MPI_Bcast(&steps,1,MPI_INT, mpi_master,MPI_COMM_WORLD); mpi_err=MPI_Bcast(&lx, 1,MPI_DOUBLE,mpi_master,MPI_COMM_WORLD); mpi_err=MPI_Bcast(&ly, 1,MPI_DOUBLE,mpi_master,MPI_COMM_WORLD); mpi_err=MPI_Bcast(&alpha,1,MPI_DOUBLE,mpi_master,MPI_COMM_WORLD); mpi_err=MPI_Bcast(&beta, 1,MPI_DOUBLE,mpi_master,MPI_COMM_WORLD); mpi_err=MPI_Bcast(&gamma,1,MPI_DOUBLE,mpi_master,MPI_COMM_WORLD); /* calculate the constants for the calculations */ dx=lx/(nx+1); dy=ly/(ny+1); dx2=dx*dx; dy2=dy*dy; bottom=2.0*(dx2+dy2); a1=(dy2/bottom)+(beta*dx2*dy2)/(2.0*gamma*dx*bottom); a2=(dy2/bottom)-(beta*dx2*dy2)/(2.0*gamma*dx*bottom); a3=dx2/bottom; a4=dx2/bottom; a5=dx2*dy2/(gamma*bottom); a6=pi/(ly); /* set the indices for the interior of the grid */ dj=(FLT)ny/(FLT)nodes_row; j1=mint(1.0+myid_row*dj); j2=mint(1.0+(myid_row+1)*dj)-1; di=(FLT)nx/(FLT)nodes_col; i1=mint(1.0+myid_col*di); i2=mint(1.0+(myid_col+1)*di)-1; if(myid == mpi_master)printf("nodes_row= %d nodes_col= %d\n",nodes_row,nodes_col); printf("myid= %d myrow= %d mycol= %d\n",myid,myrow,mycol); printf("myid= %d myid_row= %d myid_col= %d\n",myid,myid_row,myid_col); printf("myid= %d holds [%d:%d][%d:%d]\n",myid,i1,i2,j1,j2); /* allocate the grid to (i1-1:i2+1,j1-1:j2+1) this includes boundary cells */ psi= matrix((INT)(i1-1),(INT)(i2+1),(INT)(j1-1),(INT)(j2+1)); new_psi=matrix((INT)(i1-1),(INT)(i2+1),(INT)(j1-1),(INT)(j2+1)); the_for=matrix((INT)(i1-1),(INT)(i2+1),(INT)(j1-1),(INT)(j2+1)); svec1=vector((INT)(i1-1),(INT)(i2+1)); svec2=vector((INT)(i1-1),(INT)(i2+1)); rvec1=vector((INT)(i1-1),(INT)(i2+1)); rvec2=vector((INT)(i1-1),(INT)(i2+1)); /* set initial guess for the value of the grid */ for(i=i1-1;i<=i2+1;i++) for(j=j1-1;j<=j2+1;j++) psi[i][j]=1.0; /* set boundary conditions */ bc(psi,i1,i2,j1,j2); do_force(i1,i2,j1,j2); /* do the jacobian iterations */ t1=MPI_Wtime(); iout=steps/100; if(iout == 0)iout=1; if(steps > 0){ for( i=1; i<=steps;i++) { do_jacobi(psi,new_psi,&mydiff,i1,i2,j1,j2); do_transfer(psi,i1,i2,j1,j2); mpi_err= MPI_Reduce(&mydiff,&diff,1,MPI_DOUBLE,MPI_SUM,mpi_master,MPI_COMM_WORLD); if(myid == mpi_master && i % iout == 0){ printf("%8d %15.5f\n",i,diff); } } } t2=MPI_Wtime(); if(myid == mpi_master)printf("run time = %10.3g\n",t2-t1); /* write_grid(psi,i1,i2,j1,j2); */ mpi_err = MPI_Finalize(); return 0; } void bc(FLT ** psi,INT i1,INT i2,INT j1,INT j2){ /* sets the boundary conditions */ /* input is the grid and the indices for the interior cells */ INT j; /* do the top edges */ if(i1 == 1) { for(j=j1-1;j<=j2+1;j++) psi[i1-1][j]=0.0; } /* do the bottom edges */ if(i2 == ny) { for(j=j1-1;j<=j2+1;j++) psi[i2+1][j]=0.0; } /* do left edges */ if(j1 == 1) { for(j=i1-1;j<=i2+1;j++) psi[j][j1-1]=0.0; } /* do right edges */ if(j2 == nx) { for(j=i1-1;j<=i2+1;j++) psi[j][j2+1]=0.0; } } void do_jacobi(FLT ** psi,FLT ** new_psi,FLT *diff_in,INT i1,INT i2,INT j1,INT j2){ /* ! does a single Jacobi iteration step ! input is the grid and the indices for the interior cells ! new_psi is temp storage for the the updated grid ! output is the updated grid in psi and diff which is ! the sum of the differences between the old and new grids */ INT i,j; FLT diff; diff=0.0; #pragma omp parallel for schedule(static) reduction(+: diff) private(j) firstprivate (a1,a2,a3,a4,a5) for( i=i1;i<=i2;i++) { for(j=j1;j<=j2;j++){ new_psi[i][j]=a1*psi[i+1][j] + a2*psi[i-1][j] + a3*psi[i][j+1] + a4*psi[i][j-1] - a5*the_for[i][j]; diff=diff+fabs(new_psi[i][j]-psi[i][j]); } } *diff_in=diff; #pragma omp parallel for schedule(static) private(j) for( i=i1;i<=i2;i++) for(j=j1;j<=j2;j++) psi[i][j]=new_psi[i][j]; } void do_force (INT i1,INT i2,INT j1,INT j2) { /* ! sets the force conditions ! input is the grid and the indices for the interior cells */ FLT y; INT i,j; for( i=i1;i<=i2;i++) { for(j=j1;j<=j2;j++){ y=j*dy; the_for[i][j]=force(y); } } } FLT force(FLT y) { return (-alpha*sin(y*a6)); } /* The routines matrix, ivector and vector were adapted from Numerical Recipes in C The Art of Scientific Computing Press, Flannery, Teukolsky, Vetting Cambridge University Press, 1988. */ FLT **matrix(INT nrl,INT nrh,INT ncl,INT nch) { INT i; FLT **m; m=(FLT **) malloc((unsigned) (nrh-nrl+1)*sizeof(FLT*)); if (!m){ printf("allocation failure 1 in matrix()\n"); exit(1); } m -= nrl; for(i=nrl;i<=nrh;i++) { if(i == nrl){ m[i]=(FLT *) malloc((unsigned) (nrh-nrl+1)*(nch-ncl+1)*sizeof(FLT)); if (!m[i]){ printf("allocation failure 2 in matrix()\n"); exit(1); } m[i] -= ncl; } else { m[i]=m[i-1]+(nch-ncl+1); } } return m; } INT *ivector(INT nl, INT nh) { INT *v; v=(INT *)malloc((unsigned) (nh-nl+1)*sizeof(INT)); if (!v) { printf("allocation failure in ivector()\n"); exit(1); } return v-nl; } FLT *vector(INT nl, INT nh) { FLT *v; v=(FLT *)malloc((unsigned) (nh-nl+1)*sizeof(FLT)); if (!v) { printf("allocation failure in vector()\n"); exit(1); } return v-nl; } void do_transfer(FLT ** psi,INT i1,INT i2,INT j1,INT j2) { INT num_x,num_y; INT i,j; num_x=i2-i1+3; num_y=j2-j1+3; for(i=i1-1;i<=i2+1;i++){ svec1[i]=psi[i][j1]; svec2[i]=psi[i][j2]; } if((myid_col % 2) == 0){ /* send to left */ mpi_err=MPI_Send(&svec1[i1-1],num_x,MPI_DOUBLE,myleft,100,ROW_COMM); /* rec from left */ mpi_err=MPI_Recv(&rvec1[i1-1],num_x,MPI_DOUBLE,myleft,100,ROW_COMM,&status); /* rec from right */ mpi_err=MPI_Recv(&rvec2[i1-1],num_x,MPI_DOUBLE,myright,100,ROW_COMM,&status); /* send to right */ mpi_err=MPI_Send(&svec2[i1-1],num_x,MPI_DOUBLE,myright,100,ROW_COMM); } else { /* we are on an odd col processor */ /* rec from right */ mpi_err=MPI_Recv(&rvec2[i1-1],num_x,MPI_DOUBLE,myright,100,ROW_COMM,&status); /* send to right */ mpi_err=MPI_Send(&svec2[i1-1],num_x,MPI_DOUBLE,myright,100,ROW_COMM); /* send to left */ mpi_err=MPI_Send(&svec1[i1-1],num_x,MPI_DOUBLE,myleft,100,ROW_COMM); /* rec from left */ mpi_err=MPI_Recv(&rvec1[i1-1],num_x,MPI_DOUBLE,myleft,100,ROW_COMM,&status); } if(myleft != MPI_PROC_NULL){ for(i=i1-1;i<=i2+1;i++){ psi[i][j1-1]=rvec1[i]; } } if(myright != MPI_PROC_NULL){ for(i=i1-1;i<=i2+1;i++){ psi[i][j2+1]=rvec2[i]; } } if((myid_row % 2) == 0){ /* send to top */ mpi_err=MPI_Send(&psi[i1][j1-1], num_y,MPI_DOUBLE,mytop,10, COL_COMM); /* rec from top */ mpi_err=MPI_Recv(&psi[i1-1][j1-1],num_y,MPI_DOUBLE,mytop,10,COL_COMM,&status); /* rec from bot */ mpi_err=MPI_Recv(&psi[i2+1][j1-1],num_y,MPI_DOUBLE,mybot,10,COL_COMM,&status); /* send to bot */ mpi_err=MPI_Send(&psi[i2][j1-1], num_y,MPI_DOUBLE,mybot,10, COL_COMM); } else{ /* rec from bot */ mpi_err=MPI_Recv(&psi[i2+1][j1-1],num_y,MPI_DOUBLE,mybot,10,COL_COMM,&status); /* send to bot */ mpi_err=MPI_Send(&psi[i2][j1-1], num_y,MPI_DOUBLE,mybot,10,COL_COMM); /* send to top */ mpi_err=MPI_Send(&psi[i1][j1-1], num_y,MPI_DOUBLE,mytop,10,COL_COMM); /* rec from top */ mpi_err=MPI_Recv(&psi[i1-1][j1-1],num_y,MPI_DOUBLE,mytop,10,COL_COMM,&status); } } char* unique(char *name) { static char unique_str[40]; int i; for(i=0;i<40;i++) unique_str[i]=(char)0; if(myid > 99){ sprintf(unique_str,"%s%d",name,myid); } else { if(myid > 9) sprintf(unique_str,"%s0%d",name,myid); else sprintf(unique_str,"%s00%d",name,myid); } return unique_str; } void write_grid(FLT ** psi,INT i1,INT i2,INT j1,INT j2) { /* ! input is the grid and the indices for the interior cells */ INT i,j,i0,j0,i3,j3; FILE *f18; if(i1==1) { i0=0; } else { i0=i1; } if(i2==nx) { i3=nx+1; } else { i3=i2; } if(j1==1) { j0=0; } else { j0=j1; } if(j2==ny) { j3=ny+1; } else { j3=j2; } f18=fopen(unique("out2c_"),"w"); fprintf(f18,"%6d %6d\n",i3-i0+1,j3-j0+1); for( i=i0;i<=i3;i++){ for( j=j0;j<=j3;j++){ fprintf(f18,"%14.7g",psi[i][j]); if(j != j3)fprintf(f18," "); } fprintf(f18,"\n"); } fclose(f18); } INT mint(FLT x) { FLT y; INT j; j=(INT)x; y=(FLT)j; if(x-y >= 0.5)j++; return j; } FLT walltime() { return((FLT)clock()/((FLT)CLOCKS_PER_SEC)); }
DRB017-outputdep-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. */ /* The loop in this example cannot be parallelized. Data race pairs: we allow two pairs to preserve the original code pattern. 1. x@71:12 vs. x@72:5 2. x@72:5 vs. x@72:5 */ #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { int len=100; if (argc>1) len = atoi(argv[1]); int a[len]; int i,x=10; #pragma omp parallel for schedule(dynamic) for (i=0;i<len;i++) { a[i] = x; x=i; } printf("x=%d, a[0]=%d\n",x,a[0]); return 0; }
quicksort.h
// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // 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 // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file parallel/quicksort.h * @brief Implementation of a unbalanced parallel quicksort (in-place). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_QUICKSORT_H #define _GLIBCXX_PARALLEL_QUICKSORT_H 1 #include <parallel/parallel.h> #include <parallel/partition.h> namespace __gnu_parallel { /** @brief Unbalanced quicksort divide step. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __pivot_rank Desired __rank of the pivot. * @param __num_samples Choose pivot from that many samples. * @param __num_threads Number of threads that are allowed to work on * this part. */ template<typename _RAIter, typename _Compare> typename std::iterator_traits<_RAIter>::difference_type __parallel_sort_qs_divide(_RAIter __begin, _RAIter __end, _Compare __comp, typename std::iterator_traits <_RAIter>::difference_type __pivot_rank, typename std::iterator_traits <_RAIter>::difference_type __num_samples, _ThreadIndex __num_threads) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; __num_samples = std::min(__num_samples, __n); // Allocate uninitialized, to avoid default constructor. _ValueType* __samples = static_cast<_ValueType*> (::operator new(__num_samples * sizeof(_ValueType))); for (_DifferenceType __s = 0; __s < __num_samples; ++__s) { const unsigned long long __index = static_cast<unsigned long long> (__s) * __n / __num_samples; ::new(&(__samples[__s])) _ValueType(__begin[__index]); } __gnu_sequential::sort(__samples, __samples + __num_samples, __comp); _ValueType& __pivot = __samples[__pivot_rank * __num_samples / __n]; __gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool> __pred(__comp, __pivot); _DifferenceType __split = __parallel_partition(__begin, __end, __pred, __num_threads); for (_DifferenceType __s = 0; __s < __num_samples; ++__s) __samples[__s].~_ValueType(); ::operator delete(__samples); return __split; } /** @brief Unbalanced quicksort conquer step. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. */ template<typename _RAIter, typename _Compare> void __parallel_sort_qs_conquer(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; if (__num_threads <= 1) { __gnu_sequential::sort(__begin, __end, __comp); return; } _DifferenceType __n = __end - __begin, __pivot_rank; if (__n <= 1) return; _ThreadIndex __num_threads_left; if ((__num_threads % 2) == 1) __num_threads_left = __num_threads / 2 + 1; else __num_threads_left = __num_threads / 2; __pivot_rank = __n * __num_threads_left / __num_threads; _DifferenceType __split = __parallel_sort_qs_divide (__begin, __end, __comp, __pivot_rank, _Settings::get().sort_qs_num_samples_preset, __num_threads); #pragma omp parallel sections num_threads(2) { #pragma omp section __parallel_sort_qs_conquer(__begin, __begin + __split, __comp, __num_threads_left); #pragma omp section __parallel_sort_qs_conquer(__begin + __split, __end, __comp, __num_threads - __num_threads_left); } } /** @brief Unbalanced quicksort main call. * @param __begin Begin iterator of input sequence. * @param __end End iterator input sequence, ignored. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. */ template<typename _RAIter, typename _Compare> void __parallel_sort_qs(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { _GLIBCXX_CALL(__n) typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; // At least one element per processor. if (__num_threads > __n) __num_threads = static_cast<_ThreadIndex>(__n); __parallel_sort_qs_conquer( __begin, __begin + __n, __comp, __num_threads); } } //namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_QUICKSORT_H */
softmax-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file softmax-inl.h * \brief */ #ifndef MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #define MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #include <algorithm> #include <string> #include <utility> #include <vector> #include <type_traits> #include "../mxnet_op.h" #include "../operator_common.h" #include "../tensor/broadcast_reduce_op.h" using mshadow::red::limits::MinValue; namespace mxnet { namespace op { namespace mxnet_op { struct softmax_fwd { template <typename AType> MSHADOW_XINLINE static AType Map(float a, AType b) { return AType(expf(a) / b); } template <typename AType> MSHADOW_XINLINE static AType Map(double a, AType b) { return AType(exp(a) / b); } }; struct log_softmax_fwd { template <typename DType> MSHADOW_XINLINE static float Map(DType a, float b) { return a - logf(b); } template <typename DType> MSHADOW_XINLINE static double Map(DType a, double b) { return a - log(b); } }; template <typename OP, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void Softmax(Stream<cpu>* s, DType* in, OType* out, IType* length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; if (M == 0) return; index_t N = shape.Size() / M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length == nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < M; ++j) { val = negate ? -in[base + j * sa] : in[base + j * sa]; if (mmax < val) mmax = val; } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp((in_val - mmax) / temperature); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map((in_val - mmax) / temperature, sum); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t len = static_cast<index_t>(length[i]); index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < len; ++j) { val = negate ? -in[base + j * sa] : in[base + j * sa]; if (mmax < val) mmax = val; } for (index_t j = len; j < M; ++j) { out[base + j * sa] = OType(0.0f); } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp((in_val - mmax) / temperature); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map((in_val - mmax) / temperature, sum); } } } } } struct masked_softmax_where { template <typename DType, int ndim> MSHADOW_XINLINE static void Map(index_t id, DType* out, const bool* cond, const DType* x, const double y, Shape<ndim> data_shape, Shape<ndim> mask_shape) { index_t mask_pos = 0; index_t stride = 1; for (index_t i = ndim - 1, j = id; i >= 0; --i) { auto tmp = j / data_shape[i]; if (mask_shape[i] != 1) { mask_pos += (j - tmp * mask_shape[i]) * stride; } stride *= mask_shape[i]; j = tmp; } KERNEL_ASSIGN(out[id], kWriteTo, (cond[mask_pos] ? x[id] : static_cast<DType>(y))); } }; template <typename OP, bool masked_neg_inf, bool negate, typename AType, typename DType, int ndim> inline void MaskedSoftmax(Stream<cpu>* s, DType* in, DType* out, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, bool normalize, const OpContext& ctx) { Tensor<cpu, 1, DType> workspace = ctx.requested[0].get_space_typed<cpu, 1, DType>(Shape1(data_shape.Size()), s); DType* masked_input = TBlob(workspace).dptr<DType>(); double neg = MinValue<DType>(); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), masked_input, mask, in, neg, data_shape, mask_shape); int* max_lenghts = nullptr; double masked_value = 0.0; if (masked_neg_inf) masked_value = -INFINITY; Softmax<OP, negate, AType, DType>( s, masked_input, out, max_lenghts, data_shape, axis, temperature); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), out, mask, out, masked_value, data_shape, mask_shape); } struct softmax_bwd { template <typename DType, typename AType> MSHADOW_XINLINE static AType Map(DType ograd, DType out, AType sum) { return AType(out * (ograd - sum)); } }; struct log_softmax_bwd { template <typename AType> MSHADOW_XINLINE static AType Map(float ograd, float out, AType sum) { return AType(ograd - expf(out) * sum); } template <typename AType> MSHADOW_XINLINE static AType Map(double ograd, double out, AType sum) { return AType(ograd - exp(out) * sum); } }; template <typename OP1, typename OP2, int Req, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void SoftmaxGrad(Stream<cpu>* s, OType* out, OType* ograd, DType* igrad, IType* length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; if (M == 0) return; index_t N = shape.Size() / M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length != nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); index_t len = static_cast<index_t>(length[i]); AType sum = AType(0); for (index_t j = 0; j < len; ++j) { sum += OP1::Map(ograd[base + j * sa], out[base + j * sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum); final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature; final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); AType sum = AType(0); for (index_t j = 0; j < M; ++j) { sum += OP1::Map(ograd[base + j * sa], out[base + j * sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum); KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature; KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } } } } template <typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType> inline void MaskedSoftmaxGrad(Stream<cpu>* s, DType* out, DType* ograd, DType* igrad, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, const OpContext& ctx) { Tensor<cpu, 1, DType> workspace = ctx.requested[0].get_space_typed<cpu, 1, DType>(Shape1(data_shape.Size()), s); DType* masked_ograd = TBlob(workspace).dptr<DType>(); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), masked_ograd, mask, ograd, 0.0, data_shape, mask_shape); int* max_lenghts = nullptr; SoftmaxGrad<OP1, OP2, Req, negate, AType, DType, DType, int, ndim>( s, out, masked_ograd, igrad, max_lenghts, data_shape, axis, temperature); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), igrad, mask, igrad, 0.0, data_shape, mask_shape); } #ifdef __CUDACC__ const int softmax_threads_per_block = 512; template <int ndim> MSHADOW_XINLINE index_t get_mask_position(const index_t idx, const Shape<ndim>& data_shape, const Shape<ndim>& mask_shape, int axis, index_t* stride_axis) { index_t ret = 0; index_t stride = 1; *stride_axis = 1; #pragma unroll for (index_t i = ndim - 1, j = idx; i >= 0; --i) { auto tmp = j / data_shape[i]; if (i != axis && mask_shape[i] != 1) { ret += (j - tmp * mask_shape[i]) * stride; if (i > axis) *stride_axis *= mask_shape[i]; } stride *= mask_shape[i]; j = tmp; } return ret; } template <bool normalize, int x_bits, typename OP, bool masked_neg_inf, bool negate, typename AType, int ndim, typename DType> __global__ void masked_softmax_kernel(DType* in, DType* out, bool* in_mask, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, Shape<ndim> mask_shape, const double temperature) { extern __shared__ double shared[]; AType* smem = reinterpret_cast<AType*>(shared); // x_size const unsigned x_size = 1 << x_bits; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t sa_mask = 0; index_t base_mask = get_mask_position(blockIdx.x, sshape, mask_shape, axis, &sa_mask); bool bcst_mask_axis = (mask_shape[axis] == 1); index_t x = threadIdx.x; DType smax = 0.0; if (normalize) { red::maximum::SetInitValue(smem[x]); for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; if (mask_value) smem[x] = ::max(smem[x], negate ? -in[base + i * sa] : in[base + i * sa]); } __syncthreads(); cuda::Reduce1D<red::maximum, x_bits>(smem); __syncthreads(); smax = smem[0]; __syncthreads(); } red::sum::SetInitValue(smem[x]); DType val; for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; if (mask_value) { val = (negate ? -in[base + i * sa] : in[base + i * sa]); smem[x] += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); double masked_value = 0.0; if (masked_neg_inf) masked_value = -INFINITY; for (index_t i = x; i < M; i += x_size) { val = (negate ? -in[base + i * sa] : in[base + i * sa]); bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; out[base + i * sa] = mask_value ? DType(OP::Map((val - smax) / static_cast<DType>(temperature), ssum)) : DType(masked_value); } } template <bool normalize, typename OP, bool masked_neg_inf, bool negate, typename AType, typename LType, typename LTypeMask, typename DType, int ndim> __global__ void masked_softmax_stride1_kernel(const DType* in, DType* out, bool* in_mask, const index_t M, int axis, Shape<ndim> sshape, Shape<ndim> mask_shape, const double temperature, const int rows_per_block, const index_t total_rows, const size_t size_input_shared, const size_t size_mask_shared) { const int entries_per_load = sizeof(LType) / sizeof(DType); const int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const int row_length_mask = entries_per_load > 0 ? M / entries_per_load_mask : 0; extern __shared__ double shared[]; LType* persistent_storage = reinterpret_cast<LType*>(shared); // rows_per_block * M (DType), aligned to double LTypeMask* mask_shared = reinterpret_cast<LTypeMask*>(&shared[size_input_shared]); // rows_per_block * M (bool), aligned to double AType* scratch = reinterpret_cast<AType*>(&shared[size_input_shared + size_mask_shared]); // softmax_threads_per_block const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; size_t base = my_row * row_length; index_t pos_mask = 0; index_t stride = mask_shape[axis]; #pragma unroll for (index_t i = axis - 1, j = my_row; i >= 0; --i) { auto tmp = j / sshape[i]; if (mask_shape[i] != 1) { pos_mask += (j - tmp * mask_shape[i]) * stride; stride *= mask_shape[i]; } j = tmp; } const LType* in_aligned = reinterpret_cast<const LType*>(in); for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length + i] = in_aligned[base + i]; } const LTypeMask* in_mask_aligned = reinterpret_cast<const LTypeMask*>(&in_mask[pos_mask]); for (index_t i = my_id; i < row_length_mask; i += threads_per_row) { mask_shared[my_local_row * row_length_mask + i] = (mask_shape[axis] > 1) ? in_mask_aligned[i] : in_mask_aligned[0]; } DType* row = reinterpret_cast<DType*>(persistent_storage + my_local_row * row_length); bool* row_mask = reinterpret_cast<bool*>(mask_shared + my_local_row * row_length_mask); __syncthreads(); DType smax = 0.0; if (normalize) { DType my_max_value; red::maximum::SetInitValue(my_max_value); for (index_t i = my_id; i < M; i += threads_per_row) { if (row_mask[i]) my_max_value = ::max(my_max_value, negate ? -row[i] : row[i]); } scratch[threadIdx.x] = my_max_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = ::max(scratch[threadIdx.x], scratch[threadIdx.x + size]); } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return ::max(x, y); }); scratch[threadIdx.x] = my_value; } __syncthreads(); smax = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); } AType my_sum; red::sum::SetInitValue(my_sum); for (index_t i = my_id; i < M; i += threads_per_row) { if (row_mask[i]) { const DType val = (negate ? -row[i] : row[i]); my_sum += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } } scratch[threadIdx.x] = my_sum; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] += scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y; }); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); double masked_value = 0.0; if (masked_neg_inf) masked_value = -INFINITY; for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = (negate ? -row[i] : row[i]); row[i] = row_mask[i] ? DType(OP::Map((val - smax) / static_cast<DType>(temperature), ssum)) : DType(masked_value); } __syncthreads(); LType* out_aligned = reinterpret_cast<LType*>(out); for (index_t i = my_id; i < row_length; i += threads_per_row) { out_aligned[base + i] = persistent_storage[my_local_row * row_length + i]; } } template <typename OP, bool masked_neg_inf, bool negate, typename AType, typename DType, typename OType, int ndim> inline void MaskedSoftmax(Stream<gpu>* s, DType* in, OType* out, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, bool normalize, const OpContext& ctx) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = data_shape[axis]; if (M == 0 || data_shape.Size() == 0) return; index_t N = data_shape.Size() / M; Shape<ndim> stride = calc_stride(data_shape); Shape<ndim> sshape = data_shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using max of 20 kB of shared memory for InputData in the optimized case const size_t max_opt_M = 20 * 1024 / DSize; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); int ltype_mask = mxnet::common::cuda::get_load_type(mask_shape[axis] * sizeof(bool)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { CHECK_LE(sizeof(DType), sizeof(LType)); MXNET_LOAD_TYPE_SWITCH(ltype_mask, LTypeMask, { CHECK_LE(sizeof(bool), sizeof(LTypeMask)); int rows_per_block = mxnet::common::cuda::get_rows_per_block( M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); // calculate amount shared memory (slots aligned to double) int entries_per_load = entries_per_load = sizeof(LType) / sizeof(DType); int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); size_t size_input_shared = entries_per_load > 0 ? rows_per_block * M / entries_per_load : 0; size_t size_mask_shared = entries_per_load_mask > 0 ? rows_per_block * M / entries_per_load_mask : 0; size_input_shared = ((size_input_shared * sizeof(LType) + sizeof(double) - 1) / sizeof(double)); size_mask_shared = ((size_mask_shared * sizeof(LTypeMask) + sizeof(double) - 1) / sizeof(double)); size_t amount_shared = size_input_shared * sizeof(double) + size_mask_shared * sizeof(double) + softmax_threads_per_block * sizeof(AType); int nblocks = (N + rows_per_block - 1) / rows_per_block; if (normalize) { masked_softmax_stride1_kernel<true, OP, masked_neg_inf, negate, AType, LType, LTypeMask> <<<nblocks, softmax_threads_per_block, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>(in, out, mask, M, axis, sshape, mask_shape, temperature, rows_per_block, N, size_input_shared, size_mask_shared); } else { masked_softmax_stride1_kernel<false, OP, masked_neg_inf, negate, AType, LType, LTypeMask> <<<nblocks, softmax_threads_per_block, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>(in, out, mask, M, axis, sshape, mask_shape, temperature, rows_per_block, N, size_input_shared, size_mask_shared); } }); }); MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_stride1_kernel); } else { size_t amount_shared = x_size * sizeof(AType); if (normalize) { masked_softmax_kernel<true, x_bits, OP, masked_neg_inf, negate, AType, ndim> <<<N, x_size, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, mask, M, axis, sshape, stride, mask_shape, temperature); } else { masked_softmax_kernel<false, x_bits, OP, masked_neg_inf, negate, AType, ndim> <<<N, x_size, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, mask, M, axis, sshape, stride, mask_shape, temperature); } MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_kernel); } } template <typename OP1, typename OP2, int Req, bool negate, typename AType, typename LType, typename LTypeMask, typename DType, typename OType, int ndim> __global__ void masked_softmax_stride1_grad_kernel(const OType* out, const OType* ograd, DType* igrad, const bool* in_mask, const index_t M, int axis, Shape<ndim> sshape, Shape<ndim> mask_shape, const double temperature, const int rows_per_block, const index_t total_rows, const size_t size_input_shared, const size_t size_mask_shared) { const int entries_per_load = sizeof(LType) / sizeof(DType); const int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const int row_length_mask = entries_per_load > 0 ? M / entries_per_load_mask : 0; extern __shared__ double shared[]; LType* persistent_storage = reinterpret_cast<LType*>(shared); // 2 * rows_per_block * M (DType), aligned to double LTypeMask* mask_shared = reinterpret_cast<LTypeMask*>(&shared[size_input_shared]); // rows_per_block * M (bool), aligned to double AType* scratch = reinterpret_cast<AType*>(&shared[size_input_shared + size_mask_shared]); // softmax_threads_per_block const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; size_t base = my_row * row_length; index_t pos_mask = 0; index_t stride = mask_shape[axis]; #pragma unroll for (index_t i = axis - 1, j = my_row; i >= 0; --i) { auto tmp = j / sshape[i]; if (mask_shape[i] != 1) { pos_mask += (j - tmp * mask_shape[i]) * stride; stride *= mask_shape[i]; } j = tmp; } const LType* out_aligned = reinterpret_cast<const LType*>(out); const LType* ograd_aligned = reinterpret_cast<const LType*>(ograd); for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length * 2 + i] = out_aligned[base + i]; persistent_storage[my_local_row * row_length * 2 + row_length + i] = ograd_aligned[base + i]; } const LTypeMask* in_mask_aligned = reinterpret_cast<const LTypeMask*>(&in_mask[pos_mask]); for (index_t i = my_id; i < row_length_mask; i += threads_per_row) { mask_shared[my_local_row * row_length_mask + i] = (mask_shape[axis] > 1) ? in_mask_aligned[i] : in_mask_aligned[0]; } DType* row = reinterpret_cast<DType*>(persistent_storage + my_local_row * row_length * 2); bool* row_mask = reinterpret_cast<bool*>(mask_shared + my_local_row * row_length_mask); __syncthreads(); AType my_sum_value; red::sum::SetInitValue(my_sum_value); for (index_t i = my_id; i < M; i += threads_per_row) { if (row_mask[i]) my_sum_value += OP1::Map(row[i + M], row[i]); } scratch[threadIdx.x] = my_sum_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = scratch[threadIdx.x] + scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y; }); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = negate ? -OP2::Map(row[i + M], row[i], ssum) : OP2::Map(row[i + M], row[i], ssum); row[i] = row_mask[i] ? DType(val / static_cast<DType>(temperature)) : DType(0.0f); if (Req == kAddTo) { row[i] += igrad[my_row * M + i]; } } __syncthreads(); LType* igrad_aligned = reinterpret_cast<LType*>(igrad); for (index_t i = my_id; i < row_length; i += threads_per_row) { igrad_aligned[base + i] = persistent_storage[my_local_row * row_length * 2 + i]; } } template <int x_bits, typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType> __global__ void masked_softmax_grad_kernel(OType* out, OType* ograd, DType* igrad, const bool* in_mask, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, Shape<ndim> mask_shape, const double temperature) { const unsigned x_size = 1 << x_bits; __shared__ AType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t sa_mask = 0; index_t base_mask = get_mask_position(blockIdx.x, sshape, mask_shape, axis, &sa_mask); bool bcst_mask_axis = (mask_shape[axis] == 1); index_t x = threadIdx.x; red::sum::SetInitValue(smem[x]); for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; if (mask_value) smem[x] += OP1::Map(ograd[base + i * sa], out[base + i * sa]); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); DType final_result; for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; final_result = negate ? -OP2::Map(ograd[base + i * sa], out[base + i * sa], ssum) : OP2::Map(ograd[base + i * sa], out[base + i * sa], ssum); final_result = mask_value ? final_result / static_cast<DType>(temperature) : DType(0.0f); KERNEL_ASSIGN(igrad[base + i * sa], Req, final_result); } } template <typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType> inline void MaskedSoftmaxGrad(Stream<gpu>* s, OType* out, OType* ograd, DType* igrad, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, const OpContext& ctx) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = data_shape[axis]; if (M == 0 || data_shape.Size() == 0) return; index_t N = data_shape.Size() / M; Shape<ndim> stride = calc_stride(data_shape); Shape<ndim> sshape = data_shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using max of 20 kB of shared memory for InputData in the optimized case const size_t max_opt_M = 20 * 1024 / DSize; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); int ltype_mask = mxnet::common::cuda::get_load_type(mask_shape[axis] * sizeof(bool)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { CHECK_LE(sizeof(DType), sizeof(LType)); MXNET_LOAD_TYPE_SWITCH(ltype_mask, LTypeMask, { CHECK_LE(sizeof(bool), sizeof(LTypeMask)); int rows_per_block = mxnet::common::cuda::get_rows_per_block( M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); // calculate amount shared memory (slots aligned to double) int entries_per_load = entries_per_load = sizeof(LType) / sizeof(DType); int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); size_t size_input_shared = entries_per_load > 0 ? rows_per_block * M / entries_per_load : 0; size_t size_mask_shared = entries_per_load_mask > 0 ? rows_per_block * M / entries_per_load_mask : 0; size_input_shared = ((2 * size_input_shared * sizeof(LType) + sizeof(double) - 1) / sizeof(double)); size_mask_shared = ((size_mask_shared * sizeof(LTypeMask) + sizeof(double) - 1) / sizeof(double)); size_t amount_shared = size_input_shared * sizeof(double) + size_mask_shared * sizeof(double) + softmax_threads_per_block * sizeof(AType); int nblocks = (N + rows_per_block - 1) / rows_per_block; masked_softmax_stride1_grad_kernel<OP1, OP2, Req, negate, AType, LType, LTypeMask> <<<nblocks, softmax_threads_per_block, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>(out, ograd, igrad, mask, M, axis, sshape, mask_shape, temperature, rows_per_block, N, size_input_shared, size_mask_shared); }); }); MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_stride1_grad_kernel); } else { masked_softmax_grad_kernel<x_bits, OP1, OP2, Req, negate, AType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( out, ograd, igrad, mask, M, axis, sshape, stride, mask_shape, temperature); MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_grad_kernel); } } #endif } // namespace mxnet_op struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> { int axis; dmlc::optional<double> temperature; dmlc::optional<int> dtype; dmlc::optional<bool> use_length; DMLC_DECLARE_PARAMETER(SoftmaxParam) { DMLC_DECLARE_FIELD(axis).set_default(-1).describe("The axis along which to compute softmax."); DMLC_DECLARE_FIELD(temperature) .set_default(dmlc::optional<double>()) .describe("Temperature parameter in softmax"); DMLC_DECLARE_FIELD(dtype) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(dmlc::optional<int>()) .describe( "DType of the output in case this can't be inferred. " "Defaults to the same as input's dtype if not defined (dtype=None)."); DMLC_DECLARE_FIELD(use_length) .set_default(dmlc::optional<bool>(false)) .describe("Whether to use the length input as a mask over the data input."); } bool operator==(const SoftmaxParam& other) const { return this->axis == other.axis && this->temperature == other.temperature && this->dtype == other.dtype && this->use_length == other.use_length; } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream axis_s, temperature_s, dtype_s, use_length_s; axis_s << axis; temperature_s << temperature; dtype_s << dtype; use_length_s << use_length; (*dict)["axis"] = axis_s.str(); (*dict)["temperature"] = temperature_s.str(); if (dtype.has_value()) { (*dict)["dtype"] = MXNetTypeWithBool2String(dtype.value()); } else { (*dict)["dtype"] = dtype_s.str(); } (*dict)["use_length"] = use_length_s.str(); } }; struct MaskedSoftmaxParam : public dmlc::Parameter<MaskedSoftmaxParam> { int axis; dmlc::optional<double> temperature; dmlc::optional<bool> normalize; DMLC_DECLARE_PARAMETER(MaskedSoftmaxParam) { DMLC_DECLARE_FIELD(axis).set_default(-1).describe("The axis along which to compute softmax."); DMLC_DECLARE_FIELD(temperature) .set_default(dmlc::optional<double>()) .describe("Temperature parameter in softmax"); DMLC_DECLARE_FIELD(normalize) .set_default(dmlc::optional<bool>(true)) .describe("Whether to normalize input data x: x = x - max(x)"); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream axis_s, temperature_s, normalize_s; axis_s << axis; temperature_s << temperature; normalize_s << normalize; (*dict)["axis"] = axis_s.str(); (*dict)["temperature"] = temperature_s.str(); (*dict)["normalize"] = normalize_s.str(); } }; static inline bool softmax_has_dtype_override(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.dtype.has_value() && param.dtype.value() != -1; } static inline bool softmax_use_length(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.use_length.value(); } static inline bool SoftmaxOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 0, param.dtype.value()); type_assign(&(*in_attrs)[0], (*out_attrs)[0]); return true; } else { std::vector<int> tmp = {in_attrs->at(0)}; return ElemwiseType<1, 1>(attrs, &tmp, out_attrs); } } static inline bool SoftmaxOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { CHECK_EQ(out_attrs->size(), 1U); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), param.use_length.value() ? 2U : 1U); if (param.use_length.value()) { mxnet::TShape& dshape = in_attrs->at(0); mxnet::TShape tmp_shape((dshape.ndim() == 1) ? 1U : dshape.ndim() - 1, 1); int j = 0; int axis = param.axis != -1 ? param.axis : dshape.ndim() - 1; for (int i = 0; i < dshape.ndim(); ++i) { if (i != axis) { tmp_shape[j++] = dshape[i]; } } SHAPE_ASSIGN_CHECK(*in_attrs, 1, tmp_shape); } mxnet::ShapeVector tmp = {in_attrs->at(0)}; return ElemwiseShape<1, 1>(attrs, &tmp, out_attrs); } static inline bool SoftmaxGradOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { mxnet::ShapeVector ins = {in_attrs->at(0), in_attrs->at(1), in_attrs->at(3)}; mxnet::ShapeVector dgrad = {out_attrs->at(0)}; bool res = ElemwiseShape<3, 1>(attrs, &ins, &dgrad); SHAPE_ASSIGN_CHECK(*in_attrs, 0, ins[0]); SHAPE_ASSIGN_CHECK(*in_attrs, 1, ins[1]); SHAPE_ASSIGN_CHECK(*in_attrs, 3, ins[2]); SHAPE_ASSIGN_CHECK(*out_attrs, 0, dgrad[0]); mxnet::ShapeVector length = {in_attrs->at(2)}; mxnet::ShapeVector lgrad = {out_attrs->at(1)}; res = (res && ElemwiseShape<1, 1>(attrs, &length, &lgrad)); SHAPE_ASSIGN_CHECK(*in_attrs, 2, length[0]); SHAPE_ASSIGN_CHECK(*out_attrs, 1, lgrad[0]); return res; } else { return ElemwiseShape<3, 1>(attrs, in_attrs, out_attrs); } } else { return ElemwiseShape<2, 1>(attrs, in_attrs, out_attrs); } } static inline bool SoftmaxGradOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 4U : 3U); int in_dtype = (*in_attrs)[1]; int out_dtype = (*in_attrs)[softmax_use_length(attrs) ? 3 : 2]; TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_dtype); if (softmax_use_length(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 1, in_attrs->at(2)); } return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1 && (!softmax_use_length(attrs) || ((*out_attrs)[1] != -1 && (*in_attrs)[1] != -1)); } else { CHECK_EQ(in_attrs->size(), 2U); int out_dtype = (*in_attrs)[1]; TYPE_ASSIGN_CHECK(*out_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1; } } static inline std::vector<std::pair<int, int>> SoftmaxGradOpInplaceOption( const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}, {2, 1}, {3, 0}}; } else { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}, {2, 0}}; } } else { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}}; } } static inline uint32_t SoftmaxGradOpNumInputs(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { return softmax_use_length(attrs) ? 4 : 3; } return 2; } static inline std::vector<std::string> SoftmaxGradOpInputNames(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::string>{"ograd", "data", "length", "output"}; } else { return std::vector<std::string>{"ograd", "data", "output"}; } } else { return std::vector<std::string>{"ograd", "output"}; } } struct SoftmaxFGradient { const char* op_name; std::vector<nnvm::NodeEntry> operator()(const nnvm::ObjectPtr& n, const std::vector<nnvm::NodeEntry>& ograds) const { if (softmax_has_dtype_override(n->attrs) || softmax_use_length(n->attrs)) { return ElemwiseGradUseInOut{op_name}(n, ograds); // NOLINT } else { return ElemwiseGradUseOut{op_name}(n, ograds); // NOLINT } } }; static inline bool MaskedSoftmaxOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1); CHECK_EQ(in_attrs->size(), 2U); std::vector<int> tmp = {in_attrs->at(0)}; return ElemwiseType<1, 1>(attrs, &tmp, out_attrs); } static inline bool MaskedSoftmaxOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_shape, mxnet::ShapeVector* out_shape) { CHECK_EQ(out_shape->size(), 1U); CHECK_EQ(in_shape->size(), 2U); mxnet::TShape& data_shape = (*in_shape)[0]; mxnet::TShape& mask_shape = (*in_shape)[1]; if (!mxnet::ndim_is_known(data_shape) || !mxnet::ndim_is_known(mask_shape)) { return false; } CHECK(data_shape.ndim() == mask_shape.ndim()) << "Number of dimensions in data and mask does not match"; CHECK(data_shape.ndim() > 0) << "Empty tuple is not allowed"; for (int i = 0; i < data_shape.ndim(); ++i) { CHECK(data_shape[i] == mask_shape[i] || mask_shape[i] == 1) << "Mask cannot be broadcasted from " << mask_shape << " to " << data_shape; } SHAPE_ASSIGN_CHECK(*out_shape, 0, in_shape->at(0)); SHAPE_ASSIGN_CHECK(*in_shape, 0, out_shape->at(0)); return true; } static inline bool MaskedSoftmaxGradOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_shape, mxnet::ShapeVector* out_shape) { CHECK_EQ(out_shape->size(), 1U); CHECK_EQ(in_shape->size(), 3U); mxnet::TShape& ograd_shape = (*in_shape)[0]; mxnet::TShape& mask_shape = (*in_shape)[1]; if (!mxnet::ndim_is_known(ograd_shape) || !mxnet::ndim_is_known(mask_shape)) { return false; } CHECK(ograd_shape.ndim() == mask_shape.ndim()) << "Number of dimensions in data and mask does not match"; CHECK(ograd_shape.ndim() > 0) << "Empty tuple is not allowed"; for (int i = 0; i < ograd_shape.ndim(); ++i) { CHECK(ograd_shape[i] == mask_shape[i] || mask_shape[i] == 1) << "Mask cannot be broadcasted from " << mask_shape << " to " << ograd_shape; } SHAPE_ASSIGN_CHECK(*out_shape, 0, in_shape->at(0)); SHAPE_ASSIGN_CHECK(*out_shape, 0, in_shape->at(2)); SHAPE_ASSIGN_CHECK(*in_shape, 0, out_shape->at(0)); SHAPE_ASSIGN_CHECK(*in_shape, 2, out_shape->at(0)); return true; } static inline bool MaskedSoftmaxGradOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1U); CHECK_EQ(in_attrs->size(), 3U); int data_dtype = (*in_attrs)[0]; TYPE_ASSIGN_CHECK(*in_attrs, 2, data_dtype); TYPE_ASSIGN_CHECK(*out_attrs, 0, data_dtype); data_dtype = (*out_attrs)[0]; TYPE_ASSIGN_CHECK(*in_attrs, 0, data_dtype); return true; } static inline std::vector<std::pair<int, int>> MaskedSoftmaxGradOpInplaceOption( const nnvm::NodeAttrs& attrs) { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}, {2, 1}, {3, 0}}; } template <typename xpu, typename OP, bool negate = false> void SoftmaxCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp || inputs[0].Size() == 0U) return; CHECK_NE(req[0], kAddTo); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); if (!safe_acc && inputs[0].type_flag_ == mshadow::kFloat16) { common::LogOnce( "MXNET_SAFE_ACCUMULATION=1 is recommended for softmax with float16 inputs. " "See https://mxnet.apache.org/api/faq/env_var " "for more details."); } MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MSHADOW_REAL_TYPE_SWITCH( outputs[0].type_flag_, OType, { int type = kInt32; if (param.use_length.value()) { CHECK(inputs.size() > 1) << "Mask needs to be provided when using softmax with use_length=True."; type = inputs[1].type_flag_; } MXNET_INT32_INT64_TYPE_SWITCH(type, IType, { IType* mask_ptr = nullptr; if (param.use_length.value()) { mask_ptr = inputs[1].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { Softmax<OP, negate, AType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, AType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { Softmax<OP, negate, DType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, DType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); } template <typename xpu, typename OP, bool masked_neg_inf, bool negate = false> void MaskedSoftmaxCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp || inputs[0].Size() == 0U) return; CHECK_NE(req[0], kAddTo); const MaskedSoftmaxParam& param = nnvm::get<MaskedSoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); if (!safe_acc && inputs[0].type_flag_ == mshadow::kFloat16) { common::LogOnce( "MXNET_SAFE_ACCUMULATION=1 is recommended for masked_softmax with " "float16 inputs. " "See https://mxnet.apache.org/api/faq/env_var " "for more details."); } MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MXNET_NDIM_SWITCH(inputs[0].ndim(), ndim, { bool* mask_ptr = inputs[1].dptr<bool>(); if (safe_acc) { MaskedSoftmax<OP, masked_neg_inf, negate, AType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, temperature, param.normalize.value(), ctx); } else { MaskedSoftmax<OP, masked_neg_inf, negate, DType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, temperature, param.normalize.value(), ctx); } }); }); } #if MXNET_USE_CUDA struct SoftmaxRTCCompute { std::string OP; bool negate = false; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; struct SoftmaxRTCGradCompute { std::string OP1; std::string OP2; bool negate = false; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; #endif template <typename xpu, typename OP1, typename OP2, bool negate = false> void SoftmaxGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (softmax_use_length(attrs)) { MXNET_INT32_INT64_TYPE_SWITCH(inputs[2].type_flag_, IType, { if (req[1] != kNullOp) { mxnet_op::Kernel<mxnet_op::set_zero, xpu>::Launch( ctx.get_stream<xpu>(), outputs[1].Size(), outputs[1].dptr<IType>()); } }); } if (req[0] == kNullOp) return; const int itype = softmax_use_length(attrs) ? inputs[2].type_flag_ : kInt32; const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); int out_idx = softmax_has_dtype_override(attrs) ? 2 : 1; out_idx = softmax_use_length(attrs) ? 3 : out_idx; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, OType, AType, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_INT32_INT64_TYPE_SWITCH(itype, IType, { IType* length_ptr = nullptr; if (softmax_use_length(attrs)) { length_ptr = inputs[2].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, AType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, AType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, DType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, DType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); }); } template <typename xpu, typename OP1, typename OP2, bool negate = false> void MaskedSoftmaxGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; const MaskedSoftmaxParam& param = nnvm::get<MaskedSoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_NDIM_SWITCH(inputs[0].ndim(), ndim, { DType* ograd_ptr = inputs[0].dptr<DType>(); DType* out_ptr = inputs[2].dptr<DType>(); bool* mask_ptr = inputs[1].dptr<bool>(); DType* grad_data = outputs[0].dptr<DType>(); if (safe_acc) { MaskedSoftmaxGrad<OP1, OP2, Req, negate, AType>(ctx.get_stream<xpu>(), out_ptr, ograd_ptr, grad_data, mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, static_cast<DType>(temperature), ctx); } else { MaskedSoftmaxGrad<OP1, OP2, Req, negate, DType>(ctx.get_stream<xpu>(), out_ptr, ograd_ptr, grad_data, mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, static_cast<DType>(temperature), ctx); } }); }); }); } } // namespace op } // namespace mxnet namespace std { template <> struct hash<mxnet::op::SoftmaxParam> { size_t operator()(const mxnet::op::SoftmaxParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.axis); ret = dmlc::HashCombine(ret, val.temperature); ret = dmlc::HashCombine(ret, val.dtype); ret = dmlc::HashCombine(ret, val.use_length); return ret; } }; } // namespace std #endif // MXNET_OPERATOR_NN_SOFTMAX_INL_H_
cshift.h
#ifndef _CK_CSHIFT_H #define _CK_CSHIFT_H CPS_START_NAMESPACE //C-shift any 4d field with canonical ordering in the time direction //(should be trivial to generalize!) void TbarrelShift4D(Float* data, const int site_size, const int tshift){ if(tshift == 0) return; const int plane_size = GJP.VolNodeSites()/GJP.TnodeSites(); const int bulk_size = GJP.VolNodeSites()-plane_size; const int nf = GJP.Gparity() ? 2:1; Float *tplane_send = (Float*)malloc(site_size * plane_size * nf * sizeof(Float)); Float *tplane_recv = (Float*)malloc(site_size * plane_size * nf * sizeof(Float)); Float *bulk = (Float*)malloc(site_size * bulk_size * nf * sizeof(Float)); const int tsend = tshift > 0 ? GJP.TnodeSites()-1 : 0; const int trecv = tshift > 0 ? 0 : GJP.TnodeSites()-1; const int tbulk_start = tshift > 0 ? 0 : 1; const int tbulk_lessthan = tshift > 0 ? GJP.TnodeSites()-1 : GJP.TnodeSites(); const int shift_one = tshift > 0 ? 1 : -1; const int gp_foff_bulk = site_size*bulk_size; const int gp_foff_plane = site_size*plane_size; const int gp_foff_orig = site_size*GJP.VolNodeSites(); const int nshift = tshift > 0 ? tshift : -tshift; for(int shift = 0; shift < nshift; shift++){ //Pull out the time plane we are sending and the rest of the *bulk* #pragma omp parallel for for(int x3d=0;x3d<plane_size;x3d++){ for(int f=0;f<nf;f++){ int tb = 0; for(int t=tbulk_start; t<tbulk_lessthan; t++){ Float *orig_off = data + f*gp_foff_orig + site_size*(x3d + plane_size * t); Float *bulk_off = bulk + f*gp_foff_bulk + site_size*(x3d + plane_size * tb); memcpy(bulk_off,orig_off,site_size*sizeof(Float)); ++tb; } Float *orig_off = data + f*gp_foff_orig + site_size*(x3d + plane_size * tsend); Float *plane_off = tplane_send + f*gp_foff_plane + site_size*x3d; memcpy(plane_off,orig_off,site_size*sizeof(Float)); } } if(tshift > 0) getMinusData(tplane_recv,tplane_send,nf*site_size*plane_size,3); //send in +t direction else getPlusData(tplane_recv,tplane_send,nf*site_size*plane_size,3); //send in +t direction #pragma omp parallel for for(int x3d=0;x3d<plane_size;x3d++){ for(int f=0;f<nf;f++){ int tb = 0; for(int t=tbulk_start + shift_one; t<tbulk_lessthan + shift_one; t++){ //put the bulk back but shifted one in time Float *bulk_off = bulk + f*gp_foff_bulk + site_size*(x3d + plane_size * tb); Float *orig_off = data + f*gp_foff_orig + site_size*(x3d + plane_size * t); memcpy(orig_off,bulk_off,site_size*sizeof(Float)); ++tb; } Float *plane_off = tplane_recv + f*gp_foff_plane + site_size*x3d; Float *orig_off = data + f*gp_foff_orig + site_size*(x3d + plane_size * trecv); memcpy(orig_off,plane_off,site_size*sizeof(Float)); } } } free(tplane_send); free(tplane_recv); free(bulk); } void Tshift4D(Float* data, const int site_size, const int tshift){ TbarrelShift4D(data, site_size, tshift); } CPS_END_NAMESPACE #endif
GB_unaryop__lnot_int64_int32.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_int32 // op(A') function: GB_tran__lnot_int64_int32 // C type: int64_t // A type: int32_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ int32_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 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_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int64_int32 ( int64_t *restrict Cx, const int32_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_int32 ( 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
quantize.h
// Copyright 2018 The MACE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MACE_UTILS_QUANTIZE_H_ #define MACE_UTILS_QUANTIZE_H_ #include <algorithm> #include <cmath> #include <limits> #if defined(MACE_ENABLE_NEON) #include <arm_neon.h> #endif // MACE_ENABLE_NEON #include "mace/utils/logging.h" namespace mace { template<typename T> inline void AdjustRange(const float in_min_data, const float in_max_data, const bool non_zero, float *scale, int32_t *zero_point) { // re-range to make range include zero float and // make zero float as integer u8 const T quantized_min = std::numeric_limits<T>::lowest(); const T quantized_max = std::numeric_limits<T>::max(); if (quantized_min < 0) { MACE_ASSERT(!non_zero, "Cannot nudge to non_zero quantize value."); } float out_max = std::max(0.f, in_max_data); float out_min = std::min(0.f, in_min_data); // make in_min_data quantize as greater than 1 if (non_zero) { out_min = std::min(out_min, in_min_data - (out_max - in_min_data) / (quantized_max - quantized_min - 1)); } *scale = (out_max - out_min) / (quantized_max - quantized_min); const float kEps = 1e-6; if (out_min < -kEps && out_max > kEps) { float quantized_zero = -out_min / *scale; int32_t quantized_zero_near_int = static_cast<int32_t>(roundf(quantized_zero)); *zero_point = quantized_zero_near_int; if (fabs(quantized_zero - quantized_zero_near_int) > kEps) { if (quantized_zero < quantized_zero_near_int || non_zero) { // keep out_max fixed, and move out_min *zero_point = static_cast<int32_t>(std::ceil(quantized_zero)); *scale = out_max / (quantized_max - *zero_point); } else { // keep out_min fixed, and move out_max *scale = out_min / (quantized_min - *zero_point); } } } else if (out_min > -kEps) { *zero_point = quantized_min; } else { *zero_point = quantized_max; } } template<typename T> inline T Saturate(float value) { int rounded_value = static_cast<int>(value); if (rounded_value <= std::numeric_limits<T>::lowest()) { return std::numeric_limits<T>::lowest(); } else if (rounded_value >= std::numeric_limits<T>::max()) { return std::numeric_limits<T>::max(); } else { return static_cast<T>(rounded_value); } } inline void FindMinMax(const float *input, const index_t size, float *min_val, float *max_val) { float max_v = std::numeric_limits<float>::lowest(); float min_v = std::numeric_limits<float>::max(); for (index_t i = 0; i < size; ++i) { max_v = std::max(max_v, input[i]); min_v = std::min(min_v, input[i]); } *min_val = min_v; *max_val = max_v; } template<typename T> inline void QuantizeWithScaleAndZeropoint(const float *input, const index_t size, float scale, int32_t zero_point, T *output) { float recip_scale = 1 / scale; #pragma omp parallel for schedule(runtime) for (int i = 0; i < size; ++i) { output[i] = Saturate<T>(roundf(zero_point + recip_scale * input[i])); } } template<typename T> inline void Quantize(const float *input, const index_t size, bool non_zero, T *output, float *scale, int32_t *zero_point) { float in_min_data; float in_max_data; FindMinMax(input, size, &in_min_data, &in_max_data); AdjustRange<T>(in_min_data, in_max_data, non_zero, scale, zero_point); QuantizeWithScaleAndZeropoint(input, size, *scale, *zero_point, output); } template<typename T> inline void Quantize(const Tensor &input, Tensor *output, float *min_out, float *max_out) { MACE_CHECK(input.size() != 0); Tensor::MappingGuard input_guard(&input); Tensor::MappingGuard output_guard(output); auto *input_data = input.data<float>(); auto *output_data = output->mutable_data<T>(); float scale; int32_t zero_point; Quantize(input_data, input.size(), false, output_data, &scale, &zero_point); *min_out = scale * (std::numeric_limits<T>::lowest() - zero_point); *max_out = scale * (std::numeric_limits<T>::max() - zero_point); } template<typename T> inline void Dequantize(const T *input, const index_t size, const float scale, const int32_t zero_point, float *output) { #pragma omp parallel for schedule(runtime) for (int i = 0; i < size; ++i) { output[i] = scale * (input[i] - zero_point); } } #if defined(MACE_ENABLE_NEON) template<> inline void QuantizeWithScaleAndZeropoint<uint8_t>(const float *input, const index_t size, float scale, int32_t zero_point, uint8_t *output) { const float32x4_t vround = vdupq_n_f32(0.5); const float32x4_t vzero = vaddq_f32(vround, vcvtq_f32_s32(vdupq_n_s32(zero_point))); const float recip_scale = 1.f / scale; const float32x4_t vrecip_scale = vdupq_n_f32(recip_scale); const index_t block_count = size / 16; #pragma omp parallel for schedule(runtime) for (index_t i = 0; i < block_count; ++i) { float32x4_t vi0 = vld1q_f32(input + i * 16); float32x4_t vi1 = vld1q_f32(input + i * 16 + 4); float32x4_t vi2 = vld1q_f32(input + i * 16 + 8); float32x4_t vi3 = vld1q_f32(input + i * 16 + 12); int32x4_t vo0_s32 = vcvtq_s32_f32(vmlaq_f32(vzero, vi0, vrecip_scale)); int32x4_t vo1_s32 = vcvtq_s32_f32(vmlaq_f32(vzero, vi1, vrecip_scale)); int32x4_t vo2_s32 = vcvtq_s32_f32(vmlaq_f32(vzero, vi2, vrecip_scale)); int32x4_t vo3_s32 = vcvtq_s32_f32(vmlaq_f32(vzero, vi3, vrecip_scale)); uint8x8_t vo0_u8 = vqmovun_s16(vcombine_s16(vqmovn_s32(vo0_s32), vqmovn_s32(vo1_s32))); uint8x8_t vo1_u8 = vqmovun_s16(vcombine_s16(vqmovn_s32(vo2_s32), vqmovn_s32(vo3_s32))); uint8x16_t vo = vcombine_u8(vo0_u8, vo1_u8); vst1q_u8(output + i * 16, vo); } #pragma omp parallel for schedule(runtime) for (index_t i = block_count * 16; i < size; ++i) { output[i] = Saturate<uint8_t>(roundf(zero_point + recip_scale * input[i])); } } template<> inline void Dequantize<int32_t>(const int32_t *input, const index_t size, const float scale, const int32_t zero_point, float *output) { const index_t block_count = size / 4; const int32x4_t vzero = vdupq_n_s32(zero_point); const float32x4_t vscale = vdupq_n_f32(scale); #pragma omp parallel for schedule(runtime) for (index_t i = 0; i < block_count; ++i) { int32x4_t vi = vld1q_s32(input + i * 4); float32x4_t vo = vmulq_f32(vscale, vcvtq_f32_s32(vsubq_s32(vi, vzero))); vst1q_f32(output + i * 4, vo); } for (index_t i = block_count * 4; i < size; ++i) { output[i] = scale * (input[i] - zero_point); } } template<> inline void Dequantize<uint8_t>(const uint8_t *input, const index_t size, const float scale, const int32_t zero_point, float *output) { const index_t block_count = size / 16; const int32x4_t vzero = vdupq_n_s32(zero_point); const float32x4_t vscale = vdupq_n_f32(scale); #pragma omp parallel for schedule(runtime) for (index_t i = 0; i < block_count; ++i) { uint8x16_t vi = vld1q_u8(input + i * 16); float32x4x4_t vo = { vmulq_f32(vscale, vcvtq_f32_s32(vsubq_s32(vreinterpretq_s32_u32(vmovl_u16( vget_low_u16(vmovl_u8(vget_low_u8(vi))))), vzero))), vmulq_f32(vscale, vcvtq_f32_s32(vsubq_s32(vreinterpretq_s32_u32(vmovl_u16( vget_high_u16(vmovl_u8(vget_low_u8(vi))))), vzero))), vmulq_f32(vscale, vcvtq_f32_s32(vsubq_s32(vreinterpretq_s32_u32(vmovl_u16( vget_low_u16(vmovl_u8(vget_high_u8(vi))))), vzero))), vmulq_f32(vscale, vcvtq_f32_s32(vsubq_s32(vreinterpretq_s32_u32(vmovl_u16( vget_high_u16(vmovl_u8(vget_high_u8(vi))))), vzero))), }; vst1q_f32(output + i * 16, vo.val[0]); vst1q_f32(output + i * 16 + 4, vo.val[1]); vst1q_f32(output + i * 16 + 8, vo.val[2]); vst1q_f32(output + i * 16 + 12, vo.val[3]); } for (index_t i = block_count * 16; i < size; ++i) { output[i] = scale * (input[i] - zero_point); } } #endif // MACE_ENABLE_NEON template<typename T> inline void DeQuantize(const Tensor &input, const float min_in, const float max_in, Tensor *output) { MACE_CHECK(input.size() != 0); Tensor::MappingGuard input_guard(&input); Tensor::MappingGuard output_guard(output); auto *input_data = input.data<T>(); auto *output_data = output->mutable_data<float>(); float scale; int32_t zero_point; AdjustRange<T>(min_in, max_in, false, &scale, &zero_point); Dequantize(input_data, input.size(), scale, zero_point, output_data); } inline void QuantizeMultiplier(double multiplier, int32_t *output_multiplier, int32_t *shift) { const double q = std::frexp(multiplier, shift); auto qint = static_cast<int64_t>(roundl(q * (1ll << 31))); if (qint == (1ll << 31)) { qint /= 2; ++*shift; } *output_multiplier = static_cast<int32_t>(qint); MACE_CHECK(*output_multiplier <= std::numeric_limits<int32_t>::max()); } inline void GetOutputMultiplierAndShift( const float lhs_scale, const float rhs_scale, const float output_scale, int32_t *quantized_multiplier, int *right_shift) { float real_multiplier = lhs_scale * rhs_scale / output_scale; MACE_CHECK(real_multiplier > 0.f && real_multiplier < 1.f, real_multiplier); int exponent; QuantizeMultiplier(real_multiplier, quantized_multiplier, &exponent); *right_shift = -exponent; MACE_CHECK(*right_shift >= 0); } } // namespace mace #endif // MACE_UTILS_QUANTIZE_H_
depend-2.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ void bar (int a[10][10][10]); void foo (int a[10][10][10], int **b) { int c[10][10][10]; #pragma omp task depend(out: a[2:4][3:][:7], b[1:7][2:8]) bar (a); int i = 1, j = 3, k = 2, l = 6; #pragma omp task depend(in: a[++i:++j][++k:][:++l]) bar (a); #pragma omp task depend(out: a[7:2][:][:], c[5:2][:][:]) { bar (c); bar (a); } }
image_pyramid.h
/* * * This file is part of the open-source SeetaFace engine, which includes three modules: * SeetaFace Detection, SeetaFace Alignment, and SeetaFace Identification. * * This file is part of the SeetaFace Detection module, containing codes implementing the * face detection method described in the following paper: * * * Funnel-structured cascade for multi-view face detection with alignment awareness, * Shuzhe Wu, Meina Kan, Zhenliang He, Shiguang Shan, Xilin Chen. * In Neurocomputing (under review) * * * Copyright (C) 2016, Visual Information Processing and Learning (VIPL) group, * Institute of Computing Technology, Chinese Academy of Sciences, Beijing, China. * * The codes are mainly developed by Shuzhe Wu (a Ph.D supervised by Prof. Shiguang Shan) * * As an open-source face recognition engine: you can redistribute SeetaFace source codes * and/or modify it under the terms of the BSD 2-Clause License. * * You should have received a copy of the BSD 2-Clause License along with the software. * If not, see < https://opensource.org/licenses/BSD-2-Clause>. * * Contact Info: you can send an email to SeetaFace@vipl.ict.ac.cn for any problems. * * Note: the above information must be kept whenever or wherever the codes are used. * */ #ifndef SEETA_FD_UTIL_IMAGE_PYRAMID_H_ #define SEETA_FD_UTIL_IMAGE_PYRAMID_H_ #include <cstdint> #include <string> #include "../common.h" namespace seeta { namespace fd { static void ResizeImage(const seeta::ImageData & src, seeta::ImageData* dest) { int32_t src_width = src.width; int32_t src_height = src.height; int32_t dest_width = dest->width; int32_t dest_height = dest->height; if (src_width == dest_width && src_height == dest_height) { std::memcpy(dest->data, src.data, src_width * src_height * sizeof(uint8_t)); return; } double lf_x_scl = static_cast<double>(src_width) / dest_width; double lf_y_Scl = static_cast<double>(src_height) / dest_height; const uint8_t* src_data = src.data; uint8_t* dest_data = dest->data; #pragma omp parallel num_threads(SEETA_NUM_THREADS) { #pragma omp for nowait for (int32_t y = 0; y < dest_height; y++) { for (int32_t x = 0; x < dest_width; x++) { double lf_x_s = lf_x_scl * x; double lf_y_s = lf_y_Scl * y; int32_t n_x_s = static_cast<int>(lf_x_s); n_x_s = (n_x_s <= (src_width - 2) ? n_x_s : (src_width - 2)); int32_t n_y_s = static_cast<int>(lf_y_s); n_y_s = (n_y_s <= (src_height - 2) ? n_y_s : (src_height - 2)); double lf_weight_x = lf_x_s - n_x_s; double lf_weight_y = lf_y_s - n_y_s; double dest_val = (1 - lf_weight_y) * ((1 - lf_weight_x) * src_data[n_y_s * src_width + n_x_s] + lf_weight_x * src_data[n_y_s * src_width + n_x_s + 1]) + lf_weight_y * ((1 - lf_weight_x) * src_data[(n_y_s + 1) * src_width + n_x_s] + lf_weight_x * src_data[(n_y_s + 1) * src_width + n_x_s + 1]); dest_data[y * dest_width + x] = static_cast<uint8_t>(dest_val); } } } } class ImagePyramid { public: ImagePyramid() : max_scale_(1.0f), min_scale_(1.0f), scale_factor_(1.0f), scale_step_(0.8f), width1x_(0), height1x_(0), width_scaled_(0), height_scaled_(0), buf_img_width_(2), buf_img_height_(2), buf_scaled_width_(2), buf_scaled_height_(2) { buf_img_ = new uint8_t[buf_img_width_ * buf_img_height_]; buf_img_scaled_ = new uint8_t[buf_scaled_width_ * buf_scaled_height_]; } ~ImagePyramid() { delete[] buf_img_; buf_img_ = nullptr; buf_img_width_ = 0; buf_img_height_ = 0; delete[] buf_img_scaled_; buf_img_scaled_ = nullptr; buf_scaled_width_ = 0; buf_scaled_height_ = 0; img_scaled_.data = nullptr; img_scaled_.width = 0; img_scaled_.height = 0; } inline void SetScaleStep(float step) { if (step > 0.0f && step <= 1.0f) scale_step_ = step; } inline void SetMinScale(float min_scale) { min_scale_ = min_scale; } inline void SetMaxScale(float max_scale) { max_scale_ = max_scale; scale_factor_ = max_scale; UpdateBufScaled(); } void SetImage1x(const uint8_t* img_data, int32_t width, int32_t height); inline float min_scale() const { return min_scale_; } inline float max_scale() const { return max_scale_; } inline seeta::ImageData image1x() { seeta::ImageData img(width1x_, height1x_, 1); img.data = buf_img_; return img; } const seeta::ImageData* GetNextScaleImage(float* scale_factor = nullptr); private: void UpdateBufScaled(); float max_scale_; float min_scale_; float scale_factor_; float scale_step_; int32_t width1x_; int32_t height1x_; int32_t width_scaled_; int32_t height_scaled_; uint8_t* buf_img_; int32_t buf_img_width_; int32_t buf_img_height_; uint8_t* buf_img_scaled_; int32_t buf_scaled_width_; int32_t buf_scaled_height_; seeta::ImageData img_scaled_; }; } // namespace fd } // namespace seeta #endif // SEETA_FD_UTIL_IMAGE_PYRAMID_H_
hello-ordered.c
#include <stdio.h> #if defined(_OPENMP) #include <omp.h> #endif int main(void) { int i; #pragma omp parallel for ordered schedule (static,5) for (i=0;i<20;i++) { #pragma omp ordered printf("%2d,Hello,world.!\n",i); } }
explicit_solver_strategy.h
// // Authors: // Miguel Angel Celigueta maceli@cimne.upc.edu // Miquel Santasusana msantasusana@cimne.upc.edu // #if !defined(KRATOS_EXPLICIT_SOLVER_STRATEGY) #define KRATOS_EXPLICIT_SOLVER_STRATEGY // Project includes #include "utilities/timer.h" #include "custom_elements/Particle_Contact_Element.h" #include "includes/variables.h" #include "includes/deprecated_variables.h" /* System includes */ #include <limits> #include <iostream> #include <iomanip> #include <time.h> /* External includes */ #ifdef _OPENMP #include <omp.h> #endif #define CUSTOMTIMER 0 // ACTIVATES AND DISABLES ::TIMER::::: #include "includes/define.h" #include "utilities/openmp_utils.h" #include "includes/model_part.h" #include "solving_strategies/strategies/solving_strategy.h" #include "solving_strategies/schemes/scheme.h" #include "custom_strategies/schemes/dem_integration_scheme.h" #include "custom_utilities/create_and_destroy.h" #include "custom_utilities/dem_fem_utilities.h" #include "custom_utilities/GeometryFunctions.h" #include "custom_utilities/inlet.h" #include "custom_elements/cluster3D.h" #include "custom_elements/rigid_body_element.h" ////Cfeng #include "custom_utilities/dem_fem_search.h" #include "custom_utilities/discrete_particle_configure.h" #include "custom_utilities/rigid_face_geometrical_object_configure.h" #ifdef USING_CGAL #include <CGAL/spatial_sort.h> #endif /* Timer defines */ #ifdef CUSTOMTIMER #define KRATOS_TIMER_START(t) Timer::Start(t); #define KRATOS_TIMER_STOP(t) Timer::Stop(t); #else #define KRATOS_TIMER_START(t) #define KRATOS_TIMER_STOP(t) #endif namespace Kratos { class ExplicitSolverSettings { public: KRATOS_CLASS_POINTER_DEFINITION(ExplicitSolverSettings); ExplicitSolverSettings() { } ~ExplicitSolverSettings() { } ModelPart* r_model_part; ModelPart* contact_model_part; ModelPart* fem_model_part; ModelPart* cluster_model_part; ModelPart* inlet_model_part; }; class KRATOS_API(DEM_APPLICATION) ExplicitSolverStrategy { public: typedef ModelPart::NodesContainerType NodesArrayType; typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ElementsArrayType::iterator ElementsIterator; typedef ModelPart::ConditionsContainerType ConditionsArrayType; typedef ModelPart::NodesContainerType::ContainerType NodesContainerType; typedef ModelPart::ElementsContainerType::ContainerType ElementsContainerType; typedef ModelPart::ConditionsContainerType::ContainerType ConditionsContainerType; typedef SpatialSearch::ResultElementsContainerType ResultElementsContainerType; typedef SpatialSearch::VectorResultElementsContainerType VectorResultElementsContainerType; typedef SpatialSearch::RadiusArrayType RadiusArrayType; typedef SpatialSearch::DistanceType DistanceType; typedef SpatialSearch::VectorDistanceType VectorDistanceType; typedef SpatialSearch::ResultConditionsContainerType ResultConditionsContainerType; typedef SpatialSearch::VectorResultConditionsContainerType VectorResultConditionsContainerType; typedef PointerVectorSet<Properties, IndexedObject> PropertiesContainerType; typedef PropertiesContainerType::iterator PropertiesIterator; typedef DiscreteParticleConfigure<3> ElementConfigureType; typedef RigidFaceGeometricalObjectConfigure<3> RigidFaceGeometricalConfigureType; typedef Variable<double> ComponentOf3ComponentsVariableType; /// Pointer definition of ExplicitSolverStrategy KRATOS_CLASS_POINTER_DEFINITION(ExplicitSolverStrategy); ExplicitSolverStrategy() { } ExplicitSolverStrategy(ExplicitSolverSettings& settings, const double max_delta_time, const int n_step_search, const double safety_factor, const int delta_option, ParticleCreatorDestructor::Pointer p_creator_destructor, DEM_FEM_Search::Pointer p_dem_fem_search, SpatialSearch::Pointer pSpSearch, Parameters strategy_parameters) { mParameters = strategy_parameters; mDeltaOption = delta_option; mpParticleCreatorDestructor = p_creator_destructor; mpDemFemSearch = p_dem_fem_search; mpSpSearch = pSpSearch; if(mParameters["do_search_neighbours"].GetBool()) mDoSearchNeighbourElements = true; else mDoSearchNeighbourElements = false; p_creator_destructor->SetDoSearchNeighbourElements(mDoSearchNeighbourElements); mMaxTimeStep = max_delta_time; mNStepSearch = n_step_search; mSafetyFactor = safety_factor; mpDem_model_part = &(*(settings.r_model_part)); if (mpDem_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.r_model_part in ExplicitSolverStrategy constructor", "") mpContact_model_part = &(*(settings.contact_model_part)); if (mpContact_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.contact_model_part in ExplicitSolverStrategy constructor", "") mpFem_model_part = &(*(settings.fem_model_part)); if (mpFem_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.fem_model_part in ExplicitSolverStrategy constructor", "") mpCluster_model_part = &(*(settings.cluster_model_part)); if (mpCluster_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.cluster_model_part in ExplicitSolverStrategy constructor", "") mpInlet_model_part = &(*(settings.inlet_model_part)); if (mpInlet_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.inlet_model_part in ExplicitSolverStrategy constructor", "") if(mParameters["RemoveBallsInitiallyTouchingWalls"].GetBool()) mRemoveBallsInitiallyTouchingWallsOption = true; else mRemoveBallsInitiallyTouchingWallsOption = false; } /// Destructor. virtual ~ExplicitSolverStrategy() { //Timer::SetOuputFile("TimesPartialRelease"); //Timer::PrintTimingInformation(); } struct LessX { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[0] < q->GetGeometry()[0].Coordinates()[0];} }; struct LessY { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[1] < q->GetGeometry()[0].Coordinates()[1];} }; struct LessZ { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[2] < q->GetGeometry()[0].Coordinates()[2];} }; struct SpatialSortingTraits { typedef SphericParticle* Point_2; typedef LessX Less_x_2; typedef LessY Less_y_2; typedef LessZ Less_z_2; Less_x_2 less_x_2_object() const {return Less_x_2();} Less_y_2 less_y_2_object() const {return Less_y_2();} Less_z_2 less_z_2_object() const { return Less_z_2();} }; #ifdef USING_CGAL void ReorderParticles() { SpatialSortingTraits sst; CGAL::spatial_sort(mListOfSphericParticles.begin(), mListOfSphericParticles.end(), sst); } #endif template <class T> void RebuildListOfSphericParticles(ElementsArrayType& pElements, std::vector<T*>& rCustomListOfParticles){ KRATOS_TRY rCustomListOfParticles.resize(pElements.size()); #pragma omp parallel for for (int k = 0; k < (int)pElements.size(); k++){ ElementsArrayType::iterator particle_pointer_it = pElements.ptr_begin() + k; T* spheric_particle = dynamic_cast<T*>(&(*particle_pointer_it)); rCustomListOfParticles[k] = spheric_particle; } return; KRATOS_CATCH("") } void RebuildListOfDiscontinuumSphericParticles() { RebuildListOfSphericParticles<SphericParticle>(GetModelPart().GetCommunicator().LocalMesh().Elements(), mListOfSphericParticles); } void RebuildPropertiesProxyPointers(std::vector<SphericParticle*>& rCustomListOfSphericParticles); void SendProcessInfoToClustersModelPart(); void UpdateMaxIdOfCreatorDestructor(); void RepairPointersToNormalProperties(std::vector<SphericParticle*>& rCustomListOfSphericParticles); virtual void Initialize(); virtual void AttachSpheresToStickyWalls(); virtual void DisplayThreadInfo(); virtual void CalculateMaxTimeStep(); double CalculateMaxInletTimeStep(); virtual void InitializeClusters(); virtual void GetClustersForce(); virtual void GetRigidBodyElementsForce(); virtual double SolveSolutionStep(); void SearchDEMOperations(ModelPart& r_model_part, bool has_mpi = true); void SearchFEMOperations(ModelPart& r_model_part, bool has_mpi = true) ; virtual void ForceOperations(ModelPart& r_model_part); void InitialTimeStepCalculation(); //TODO: remove this one void GetForce(); void FastGetForce(); virtual void PerformTimeIntegrationOfMotion(int StepFlag = 0); void InitializeSolutionStep(); virtual void BoundingBoxUtility(bool is_time_to_mark_and_remove = true); virtual void FinalizeSolutionStep(); void InitializeElements(); void InitializeDEMElements(); void InitializeFEMElements(); //void InitializeRigidBodyElements(); void InitializeFEMWallsAsRigidBodyElements(ModelPart::SubModelPartsContainerType::iterator& sub_model_part); void MarkToDeleteAllSpheresInitiallyIndentedWithFEM(ModelPart& rSpheresModelPart); void ComputeNodalArea(); void ComputeNormalPressureVectorField(); virtual void CalculateConditionsRHSAndAdd(); void ClearFEMForces(); void CalculateNodalPressuresAndStressesOnWalls(); void SetFlagAndVariableToNodes(const Kratos::Flags& r_flag_name, ComponentOf3ComponentsVariableType& r_variable_to_set, const double value, NodesArrayType& r_nodes_array); void SetVariableToNodes(ComponentOf3ComponentsVariableType& r_variable_to_set, const double value, NodesArrayType& r_nodes_array); void ResetPrescribedMotionFlagsRespectingImposedDofs(); void ApplyPrescribedBoundaryConditions(); void ApplyInitialConditions(); void SetSearchRadiiOnAllParticles(ModelPart& r_model_part, const double added_search_distance = 0.0, const double amplification = 1.0); void SetNormalRadiiOnAllParticles(ModelPart& r_model_part); void SetSearchRadiiWithFemOnAllParticles(ModelPart& r_model_part, const double added_search_distance = 0.0, const double amplification = 1.0); virtual void SearchNeighbours(); virtual void ComputeNewNeighboursHistoricalData(); virtual void CreateContactElements(); void InitializeContactElements(); // void ContactInitializeSolutionStep(); void PrepareContactElementsForPrinting(); virtual void ComputeNewRigidFaceNeighboursHistoricalData(); virtual void SearchRigidFaceNeighbours(); void CheckHierarchyWithCurrentNeighbours(); /* This should work only with one iteration, but it with mpi does not */ void CalculateInitialMaxIndentations(ProcessInfo& r_process_info); void PrepareContactModelPart(ModelPart& r_model_part, ModelPart& mcontacts_model_part); void PrepareElementsForPrinting(); void SynchronizeHistoricalVariables(ModelPart& r_model_part); void SynchronizeRHS(ModelPart& r_model_part); void CleanEnergies(); ModelPart& GetModelPart() { return (*mpDem_model_part);} ModelPart& GetFemModelPart() { return (*mpFem_model_part);} ModelPart& GetContactModelPart() { return (*mpContact_model_part);} ModelPart& GetClusterModelPart() { return (*mpCluster_model_part);} ModelPart& GetInletModelPart() { return (*mpInlet_model_part);} ModelPart& GetRigidBodyModelPart() { return (*mpRigidBody_model_part);} VectorResultElementsContainerType& GetResults() { return (mResults);} VectorDistanceType& GetResultsDistances() { return (mResultsDistances);} RadiusArrayType& GetArrayOfAmplifiedRadii() { return (mArrayOfAmplifiedRadii);} int& GetNStepSearch() { return (mNStepSearch);} int& GetSearchControl() { return mSearchControl;} int& GetNumberOfThreads() { return (mNumberOfThreads);} double& GetMaxTimeStep() { return (mMaxTimeStep);} double& GetSafetyFactor() { return (mSafetyFactor);} int& GetDeltaOption() { return (mDeltaOption);} std::vector<unsigned int>& GetElementPartition() { return (mElementPartition);} ParticleCreatorDestructor::Pointer& GetParticleCreatorDestructor() { return (mpParticleCreatorDestructor);} SpatialSearch::Pointer& GetSpSearch() { return (mpSpSearch);} VectorResultConditionsContainerType& GetRigidFaceResults() { return (mRigidFaceResults);} VectorDistanceType& GetRigidFaceResultsDistances() { return (mRigidFaceResultsDistances);} std::vector<unsigned int>& GetConditionPartition() { return (mConditionPartition);} DEM_FEM_Search::Pointer& GetDemFemSearch() { return (mpDemFemSearch);} virtual ElementsArrayType& GetElements(ModelPart& r_model_part) { return r_model_part.GetCommunicator().LocalMesh().Elements();} virtual ElementsArrayType& GetAllElements(ModelPart& r_model_part) { return r_model_part.Elements(); } protected: Parameters mParameters; bool mRemoveBallsInitiallyTouchingWallsOption; VectorResultElementsContainerType mResults; VectorDistanceType mResultsDistances; RadiusArrayType mArrayOfAmplifiedRadii; int mNStepSearch; int mSearchControl; int mNumberOfThreads; double mMaxTimeStep; double mSafetyFactor; int mDeltaOption; std::vector<unsigned int> mElementPartition; ParticleCreatorDestructor::Pointer mpParticleCreatorDestructor; DEM_FEM_Search::Pointer mpDemFemSearch; SpatialSearch::Pointer mpSpSearch; bool mDoSearchNeighbourElements; VectorResultConditionsContainerType mRigidFaceResults; VectorDistanceType mRigidFaceResultsDistances; std::vector<unsigned int> mConditionPartition; ModelPart *mpFem_model_part; ModelPart *mpDem_model_part; ModelPart *mpInlet_model_part; ModelPart *mpContact_model_part; ModelPart *mpCluster_model_part; ModelPart *mpRigidBody_model_part; std::vector<SphericParticle*> mListOfSphericParticles; std::vector<SphericParticle*> mListOfGhostSphericParticles; }; // Class ExplicitSolverStrategy } // namespace Kratos. #endif // KRATOS_EXPLICIT_SOLVER_STRATEGY defined
DRB001-antidep1-orig-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. */ /* A loop with loop-carried anti-dependence. Data race pair: a[i+1]@64:10 vs. a[i]@64:5 */ #include <stdio.h> int main(int argc, char* argv[]) { int i; int len = 1000; int a[1000]; for (i=0; i<len; i++) a[i]= i; #pragma omp parallel for for (i=0;i< len -1 ;i++) a[i]=a[i+1]+1; printf ("a[500]=%d\n", a[500] ); return 0; }
core_zlascl.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" /******************************************************************************/ __attribute__((weak)) void plasma_core_zlascl(plasma_enum_t uplo, double cfrom, double cto, int m, int n, plasma_complex64_t *A, int lda) { // LAPACKE_zlascl is not available in LAPACKE < 3.6.0 int kl; int ku; int info; char type = lapack_const(uplo); LAPACK_zlascl(&type, &kl, &ku, &cfrom, &cto, &m, &n, A, &lda, &info); } /******************************************************************************/ void plasma_core_omp_zlascl(plasma_enum_t uplo, double cfrom, double cto, int m, int n, plasma_complex64_t *A, int lda, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A[0:lda*n]) { if (sequence->status == PlasmaSuccess) plasma_core_zlascl(uplo, cfrom, cto, m, n, A, lda); } }
tree-parloops.c
/* Loop autoparallelization. Copyright (C) 2006-2015 Free Software Foundation, Inc. Contributed by Sebastian Pop <pop@cri.ensmp.fr> Zdenek Dvorak <dvorakz@suse.cz> and Razya Ladelsky <razya@il.ibm.com>. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "options.h" #include "wide-int.h" #include "inchash.h" #include "tree.h" #include "fold-const.h" #include "predict.h" #include "tm.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "dominance.h" #include "cfg.h" #include "basic-block.h" #include "tree-ssa-alias.h" #include "internal-fn.h" #include "gimple-expr.h" #include "is-a.h" #include "gimple.h" #include "gimplify.h" #include "gimple-iterator.h" #include "gimplify-me.h" #include "gimple-walk.h" #include "stor-layout.h" #include "tree-nested.h" #include "gimple-ssa.h" #include "tree-cfg.h" #include "tree-phinodes.h" #include "ssa-iterators.h" #include "stringpool.h" #include "tree-ssanames.h" #include "tree-ssa-loop-ivopts.h" #include "tree-ssa-loop-manip.h" #include "tree-ssa-loop-niter.h" #include "tree-ssa-loop.h" #include "tree-into-ssa.h" #include "cfgloop.h" #include "tree-data-ref.h" #include "tree-scalar-evolution.h" #include "gimple-pretty-print.h" #include "tree-pass.h" #include "langhooks.h" #include "tree-vectorizer.h" #include "tree-hasher.h" #include "tree-parloops.h" #include "omp-low.h" #include "tree-nested.h" #include "plugin-api.h" #include "ipa-ref.h" #include "cgraph.h" /* This pass tries to distribute iterations of loops into several threads. The implementation is straightforward -- for each loop we test whether its iterations are independent, and if it is the case (and some additional conditions regarding profitability and correctness are satisfied), we add GIMPLE_OMP_PARALLEL and GIMPLE_OMP_FOR codes and let omp expansion machinery do its job. The most of the complexity is in bringing the code into shape expected by the omp expanders: -- for GIMPLE_OMP_FOR, ensuring that the loop has only one induction variable and that the exit test is at the start of the loop body -- for GIMPLE_OMP_PARALLEL, replacing the references to local addressable variables by accesses through pointers, and breaking up ssa chains by storing the values incoming to the parallelized loop to a structure passed to the new function as an argument (something similar is done in omp gimplification, unfortunately only a small part of the code can be shared). TODO: -- if there are several parallelizable loops in a function, it may be possible to generate the threads just once (using synchronization to ensure that cross-loop dependences are obeyed). -- handling of common reduction patterns for outer loops. More info can also be found at http://gcc.gnu.org/wiki/AutoParInGCC */ /* Reduction handling: currently we use vect_force_simple_reduction() to detect reduction patterns. The code transformation will be introduced by an example. parloop { int sum=1; for (i = 0; i < N; i++) { x[i] = i + 3; sum+=x[i]; } } gimple-like code: header_bb: # sum_29 = PHI <sum_11(5), 1(3)> # i_28 = PHI <i_12(5), 0(3)> D.1795_8 = i_28 + 3; x[i_28] = D.1795_8; sum_11 = D.1795_8 + sum_29; i_12 = i_28 + 1; if (N_6(D) > i_12) goto header_bb; exit_bb: # sum_21 = PHI <sum_11(4)> printf (&"%d"[0], sum_21); after reduction transformation (only relevant parts): parloop { .... # Storing the initial value given by the user. # .paral_data_store.32.sum.27 = 1; #pragma omp parallel num_threads(4) #pragma omp for schedule(static) # The neutral element corresponding to the particular reduction's operation, e.g. 0 for PLUS_EXPR, 1 for MULT_EXPR, etc. replaces the user's initial value. # # sum.27_29 = PHI <sum.27_11, 0> sum.27_11 = D.1827_8 + sum.27_29; GIMPLE_OMP_CONTINUE # Adding this reduction phi is done at create_phi_for_local_result() # # sum.27_56 = PHI <sum.27_11, 0> GIMPLE_OMP_RETURN # Creating the atomic operation is done at create_call_for_reduction_1() # #pragma omp atomic_load D.1839_59 = *&.paral_data_load.33_51->reduction.23; D.1840_60 = sum.27_56 + D.1839_59; #pragma omp atomic_store (D.1840_60); GIMPLE_OMP_RETURN # collecting the result after the join of the threads is done at create_loads_for_reductions(). The value computed by the threads is loaded from the shared struct. # .paral_data_load.33_52 = &.paral_data_store.32; sum_37 = .paral_data_load.33_52->sum.27; sum_43 = D.1795_41 + sum_37; exit bb: # sum_21 = PHI <sum_43, sum_26> printf (&"%d"[0], sum_21); ... } */ /* Minimal number of iterations of a loop that should be executed in each thread. */ #define MIN_PER_THREAD 100 /* Element of the hashtable, representing a reduction in the current loop. */ struct reduction_info { gimple reduc_stmt; /* reduction statement. */ gimple reduc_phi; /* The phi node defining the reduction. */ enum tree_code reduction_code;/* code for the reduction operation. */ unsigned reduc_version; /* SSA_NAME_VERSION of original reduc_phi result. */ gphi *keep_res; /* The PHI_RESULT of this phi is the resulting value of the reduction variable when existing the loop. */ tree initial_value; /* The initial value of the reduction var before entering the loop. */ tree field; /* the name of the field in the parloop data structure intended for reduction. */ tree init; /* reduction initialization value. */ gphi *new_phi; /* (helper field) Newly created phi node whose result will be passed to the atomic operation. Represents the local result each thread computed for the reduction operation. */ }; /* Reduction info hashtable helpers. */ struct reduction_hasher : typed_free_remove <reduction_info> { typedef reduction_info value_type; typedef reduction_info compare_type; static inline hashval_t hash (const value_type *); static inline bool equal (const value_type *, const compare_type *); }; /* Equality and hash functions for hashtab code. */ inline bool reduction_hasher::equal (const value_type *a, const compare_type *b) { return (a->reduc_phi == b->reduc_phi); } inline hashval_t reduction_hasher::hash (const value_type *a) { return a->reduc_version; } typedef hash_table<reduction_hasher> reduction_info_table_type; static struct reduction_info * reduction_phi (reduction_info_table_type *reduction_list, gimple phi) { struct reduction_info tmpred, *red; if (reduction_list->elements () == 0 || phi == NULL) return NULL; tmpred.reduc_phi = phi; tmpred.reduc_version = gimple_uid (phi); red = reduction_list->find (&tmpred); return red; } /* Element of hashtable of names to copy. */ struct name_to_copy_elt { unsigned version; /* The version of the name to copy. */ tree new_name; /* The new name used in the copy. */ tree field; /* The field of the structure used to pass the value. */ }; /* Name copies hashtable helpers. */ struct name_to_copy_hasher : typed_free_remove <name_to_copy_elt> { typedef name_to_copy_elt value_type; typedef name_to_copy_elt compare_type; static inline hashval_t hash (const value_type *); static inline bool equal (const value_type *, const compare_type *); }; /* Equality and hash functions for hashtab code. */ inline bool name_to_copy_hasher::equal (const value_type *a, const compare_type *b) { return a->version == b->version; } inline hashval_t name_to_copy_hasher::hash (const value_type *a) { return (hashval_t) a->version; } typedef hash_table<name_to_copy_hasher> name_to_copy_table_type; /* A transformation matrix, which is a self-contained ROWSIZE x COLSIZE matrix. Rather than use floats, we simply keep a single DENOMINATOR that represents the denominator for every element in the matrix. */ typedef struct lambda_trans_matrix_s { lambda_matrix matrix; int rowsize; int colsize; int denominator; } *lambda_trans_matrix; #define LTM_MATRIX(T) ((T)->matrix) #define LTM_ROWSIZE(T) ((T)->rowsize) #define LTM_COLSIZE(T) ((T)->colsize) #define LTM_DENOMINATOR(T) ((T)->denominator) /* Allocate a new transformation matrix. */ static lambda_trans_matrix lambda_trans_matrix_new (int colsize, int rowsize, struct obstack * lambda_obstack) { lambda_trans_matrix ret; ret = (lambda_trans_matrix) obstack_alloc (lambda_obstack, sizeof (struct lambda_trans_matrix_s)); LTM_MATRIX (ret) = lambda_matrix_new (rowsize, colsize, lambda_obstack); LTM_ROWSIZE (ret) = rowsize; LTM_COLSIZE (ret) = colsize; LTM_DENOMINATOR (ret) = 1; return ret; } /* Multiply a vector VEC by a matrix MAT. MAT is an M*N matrix, and VEC is a vector with length N. The result is stored in DEST which must be a vector of length M. */ static void lambda_matrix_vector_mult (lambda_matrix matrix, int m, int n, lambda_vector vec, lambda_vector dest) { int i, j; lambda_vector_clear (dest, m); for (i = 0; i < m; i++) for (j = 0; j < n; j++) dest[i] += matrix[i][j] * vec[j]; } /* Return true if TRANS is a legal transformation matrix that respects the dependence vectors in DISTS and DIRS. The conservative answer is false. "Wolfe proves that a unimodular transformation represented by the matrix T is legal when applied to a loop nest with a set of lexicographically non-negative distance vectors RDG if and only if for each vector d in RDG, (T.d >= 0) is lexicographically positive. i.e.: if and only if it transforms the lexicographically positive distance vectors to lexicographically positive vectors. Note that a unimodular matrix must transform the zero vector (and only it) to the zero vector." S.Muchnick. */ static bool lambda_transform_legal_p (lambda_trans_matrix trans, int nb_loops, vec<ddr_p> dependence_relations) { unsigned int i, j; lambda_vector distres; struct data_dependence_relation *ddr; gcc_assert (LTM_COLSIZE (trans) == nb_loops && LTM_ROWSIZE (trans) == nb_loops); /* When there are no dependences, the transformation is correct. */ if (dependence_relations.length () == 0) return true; ddr = dependence_relations[0]; if (ddr == NULL) return true; /* When there is an unknown relation in the dependence_relations, we know that it is no worth looking at this loop nest: give up. */ if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know) return false; distres = lambda_vector_new (nb_loops); /* For each distance vector in the dependence graph. */ FOR_EACH_VEC_ELT (dependence_relations, i, ddr) { /* Don't care about relations for which we know that there is no dependence, nor about read-read (aka. output-dependences): these data accesses can happen in any order. */ if (DDR_ARE_DEPENDENT (ddr) == chrec_known || (DR_IS_READ (DDR_A (ddr)) && DR_IS_READ (DDR_B (ddr)))) continue; /* Conservatively answer: "this transformation is not valid". */ if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know) return false; /* If the dependence could not be captured by a distance vector, conservatively answer that the transform is not valid. */ if (DDR_NUM_DIST_VECTS (ddr) == 0) return false; /* Compute trans.dist_vect */ for (j = 0; j < DDR_NUM_DIST_VECTS (ddr); j++) { lambda_matrix_vector_mult (LTM_MATRIX (trans), nb_loops, nb_loops, DDR_DIST_VECT (ddr, j), distres); if (!lambda_vector_lexico_pos (distres, nb_loops)) return false; } } return true; } /* Data dependency analysis. Returns true if the iterations of LOOP are independent on each other (that is, if we can execute them in parallel). */ static bool loop_parallel_p (struct loop *loop, struct obstack * parloop_obstack) { vec<ddr_p> dependence_relations; vec<data_reference_p> datarefs; lambda_trans_matrix trans; bool ret = false; if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Considering loop %d\n", loop->num); if (!loop->inner) fprintf (dump_file, "loop is innermost\n"); else fprintf (dump_file, "loop NOT innermost\n"); } /* Check for problems with dependences. If the loop can be reversed, the iterations are independent. */ auto_vec<loop_p, 3> loop_nest; datarefs.create (10); dependence_relations.create (100); if (! compute_data_dependences_for_loop (loop, true, &loop_nest, &datarefs, &dependence_relations)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " FAILED: cannot analyze data dependencies\n"); ret = false; goto end; } if (dump_file && (dump_flags & TDF_DETAILS)) dump_data_dependence_relations (dump_file, dependence_relations); trans = lambda_trans_matrix_new (1, 1, parloop_obstack); LTM_MATRIX (trans)[0][0] = -1; if (lambda_transform_legal_p (trans, 1, dependence_relations)) { ret = true; if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " SUCCESS: may be parallelized\n"); } else if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " FAILED: data dependencies exist across iterations\n"); end: free_dependence_relations (dependence_relations); free_data_refs (datarefs); return ret; } /* Return true when LOOP contains basic blocks marked with the BB_IRREDUCIBLE_LOOP flag. */ static inline bool loop_has_blocks_with_irreducible_flag (struct loop *loop) { unsigned i; basic_block *bbs = get_loop_body_in_dom_order (loop); bool res = true; for (i = 0; i < loop->num_nodes; i++) if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP) goto end; res = false; end: free (bbs); return res; } /* Assigns the address of OBJ in TYPE to an ssa name, and returns this name. The assignment statement is placed on edge ENTRY. DECL_ADDRESS maps decls to their addresses that can be reused. The address of OBJ is known to be invariant in the whole function. Other needed statements are placed right before GSI. */ static tree take_address_of (tree obj, tree type, edge entry, int_tree_htab_type *decl_address, gimple_stmt_iterator *gsi) { int uid; tree *var_p, name, addr; gassign *stmt; gimple_seq stmts; /* Since the address of OBJ is invariant, the trees may be shared. Avoid rewriting unrelated parts of the code. */ obj = unshare_expr (obj); for (var_p = &obj; handled_component_p (*var_p); var_p = &TREE_OPERAND (*var_p, 0)) continue; /* Canonicalize the access to base on a MEM_REF. */ if (DECL_P (*var_p)) *var_p = build_simple_mem_ref (build_fold_addr_expr (*var_p)); /* Assign a canonical SSA name to the address of the base decl used in the address and share it for all accesses and addresses based on it. */ uid = DECL_UID (TREE_OPERAND (TREE_OPERAND (*var_p, 0), 0)); int_tree_map elt; elt.uid = uid; int_tree_map *slot = decl_address->find_slot (elt, INSERT); if (!slot->to) { if (gsi == NULL) return NULL; addr = TREE_OPERAND (*var_p, 0); const char *obj_name = get_name (TREE_OPERAND (TREE_OPERAND (*var_p, 0), 0)); if (obj_name) name = make_temp_ssa_name (TREE_TYPE (addr), NULL, obj_name); else name = make_ssa_name (TREE_TYPE (addr)); stmt = gimple_build_assign (name, addr); gsi_insert_on_edge_immediate (entry, stmt); slot->uid = uid; slot->to = name; } else name = slot->to; /* Express the address in terms of the canonical SSA name. */ TREE_OPERAND (*var_p, 0) = name; if (gsi == NULL) return build_fold_addr_expr_with_type (obj, type); name = force_gimple_operand (build_addr (obj, current_function_decl), &stmts, true, NULL_TREE); if (!gimple_seq_empty_p (stmts)) gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT); if (!useless_type_conversion_p (type, TREE_TYPE (name))) { name = force_gimple_operand (fold_convert (type, name), &stmts, true, NULL_TREE); if (!gimple_seq_empty_p (stmts)) gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT); } return name; } /* Callback for htab_traverse. Create the initialization statement for reduction described in SLOT, and place it at the preheader of the loop described in DATA. */ int initialize_reductions (reduction_info **slot, struct loop *loop) { tree init, c; tree bvar, type, arg; edge e; struct reduction_info *const reduc = *slot; /* Create initialization in preheader: reduction_variable = initialization value of reduction. */ /* In the phi node at the header, replace the argument coming from the preheader with the reduction initialization value. */ /* Create a new variable to initialize the reduction. */ type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi)); bvar = create_tmp_var (type, "reduction"); c = build_omp_clause (gimple_location (reduc->reduc_stmt), OMP_CLAUSE_REDUCTION); OMP_CLAUSE_REDUCTION_CODE (c) = reduc->reduction_code; OMP_CLAUSE_DECL (c) = SSA_NAME_VAR (gimple_assign_lhs (reduc->reduc_stmt)); init = omp_reduction_init (c, TREE_TYPE (bvar)); reduc->init = init; /* Replace the argument representing the initialization value with the initialization value for the reduction (neutral element for the particular operation, e.g. 0 for PLUS_EXPR, 1 for MULT_EXPR, etc). Keep the old value in a new variable "reduction_initial", that will be taken in consideration after the parallel computing is done. */ e = loop_preheader_edge (loop); arg = PHI_ARG_DEF_FROM_EDGE (reduc->reduc_phi, e); /* Create new variable to hold the initial value. */ SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (reduc->reduc_phi, loop_preheader_edge (loop)), init); reduc->initial_value = arg; return 1; } struct elv_data { struct walk_stmt_info info; edge entry; int_tree_htab_type *decl_address; gimple_stmt_iterator *gsi; bool changed; bool reset; }; /* Eliminates references to local variables in *TP out of the single entry single exit region starting at DTA->ENTRY. DECL_ADDRESS contains addresses of the references that had their address taken already. If the expression is changed, CHANGED is set to true. Callback for walk_tree. */ static tree eliminate_local_variables_1 (tree *tp, int *walk_subtrees, void *data) { struct elv_data *const dta = (struct elv_data *) data; tree t = *tp, var, addr, addr_type, type, obj; if (DECL_P (t)) { *walk_subtrees = 0; if (!SSA_VAR_P (t) || DECL_EXTERNAL (t)) return NULL_TREE; type = TREE_TYPE (t); addr_type = build_pointer_type (type); addr = take_address_of (t, addr_type, dta->entry, dta->decl_address, dta->gsi); if (dta->gsi == NULL && addr == NULL_TREE) { dta->reset = true; return NULL_TREE; } *tp = build_simple_mem_ref (addr); dta->changed = true; return NULL_TREE; } if (TREE_CODE (t) == ADDR_EXPR) { /* ADDR_EXPR may appear in two contexts: -- as a gimple operand, when the address taken is a function invariant -- as gimple rhs, when the resulting address in not a function invariant We do not need to do anything special in the latter case (the base of the memory reference whose address is taken may be replaced in the DECL_P case). The former case is more complicated, as we need to ensure that the new address is still a gimple operand. Thus, it is not sufficient to replace just the base of the memory reference -- we need to move the whole computation of the address out of the loop. */ if (!is_gimple_val (t)) return NULL_TREE; *walk_subtrees = 0; obj = TREE_OPERAND (t, 0); var = get_base_address (obj); if (!var || !SSA_VAR_P (var) || DECL_EXTERNAL (var)) return NULL_TREE; addr_type = TREE_TYPE (t); addr = take_address_of (obj, addr_type, dta->entry, dta->decl_address, dta->gsi); if (dta->gsi == NULL && addr == NULL_TREE) { dta->reset = true; return NULL_TREE; } *tp = addr; dta->changed = true; return NULL_TREE; } if (!EXPR_P (t)) *walk_subtrees = 0; return NULL_TREE; } /* Moves the references to local variables in STMT at *GSI out of the single entry single exit region starting at ENTRY. DECL_ADDRESS contains addresses of the references that had their address taken already. */ static void eliminate_local_variables_stmt (edge entry, gimple_stmt_iterator *gsi, int_tree_htab_type *decl_address) { struct elv_data dta; gimple stmt = gsi_stmt (*gsi); memset (&dta.info, '\0', sizeof (dta.info)); dta.entry = entry; dta.decl_address = decl_address; dta.changed = false; dta.reset = false; if (gimple_debug_bind_p (stmt)) { dta.gsi = NULL; walk_tree (gimple_debug_bind_get_value_ptr (stmt), eliminate_local_variables_1, &dta.info, NULL); if (dta.reset) { gimple_debug_bind_reset_value (stmt); dta.changed = true; } } else if (gimple_clobber_p (stmt)) { stmt = gimple_build_nop (); gsi_replace (gsi, stmt, false); dta.changed = true; } else { dta.gsi = gsi; walk_gimple_op (stmt, eliminate_local_variables_1, &dta.info); } if (dta.changed) update_stmt (stmt); } /* Eliminates the references to local variables from the single entry single exit region between the ENTRY and EXIT edges. This includes: 1) Taking address of a local variable -- these are moved out of the region (and temporary variable is created to hold the address if necessary). 2) Dereferencing a local variable -- these are replaced with indirect references. */ static void eliminate_local_variables (edge entry, edge exit) { basic_block bb; auto_vec<basic_block, 3> body; unsigned i; gimple_stmt_iterator gsi; bool has_debug_stmt = false; int_tree_htab_type decl_address (10); basic_block entry_bb = entry->src; basic_block exit_bb = exit->dest; gather_blocks_in_sese_region (entry_bb, exit_bb, &body); FOR_EACH_VEC_ELT (body, i, bb) if (bb != entry_bb && bb != exit_bb) for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi)) if (is_gimple_debug (gsi_stmt (gsi))) { if (gimple_debug_bind_p (gsi_stmt (gsi))) has_debug_stmt = true; } else eliminate_local_variables_stmt (entry, &gsi, &decl_address); if (has_debug_stmt) FOR_EACH_VEC_ELT (body, i, bb) if (bb != entry_bb && bb != exit_bb) for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi)) if (gimple_debug_bind_p (gsi_stmt (gsi))) eliminate_local_variables_stmt (entry, &gsi, &decl_address); } /* Returns true if expression EXPR is not defined between ENTRY and EXIT, i.e. if all its operands are defined outside of the region. */ static bool expr_invariant_in_region_p (edge entry, edge exit, tree expr) { basic_block entry_bb = entry->src; basic_block exit_bb = exit->dest; basic_block def_bb; if (is_gimple_min_invariant (expr)) return true; if (TREE_CODE (expr) == SSA_NAME) { def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr)); if (def_bb && dominated_by_p (CDI_DOMINATORS, def_bb, entry_bb) && !dominated_by_p (CDI_DOMINATORS, def_bb, exit_bb)) return false; return true; } return false; } /* If COPY_NAME_P is true, creates and returns a duplicate of NAME. The copies are stored to NAME_COPIES, if NAME was already duplicated, its duplicate stored in NAME_COPIES is returned. Regardless of COPY_NAME_P, the decl used as a base of the ssa name is also duplicated, storing the copies in DECL_COPIES. */ static tree separate_decls_in_region_name (tree name, name_to_copy_table_type *name_copies, int_tree_htab_type *decl_copies, bool copy_name_p) { tree copy, var, var_copy; unsigned idx, uid, nuid; struct int_tree_map ielt; struct name_to_copy_elt elt, *nelt; name_to_copy_elt **slot; int_tree_map *dslot; if (TREE_CODE (name) != SSA_NAME) return name; idx = SSA_NAME_VERSION (name); elt.version = idx; slot = name_copies->find_slot_with_hash (&elt, idx, copy_name_p ? INSERT : NO_INSERT); if (slot && *slot) return (*slot)->new_name; if (copy_name_p) { copy = duplicate_ssa_name (name, NULL); nelt = XNEW (struct name_to_copy_elt); nelt->version = idx; nelt->new_name = copy; nelt->field = NULL_TREE; *slot = nelt; } else { gcc_assert (!slot); copy = name; } var = SSA_NAME_VAR (name); if (!var) return copy; uid = DECL_UID (var); ielt.uid = uid; dslot = decl_copies->find_slot_with_hash (ielt, uid, INSERT); if (!dslot->to) { var_copy = create_tmp_var (TREE_TYPE (var), get_name (var)); DECL_GIMPLE_REG_P (var_copy) = DECL_GIMPLE_REG_P (var); dslot->uid = uid; dslot->to = var_copy; /* Ensure that when we meet this decl next time, we won't duplicate it again. */ nuid = DECL_UID (var_copy); ielt.uid = nuid; dslot = decl_copies->find_slot_with_hash (ielt, nuid, INSERT); gcc_assert (!dslot->to); dslot->uid = nuid; dslot->to = var_copy; } else var_copy = dslot->to; replace_ssa_name_symbol (copy, var_copy); return copy; } /* Finds the ssa names used in STMT that are defined outside the region between ENTRY and EXIT and replaces such ssa names with their duplicates. The duplicates are stored to NAME_COPIES. Base decls of all ssa names used in STMT (including those defined in LOOP) are replaced with the new temporary variables; the replacement decls are stored in DECL_COPIES. */ static void separate_decls_in_region_stmt (edge entry, edge exit, gimple stmt, name_to_copy_table_type *name_copies, int_tree_htab_type *decl_copies) { use_operand_p use; def_operand_p def; ssa_op_iter oi; tree name, copy; bool copy_name_p; FOR_EACH_PHI_OR_STMT_DEF (def, stmt, oi, SSA_OP_DEF) { name = DEF_FROM_PTR (def); gcc_assert (TREE_CODE (name) == SSA_NAME); copy = separate_decls_in_region_name (name, name_copies, decl_copies, false); gcc_assert (copy == name); } FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE) { name = USE_FROM_PTR (use); if (TREE_CODE (name) != SSA_NAME) continue; copy_name_p = expr_invariant_in_region_p (entry, exit, name); copy = separate_decls_in_region_name (name, name_copies, decl_copies, copy_name_p); SET_USE (use, copy); } } /* Finds the ssa names used in STMT that are defined outside the region between ENTRY and EXIT and replaces such ssa names with their duplicates. The duplicates are stored to NAME_COPIES. Base decls of all ssa names used in STMT (including those defined in LOOP) are replaced with the new temporary variables; the replacement decls are stored in DECL_COPIES. */ static bool separate_decls_in_region_debug (gimple stmt, name_to_copy_table_type *name_copies, int_tree_htab_type *decl_copies) { use_operand_p use; ssa_op_iter oi; tree var, name; struct int_tree_map ielt; struct name_to_copy_elt elt; name_to_copy_elt **slot; int_tree_map *dslot; if (gimple_debug_bind_p (stmt)) var = gimple_debug_bind_get_var (stmt); else if (gimple_debug_source_bind_p (stmt)) var = gimple_debug_source_bind_get_var (stmt); else return true; if (TREE_CODE (var) == DEBUG_EXPR_DECL || TREE_CODE (var) == LABEL_DECL) return true; gcc_assert (DECL_P (var) && SSA_VAR_P (var)); ielt.uid = DECL_UID (var); dslot = decl_copies->find_slot_with_hash (ielt, ielt.uid, NO_INSERT); if (!dslot) return true; if (gimple_debug_bind_p (stmt)) gimple_debug_bind_set_var (stmt, dslot->to); else if (gimple_debug_source_bind_p (stmt)) gimple_debug_source_bind_set_var (stmt, dslot->to); FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE) { name = USE_FROM_PTR (use); if (TREE_CODE (name) != SSA_NAME) continue; elt.version = SSA_NAME_VERSION (name); slot = name_copies->find_slot_with_hash (&elt, elt.version, NO_INSERT); if (!slot) { gimple_debug_bind_reset_value (stmt); update_stmt (stmt); break; } SET_USE (use, (*slot)->new_name); } return false; } /* Callback for htab_traverse. Adds a field corresponding to the reduction specified in SLOT. The type is passed in DATA. */ int add_field_for_reduction (reduction_info **slot, tree type) { struct reduction_info *const red = *slot; tree var = gimple_assign_lhs (red->reduc_stmt); tree field = build_decl (gimple_location (red->reduc_stmt), FIELD_DECL, SSA_NAME_IDENTIFIER (var), TREE_TYPE (var)); insert_field_into_struct (type, field); red->field = field; return 1; } /* Callback for htab_traverse. Adds a field corresponding to a ssa name described in SLOT. The type is passed in DATA. */ int add_field_for_name (name_to_copy_elt **slot, tree type) { struct name_to_copy_elt *const elt = *slot; tree name = ssa_name (elt->version); tree field = build_decl (UNKNOWN_LOCATION, FIELD_DECL, SSA_NAME_IDENTIFIER (name), TREE_TYPE (name)); insert_field_into_struct (type, field); elt->field = field; return 1; } /* Callback for htab_traverse. A local result is the intermediate result computed by a single thread, or the initial value in case no iteration was executed. This function creates a phi node reflecting these values. The phi's result will be stored in NEW_PHI field of the reduction's data structure. */ int create_phi_for_local_result (reduction_info **slot, struct loop *loop) { struct reduction_info *const reduc = *slot; edge e; gphi *new_phi; basic_block store_bb; tree local_res; source_location locus; /* STORE_BB is the block where the phi should be stored. It is the destination of the loop exit. (Find the fallthru edge from GIMPLE_OMP_CONTINUE). */ store_bb = FALLTHRU_EDGE (loop->latch)->dest; /* STORE_BB has two predecessors. One coming from the loop (the reduction's result is computed at the loop), and another coming from a block preceding the loop, when no iterations are executed (the initial value should be taken). */ if (EDGE_PRED (store_bb, 0) == FALLTHRU_EDGE (loop->latch)) e = EDGE_PRED (store_bb, 1); else e = EDGE_PRED (store_bb, 0); local_res = copy_ssa_name (gimple_assign_lhs (reduc->reduc_stmt)); locus = gimple_location (reduc->reduc_stmt); new_phi = create_phi_node (local_res, store_bb); add_phi_arg (new_phi, reduc->init, e, locus); add_phi_arg (new_phi, gimple_assign_lhs (reduc->reduc_stmt), FALLTHRU_EDGE (loop->latch), locus); reduc->new_phi = new_phi; return 1; } struct clsn_data { tree store; tree load; basic_block store_bb; basic_block load_bb; }; /* Callback for htab_traverse. Create an atomic instruction for the reduction described in SLOT. DATA annotates the place in memory the atomic operation relates to, and the basic block it needs to be generated in. */ int create_call_for_reduction_1 (reduction_info **slot, struct clsn_data *clsn_data) { struct reduction_info *const reduc = *slot; gimple_stmt_iterator gsi; tree type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi)); tree load_struct; basic_block bb; basic_block new_bb; edge e; tree t, addr, ref, x; tree tmp_load, name; gimple load; load_struct = build_simple_mem_ref (clsn_data->load); t = build3 (COMPONENT_REF, type, load_struct, reduc->field, NULL_TREE); addr = build_addr (t, current_function_decl); /* Create phi node. */ bb = clsn_data->load_bb; gsi = gsi_last_bb (bb); e = split_block (bb, gsi_stmt (gsi)); new_bb = e->dest; tmp_load = create_tmp_var (TREE_TYPE (TREE_TYPE (addr))); tmp_load = make_ssa_name (tmp_load); load = gimple_build_omp_atomic_load (tmp_load, addr); SSA_NAME_DEF_STMT (tmp_load) = load; gsi = gsi_start_bb (new_bb); gsi_insert_after (&gsi, load, GSI_NEW_STMT); e = split_block (new_bb, load); new_bb = e->dest; gsi = gsi_start_bb (new_bb); ref = tmp_load; x = fold_build2 (reduc->reduction_code, TREE_TYPE (PHI_RESULT (reduc->new_phi)), ref, PHI_RESULT (reduc->new_phi)); name = force_gimple_operand_gsi (&gsi, x, true, NULL_TREE, true, GSI_CONTINUE_LINKING); gsi_insert_after (&gsi, gimple_build_omp_atomic_store (name), GSI_NEW_STMT); return 1; } /* Create the atomic operation at the join point of the threads. REDUCTION_LIST describes the reductions in the LOOP. LD_ST_DATA describes the shared data structure where shared data is stored in and loaded from. */ static void create_call_for_reduction (struct loop *loop, reduction_info_table_type *reduction_list, struct clsn_data *ld_st_data) { reduction_list->traverse <struct loop *, create_phi_for_local_result> (loop); /* Find the fallthru edge from GIMPLE_OMP_CONTINUE. */ ld_st_data->load_bb = FALLTHRU_EDGE (loop->latch)->dest; reduction_list ->traverse <struct clsn_data *, create_call_for_reduction_1> (ld_st_data); } /* Callback for htab_traverse. Loads the final reduction value at the join point of all threads, and inserts it in the right place. */ int create_loads_for_reductions (reduction_info **slot, struct clsn_data *clsn_data) { struct reduction_info *const red = *slot; gimple stmt; gimple_stmt_iterator gsi; tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt)); tree load_struct; tree name; tree x; gsi = gsi_after_labels (clsn_data->load_bb); load_struct = build_simple_mem_ref (clsn_data->load); load_struct = build3 (COMPONENT_REF, type, load_struct, red->field, NULL_TREE); x = load_struct; name = PHI_RESULT (red->keep_res); stmt = gimple_build_assign (name, x); gsi_insert_after (&gsi, stmt, GSI_NEW_STMT); for (gsi = gsi_start_phis (gimple_bb (red->keep_res)); !gsi_end_p (gsi); gsi_next (&gsi)) if (gsi_stmt (gsi) == red->keep_res) { remove_phi_node (&gsi, false); return 1; } gcc_unreachable (); } /* Load the reduction result that was stored in LD_ST_DATA. REDUCTION_LIST describes the list of reductions that the loads should be generated for. */ static void create_final_loads_for_reduction (reduction_info_table_type *reduction_list, struct clsn_data *ld_st_data) { gimple_stmt_iterator gsi; tree t; gimple stmt; gsi = gsi_after_labels (ld_st_data->load_bb); t = build_fold_addr_expr (ld_st_data->store); stmt = gimple_build_assign (ld_st_data->load, t); gsi_insert_before (&gsi, stmt, GSI_NEW_STMT); reduction_list ->traverse <struct clsn_data *, create_loads_for_reductions> (ld_st_data); } /* Callback for htab_traverse. Store the neutral value for the particular reduction's operation, e.g. 0 for PLUS_EXPR, 1 for MULT_EXPR, etc. into the reduction field. The reduction is specified in SLOT. The store information is passed in DATA. */ int create_stores_for_reduction (reduction_info **slot, struct clsn_data *clsn_data) { struct reduction_info *const red = *slot; tree t; gimple stmt; gimple_stmt_iterator gsi; tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt)); gsi = gsi_last_bb (clsn_data->store_bb); t = build3 (COMPONENT_REF, type, clsn_data->store, red->field, NULL_TREE); stmt = gimple_build_assign (t, red->initial_value); gsi_insert_after (&gsi, stmt, GSI_NEW_STMT); return 1; } /* Callback for htab_traverse. Creates loads to a field of LOAD in LOAD_BB and store to a field of STORE in STORE_BB for the ssa name and its duplicate specified in SLOT. */ int create_loads_and_stores_for_name (name_to_copy_elt **slot, struct clsn_data *clsn_data) { struct name_to_copy_elt *const elt = *slot; tree t; gimple stmt; gimple_stmt_iterator gsi; tree type = TREE_TYPE (elt->new_name); tree load_struct; gsi = gsi_last_bb (clsn_data->store_bb); t = build3 (COMPONENT_REF, type, clsn_data->store, elt->field, NULL_TREE); stmt = gimple_build_assign (t, ssa_name (elt->version)); gsi_insert_after (&gsi, stmt, GSI_NEW_STMT); gsi = gsi_last_bb (clsn_data->load_bb); load_struct = build_simple_mem_ref (clsn_data->load); t = build3 (COMPONENT_REF, type, load_struct, elt->field, NULL_TREE); stmt = gimple_build_assign (elt->new_name, t); gsi_insert_after (&gsi, stmt, GSI_NEW_STMT); return 1; } /* Moves all the variables used in LOOP and defined outside of it (including the initial values of loop phi nodes, and *PER_THREAD if it is a ssa name) to a structure created for this purpose. The code while (1) { use (a); use (b); } is transformed this way: bb0: old.a = a; old.b = b; bb1: a' = new->a; b' = new->b; while (1) { use (a'); use (b'); } `old' is stored to *ARG_STRUCT and `new' is stored to NEW_ARG_STRUCT. The pointer `new' is intentionally not initialized (the loop will be split to a separate function later, and `new' will be initialized from its arguments). LD_ST_DATA holds information about the shared data structure used to pass information among the threads. It is initialized here, and gen_parallel_loop will pass it to create_call_for_reduction that needs this information. REDUCTION_LIST describes the reductions in LOOP. */ static void separate_decls_in_region (edge entry, edge exit, reduction_info_table_type *reduction_list, tree *arg_struct, tree *new_arg_struct, struct clsn_data *ld_st_data) { basic_block bb1 = split_edge (entry); basic_block bb0 = single_pred (bb1); name_to_copy_table_type name_copies (10); int_tree_htab_type decl_copies (10); unsigned i; tree type, type_name, nvar; gimple_stmt_iterator gsi; struct clsn_data clsn_data; auto_vec<basic_block, 3> body; basic_block bb; basic_block entry_bb = bb1; basic_block exit_bb = exit->dest; bool has_debug_stmt = false; entry = single_succ_edge (entry_bb); gather_blocks_in_sese_region (entry_bb, exit_bb, &body); FOR_EACH_VEC_ELT (body, i, bb) { if (bb != entry_bb && bb != exit_bb) { for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi)) separate_decls_in_region_stmt (entry, exit, gsi_stmt (gsi), &name_copies, &decl_copies); for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi)) { gimple stmt = gsi_stmt (gsi); if (is_gimple_debug (stmt)) has_debug_stmt = true; else separate_decls_in_region_stmt (entry, exit, stmt, &name_copies, &decl_copies); } } } /* Now process debug bind stmts. We must not create decls while processing debug stmts, so we defer their processing so as to make sure we will have debug info for as many variables as possible (all of those that were dealt with in the loop above), and discard those for which we know there's nothing we can do. */ if (has_debug_stmt) FOR_EACH_VEC_ELT (body, i, bb) if (bb != entry_bb && bb != exit_bb) { for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);) { gimple stmt = gsi_stmt (gsi); if (is_gimple_debug (stmt)) { if (separate_decls_in_region_debug (stmt, &name_copies, &decl_copies)) { gsi_remove (&gsi, true); continue; } } gsi_next (&gsi); } } if (name_copies.elements () == 0 && reduction_list->elements () == 0) { /* It may happen that there is nothing to copy (if there are only loop carried and external variables in the loop). */ *arg_struct = NULL; *new_arg_struct = NULL; } else { /* Create the type for the structure to store the ssa names to. */ type = lang_hooks.types.make_type (RECORD_TYPE); type_name = build_decl (UNKNOWN_LOCATION, TYPE_DECL, create_tmp_var_name (".paral_data"), type); TYPE_NAME (type) = type_name; name_copies.traverse <tree, add_field_for_name> (type); if (reduction_list && reduction_list->elements () > 0) { /* Create the fields for reductions. */ reduction_list->traverse <tree, add_field_for_reduction> (type); } layout_type (type); /* Create the loads and stores. */ *arg_struct = create_tmp_var (type, ".paral_data_store"); nvar = create_tmp_var (build_pointer_type (type), ".paral_data_load"); *new_arg_struct = make_ssa_name (nvar); ld_st_data->store = *arg_struct; ld_st_data->load = *new_arg_struct; ld_st_data->store_bb = bb0; ld_st_data->load_bb = bb1; name_copies .traverse <struct clsn_data *, create_loads_and_stores_for_name> (ld_st_data); /* Load the calculation from memory (after the join of the threads). */ if (reduction_list && reduction_list->elements () > 0) { reduction_list ->traverse <struct clsn_data *, create_stores_for_reduction> (ld_st_data); clsn_data.load = make_ssa_name (nvar); clsn_data.load_bb = exit->dest; clsn_data.store = ld_st_data->store; create_final_loads_for_reduction (reduction_list, &clsn_data); } } } /* Returns true if FN was created to run in parallel. */ bool parallelized_function_p (tree fndecl) { cgraph_node *node = cgraph_node::get (fndecl); gcc_assert (node != NULL); return node->parallelized_function; } /* Creates and returns an empty function that will receive the body of a parallelized loop. */ static tree create_loop_fn (location_t loc) { char buf[100]; char *tname; tree decl, type, name, t; struct function *act_cfun = cfun; static unsigned loopfn_num; loc = LOCATION_LOCUS (loc); snprintf (buf, 100, "%s.$loopfn", current_function_name ()); ASM_FORMAT_PRIVATE_NAME (tname, buf, loopfn_num++); clean_symbol_name (tname); name = get_identifier (tname); type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE); decl = build_decl (loc, FUNCTION_DECL, name, type); TREE_STATIC (decl) = 1; TREE_USED (decl) = 1; DECL_ARTIFICIAL (decl) = 1; DECL_IGNORED_P (decl) = 0; TREE_PUBLIC (decl) = 0; DECL_UNINLINABLE (decl) = 1; DECL_EXTERNAL (decl) = 0; DECL_CONTEXT (decl) = NULL_TREE; DECL_INITIAL (decl) = make_node (BLOCK); t = build_decl (loc, RESULT_DECL, NULL_TREE, void_type_node); DECL_ARTIFICIAL (t) = 1; DECL_IGNORED_P (t) = 1; DECL_RESULT (decl) = t; t = build_decl (loc, PARM_DECL, get_identifier (".paral_data_param"), ptr_type_node); DECL_ARTIFICIAL (t) = 1; DECL_ARG_TYPE (t) = ptr_type_node; DECL_CONTEXT (t) = decl; TREE_USED (t) = 1; DECL_ARGUMENTS (decl) = t; allocate_struct_function (decl, false); /* The call to allocate_struct_function clobbers CFUN, so we need to restore it. */ set_cfun (act_cfun); return decl; } /* Moves the exit condition of LOOP to the beginning of its header, and duplicates the part of the last iteration that gets disabled to the exit of the loop. NIT is the number of iterations of the loop (used to initialize the variables in the duplicated part). TODO: the common case is that latch of the loop is empty and immediately follows the loop exit. In this case, it would be better not to copy the body of the loop, but only move the entry of the loop directly before the exit check and increase the number of iterations of the loop by one. This may need some additional preconditioning in case NIT = ~0. REDUCTION_LIST describes the reductions in LOOP. */ static void transform_to_exit_first_loop (struct loop *loop, reduction_info_table_type *reduction_list, tree nit) { basic_block *bbs, *nbbs, ex_bb, orig_header; unsigned n; bool ok; edge exit = single_dom_exit (loop), hpred; tree control, control_name, res, t; gphi *phi, *nphi; gassign *stmt; gcond *cond_stmt, *cond_nit; tree nit_1; split_block_after_labels (loop->header); orig_header = single_succ (loop->header); hpred = single_succ_edge (loop->header); cond_stmt = as_a <gcond *> (last_stmt (exit->src)); control = gimple_cond_lhs (cond_stmt); gcc_assert (gimple_cond_rhs (cond_stmt) == nit); /* Make sure that we have phi nodes on exit for all loop header phis (create_parallel_loop requires that). */ for (gphi_iterator gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi)) { phi = gsi.phi (); res = PHI_RESULT (phi); t = copy_ssa_name (res, phi); SET_PHI_RESULT (phi, t); nphi = create_phi_node (res, orig_header); add_phi_arg (nphi, t, hpred, UNKNOWN_LOCATION); if (res == control) { gimple_cond_set_lhs (cond_stmt, t); update_stmt (cond_stmt); control = t; } } bbs = get_loop_body_in_dom_order (loop); for (n = 0; bbs[n] != exit->src; n++) continue; nbbs = XNEWVEC (basic_block, n); ok = gimple_duplicate_sese_tail (single_succ_edge (loop->header), exit, bbs + 1, n, nbbs); gcc_assert (ok); free (bbs); ex_bb = nbbs[0]; free (nbbs); /* Other than reductions, the only gimple reg that should be copied out of the loop is the control variable. */ exit = single_dom_exit (loop); control_name = NULL_TREE; for (gphi_iterator gsi = gsi_start_phis (ex_bb); !gsi_end_p (gsi); ) { phi = gsi.phi (); res = PHI_RESULT (phi); if (virtual_operand_p (res)) { gsi_next (&gsi); continue; } /* Check if it is a part of reduction. If it is, keep the phi at the reduction's keep_res field. The PHI_RESULT of this phi is the resulting value of the reduction variable when exiting the loop. */ if (reduction_list->elements () > 0) { struct reduction_info *red; tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit); red = reduction_phi (reduction_list, SSA_NAME_DEF_STMT (val)); if (red) { red->keep_res = phi; gsi_next (&gsi); continue; } } gcc_assert (control_name == NULL_TREE && SSA_NAME_VAR (res) == SSA_NAME_VAR (control)); control_name = res; remove_phi_node (&gsi, false); } gcc_assert (control_name != NULL_TREE); /* Initialize the control variable to number of iterations according to the rhs of the exit condition. */ gimple_stmt_iterator gsi = gsi_after_labels (ex_bb); cond_nit = as_a <gcond *> (last_stmt (exit->src)); nit_1 = gimple_cond_rhs (cond_nit); nit_1 = force_gimple_operand_gsi (&gsi, fold_convert (TREE_TYPE (control_name), nit_1), false, NULL_TREE, false, GSI_SAME_STMT); stmt = gimple_build_assign (control_name, nit_1); gsi_insert_before (&gsi, stmt, GSI_NEW_STMT); } /* Create the parallel constructs for LOOP as described in gen_parallel_loop. LOOP_FN and DATA are the arguments of GIMPLE_OMP_PARALLEL. NEW_DATA is the variable that should be initialized from the argument of LOOP_FN. N_THREADS is the requested number of threads. Returns the basic block containing GIMPLE_OMP_PARALLEL tree. */ static basic_block create_parallel_loop (struct loop *loop, tree loop_fn, tree data, tree new_data, unsigned n_threads, location_t loc) { gimple_stmt_iterator gsi; basic_block bb, paral_bb, for_bb, ex_bb; tree t, param; gomp_parallel *omp_par_stmt; gimple omp_return_stmt1, omp_return_stmt2; gimple phi; gcond *cond_stmt; gomp_for *for_stmt; gomp_continue *omp_cont_stmt; tree cvar, cvar_init, initvar, cvar_next, cvar_base, type; edge exit, nexit, guard, end, e; /* Prepare the GIMPLE_OMP_PARALLEL statement. */ bb = loop_preheader_edge (loop)->src; paral_bb = single_pred (bb); gsi = gsi_last_bb (paral_bb); t = build_omp_clause (loc, OMP_CLAUSE_NUM_THREADS); OMP_CLAUSE_NUM_THREADS_EXPR (t) = build_int_cst (integer_type_node, n_threads); omp_par_stmt = gimple_build_omp_parallel (NULL, t, loop_fn, data); gimple_set_location (omp_par_stmt, loc); gsi_insert_after (&gsi, omp_par_stmt, GSI_NEW_STMT); /* Initialize NEW_DATA. */ if (data) { gassign *assign_stmt; gsi = gsi_after_labels (bb); param = make_ssa_name (DECL_ARGUMENTS (loop_fn)); assign_stmt = gimple_build_assign (param, build_fold_addr_expr (data)); gsi_insert_before (&gsi, assign_stmt, GSI_SAME_STMT); assign_stmt = gimple_build_assign (new_data, fold_convert (TREE_TYPE (new_data), param)); gsi_insert_before (&gsi, assign_stmt, GSI_SAME_STMT); } /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_PARALLEL. */ bb = split_loop_exit_edge (single_dom_exit (loop)); gsi = gsi_last_bb (bb); omp_return_stmt1 = gimple_build_omp_return (false); gimple_set_location (omp_return_stmt1, loc); gsi_insert_after (&gsi, omp_return_stmt1, GSI_NEW_STMT); /* Extract data for GIMPLE_OMP_FOR. */ gcc_assert (loop->header == single_dom_exit (loop)->src); cond_stmt = as_a <gcond *> (last_stmt (loop->header)); cvar = gimple_cond_lhs (cond_stmt); cvar_base = SSA_NAME_VAR (cvar); phi = SSA_NAME_DEF_STMT (cvar); cvar_init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop)); initvar = copy_ssa_name (cvar); SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (phi, loop_preheader_edge (loop)), initvar); cvar_next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop)); gsi = gsi_last_nondebug_bb (loop->latch); gcc_assert (gsi_stmt (gsi) == SSA_NAME_DEF_STMT (cvar_next)); gsi_remove (&gsi, true); /* Prepare cfg. */ for_bb = split_edge (loop_preheader_edge (loop)); ex_bb = split_loop_exit_edge (single_dom_exit (loop)); extract_true_false_edges_from_block (loop->header, &nexit, &exit); gcc_assert (exit == single_dom_exit (loop)); guard = make_edge (for_bb, ex_bb, 0); single_succ_edge (loop->latch)->flags = 0; end = make_edge (loop->latch, ex_bb, EDGE_FALLTHRU); for (gphi_iterator gpi = gsi_start_phis (ex_bb); !gsi_end_p (gpi); gsi_next (&gpi)) { source_location locus; tree def; gphi *phi = gpi.phi (); gphi *stmt; stmt = as_a <gphi *> ( SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, exit))); def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_preheader_edge (loop)); locus = gimple_phi_arg_location_from_edge (stmt, loop_preheader_edge (loop)); add_phi_arg (phi, def, guard, locus); def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_latch_edge (loop)); locus = gimple_phi_arg_location_from_edge (stmt, loop_latch_edge (loop)); add_phi_arg (phi, def, end, locus); } e = redirect_edge_and_branch (exit, nexit->dest); PENDING_STMT (e) = NULL; /* Emit GIMPLE_OMP_FOR. */ gimple_cond_set_lhs (cond_stmt, cvar_base); type = TREE_TYPE (cvar); t = build_omp_clause (loc, OMP_CLAUSE_SCHEDULE); OMP_CLAUSE_SCHEDULE_KIND (t) = OMP_CLAUSE_SCHEDULE_STATIC; for_stmt = gimple_build_omp_for (NULL, GF_OMP_FOR_KIND_FOR, t, 1, NULL); gimple_set_location (for_stmt, loc); gimple_omp_for_set_index (for_stmt, 0, initvar); gimple_omp_for_set_initial (for_stmt, 0, cvar_init); gimple_omp_for_set_final (for_stmt, 0, gimple_cond_rhs (cond_stmt)); gimple_omp_for_set_cond (for_stmt, 0, gimple_cond_code (cond_stmt)); gimple_omp_for_set_incr (for_stmt, 0, build2 (PLUS_EXPR, type, cvar_base, build_int_cst (type, 1))); gsi = gsi_last_bb (for_bb); gsi_insert_after (&gsi, for_stmt, GSI_NEW_STMT); SSA_NAME_DEF_STMT (initvar) = for_stmt; /* Emit GIMPLE_OMP_CONTINUE. */ gsi = gsi_last_bb (loop->latch); omp_cont_stmt = gimple_build_omp_continue (cvar_next, cvar); gimple_set_location (omp_cont_stmt, loc); gsi_insert_after (&gsi, omp_cont_stmt, GSI_NEW_STMT); SSA_NAME_DEF_STMT (cvar_next) = omp_cont_stmt; /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_FOR. */ gsi = gsi_last_bb (ex_bb); omp_return_stmt2 = gimple_build_omp_return (true); gimple_set_location (omp_return_stmt2, loc); gsi_insert_after (&gsi, omp_return_stmt2, GSI_NEW_STMT); /* After the above dom info is hosed. Re-compute it. */ free_dominance_info (CDI_DOMINATORS); calculate_dominance_info (CDI_DOMINATORS); return paral_bb; } /* Generates code to execute the iterations of LOOP in N_THREADS threads in parallel. NITER describes number of iterations of LOOP. REDUCTION_LIST describes the reductions existent in the LOOP. */ static void gen_parallel_loop (struct loop *loop, reduction_info_table_type *reduction_list, unsigned n_threads, struct tree_niter_desc *niter) { tree many_iterations_cond, type, nit; tree arg_struct, new_arg_struct; gimple_seq stmts; edge entry, exit; struct clsn_data clsn_data; unsigned prob; location_t loc; gimple cond_stmt; unsigned int m_p_thread=2; /* From --------------------------------------------------------------------- loop { IV = phi (INIT, IV + STEP) BODY1; if (COND) break; BODY2; } --------------------------------------------------------------------- with # of iterations NITER (possibly with MAY_BE_ZERO assumption), we generate the following code: --------------------------------------------------------------------- if (MAY_BE_ZERO || NITER < MIN_PER_THREAD * N_THREADS) goto original; BODY1; store all local loop-invariant variables used in body of the loop to DATA. GIMPLE_OMP_PARALLEL (OMP_CLAUSE_NUM_THREADS (N_THREADS), LOOPFN, DATA); load the variables from DATA. GIMPLE_OMP_FOR (IV = INIT; COND; IV += STEP) (OMP_CLAUSE_SCHEDULE (static)) BODY2; BODY1; GIMPLE_OMP_CONTINUE; GIMPLE_OMP_RETURN -- GIMPLE_OMP_FOR GIMPLE_OMP_RETURN -- GIMPLE_OMP_PARALLEL goto end; original: loop { IV = phi (INIT, IV + STEP) BODY1; if (COND) break; BODY2; } end: */ /* Create two versions of the loop -- in the old one, we know that the number of iterations is large enough, and we will transform it into the loop that will be split to loop_fn, the new one will be used for the remaining iterations. */ /* We should compute a better number-of-iterations value for outer loops. That is, if we have for (i = 0; i < n; ++i) for (j = 0; j < m; ++j) ... we should compute nit = n * m, not nit = n. Also may_be_zero handling would need to be adjusted. */ type = TREE_TYPE (niter->niter); nit = force_gimple_operand (unshare_expr (niter->niter), &stmts, true, NULL_TREE); if (stmts) gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts); if (loop->inner) m_p_thread=2; else m_p_thread=MIN_PER_THREAD; many_iterations_cond = fold_build2 (GE_EXPR, boolean_type_node, nit, build_int_cst (type, m_p_thread * n_threads)); many_iterations_cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, invert_truthvalue (unshare_expr (niter->may_be_zero)), many_iterations_cond); many_iterations_cond = force_gimple_operand (many_iterations_cond, &stmts, false, NULL_TREE); if (stmts) gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts); if (!is_gimple_condexpr (many_iterations_cond)) { many_iterations_cond = force_gimple_operand (many_iterations_cond, &stmts, true, NULL_TREE); if (stmts) gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts); } initialize_original_copy_tables (); /* We assume that the loop usually iterates a lot. */ prob = 4 * REG_BR_PROB_BASE / 5; loop_version (loop, many_iterations_cond, NULL, prob, prob, REG_BR_PROB_BASE - prob, true); update_ssa (TODO_update_ssa); free_original_copy_tables (); /* Base all the induction variables in LOOP on a single control one. */ canonicalize_loop_ivs (loop, &nit, true); /* Ensure that the exit condition is the first statement in the loop. */ transform_to_exit_first_loop (loop, reduction_list, nit); /* Generate initializations for reductions. */ if (reduction_list->elements () > 0) reduction_list->traverse <struct loop *, initialize_reductions> (loop); /* Eliminate the references to local variables from the loop. */ gcc_assert (single_exit (loop)); entry = loop_preheader_edge (loop); exit = single_dom_exit (loop); eliminate_local_variables (entry, exit); /* In the old loop, move all variables non-local to the loop to a structure and back, and create separate decls for the variables used in loop. */ separate_decls_in_region (entry, exit, reduction_list, &arg_struct, &new_arg_struct, &clsn_data); /* Create the parallel constructs. */ loc = UNKNOWN_LOCATION; cond_stmt = last_stmt (loop->header); if (cond_stmt) loc = gimple_location (cond_stmt); create_parallel_loop (loop, create_loop_fn (loc), arg_struct, new_arg_struct, n_threads, loc); if (reduction_list->elements () > 0) create_call_for_reduction (loop, reduction_list, &clsn_data); scev_reset (); /* Cancel the loop (it is simpler to do it here rather than to teach the expander to do it). */ cancel_loop_tree (loop); /* Free loop bound estimations that could contain references to removed statements. */ FOR_EACH_LOOP (loop, 0) free_numbers_of_iterations_estimates_loop (loop); } /* Returns true when LOOP contains vector phi nodes. */ static bool loop_has_vector_phi_nodes (struct loop *loop ATTRIBUTE_UNUSED) { unsigned i; basic_block *bbs = get_loop_body_in_dom_order (loop); gphi_iterator gsi; bool res = true; for (i = 0; i < loop->num_nodes; i++) for (gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi); gsi_next (&gsi)) if (TREE_CODE (TREE_TYPE (PHI_RESULT (gsi.phi ()))) == VECTOR_TYPE) goto end; res = false; end: free (bbs); return res; } /* Create a reduction_info struct, initialize it with REDUC_STMT and PHI, insert it to the REDUCTION_LIST. */ static void build_new_reduction (reduction_info_table_type *reduction_list, gimple reduc_stmt, gphi *phi) { reduction_info **slot; struct reduction_info *new_reduction; gcc_assert (reduc_stmt); if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Detected reduction. reduction stmt is: \n"); print_gimple_stmt (dump_file, reduc_stmt, 0, 0); fprintf (dump_file, "\n"); } new_reduction = XCNEW (struct reduction_info); new_reduction->reduc_stmt = reduc_stmt; new_reduction->reduc_phi = phi; new_reduction->reduc_version = SSA_NAME_VERSION (gimple_phi_result (phi)); new_reduction->reduction_code = gimple_assign_rhs_code (reduc_stmt); slot = reduction_list->find_slot (new_reduction, INSERT); *slot = new_reduction; } /* Callback for htab_traverse. Sets gimple_uid of reduc_phi stmts. */ int set_reduc_phi_uids (reduction_info **slot, void *data ATTRIBUTE_UNUSED) { struct reduction_info *const red = *slot; gimple_set_uid (red->reduc_phi, red->reduc_version); return 1; } /* Detect all reductions in the LOOP, insert them into REDUCTION_LIST. */ static void gather_scalar_reductions (loop_p loop, reduction_info_table_type *reduction_list) { gphi_iterator gsi; loop_vec_info simple_loop_info; simple_loop_info = vect_analyze_loop_form (loop); for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi)) { gphi *phi = gsi.phi (); affine_iv iv; tree res = PHI_RESULT (phi); bool double_reduc; if (virtual_operand_p (res)) continue; if (!simple_iv (loop, loop, res, &iv, true) && simple_loop_info) { gimple reduc_stmt = vect_force_simple_reduction (simple_loop_info, phi, true, &double_reduc); if (reduc_stmt && !double_reduc) build_new_reduction (reduction_list, reduc_stmt, phi); } } destroy_loop_vec_info (simple_loop_info, true); /* As gimple_uid is used by the vectorizer in between vect_analyze_loop_form and destroy_loop_vec_info, we can set gimple_uid of reduc_phi stmts only now. */ reduction_list->traverse <void *, set_reduc_phi_uids> (NULL); } /* Try to initialize NITER for code generation part. */ static bool try_get_loop_niter (loop_p loop, struct tree_niter_desc *niter) { edge exit = single_dom_exit (loop); gcc_assert (exit); /* We need to know # of iterations, and there should be no uses of values defined inside loop outside of it, unless the values are invariants of the loop. */ if (!number_of_iterations_exit (loop, exit, niter, false)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " FAILED: number of iterations not known\n"); return false; } return true; } /* Try to initialize REDUCTION_LIST for code generation part. REDUCTION_LIST describes the reductions. */ static bool try_create_reduction_list (loop_p loop, reduction_info_table_type *reduction_list) { edge exit = single_dom_exit (loop); gphi_iterator gsi; gcc_assert (exit); gather_scalar_reductions (loop, reduction_list); for (gsi = gsi_start_phis (exit->dest); !gsi_end_p (gsi); gsi_next (&gsi)) { gphi *phi = gsi.phi (); struct reduction_info *red; imm_use_iterator imm_iter; use_operand_p use_p; gimple reduc_phi; tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit); if (!virtual_operand_p (val)) { if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "phi is "); print_gimple_stmt (dump_file, phi, 0, 0); fprintf (dump_file, "arg of phi to exit: value "); print_generic_expr (dump_file, val, 0); fprintf (dump_file, " used outside loop\n"); fprintf (dump_file, " checking if it a part of reduction pattern: \n"); } if (reduction_list->elements () == 0) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " FAILED: it is not a part of reduction.\n"); return false; } reduc_phi = NULL; FOR_EACH_IMM_USE_FAST (use_p, imm_iter, val) { if (!gimple_debug_bind_p (USE_STMT (use_p)) && flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p)))) { reduc_phi = USE_STMT (use_p); break; } } red = reduction_phi (reduction_list, reduc_phi); if (red == NULL) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " FAILED: it is not a part of reduction.\n"); return false; } if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "reduction phi is "); print_gimple_stmt (dump_file, red->reduc_phi, 0, 0); fprintf (dump_file, "reduction stmt is "); print_gimple_stmt (dump_file, red->reduc_stmt, 0, 0); } } } /* The iterations of the loop may communicate only through bivs whose iteration space can be distributed efficiently. */ for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi)) { gphi *phi = gsi.phi (); tree def = PHI_RESULT (phi); affine_iv iv; if (!virtual_operand_p (def) && !simple_iv (loop, loop, def, &iv, true)) { struct reduction_info *red; red = reduction_phi (reduction_list, phi); if (red == NULL) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " FAILED: scalar dependency between iterations\n"); return false; } } } return true; } /* Detect parallel loops and generate parallel code using libgomp primitives. Returns true if some loop was parallelized, false otherwise. */ static bool parallelize_loops (void) { unsigned n_threads = flag_tree_parallelize_loops; bool changed = false; struct loop *loop; struct tree_niter_desc niter_desc; struct obstack parloop_obstack; HOST_WIDE_INT estimated; source_location loop_loc; /* Do not parallelize loops in the functions created by parallelization. */ if (parallelized_function_p (cfun->decl)) return false; if (cfun->has_nonlocal_label) return false; gcc_obstack_init (&parloop_obstack); reduction_info_table_type reduction_list (10); init_stmt_vec_info_vec (); FOR_EACH_LOOP (loop, 0) { reduction_list.empty (); if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Trying loop %d as candidate\n",loop->num); if (loop->inner) fprintf (dump_file, "loop %d is not innermost\n",loop->num); else fprintf (dump_file, "loop %d is innermost\n",loop->num); } /* If we use autopar in graphite pass, we use its marked dependency checking results. */ if (flag_loop_parallelize_all && !loop->can_be_parallel) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "loop is not parallel according to graphite\n"); continue; } if (!single_dom_exit (loop)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "loop is !single_dom_exit\n"); continue; } if (/* And of course, the loop must be parallelizable. */ !can_duplicate_loop_p (loop) || loop_has_blocks_with_irreducible_flag (loop) || (loop_preheader_edge (loop)->src->flags & BB_IRREDUCIBLE_LOOP) /* FIXME: the check for vector phi nodes could be removed. */ || loop_has_vector_phi_nodes (loop)) continue; estimated = estimated_stmt_executions_int (loop); if (estimated == -1) estimated = max_stmt_executions_int (loop); /* FIXME: Bypass this check as graphite doesn't update the count and frequency correctly now. */ if (!flag_loop_parallelize_all && ((estimated != -1 && estimated <= (HOST_WIDE_INT) n_threads * MIN_PER_THREAD) /* Do not bother with loops in cold areas. */ || optimize_loop_nest_for_size_p (loop))) continue; if (!try_get_loop_niter (loop, &niter_desc)) continue; if (!try_create_reduction_list (loop, &reduction_list)) continue; if (!flag_loop_parallelize_all && !loop_parallel_p (loop, &parloop_obstack)) continue; changed = true; if (dump_file && (dump_flags & TDF_DETAILS)) { if (loop->inner) fprintf (dump_file, "parallelizing outer loop %d\n",loop->header->index); else fprintf (dump_file, "parallelizing inner loop %d\n",loop->header->index); loop_loc = find_loop_location (loop); if (loop_loc != UNKNOWN_LOCATION) fprintf (dump_file, "\nloop at %s:%d: ", LOCATION_FILE (loop_loc), LOCATION_LINE (loop_loc)); } gen_parallel_loop (loop, &reduction_list, n_threads, &niter_desc); } free_stmt_vec_info_vec (); obstack_free (&parloop_obstack, NULL); /* Parallelization will cause new function calls to be inserted through which local variables will escape. Reset the points-to solution for ESCAPED. */ if (changed) pt_solution_reset (&cfun->gimple_df->escaped); return changed; } /* Parallelization. */ namespace { const pass_data pass_data_parallelize_loops = { GIMPLE_PASS, /* type */ "parloops", /* name */ OPTGROUP_LOOP, /* optinfo_flags */ TV_TREE_PARALLELIZE_LOOPS, /* tv_id */ ( PROP_cfg | PROP_ssa ), /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ 0, /* todo_flags_finish */ }; class pass_parallelize_loops : public gimple_opt_pass { public: pass_parallelize_loops (gcc::context *ctxt) : gimple_opt_pass (pass_data_parallelize_loops, ctxt) {} /* opt_pass methods: */ virtual bool gate (function *) { return flag_tree_parallelize_loops > 1; } virtual unsigned int execute (function *); }; // class pass_parallelize_loops unsigned pass_parallelize_loops::execute (function *fun) { if (number_of_loops (fun) <= 1) return 0; if (parallelize_loops ()) { fun->curr_properties &= ~(PROP_gimple_eomp); return TODO_update_ssa; } return 0; } } // anon namespace gimple_opt_pass * make_pass_parallelize_loops (gcc::context *ctxt) { return new pass_parallelize_loops (ctxt); }
omp_schedule.c
#include <unistd.h> #include <stdlib.h> #include <omp.h> #include <stdio.h> #define THREADS 4 #define CHUNK 3 #define N 20 int main ( ) { unsigned int i; // default chunk is N / numthread #pragma omp parallel for schedule(static, CHUNK) num_threads(THREADS) for (i = 0; i < N; i++) { /* wait for i seconds */ sleep(i); printf("Thread %d has completed iteration %d.\n", omp_get_thread_num( ), i); } /* all threads done */ printf("All done!\n"); return 0; }
GB_binop__lor_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__lor_uint32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__lor_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__lor_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lor_uint32) // A*D function (colscale): GB (_AxD__lor_uint32) // D*A function (rowscale): GB (_DxB__lor_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__lor_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__lor_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lor_uint32) // C=scalar+B GB (_bind1st__lor_uint32) // C=scalar+B' GB (_bind1st_tran__lor_uint32) // C=A+scalar GB (_bind2nd__lor_uint32) // C=A'+scalar GB (_bind2nd_tran__lor_uint32) // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = ((aij != 0) || (bij != 0)) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_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) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = ((x != 0) || (y != 0)) ; // 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_LOR || GxB_NO_UINT32 || GxB_NO_LOR_UINT32) //------------------------------------------------------------------------------ // 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__lor_uint32) ( 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__lor_uint32) ( 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__lor_uint32) ( 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 uint32_t uint32_t bwork = (*((uint32_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__lor_uint32) ( 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 uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__lor_uint32) ( 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 uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__lor_uint32) ( 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__lor_uint32) ( 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__lor_uint32) ( 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__lor_uint32) ( 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__lor_uint32) ( 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__lor_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = Bx [p] ; Cx [p] = ((x != 0) || (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__lor_uint32) ( 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 ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = Ax [p] ; Cx [p] = ((aij != 0) || (y != 0)) ; } 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) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) || (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__lor_uint32) ( 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 \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_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) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) || (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__lor_uint32) ( 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 uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
owl_slicing_basic_impl_omp.h
/* * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2018 Liang Wang <liang.wang@cl.cam.ac.uk> */ #ifdef OWL_ENABLE_TEMPLATE // Level 1 optimisation void FUNCTION (c, slice_1) (struct slice_pair *p) { TYPE *x = (TYPE *) p->x; TYPE *y = (TYPE *) p->y; int d = p->dim - 1; int n = p->n[d]; int posx = p->posx + p->ofsx[d]; int posy = p->posy + p->ofsy[d]; int incx = p->incx[d]; int incy = p->incy[d]; for (int i = 0; i < n; i++) { MAPFUN (*(x + posx), *(y + posy)); posx += incx; posy += incy; } } // Level 2 optimisation void FUNCTION (c, slice_2) (struct slice_pair *p) { TYPE *x = (TYPE *) p->x; TYPE *y = (TYPE *) p->y; int d0 = p->dim - 2; int d1 = p->dim - 1; int n0 = p->n[d0]; int n1 = p->n[d1]; int ofsx0 = p->ofsx[d0]; int ofsy0 = p->ofsy[d0]; int incx0 = p->incx[d0]; int incy0 = p->incy[d0]; int ofsx1 = p->ofsx[d1]; int ofsy1 = p->ofsy[d1]; int incx1 = p->incx[d1]; int incy1 = p->incy[d1]; int posx0 = p->posx + ofsx0; int posy0 = p->posy + ofsy0; #pragma omp parallel for schedule(static) for (int i0 = 0; i0 < n0; i0++) { int posx1 = posx0 + ofsx1 + i0 * incx0; int posy1 = posy0 + ofsy1 + i0 * incy0; for (int i1 = 0; i1 < n1; i1++) { MAPFUN (*(x + posx1), *(y + posy1)); posx1 += incx1; posy1 += incy1; } } } // Level 3 optimisation void FUNCTION (c, slice_3) (struct slice_pair *p) { TYPE *x = (TYPE *) p->x; TYPE *y = (TYPE *) p->y; int d0 = p->dim - 3; int d1 = p->dim - 2; int d2 = p->dim - 1; int n0 = p->n[d0]; int n1 = p->n[d1]; int n2 = p->n[d2]; int ofsx0 = p->ofsx[d0]; int ofsy0 = p->ofsy[d0]; int incx0 = p->incx[d0]; int incy0 = p->incy[d0]; int ofsx1 = p->ofsx[d1]; int ofsy1 = p->ofsy[d1]; int incx1 = p->incx[d1]; int incy1 = p->incy[d1]; int ofsx2 = p->ofsx[d2]; int ofsy2 = p->ofsy[d2]; int incx2 = p->incx[d2]; int incy2 = p->incy[d2]; int posx0 = p->posx + ofsx0; int posy0 = p->posy + ofsy0; #pragma omp parallel for schedule(static) for (int i0 = 0; i0 < n0; i0++) { int posx1 = posx0 + ofsx1 + i0 * incx0; int posy1 = posy0 + ofsy1 + i0 * incy0; for (int i1 = 0; i1 < n1; i1++) { int posx2 = posx1 + ofsx2; int posy2 = posy1 + ofsy2; for (int i2 = 0; i2 < n2; i2++) { MAPFUN (*(x + posx2), *(y + posy2)); posx2 += incx2; posy2 += incy2; } posx1 += incx1; posy1 += incy1; } } } // Level 4 optimisation void FUNCTION (c, slice_4) (struct slice_pair *p) { TYPE *x = (TYPE *) p->x; TYPE *y = (TYPE *) p->y; int d0 = p->dim - 4; int d1 = p->dim - 3; int d2 = p->dim - 2; int d3 = p->dim - 1; int n0 = p->n[d0]; int n1 = p->n[d1]; int n2 = p->n[d2]; int n3 = p->n[d3]; int ofsx0 = p->ofsx[d0]; int ofsy0 = p->ofsy[d0]; int incx0 = p->incx[d0]; int incy0 = p->incy[d0]; int ofsx1 = p->ofsx[d1]; int ofsy1 = p->ofsy[d1]; int incx1 = p->incx[d1]; int incy1 = p->incy[d1]; int ofsx2 = p->ofsx[d2]; int ofsy2 = p->ofsy[d2]; int incx2 = p->incx[d2]; int incy2 = p->incy[d2]; int ofsx3 = p->ofsx[d3]; int ofsy3 = p->ofsy[d3]; int incx3 = p->incx[d3]; int incy3 = p->incy[d3]; int posx0 = p->posx + ofsx0; int posy0 = p->posy + ofsy0; #pragma omp parallel for schedule(static) for (int i0 = 0; i0 < n0; i0++) { int posx1 = posx0 + ofsx1 + i0 * incx0; int posy1 = posy0 + ofsy1 + i0 * incy0; for (int i1 = 0; i1 < n1; i1++) { int posx2 = posx1 + ofsx2; int posy2 = posy1 + ofsy2; for (int i2 = 0; i2 < n2; i2++) { int posx3 = posx2 + ofsx3; int posy3 = posy2 + ofsy3; for (int i3 = 0; i3 < n3; i3++) { MAPFUN (*(x + posx3), *(y + posy3)); posx3 += incx3; posy3 += incy3; } posx2 += incx2; posy2 += incy2; } posx1 += incx1; posy1 += incy1; } } } // slice x based on the basic slice definition and save to y. void FUNCTION (c, slice) (struct slice_pair *p) { if (p->dep == p->dim - 1) FUNCTION (c, slice_1) (p); else if (p->dep == p->dim - 2) FUNCTION (c, slice_2) (p); else if (p->dep == p->dim - 3) FUNCTION (c, slice_3) (p); else if (p->dep == p->dim - 4) FUNCTION (c, slice_4) (p); else { const int d = p->dep; const int n = p->n[d]; const int incx = p->incx[d]; const int incy = p->incy[d]; const int save_posx = p->posx; const int save_posy = p->posy; p->posx += p->ofsx[d]; p->posy += p->ofsy[d]; for (int i = 0; i < n; i++) { p->dep += 1; FUNCTION (c, slice) (p); p->dep -= 1; p->posx += incx; p->posy += incy; } p->posx = save_posx; p->posy = save_posy; } } // stub function CAMLprim value FUNCTION (stub, slice) (value vX, value vY, value vZ) { struct caml_ba_array *X = Caml_ba_array_val(vX); TYPE *X_data = (TYPE *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); TYPE *Y_data = (TYPE *) Y->data; struct caml_ba_array *Z = Caml_ba_array_val(vZ); int64_t *slice = (int64_t *) Z->data; struct slice_pair * sp = calloc(1, sizeof(struct slice_pair)); sp->dim = X->num_dims; sp->dep = 0; sp->n = Y->dim; sp->x = X_data; sp->y = Y_data; sp->posx = 0; sp->posy = 0; sp->ofsx = calloc(sp->dim, sizeof(int)); sp->ofsy = calloc(sp->dim, sizeof(int)); sp->incx = calloc(sp->dim, sizeof(int)); sp->incy = calloc(sp->dim, sizeof(int)); c_slicing_offset(X, slice, sp->ofsx); c_slicing_stride(X, slice, sp->incx); c_ndarray_stride(Y, sp->incy); FUNCTION (c, slice) (sp); free(sp->ofsx); free(sp->ofsy); free(sp->incx); free(sp->incy); free(sp); return Val_unit; } #endif /* OWL_ENABLE_TEMPLATE */
depthwise_convolution_3x3_int8.c
/* * Copyright (C) 2016-2022 T-Head Semiconductor Co., Ltd. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* CSI-NN2 version 1.12.x */ #include "csi_thead_rvv.h" static vint8m1_t requantize_m4(vint32m4_t _src, int32_t multiplier, int32_t shift, int32_t out_zp, int vl) { vint32m4_t _mulh = vmulh_vx_i32m4(_src, multiplier, vl); _mulh = vssra_vx_i32m4(_mulh, -shift - 1, vl); _mulh = vadd_vx_i32m4(_mulh, out_zp, vl); vint16m2_t _tmp1 = vnclip_wx_i16m2(_mulh, 0, vl); vint8m1_t _tmp2 = vnclip_wx_i8m1(_tmp1, 0, vl); return _tmp2; } int csi_nn_rvv_dwconv3x3s1_int8(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { int8_t *input_data = (int8_t *)input->data; int8_t *output_data = (int8_t *)output->data; int8_t *kernel_data = (int8_t *)kernel->data; int32_t *bias_data = (int32_t *)bias->data; int32_t batch = input->dim[0]; int32_t in_c = input->dim[1]; // group = in_channel int32_t in_h = input->dim[2]; int32_t in_w = input->dim[3]; int32_t out_c = output->dim[1]; int32_t out_h = output->dim[2]; int32_t out_w = output->dim[3]; int8_t *input_padd_buf = (int8_t *)csi_mem_alloc((in_h + params->pad_top + params->pad_down) * (in_w + params->pad_left + params->pad_right) * in_c * sizeof(int8_t)); csi_nn_rvv_pad_input_int8(input_data, input_padd_buf, in_c, in_h, in_w, in_h + params->pad_top + params->pad_down, in_w + params->pad_left + params->pad_right, params->pad_top, params->pad_left, input->qinfo->zero_point); in_h = in_h + params->pad_top + params->pad_down; in_w = in_w + params->pad_left + params->pad_right; #pragma omp parallel for num_threads(1) for (int c = 0; c < in_c; c++) { int8_t *outptr0 = output_data; int8_t *outptr1 = outptr0 + out_w; // please use fuse_zp2bias option in hhb, thus bias_data wont be NULL int32_t bias0 = bias_data[c]; int8_t *img0 = input_padd_buf + c * in_h * in_w; int8_t *r0 = img0; int8_t *r1 = r0 + in_w; int8_t *r2 = r1 + in_w; int8_t *r3 = r2 + in_w; const int8_t *kernel0 = kernel_data + c * 9; int8_t k00 = kernel0[0]; int8_t k01 = kernel0[1]; int8_t k02 = kernel0[2]; int8_t k10 = kernel0[3]; int8_t k11 = kernel0[4]; int8_t k12 = kernel0[5]; int8_t k20 = kernel0[6]; int8_t k21 = kernel0[7]; int8_t k22 = kernel0[8]; int vl; int h = 0; // h2 loop for (; h + 1 < out_h; h += 2) { int w = out_w; // h2w8 loop while (w > 0) { vl = vsetvl_e32m4(w); vint32m4_t _acc0 = vmv_v_x_i32m4(bias0, vl); vint32m4_t _acc1 = vmv_v_x_i32m4(bias0, vl); vint8m1_t _r0_0_7 = vle8_v_i8m1(r0, vl); vint8m1_t _r0_1_8 = vle8_v_i8m1(r0 + 1, vl); vint8m1_t _r0_2_9 = vle8_v_i8m1(r0 + 2, vl); vint8m1_t _r1_0_7 = vle8_v_i8m1(r1, vl); vint8m1_t _r1_1_8 = vle8_v_i8m1(r1 + 1, vl); vint8m1_t _r1_2_9 = vle8_v_i8m1(r1 + 2, vl); vint8m1_t _r2_0_7 = vle8_v_i8m1(r2, vl); vint8m1_t _r2_1_8 = vle8_v_i8m1(r2 + 1, vl); vint8m1_t _r2_2_9 = vle8_v_i8m1(r2 + 2, vl); vint8m1_t _r3_0_7 = vle8_v_i8m1(r3, vl); vint8m1_t _r3_1_8 = vle8_v_i8m1(r3 + 1, vl); vint8m1_t _r3_2_9 = vle8_v_i8m1(r3 + 2, vl); vint16m2_t _r0_0_7_w = vwadd_vx_i16m2(_r0_0_7, 0, vl); // widden 8->16 vint16m2_t _r0_1_8_w = vwadd_vx_i16m2(_r0_1_8, 0, vl); vint16m2_t _r0_2_9_w = vwadd_vx_i16m2(_r0_2_9, 0, vl); vint16m2_t _r1_0_7_w = vwadd_vx_i16m2(_r1_0_7, 0, vl); vint16m2_t _r1_1_8_w = vwadd_vx_i16m2(_r1_1_8, 0, vl); vint16m2_t _r1_2_9_w = vwadd_vx_i16m2(_r1_2_9, 0, vl); vint16m2_t _r2_0_7_w = vwadd_vx_i16m2(_r2_0_7, 0, vl); vint16m2_t _r2_1_8_w = vwadd_vx_i16m2(_r2_1_8, 0, vl); vint16m2_t _r2_2_9_w = vwadd_vx_i16m2(_r2_2_9, 0, vl); vint16m2_t _r3_0_7_w = vwadd_vx_i16m2(_r3_0_7, 0, vl); vint16m2_t _r3_1_8_w = vwadd_vx_i16m2(_r3_1_8, 0, vl); vint16m2_t _r3_2_9_w = vwadd_vx_i16m2(_r3_2_9, 0, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k00, _r0_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k01, _r0_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k02, _r0_2_9_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k00, _r1_0_7_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k01, _r1_1_8_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k02, _r1_2_9_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k10, _r1_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k11, _r1_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k12, _r1_2_9_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k10, _r2_0_7_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k11, _r2_1_8_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k12, _r2_2_9_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k20, _r2_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k21, _r2_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k22, _r2_2_9_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k20, _r3_0_7_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k21, _r3_1_8_w, vl); _acc1 = vwmacc_vx_i32m4(_acc1, k22, _r3_2_9_w, vl); // int32_t q1z2 = (k00 + k01 + k02 + k10 + k11 + k12 + // k20 + k21 + k22) * input->qinfo->zero_point; // _acc0 = vsub_vx_i32m2(_acc0, q1z2, vl); // _acc1 = vsub_vx_i32m2(_acc1, q1z2, vl); // vint16m1_t _mul0_0 = vwmul_vx_i16m1(_r0_0_7, k00, vl); // vint16m1_t _mul0_1 = vwmul_vx_i16m1(_r0_1_8, k01, vl); // vint16m1_t _mul0_2 = vwmul_vx_i16m1(_r0_2_9, k02, vl); // vint16m1_t _mul1_0 = vwmul_vx_i16m1(_r1_0_7, k00, vl); // vint16m1_t _mul1_1 = vwmul_vx_i16m1(_r1_1_8, k01, vl); // vint16m1_t _mul1_2 = vwmul_vx_i16m1(_r1_2_9, k02, vl); // vint16m1_t _mul0_3 = vwmul_vx_i16m1(_r1_0_7, k10, vl); // vint16m1_t _mul0_4 = vwmul_vx_i16m1(_r1_1_8, k11, vl); // vint16m1_t _mul0_5 = vwmul_vx_i16m1(_r1_2_9, k12, vl); // vint16m1_t _mul1_3 = vwmul_vx_i16m1(_r2_0_7, k10, vl); // vint16m1_t _mul1_4 = vwmul_vx_i16m1(_r2_1_8, k11, vl); // vint16m1_t _mul1_5 = vwmul_vx_i16m1(_r2_2_9, k12, vl); // vint16m1_t _mul0_6 = vwmul_vx_i16m1(_r2_0_7, k20, vl); // vint16m1_t _mul0_7 = vwmul_vx_i16m1(_r2_1_8, k21, vl); // vint16m1_t _mul0_8 = vwmul_vx_i16m1(_r2_2_9, k22, vl); // vint16m1_t _mul1_6 = vwmul_vx_i16m1(_r3_0_7, k20, vl); // vint16m1_t _mul1_7 = vwmul_vx_i16m1(_r3_1_8, k21, vl); // vint16m1_t _mul1_8 = vwmul_vx_i16m1(_r3_2_9, k22, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_0, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_1, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_2, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_0, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_1, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_2, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_3, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_4, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_5, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_3, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_4, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_5, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_6, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_7, vl); // _acc0 = vwadd_wv_i32m2(_acc0, _mul0_8, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_6, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_7, vl); // _acc1 = vwadd_wv_i32m2(_acc1, _mul1_8, vl); vint8m1_t _res0, _res1; if (kernel->quant_channel > 1) { _res0 = requantize_m4(_acc0, kernel->qinfo[c].multiplier, kernel->qinfo[c].shift, output->qinfo->zero_point, vl); _res1 = requantize_m4(_acc1, kernel->qinfo[c].multiplier, kernel->qinfo[c].shift, output->qinfo->zero_point, vl); } else if (kernel->quant_channel == 1) { _res0 = requantize_m4(_acc0, kernel->qinfo[0].multiplier, kernel->qinfo[0].shift, output->qinfo->zero_point, vl); _res1 = requantize_m4(_acc1, kernel->qinfo[0].multiplier, kernel->qinfo[0].shift, output->qinfo->zero_point, vl); } vse8_v_i8m1(outptr0, _res0, vl); vse8_v_i8m1(outptr1, _res1, vl); r0 += vl; r1 += vl; r2 += vl; r3 += vl; outptr0 += vl; outptr1 += vl; w -= vl; } r0 += 2 + in_w; r1 += 2 + in_w; r2 += 2 + in_w; r3 += 2 + in_w; outptr0 += out_w; outptr1 += out_w; } for (; h < out_h; h++) { int w = out_w; // h2w8 loop while (w > 0) { vl = vsetvl_e32m4(w); vint32m4_t _acc0 = vmv_v_x_i32m4(bias0, vl); vint8m1_t _r0_0_7 = vle8_v_i8m1(r0, vl); vint8m1_t _r0_1_8 = vle8_v_i8m1(r0 + 1, vl); vint8m1_t _r0_2_9 = vle8_v_i8m1(r0 + 2, vl); vint8m1_t _r1_0_7 = vle8_v_i8m1(r1, vl); vint8m1_t _r1_1_8 = vle8_v_i8m1(r1 + 1, vl); vint8m1_t _r1_2_9 = vle8_v_i8m1(r1 + 2, vl); vint8m1_t _r2_0_7 = vle8_v_i8m1(r2, vl); vint8m1_t _r2_1_8 = vle8_v_i8m1(r2 + 1, vl); vint8m1_t _r2_2_9 = vle8_v_i8m1(r2 + 2, vl); vint16m2_t _r0_0_7_w = vwadd_vx_i16m2(_r0_0_7, 0, vl); // widden 8->16 vint16m2_t _r0_1_8_w = vwadd_vx_i16m2(_r0_1_8, 0, vl); vint16m2_t _r0_2_9_w = vwadd_vx_i16m2(_r0_2_9, 0, vl); vint16m2_t _r1_0_7_w = vwadd_vx_i16m2(_r1_0_7, 0, vl); vint16m2_t _r1_1_8_w = vwadd_vx_i16m2(_r1_1_8, 0, vl); vint16m2_t _r1_2_9_w = vwadd_vx_i16m2(_r1_2_9, 0, vl); vint16m2_t _r2_0_7_w = vwadd_vx_i16m2(_r2_0_7, 0, vl); vint16m2_t _r2_1_8_w = vwadd_vx_i16m2(_r2_1_8, 0, vl); vint16m2_t _r2_2_9_w = vwadd_vx_i16m2(_r2_2_9, 0, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k00, _r0_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k01, _r0_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k02, _r0_2_9_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k10, _r1_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k11, _r1_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k12, _r1_2_9_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k20, _r2_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k21, _r2_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k22, _r2_2_9_w, vl); vint8m1_t _res0; if (kernel->quant_channel > 1) { _res0 = requantize_m4(_acc0, kernel->qinfo[c].multiplier, kernel->qinfo[c].shift, output->qinfo->zero_point, vl); } else if (kernel->quant_channel == 1) { _res0 = requantize_m4(_acc0, kernel->qinfo[0].multiplier, kernel->qinfo[0].shift, output->qinfo->zero_point, vl); } vse8_v_i8m1(outptr0, _res0, vl); r0 += vl; r1 += vl; r2 += vl; outptr0 += vl; w -= vl; } } output_data += out_h * out_w; } csi_mem_free(input_padd_buf); return CSINN_TRUE; } int csi_nn_rvv_dwconv3x3s2_int8(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { int8_t *input_data = (int8_t *)input->data; int8_t *output_data = (int8_t *)output->data; int8_t *kernel_data = (int8_t *)kernel->data; int32_t *bias_data = (int32_t *)bias->data; int32_t batch = input->dim[0]; int32_t in_c = input->dim[1]; // group = in_channel int32_t in_h = input->dim[2]; int32_t in_w = input->dim[3]; int32_t out_c = output->dim[1]; int32_t out_h = output->dim[2]; int32_t out_w = output->dim[3]; int8_t *input_padd_buf = (int8_t *)csi_mem_alloc((in_h + params->pad_top + params->pad_down) * (in_w + params->pad_left + params->pad_right) * in_c * sizeof(int8_t)); csi_nn_rvv_pad_input_int8(input_data, input_padd_buf, in_c, in_h, in_w, in_h + params->pad_top + params->pad_down, in_w + params->pad_left + params->pad_right, params->pad_top, params->pad_left, input->qinfo->zero_point); in_h = in_h + params->pad_top + params->pad_down; in_w = in_w + params->pad_left + params->pad_right; int tailstep = in_w - 2 * out_w + in_w; #pragma omp parallel for num_threads(1) for (int c = 0; c < in_c; c++) { int8_t *outptr0 = output_data; int32_t bias0 = bias_data[c]; int8_t *img0 = input_padd_buf + c * in_h * in_w; int8_t *r0 = img0; int8_t *r1 = r0 + in_w; int8_t *r2 = r1 + in_w; const int8_t *kernel0 = kernel_data + c * 9; int8_t k00 = kernel0[0]; int8_t k01 = kernel0[1]; int8_t k02 = kernel0[2]; int8_t k10 = kernel0[3]; int8_t k11 = kernel0[4]; int8_t k12 = kernel0[5]; int8_t k20 = kernel0[6]; int8_t k21 = kernel0[7]; int8_t k22 = kernel0[8]; int vl; for (int h = 0; h < out_h; h++) { int w = out_w; while (w > 0) { vl = vsetvl_e32m4(w); vint32m4_t _acc0 = vmv_v_x_i32m4(bias0, vl); // vint8mf2_t _r0_0_7, _r0_1_8; // vint8mf2_t _r1_0_7, _r1_1_8; // vint8mf2_t _r2_0_7, _r2_1_8; // vlseg2e8_v_i8mf2(&_r0_0_7, &_r0_1_8, r0, vl); // r0 += 2; // vint8mf2_t _r0_2_9 = vlse8_v_i8mf2(r0, 2 * sizeof(int8_t), vl); // r0 += (vl - 1) * 2; // vlseg2e8_v_i8mf2(&_r1_0_7, &_r1_1_8, r1, vl); // r1 += 2; // vint8mf2_t _r1_2_9 = vlse8_v_i8mf2(r1, 2 * sizeof(int8_t), vl); // r1 += (vl - 1) * 2; // vlseg2e8_v_i8mf2(&_r2_0_7, &_r2_1_8, r2, vl); // r2 += 2; // vint8mf2_t _r2_2_9 = vlse8_v_i8mf2(r2, 2 * sizeof(int8_t), vl); // r2 += (vl - 1) * 2; vint8m1_t _r0_0_7 = vlse8_v_i8m1(r0, 2 * sizeof(int8_t), vl); r0 += 1; vint8m1_t _r0_1_8 = vlse8_v_i8m1(r0, 2 * sizeof(int8_t), vl); r0 += 1; vint8m1_t _r0_2_9 = vlse8_v_i8m1(r0, 2 * sizeof(int8_t), vl); r0 += (vl - 1) * 2; vint8m1_t _r1_0_7 = vlse8_v_i8m1(r1, 2 * sizeof(int8_t), vl); r1 += 1; vint8m1_t _r1_1_8 = vlse8_v_i8m1(r1, 2 * sizeof(int8_t), vl); r1 += 1; vint8m1_t _r1_2_9 = vlse8_v_i8m1(r1, 2 * sizeof(int8_t), vl); r1 += (vl - 1) * 2; vint8m1_t _r2_0_7 = vlse8_v_i8m1(r2, 2 * sizeof(int8_t), vl); r2 += 1; vint8m1_t _r2_1_8 = vlse8_v_i8m1(r2, 2 * sizeof(int8_t), vl); r2 += 1; vint8m1_t _r2_2_9 = vlse8_v_i8m1(r2, 2 * sizeof(int8_t), vl); r2 += (vl - 1) * 2; vint16m2_t _r0_0_7_w = vwadd_vx_i16m2(_r0_0_7, 0, vl); // widden 8->16 vint16m2_t _r0_1_8_w = vwadd_vx_i16m2(_r0_1_8, 0, vl); vint16m2_t _r0_2_9_w = vwadd_vx_i16m2(_r0_2_9, 0, vl); vint16m2_t _r1_0_7_w = vwadd_vx_i16m2(_r1_0_7, 0, vl); vint16m2_t _r1_1_8_w = vwadd_vx_i16m2(_r1_1_8, 0, vl); vint16m2_t _r1_2_9_w = vwadd_vx_i16m2(_r1_2_9, 0, vl); vint16m2_t _r2_0_7_w = vwadd_vx_i16m2(_r2_0_7, 0, vl); vint16m2_t _r2_1_8_w = vwadd_vx_i16m2(_r2_1_8, 0, vl); vint16m2_t _r2_2_9_w = vwadd_vx_i16m2(_r2_2_9, 0, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k00, _r0_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k01, _r0_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k02, _r0_2_9_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k10, _r1_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k11, _r1_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k12, _r1_2_9_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k20, _r2_0_7_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k21, _r2_1_8_w, vl); _acc0 = vwmacc_vx_i32m4(_acc0, k22, _r2_2_9_w, vl); vint8m1_t _res0; if (kernel->quant_channel > 1) { _res0 = requantize_m4(_acc0, kernel->qinfo[c].multiplier, kernel->qinfo[c].shift, output->qinfo->zero_point, 16); } else if (kernel->quant_channel == 1) { _res0 = requantize_m4(_acc0, kernel->qinfo[0].multiplier, kernel->qinfo[0].shift, output->qinfo->zero_point, 16); } vse8_v_i8m1(outptr0, _res0, vl); outptr0 += vl; w -= vl; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } output_data += out_h * out_w; } csi_mem_free(input_padd_buf); return CSINN_TRUE; }
nestedpar.c
#include<omp.h> #include <stdio.h> void paroutput(char* s) { #pragma omp parallel printf("%s\n",s); } int main(void) { #pragma omp parallel { paroutput("before single"); #pragma omp single { paroutput("inside single"); } paroutput("after single"); } }
test-math-vector-sincos.h
/* Wrappers definitions for tests of ABI of vector sincos/sincosf having vector declaration "#pragma omp declare simd notinbranch". Copyright (C) 2016-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. 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 <https://www.gnu.org/licenses/>. */ #define INIT_VEC_PTRS_LOOP(vec, val, len) \ do \ { \ union { VEC_INT_TYPE v; __typeof__ ((val)[0]) *a[(len)]; } u; \ for (i = 0; i < len; i++) \ u.a[i] = &(val)[i]; \ (vec) = u.v; \ } \ while (0) /* Wrapper for vector sincos/sincosf compatible with x86_64 and x32 variants of _ZGVbN2vvv_sincos, _ZGVdN4vvv_sincos, _ZGVeN8vvv_sincos; x32 variants of _ZGVbN4vvv_sincosf, _ZGVcN4vvv_sincos, _ZGVdN8vvv_sincosf, _ZGVeN16vvv_sincosf. */ #define VECTOR_WRAPPER_fFF_2(scalar_func, vector_func) \ extern void vector_func (VEC_TYPE, VEC_INT_TYPE, VEC_INT_TYPE); \ void scalar_func (FLOAT x, FLOAT * r, FLOAT * r1) \ { \ int i; \ FLOAT r_loc[VEC_LEN], r1_loc[VEC_LEN]; \ VEC_TYPE mx; \ VEC_INT_TYPE mr, mr1; \ INIT_VEC_LOOP (mx, x, VEC_LEN); \ INIT_VEC_PTRS_LOOP (mr, r_loc, VEC_LEN); \ INIT_VEC_PTRS_LOOP (mr1, r1_loc, VEC_LEN); \ vector_func (mx, mr, mr1); \ TEST_VEC_LOOP (r_loc, VEC_LEN); \ TEST_VEC_LOOP (r1_loc, VEC_LEN); \ *r = r_loc[0]; \ *r1 = r1_loc[0]; \ return; \ } /* Wrapper for vector sincos/sincosf compatible with x86_64 variants of _ZGVcN4vvv_sincos, _ZGVeN16vvv_sincosf, _ZGVbN4vvv_sincosf, _ZGVdN8vvv_sincosf, _ZGVcN8vvv_sincosf. */ #define VECTOR_WRAPPER_fFF_3(scalar_func, vector_func) \ extern void vector_func (VEC_TYPE, VEC_INT_TYPE, VEC_INT_TYPE, \ VEC_INT_TYPE, VEC_INT_TYPE); \ void scalar_func (FLOAT x, FLOAT * r, FLOAT * r1) \ { \ int i; \ FLOAT r_loc[VEC_LEN/2], r1_loc[VEC_LEN/2]; \ VEC_TYPE mx; \ VEC_INT_TYPE mr, mr1; \ INIT_VEC_LOOP (mx, x, VEC_LEN); \ INIT_VEC_PTRS_LOOP (mr, r_loc, VEC_LEN/2); \ INIT_VEC_PTRS_LOOP (mr1, r1_loc, VEC_LEN/2); \ vector_func (mx, mr, mr, mr1, mr1); \ TEST_VEC_LOOP (r_loc, VEC_LEN/2); \ TEST_VEC_LOOP (r1_loc, VEC_LEN/2); \ *r = r_loc[0]; \ *r1 = r1_loc[0]; \ return; \ } /* Wrapper for vector sincosf compatible with x86_64 variant of _ZGVcN8vvv_sincosf. */ #define VECTOR_WRAPPER_fFF_4(scalar_func, vector_func) \ extern void vector_func (VEC_TYPE, VEC_INT_TYPE, VEC_INT_TYPE, \ VEC_INT_TYPE, VEC_INT_TYPE, \ VEC_INT_TYPE, VEC_INT_TYPE, \ VEC_INT_TYPE, VEC_INT_TYPE); \ void scalar_func (FLOAT x, FLOAT * r, FLOAT * r1) \ { \ int i; \ FLOAT r_loc[VEC_LEN/4], r1_loc[VEC_LEN/4]; \ VEC_TYPE mx; \ VEC_INT_TYPE mr, mr1; \ INIT_VEC_LOOP (mx, x, VEC_LEN); \ INIT_VEC_PTRS_LOOP (mr, r_loc, VEC_LEN/4); \ INIT_VEC_PTRS_LOOP (mr1, r1_loc, VEC_LEN/4); \ vector_func (mx, mr, mr, mr, mr, mr1, mr1, mr1, mr1); \ TEST_VEC_LOOP (r_loc, VEC_LEN/4); \ TEST_VEC_LOOP (r1_loc, VEC_LEN/4); \ *r = r_loc[0]; \ *r1 = r1_loc[0]; \ return; \ }
GB_binop__times_fc32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__times_fc32 // A.*B function (eWiseMult): GB_AemultB__times_fc32 // A*D function (colscale): GB_AxD__times_fc32 // D*A function (rowscale): GB_DxB__times_fc32 // C+=B function (dense accum): GB_Cdense_accumB__times_fc32 // C+=b function (dense accum): GB_Cdense_accumb__times_fc32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__times_fc32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__times_fc32 // C=scalar+B GB_bind1st__times_fc32 // C=scalar+B' GB_bind1st_tran__times_fc32 // C=A+scalar GB_bind2nd__times_fc32 // C=A'+scalar GB_bind2nd_tran__times_fc32 // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_mul (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_FC32_mul (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TIMES || GxB_NO_FC32 || GxB_NO_TIMES_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__times_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__times_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__times_fc32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__times_fc32 ( 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_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__times_fc32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__times_fc32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__times_fc32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__times_fc32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__times_fc32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; GxB_FC32_t bij = Bx [p] ; Cx [p] = GB_FC32_mul (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__times_fc32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC32_t aij = Ax [p] ; Cx [p] = GB_FC32_mul (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_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_mul (x, aij) ; \ } GrB_Info GB_bind1st_tran__times_fc32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_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_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_mul (aij, y) ; \ } GrB_Info GB_bind2nd_tran__times_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
pr35439.c
/* PR c/35439 */ /* { dg-do compile } */ /* { dg-options "-fopenmp" } */ void x[1]; /* { dg-error "array of voids" } */ #pragma omp threadprivate(x)
GB_binop__times_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__times_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__times_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__times_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__times_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__times_uint64) // A*D function (colscale): GB (_AxD__times_uint64) // D*A function (rowscale): GB (_DxB__times_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__times_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__times_uint64) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_uint64) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_uint64) // C=scalar+B GB (_bind1st__times_uint64) // C=scalar+B' GB (_bind1st_tran__times_uint64) // C=A+scalar GB (_bind2nd__times_uint64) // C=A'+scalar GB (_bind2nd_tran__times_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_TIMES || GxB_NO_UINT64 || GxB_NO_TIMES_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__times_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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
GrB_UnaryOp_wait.c
//------------------------------------------------------------------------------ // GrB_UnaryOp_wait: wait for a user-defined GrB_UnaryOp to complete //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // In SuiteSparse:GraphBLAS, a user-defined GrB_UnaryOp has no pending // operations to wait for. All this method does is verify that the op is // properly initialized, and then it does an OpenMP flush. #include "GB.h" GrB_Info GrB_UnaryOp_wait // no work, just check if the GrB_UnaryOp is valid ( #if (GxB_IMPLEMENTATION_MAJOR <= 5) GrB_UnaryOp *op #else GrB_UnaryOp op, GrB_WaitMode waitmode #endif ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- #if (GxB_IMPLEMENTATION_MAJOR <= 5) GB_WHERE1 ("GrB_UnaryOp_wait (&op)") ; GB_RETURN_IF_NULL (op) ; GB_RETURN_IF_NULL_OR_FAULTY (*op) ; #else GB_WHERE1 ("GrB_UnaryOp_wait (op, waitmode)") ; GB_RETURN_IF_NULL_OR_FAULTY (op) ; #endif //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- #pragma omp flush return (GrB_SUCCESS) ; }
exm.c
// SPDX-License-Identifier: BSD-2-Clause /* Copyright 1998-2002 Bernard Parent Copyright 2019 Jaehyuk Lee Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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. */ /* EXM: External Module Functions that can be used with CFDWARP or any other code */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <sys/ioctl.h> #include <unistd.h> #include <stdarg.h> #include "exm.h" void EXM_fatal_error(const char *formatstr, ...){ va_list ap; char *newstr; int term_width,term_height; newstr=(char *)malloc(10000*sizeof(char)); fprintf(stderr,"\n\n"); va_start(ap, formatstr); vsprintf(newstr,formatstr, ap); va_end(ap); find_terminal_window_size(&term_width,&term_height); fprintf(stderr,"%s",strwrp(newstr,min(term_width-1,70))); free(newstr); fprintf(stderr,"\n\nEXM fatal error. Exiting.\n\n"); exit(EXIT_FAILURE); } long EXM_ai3(EXM_gl3D_t gl, long i, long j, long k) { long ii; long isr,jsr,jer,ksr,ker; isr=gl.is; jsr=gl.js; jer=gl.je; ksr=gl.ks; ker=gl.ke; ii=(i-isr)*(jer-jsr+1)+(j-jsr); ii=ii*(ker-ksr+1)+(k-ksr); return(ii); } long EXM_ai2(EXM_gl2D_t gl, long i, long j) { long ii; long isr,jsr,jer; isr=gl.is; jsr=gl.js; jer=gl.je; ii=(i-isr)*(jer-jsr+1)+(j-jsr); return(ii); } long EXM_ai1(EXM_gl1D_t gl, long i) { long ii; long isr; isr=gl.is; ii=(i-isr); return(ii); } long EXM_aim(EXM_glm_t gl, long row, long col) { long ii; ii=row*gl.numcol+col; return(ii); } /*=========================================================================== find root solver ============================================================================*/ double SIGN(NUM1, NUM2) double NUM1, NUM2; { double NUM3; double tmp; if (NUM2<0.0e0) tmp=-1.0e0; else tmp=1.0e0; NUM3 = NUM1 * tmp; return NUM3; } /* BASED ON A METHOD BY T J DEKKER WRITTEN BY L F SHAMPINE AND H A WATTS MODIFIED FOR THE MATH LIBRARY BY C B BAILEY TRANSLATED FROM FORTRAN TO PASCAL TO C BY B PARENT ABSTRACT EXM_find_root_zero_in SEARCHES FOR A ZERO OF A FUNCTION F(X) BETWEEN THE GIVEN VALUES B AND C UNTIL THE WIDTH OF THE INTERVAL (B,C) HAS COLLAPSED TO WITHIN A TOLERANCE SPECIFIED BY THE STOPPING CRITERION, ABS(B-C) .LE. 2.*(RW*ABS(B)+AE). THE METHOD USED IS AN EFFICIENT COMBINATION OF BISECTION AND THE SECANT RULE. IN ORDER TO INSURE THAT EXM_find_root_zero_in WILL CONVERGE TO A ZERO, THE USER SHOULD PICK VALUES FOR B AND C AT WHICH THE FUNCTION DIFFERS IN SIGN. DESCRIPTION OF ARGUMENTS F,B,C,RE AND AE ARE INPUT PARAMETERS B,C AND IFLAG ARE OUTPUT PARAMETERS F - NAME OF THE REAL VALUED EXTERNAL FUNCTION. THIS NAME MUST BE IN AN EXTERNAL STATEMENT IN THE CALLING PROGRAM. F MUST BE A FUNCTION OF ONE REAL ARGUMENT. minval- ONE END OF THE INTERVAL (B,C). THE VALUE RETURNED FOR B USUALLY IS THE BETTER APPROXIMATION TO A ZERO OF F. maxval- THE OTHER END OF THE INTERVAL (B,C) relerr- RELATIVE ERROR USED FOR RW IN THE STOPPING CRITERION. IF THE REQUESTED RE IS LESS THAN MACHINE PRECISION, THEN RW IS SET TO APPROXIMATELY MACHINE PRECISION. abserr- ABSOLUTE ERROR USED IN THE STOPPING CRITERION. IF THE GIVEN INTERVAL (B,C) CONTAINS THE ORIGIN, THEN A NONZERO VALUE SHOULD BE CHOSEN FOR AE. IFLAG - A STATUS CODE. USER MUST CHECK IFLAG AFTER EACH CALL. CONTROL RETURNS TO THE USER FROM EXM_find_root_zero_in IN ALL CASES. XERROR DOES NOT PROCESS DIAGNOSTICS IN THESE CASES. 1 B IS WITHIN THE REQUESTED TOLERANCE OF A ZERO. THE INTERVAL (B,C) COLLAPSED TO THE REQUESTED TOLERANCE, THE FUNCTION CHANGES SIGN IN (B,C), AND F(X) DECREASED IN MAGNITUDE AS (B,C) COLLAPSED. 2 F(B) = 0. HOWEVER, THE INTERVAL (B,C) MAY NOT HAVE COLLAPSED TO THE REQUESTED TOLERANCE. 3 B MAY BE NEAR A SINGULAR POINT OF F(X). THE INTERVAL (B,C) COLLAPSED TO THE REQUESTED TOLERANCE AND THE FUNCTION CHANGES SIGN IN (B,C) BUT F(X) INCREASED IN MAGNITUDE AS (B,C) COLLAPSED,I.E. ABS(F(B OUT)) .GT. MAX(ABS(F(B IN)),ABS(F(C IN))) 4 NO CHANGE IN SIGN OF F(X) WAS FOUND ALTHOUGH THE INTERVAL (B,C) COLLAPSED TO THE REQUESTED TOLERANCE. THE USER MUST EXAMINE THIS CASE AND DECIDE WHETHER B IS NEAR A LOCAL MINIMUM OF F(X), OR B IS NEAR A ZERO OF EVEN MULTIPLICITY, OR NEITHER OF THESE. 5 TOO MANY (.GT. 500) FUNCTION EVALUATIONS USED. REFERENCES 1. L F SHAMPINE AND H A WATTS, EXM_find_root_zero_in, A ROOT-SOLVING CODE, SC-TM-70-631, SEPT 1970. 2. T J DEKKER, FINDING A ZERO BY MEANS OF SUCCESSIVE LINEAR INTERPOLATION, *CONSTRUCTIVE ASPECTS OF THE FUNDAMENTAL THEOREM OF ALGEBRA*, EDITED BY B DEJON AND P HENRICI, 1969. ER IS TWO TIMES THE COMPUTER UNIT ROUNDOFF VALUE WHICH IS DEFINED HERE TO BE THE VALUE FOR THE IBM PC DOUBLE PRECISION*/ double EXM_find_root_zero_in(double(*FUNCT)(void *, double), void *arg_ptr, double minval, double maxval, double relerr, double abserr, long *IFLAG){ double T, A, P, U, TOL, ACMB, CMB, FX, FC, FB, FA, ACBS, ER, RW, AW; long IC, KOUNT; *IFLAG = 0; ER = 2.0e-13; RW = max(relerr, ER); AW = max(abserr, 0.0e0); IC = 0; ACBS = fabs(minval - maxval); A = maxval; T = A; FA = (*FUNCT)(arg_ptr,T); T = minval; FB = (*FUNCT)(arg_ptr,T); FC = FA; KOUNT = 2; FX = max(fabs(FB), fabs(FC)); _L1: if (fabs(FC) > fabs(FB)) goto _L2; A = minval; FA = FB; minval = maxval; FB = FC; maxval = A; FC = FA; _L2: if (FB == 0.0e0) *IFLAG = 2; CMB = 0.5e0 * (maxval - minval); ACMB = fabs(CMB); TOL = RW * fabs(minval) + AW; if (ACMB <= TOL) { *IFLAG = 1; if (SIGN(1.0e0, FB) == SIGN(1.0e0, FC)) *IFLAG = 4; if (fabs(FB) > FX) *IFLAG = 3; } P = (minval - A) * FB; U = FA - FB; if (P >= 0.0e0) goto _L3; P = -P; U = -U; _L3: A = minval; FA = FB; IC++; if (IC < 4) goto _L4; if (8.0e0 * ACMB >= ACBS) goto _L6; IC = 0; ACBS = ACMB; _L4: if (P > fabs(U) * TOL) goto _L5; minval += SIGN(TOL, CMB); goto _L7; _L5: if (P >= CMB * U) goto _L6; assert(U!=0.0e0); minval += P / U; goto _L7; _L6: minval = 0.5e0 * (maxval + minval); _L7: T = minval; FB = (*FUNCT)(arg_ptr,T); if (FB == 0.0e0) *IFLAG = 2; if (SIGN(1.0e0, FB) != SIGN(1.0e0, FC)) goto _L8; maxval = A; FC = FA; _L8: KOUNT++; if (KOUNT > 500) *IFLAG = 5; if (*IFLAG == 0) goto _L1; return(minval); } /* root_guess: enter a value as a first guess of the root droot_init: a small value, usually set to about 10^8 times smaller than the maximum value of a root you would expect to obtain relerr: the maximum admissible relative error on the residual to obtain convergence abserr: the maximum admissible absolute error on the residual to obtain convergence *IFLAG= 1: convergence has been obtained correctly; 2: problem in convergence, too many iterations 3: droot_init can not be zero 4: problem finding adequate dx from droot_init (droot_init may be too small or too large) 5: the function provided returned NaN or a non finite number */ double EXM_find_root_Newton_Raphson( double(*FUNCT)(void *, double), void *arg_ptr, double root_guess, double droot_init, double relerr, double abserr, long *IFLAG){ double x1,x2,dx; double res1,res2,resref; long cnt; bool PROBLEM,NEEDEDADJUSTMENT; x1=0.0; *IFLAG=0; if (droot_init==0.0) *IFLAG=3; /* check if droot_init is proper and adjust it if required */ PROBLEM=FALSE; NEEDEDADJUSTMENT=FALSE; res1=(*FUNCT)(arg_ptr,x1); cnt=0; do { res2=(*FUNCT)(arg_ptr,x1+droot_init); if (res2-res1==0.0) { PROBLEM=TRUE; NEEDEDADJUSTMENT=TRUE; droot_init*=10.0; } else { PROBLEM=FALSE; } cnt++; } while (PROBLEM && cnt<=100); if (NEEDEDADJUSTMENT) droot_init*=100.0; if (cnt>=100) *IFLAG=4; resref=max(fabs(res2),max(fabs(res1),fabs((*FUNCT)(arg_ptr,x1+droot_init)))); if (isnan(resref) || !isfinite(resref)) *IFLAG=5; if (*IFLAG==0){ PROBLEM=FALSE; x1=root_guess; res1=(*FUNCT)(arg_ptr,x1); dx=droot_init; cnt=0; do { cnt++; x2=x1+dx; res2=(*FUNCT)(arg_ptr,x2); if (res2-res1==0.0 || x2-x1==0.0){ droot_init*=2.0; dx=droot_init; PROBLEM=TRUE; } else { PROBLEM=FALSE; dx=-res2/(res2-res1)*(x2-x1); } res1=res2; x1=x2; } while ((fabs(res1)>=abserr || PROBLEM) && (fabs(res1/resref)>=relerr || PROBLEM) && (cnt<=300)); *IFLAG=1; if (cnt>=300) *IFLAG=2; if (isnan(res1) || !isfinite(res1)) *IFLAG=5; } return(x1); } /*============================================================================ XDMA solver =============================================================================*/ /* #define maxXDMAthread 5 typedef struct { EXM_gl2D_t *gl; long hbw,line,line2min,line2max; double *xdma; } XDMAthreadptr_t; void *XDMAthreadfunct(void *XDMAthreadptr){ EXM_gl2D_t *gl; long col,hbw,line,line2min,line2max,line2,dc; double fact; double *xdma; xdma=((XDMAthreadptr_t *)XDMAthreadptr)->xdma; gl=((XDMAthreadptr_t *)XDMAthreadptr)->gl; hbw=((XDMAthreadptr_t *)XDMAthreadptr)->hbw; line=((XDMAthreadptr_t *)XDMAthreadptr)->line; line2min=((XDMAthreadptr_t *)XDMAthreadptr)->line2min; line2max=((XDMAthreadptr_t *)XDMAthreadptr)->line2max; for (line2=line2min; line2<=line2max; line2++){ dc=(line2-line); // here the idea is to add line*fact to line2, with dc added to the // column index of line fact=-xdma[EXM_ai2(*gl,hbw-dc,line2)]/xdma[EXM_ai2(*gl,hbw,line)]; for (col=hbw; col<gl->ie; col++){ xdma[EXM_ai2(*gl,col-dc,line2)]+=fact*xdma[EXM_ai2(*gl,col,line)]; } xdma[EXM_ai2(*gl,gl->ie,line2)]+=fact*xdma[EXM_ai2(*gl,gl->ie,line)]; } return(NULL); } // solves a x-diagonal matrix as defined by the pointer variable xdma with the size // in gl void EXM_SolveXDMAthread(double *xdma, EXM_gl2D_t gl){ long numXDMAthread,cntXDMAthread,hbw,line,line2,dc,linemax,col,line2min,line2max,numline; double fact; void *retval; pthread_t XDMAthread[maxXDMAthread]; XDMAthreadptr_t XDMAthreadptr[maxXDMAthread]; // NOTE: gl.js must be equal to zero // gl.is must be equal to zero hbw=(gl.ie-gl.is+1)/2-1; linemax=gl.je; for (line=0; line<linemax; line++){ line2min=line+1; line2max=min(line+hbw,linemax); cntXDMAthread=0; numline=max(1,round((line2max-line2min)/maxXDMAthread)); do { XDMAthreadptr[cntXDMAthread].gl=&gl; XDMAthreadptr[cntXDMAthread].hbw=hbw; XDMAthreadptr[cntXDMAthread].line=line; XDMAthreadptr[cntXDMAthread].xdma=xdma; XDMAthreadptr[cntXDMAthread].line2min=line2min+cntXDMAthread*numline; XDMAthreadptr[cntXDMAthread].line2max=min(line2max,line2min+(cntXDMAthread+1)*numline-1); if (cntXDMAthread==maxXDMAthread-1) XDMAthreadptr[cntXDMAthread].line2max=line2max; if (line==0 && FALSE) fprintf(stderr,"%ld %ld %ld %ld %ld %ld\n",line2min,line2max,XDMAthreadptr[cntXDMAthread].line2min,XDMAthreadptr[cntXDMAthread].line2max,hbw,numline); if (pthread_create(&((XDMAthread)[cntXDMAthread]), NULL, &XDMAthreadfunct, (void *)(&(XDMAthreadptr[cntXDMAthread])))) fprintf(stderr,"Cannot create XDMA thread.\n"); cntXDMAthread++; } while (cntXDMAthread<maxXDMAthread || XDMAthreadptr[cntXDMAthread-1].line2max!=line2max); numXDMAthread=cntXDMAthread; for (cntXDMAthread=0; cntXDMAthread<numXDMAthread; cntXDMAthread++){ if (pthread_join(XDMAthread[cntXDMAthread],&retval)) fprintf(stderr,"Cannot join XDMA thread %ld.\n",cntXDMAthread); } } for (line=linemax; line>0; line--){ for (line2=line-1; line2>=max(line-hbw,0); line2--){ dc=(line2-line); // here the idea is to add line*fact to line2, with dc added to the // column index of line fact=-xdma[EXM_ai2(gl,hbw-dc,line2)]/xdma[EXM_ai2(gl,hbw,line)]; col=hbw; xdma[EXM_ai2(gl,col-dc,line2)]+=fact*xdma[EXM_ai2(gl,col,line)]; xdma[EXM_ai2(gl,gl.ie,line2)]+=fact*xdma[EXM_ai2(gl,gl.ie,line)]; } } for (line=0; line<=linemax; line++){ xdma[EXM_ai2(gl,gl.ie,line)]/=xdma[EXM_ai2(gl,hbw,line)]; xdma[EXM_ai2(gl,hbw,line)]=1.0e0; } } */ /*solves a x-diagonal matrix as defined by the pointer variable xdma with the size in gl*/ void EXM_solve_XDMA(double *xdma, EXM_gl2D_t gl){ long hbw,line,line2,dc,linemax,col; double fact,sum,aux; /* NOTE: gl.js must be equal to zero gl.is must be equal to zero */ hbw=(gl.ie-gl.is+1)/2-1; linemax=gl.je; for (line=0; line<linemax; line++){ #if defined(OPENMPTHREADS) #pragma omp parallel for private(line2,dc,fact,col) schedule(static) #endif for (line2=line+1; line2<=min(line+hbw,linemax); line2++){ dc=(line2-line); // here the idea is to add line*fact to line2, with dc added to the // column index of line assert(xdma[EXM_ai2(gl,hbw,line)]!=0.0); fact=-xdma[EXM_ai2(gl,hbw-dc,line2)]/xdma[EXM_ai2(gl,hbw,line)]; for (col=hbw; col<gl.ie; col++){ xdma[EXM_ai2(gl,col-dc,line2)]+=fact*xdma[EXM_ai2(gl,col,line)]; } xdma[EXM_ai2(gl,gl.ie,line2)]+=fact*xdma[EXM_ai2(gl,gl.ie,line)]; } } xdma[EXM_ai2(gl,gl.ie,linemax)]/=xdma[EXM_ai2(gl,hbw,linemax)]; xdma[EXM_ai2(gl,hbw,linemax)]=1.0; for (line=linemax-1; line>=0; line--){ sum=0.0; #if defined(OPENMPTHREADS) #pragma omp parallel for reduction(+:sum) private(line2,aux) schedule(static) #endif for (line2=line+1; line2<=min(line+hbw,linemax); line2++){ aux=xdma[EXM_ai2(gl,hbw+line2-line,line)]*xdma[EXM_ai2(gl,gl.ie,line2)]; sum=sum+aux; } xdma[EXM_ai2(gl,gl.ie,line)]-=sum; assert(xdma[EXM_ai2(gl,hbw,line)]!=0.0); xdma[EXM_ai2(gl,gl.ie,line)]/=xdma[EXM_ai2(gl,hbw,line)]; xdma[EXM_ai2(gl,hbw,line)]=1.0; } } void EXM_solve_XDMA_old(double *xdma, EXM_gl2D_t gl){ long hbw,line,line2,dc,linemax,col; double fact; /* NOTE: gl.js must be equal to zero gl.is must be equal to zero */ hbw=(gl.ie-gl.is+1)/2-1; linemax=gl.je; for (line=0; line<linemax; line++){ for (line2=line+1; line2<=min(line+hbw,linemax); line2++){ dc=(line2-line); /* here the idea is to add line*fact to line2, with dc added to the column index of line */ fact=-xdma[EXM_ai2(gl,hbw-dc,line2)]/xdma[EXM_ai2(gl,hbw,line)]; for (col=hbw; col<gl.ie; col++){ xdma[EXM_ai2(gl,col-dc,line2)]+=fact*xdma[EXM_ai2(gl,col,line)]; } xdma[EXM_ai2(gl,gl.ie,line2)]+=fact*xdma[EXM_ai2(gl,gl.ie,line)]; } } for (line=linemax; line>0; line--){ for (line2=line-1; line2>=max(line-hbw,0); line2--){ dc=(line2-line); /* here the idea is to add line*fact to line2, with dc added to the column index of line */ fact=-xdma[EXM_ai2(gl,hbw-dc,line2)]/xdma[EXM_ai2(gl,hbw,line)]; col=hbw; xdma[EXM_ai2(gl,col-dc,line2)]+=fact*xdma[EXM_ai2(gl,col,line)]; xdma[EXM_ai2(gl,gl.ie,line2)]+=fact*xdma[EXM_ai2(gl,gl.ie,line)]; } } for (line=0; line<=linemax; line++){ xdma[EXM_ai2(gl,gl.ie,line)]/=xdma[EXM_ai2(gl,hbw,line)]; xdma[EXM_ai2(gl,hbw,line)]=1.0e0; } } /*============================================================================ TDMA solver =============================================================================*/ /*solves a tri-diagonal matrix as defined by the pointer variables tdm lines*/ void EXM_solve_TDMA(EXM_tdmaline_t *tdma, long numlines) { long line,cnt; double tmp; /*tdma[0].val[0] must be equal to zero*/ /*tdma[numlines-1].val[2] must be equal to zero*/ for (line=0; line<numlines-1; line++){ tmp = -(tdma[line+1].val[0] / tdma[line].val[1]); for (cnt = 1; cnt <= 2; cnt++) tdma[line+1].val[cnt - 1] += tdma[line].val[cnt] * tmp; tdma[line+1].val[3] += tdma[line].val[3] * tmp; tdma[line+1].val[0] = 0.0; } for (line=numlines-1; line>0; line--){ tdma[line].val[3] /= tdma[line].val[1]; tdma[line].val[1] = 1.0; tdma[line-1].val[3] -= tdma[line].val[3] * tdma[line-1].val[2]; tdma[line-1].val[2] = 0.0; } tdma[0].val[3] /= tdma[0].val[1]; tdma[0].val[1] = 1.0; } /*============================================================================ PDMA solver =============================================================================*/ /*solves a penta-diagonal matrix as defined by the pointer variables pdm lines*/ void EXM_solve_PDMA(EXM_pdmaline_t *pdma, long numlines) { long line; double tmp; /* first sweep downwards */ for (line=1; line<numlines-1; line++){ tmp = -(pdma[line+1].val[0] / pdma[line].val[1]); pdma[line+1].val[0] = 0.0; pdma[line+1].val[1] += pdma[line].val[2] * tmp; pdma[line+1].val[2] += pdma[line].val[3] * tmp; pdma[line+1].val[3] += pdma[line].val[4] * tmp; pdma[line+1].val[5] += pdma[line].val[5] * tmp; } /* second sweep downwards */ for (line=0; line<numlines-1; line++){ tmp = -(pdma[line+1].val[1] / pdma[line].val[2]); pdma[line+1].val[1] = 0.0; pdma[line+1].val[2] += pdma[line].val[3] * tmp; pdma[line+1].val[3] += pdma[line].val[4] * tmp; pdma[line+1].val[5] += pdma[line].val[5] * tmp; } /* first sweep upwards */ for (line=numlines-2; line>0; line--){ tmp = -(pdma[line-1].val[4] / pdma[line].val[3]); pdma[line-1].val[4] =0.0; pdma[line-1].val[3] += pdma[line].val[2]*tmp ; pdma[line-1].val[2] += pdma[line].val[1]*tmp ; pdma[line-1].val[1] += pdma[line].val[0]*tmp ; pdma[line-1].val[5] += pdma[line].val[5]*tmp; } /* second sweep upwards */ for (line=numlines-1; line>0; line--){ pdma[line].val[5] /= pdma[line].val[2]; pdma[line].val[2] = 1.0; pdma[line-1].val[5] -= pdma[line].val[5] * pdma[line-1].val[3]; pdma[line-1].val[3] = 0.0; } pdma[0].val[5] /= pdma[0].val[2]; pdma[0].val[2] = 1.0; } /*====================================================================== Block TDMA solver ====================================================================== */ long EXM_mi(long k, long line, long row, long col){ long tmp; tmp=line*k*k+col*k+row; return(tmp); } static void mat_add_tdma(double *mat1, long line1, double *mat2, long line2, double *mat3, long line3, long k){ long row,col; for (row=0; row<k; row++){ for (col=0; col<k; col++){ mat3[EXM_mi(k,line3,row,col)]= mat1[EXM_mi(k,line1,row,col)] +mat2[EXM_mi(k,line2,row,col)]; } } } static void mat_mult_tdma(double *mat1, long line1, double *mat2,long line2, double *mat3, long line3, long k){ long row,col,cnt; for (row=0; row<k; row++){ for (col=0; col<k; col++){ mat3[EXM_mi(k,line3,row,col)]=0.0e0; for (cnt=0; cnt<k; cnt++){ mat3[EXM_mi(k,line3,row,col)]=mat3[EXM_mi(k,line3,row,col)]+ mat1[EXM_mi(k,line1,row,cnt)]*mat2[EXM_mi(k,line2,cnt,col)]; } } } } static void mat_init_i_tdma(double *mat1, long line1, long k){ long m,n; for (m=0; m<k; m++){ for (n=0; n<k; n++){ mat1[EXM_mi(k,line1,m,n)]=0.0e0; } } for (m=0; m<k; m++){ mat1[EXM_mi(k,line1,m,m)]=1.0e0; } } static void mat_inv_tdma(double *mat1,long line1,double *mat2,long line2,long k){ long row,row2,col; double multfact; /* Idea: init mat2 as identity; gaussian elimination on mat1/mat2 */ mat_init_i_tdma(mat2,line2,k); for (row=0; row<k; row++){ for (row2=0; row2<k; row2++){ if (row2 != row) { multfact=-mat1[EXM_mi(k,line1,row2,row)] /(mat1[EXM_mi(k,line1,row,row)]+0.0e-30); /* Add line row*multfact to line row2 */ for (col=0; col<k; col++){ mat1[EXM_mi(k,line1,row2,col)]=mat1[EXM_mi(k,line1,row2,col)]+ mat1[EXM_mi(k,line1,row,col)]*multfact; mat2[EXM_mi(k,line2,row2,col)]=mat2[EXM_mi(k,line2,row2,col)]+ mat2[EXM_mi(k,line2,row,col)]*multfact; } } } } for (row=0; row<k; row++){ for (col=0; col<k; col++){ assert(mat1[EXM_mi(k,line1,row,row)]!=0.0e0); mat2[EXM_mi(k,line2,row,col)]=mat2[EXM_mi(k,line2,row,col)]/(mat1[EXM_mi(k,line1,row,row)]); } mat1[EXM_mi(k,line1,row,row)]=1.e0; } } static void mat_equal_tdma(double *mat1,long line1,double *mat2,long line2, long k){ long row,col; for (row=0; row<k; row++){ for (col=0; col<k; col++){ mat2[EXM_mi(k,line2,row,col)]=mat1[EXM_mi(k,line1,row,col)]; } } } static void find_multfact(double *mat1,long line1,double *mat2,long line2, double *mat3,long line3, long k){ long row,col; /* Idea: mat3*mat1=-mat2 or: mat3=-mat2*mat1_inv */ mat_equal_tdma(mat1,line1,mat3,5,k); mat_inv_tdma(mat3,5,mat3,4,k); mat_mult_tdma(mat2,line2,mat3,4,mat3,line3,k); for (row=0; row<k; row++){ for (col=0; col<k; col++){ mat3[EXM_mi(k,line3,row,col)]=-mat3[EXM_mi(k,line3,row,col)]; } } } /* solve block TDMA with first line at line=0 and last line at line=linemax */ void EXM_solve_block_TDMA(double *AA, double *BB, double *CC, double *RHS, long linemax, long k){ long line; double *TMP; TMP=(double *) malloc(6*k*k*sizeof(double)); /* -------------------------------------------------------------- Sweep Downward -------------------------------------------------------------- */ for (line=0; line<linemax; line++){ find_multfact(BB,line,AA,line+1,TMP,1,k); mat_mult_tdma(TMP,1,CC,line,TMP,2,k); mat_add_tdma(TMP,2,BB,line+1,TMP,3,k); mat_equal_tdma(TMP,3,BB,line+1,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_add_tdma(TMP,2,RHS,line+1,TMP,3,k); mat_equal_tdma(TMP,3,RHS,line+1,k); } /* -------------------------------------------------------------- Sweep Upward -------------------------------------------------------------- */ for (line=linemax; line>0; line--){ find_multfact(BB,line,CC,line-1,TMP,1,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_add_tdma(TMP,2,RHS,line-1,TMP,3,k); mat_equal_tdma(TMP,3,RHS,line-1,k); } /* -------------------------------------------------------------- Make BB identity -------------------------------------------------------------- */ for (line=0; line<=linemax; line++){ mat_inv_tdma(BB,line,TMP,1,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_equal_tdma(TMP,2,RHS,line,k); } free(TMP); } void EXM_solve_block_TDMA_and_check(double *AA, double *BB, double *CC, double *DD, long linemax, long k){ long line,cnt; double *A,*B,*C,*D; double *TMP; bool PROBLEM; TMP=(double *) malloc(20*k*k*sizeof(double)); A=(double *) malloc((linemax+2)*k*k*sizeof(double)); B=(double *) malloc((linemax+2)*k*k*sizeof(double)); C=(double *) malloc((linemax+2)*k*k*sizeof(double)); D=(double *) malloc((linemax+2)*k*k*sizeof(double)); for (line=0; line<=linemax; line++){ mat_equal_tdma(AA,line,A,line,k); mat_equal_tdma(BB,line,B,line,k); mat_equal_tdma(CC,line,C,line,k); mat_equal_tdma(DD,line,D,line,k); } EXM_solve_block_TDMA(AA, BB, CC, DD, linemax, k); /* now, compare A[line]*DD[line-1]+B[line]*DD[line]+C[line]*DD[line+1] and D[line] */ for (line=0; line<=linemax; line++){ mat_mult_tdma(B,line,DD,line,TMP,10,k); if (line!=linemax) { mat_mult_tdma(C,line,DD,line+1,TMP,11,k); mat_add_tdma(TMP,10,TMP,11,TMP,12,k); mat_equal_tdma(TMP,12,TMP,10,k); } if (line!=0) { mat_mult_tdma(A,line,DD,line-1,TMP,11,k); mat_add_tdma(TMP,10,TMP,11,TMP,12,k); mat_equal_tdma(TMP,12,TMP,10,k); } PROBLEM=FALSE; for (cnt=0; cnt<k; cnt++) if (fabs(TMP[EXM_mi(k,10,cnt,0)]-D[EXM_mi(k,line,cnt,0)])>1.0e-10) PROBLEM=TRUE; if (PROBLEM) { for (cnt=0; cnt<k; cnt++) printf("%E ",TMP[EXM_mi(k,10,cnt,0)]); printf("\n"); for (cnt=0; cnt<k; cnt++) printf("%E ",D[EXM_mi(k,line,cnt,0)]); printf("\n\n"); } } free(A); free(B); free(C); free(D); free(TMP); } /* solve block PDMA with first line at line=0 and last line at line=linemax */ void EXM_solve_block_PDMA(double *AA, double *BB, double *CC, double *DD, double *EE, double *RHS, long linemax, long k){ long line; double *TMP; TMP=(double *) malloc(6*k*k*sizeof(double)); /* -------------------------------------------------------------- Sweep Downward -------------------------------------------------------------- */ for (line=1; line<linemax; line++){ /* ------------First line Downwards------------------------ */ find_multfact(CC,line,BB,line+1,TMP,1,k); mat_mult_tdma(TMP,1,DD,line,TMP,2,k); mat_add_tdma(TMP,2,CC,line+1,TMP,3,k); mat_equal_tdma(TMP,3,CC,line+1,k); mat_mult_tdma(TMP,1,EE,line,TMP,2,k); mat_add_tdma(TMP,2,DD,line+1,TMP,3,k); mat_equal_tdma(TMP,3,DD,line+1,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_add_tdma(TMP,2,RHS,line+1,TMP,3,k); mat_equal_tdma(TMP,3,RHS,line+1,k); /* ------------Second Line Downwards----------------------- */ if (line != linemax-1) { find_multfact(CC,line,AA,line+2,TMP,1,k); mat_mult_tdma(TMP,1,DD,line,TMP,2,k); mat_add_tdma(TMP,2,BB,line+2,TMP,3,k); mat_equal_tdma(TMP,3,BB,line+2,k); mat_mult_tdma(TMP,1,EE,line,TMP,2,k); mat_add_tdma(TMP,2,CC,line+2,TMP,3,k); mat_equal_tdma(TMP,3,CC,line+2,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_add_tdma(TMP,2,RHS,line+2,TMP,3,k); mat_equal_tdma(TMP,3,RHS,line+2,k); } } /* -------------------------------------------------------------- Sweep Upward -------------------------------------------------------------- */ for (line=linemax; line>0; line--){ /* -------First Line upwards------------------------------ */ find_multfact(CC,line,DD,line-1,TMP,1,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_add_tdma(TMP,2,RHS,line-1,TMP,3,k); mat_equal_tdma(TMP,3,RHS,line-1,k); /* -------Second Line Upwards----------------------------- */ if (line != 1) { find_multfact(CC,line,EE,line-2,TMP,1,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_add_tdma(TMP,2,RHS,line-2,TMP,3,k); mat_equal_tdma(TMP,3,RHS,line-2,k); } } /* -------------------------------------------------------------- Make CC identity -------------------------------------------------------------- */ for (line=0; line<=linemax; line++){ mat_inv_tdma(CC,line,TMP,1,k); mat_mult_tdma(TMP,1,RHS,line,TMP,2,k); mat_equal_tdma(TMP,2,RHS,line,k); } free(TMP); } /* Other Math subroutines of interes*/ double sign_old(double x){ double tmp; if (x<0) { tmp=-1.0e0; } else { tmp=1.0e0; } return(tmp); } long mod_old(long numb, long div){ long tmp; long tmp2; long tmp3; tmp=numb/div; tmp2=tmp*div; tmp3=numb-tmp2; return (tmp3); } long mod_old2 (long a, long b) { if(b < 0) //you can check for b == 0 separately and do what you want return mod(-a, -b); long ret = a % b; if(ret < 0) ret+=b; return ret; } double powint(double x, long y){ double sum; long cnt; sum=1.0e0; for (cnt=1; cnt<=labs(y); cnt++){ sum=sum*x; } return(sum); } double krodelta(long i, long j){ double tmp; if (i==j) { tmp=1.0e0; } else { tmp=0.0e0; } return(tmp); } void EXM_init_matrix(EXM_mat_t *mat, long numrow, long numcol){ long row,col; mat->cont=(double *)malloc(numrow*numcol*sizeof(double)); mat->glm.numcol=numcol; mat->glm.numrow=numrow; for (row=0; row<numrow; row++){ for (col=0; col<numcol; col++){ mat->cont[EXM_aim(mat->glm,row,col)]=0.0e0; } } } void EXM_reinit_matrix(EXM_mat_t *mat, long numrow, long numcol){ long row,col; mat->cont=(double *)realloc(mat->cont,numrow*numcol*sizeof(double)); mat->glm.numcol=numcol; mat->glm.numrow=numrow; for (row=0; row<numrow; row++){ for (col=0; col<numcol; col++){ mat->cont[EXM_aim(mat->glm,row,col)]=0.0e0; } } } void EXM_free_matrix(EXM_mat_t *mat){ free(mat->cont); } void EXM_init_identity_matrix(EXM_mat_t *mat, long numrow, long numcol){ long row,col; mat->cont=(double *)malloc(numrow*numcol*sizeof(double)); mat->glm.numcol=numcol; mat->glm.numrow=numrow; for (row=0; row<numrow; row++){ for (col=0; col<numcol; col++){ if (row==col) { mat->cont[EXM_aim(mat->glm,row,col)]=1.0e0; } else { mat->cont[EXM_aim(mat->glm,row,col)]=0.0e0; } } } } void EXM_display_matrix(EXM_mat_t mat){ long row,col; printf("numrow=%ld numcol=%ld\n",mat.glm.numrow,mat.glm.numcol); for (row=0; row<mat.glm.numrow; row++){ for (col=0; col<mat.glm.numcol; col++){ printf("%E ",mat.cont[EXM_aim(mat.glm,row,col)]); } printf("\n"); } printf("\n"); } void EXM_multiply_matrices(EXM_mat_t mat1, EXM_mat_t mat2, EXM_mat_t *matr){ long cnt,numrow,numcol,row,col; numrow=mat1.glm.numrow; numcol=mat2.glm.numcol; EXM_reinit_matrix(matr,numrow,numcol); if (mat2.glm.numrow==mat1.glm.numcol) { for (row=0; row<numrow; row++){ for (col=0; col<numcol; col++){ matr->cont[EXM_aim(matr->glm,row,col)]=0.0e0; for (cnt=0; cnt<mat1.glm.numcol; cnt++){ matr->cont[EXM_aim(matr->glm,row,col)]=matr->cont[EXM_aim(matr->glm,row,col)] +mat1.cont[EXM_aim(mat1.glm,row,cnt)] *mat2.cont[EXM_aim(mat2.glm,cnt,col)]; } } } } else { printf("cannot multiply the two matrices\n"); } } void EXM_invert_matrix_gaussian_elimination(EXM_mat_t mat, EXM_mat_t *matinv){ long row,col,row2; double fact; EXM_mat_t mattmp; EXM_init_matrix(&mattmp,mat.glm.numrow,mat.glm.numcol); if (mat.glm.numrow==mat.glm.numcol) { EXM_reinit_matrix(matinv,mat.glm.numrow,mat.glm.numcol); for (row=0; row<mat.glm.numrow; row++){ for (col=0; col<mat.glm.numcol; col++){ mattmp.cont[EXM_aim(mat.glm,row,col)]=mat.cont[EXM_aim(mat.glm,row,col)]; matinv->cont[EXM_aim(mat.glm,row,col)]=0.0; } matinv->cont[EXM_aim(mat.glm,row,row)]=1.0; } // make the non-diagonal elements zero for mattmp for (row=0; row<mat.glm.numrow; row++){ for (row2=0; row2<mat.glm.numrow; row2++){ if (row2!=row) { if (mattmp.cont[EXM_aim(mat.glm,row,row)]==0.0){ printf("matrix cannot be inverted\n"); } fact=-mattmp.cont[EXM_aim(mat.glm,row2,row)]/mattmp.cont[EXM_aim(mat.glm,row,row)]; for (col=0; col<mat.glm.numcol; col++){ mattmp.cont[EXM_aim(mat.glm,row2,col)]+=fact*mattmp.cont[EXM_aim(mat.glm,row,col)]; matinv->cont[EXM_aim(mat.glm,row2,col)]+=fact*matinv->cont[EXM_aim(mat.glm,row,col)]; } } } } // EXM_display_matrix(mattmp); // make the diagonal elements equal to 1 for mattmp for (row=0; row<mat.glm.numrow; row++){ if (mattmp.cont[EXM_aim(mat.glm,row,row)]==0.0){ printf("matrix cannot be inverted\n"); } fact=1.0/mattmp.cont[EXM_aim(mat.glm,row,row)]; for (col=0; col<mat.glm.numcol; col++){ mattmp.cont[EXM_aim(mat.glm,row,col)]*=fact; matinv->cont[EXM_aim(mat.glm,row,col)]*=fact; } } } else { printf("matrix cannot be inverted\n"); printf("number of rows not equal to number of columns \n"); } EXM_free_matrix(&mattmp); } // function by Jaehyuk Lee void EXM_invert_matrix_partial_pivoting(EXM_mat_t mat, EXM_mat_t *matinv){ long pivot,row,row2,col; double temp,pivotval,fact; EXM_mat_t mattmp; EXM_init_matrix(&mattmp,mat.glm.numrow,mat.glm.numcol); if (mat.glm.numrow==mat.glm.numcol) { EXM_reinit_matrix(matinv,mat.glm.numrow,mat.glm.numcol); for (row=0; row<mat.glm.numrow; row++){ for (col=0; col<mat.glm.numcol; col++){ mattmp.cont[EXM_aim(mat.glm,row,col)]=mat.cont[EXM_aim(mat.glm,row,col)]; matinv->cont[EXM_aim(mat.glm,row,col)]=0.0; } matinv->cont[EXM_aim(mat.glm,row,row)]=1.0; } //process starts from here for(row=0;row<mat.glm.numrow-1;row++){ //partial pivoting start pivot=row; pivotval=mattmp.cont[EXM_aim(mat.glm,row,row)]; for(row2=row+1;row2<mat.glm.numrow;row2++){ if(fabs(pivotval)<fabs(mattmp.cont[EXM_aim(mat.glm,row2,row)])){ pivot=row2; pivotval=mattmp.cont[EXM_aim(mat.glm,row2,row)]; } } if(pivot!=row){ for(col=0;col<mat.glm.numrow;col++){ //partial pivoting of mattmp temp=mattmp.cont[EXM_aim(mat.glm,pivot,col)]; mattmp.cont[EXM_aim(mat.glm,pivot,col)]=mattmp.cont[EXM_aim(mat.glm,row,col)]; mattmp.cont[EXM_aim(mat.glm,row,col)]=temp; //partial pivoting of matinv temp=matinv->cont[EXM_aim(mat.glm,pivot,col)]; matinv->cont[EXM_aim(mat.glm,pivot,col)]=matinv->cont[EXM_aim(mat.glm,row,col)]; matinv->cont[EXM_aim(mat.glm,row,col)]=temp; } }//partial pivoting complete //forward substitution start for(row2=row+1;row2<mat.glm.numrow;row2++){ assert(mattmp.cont[EXM_aim(mat.glm,row,row)]!=0.0e0); fact=-(mattmp.cont[EXM_aim(mat.glm,row2,row)])/(mattmp.cont[EXM_aim(mat.glm,row,row)]); for(col=0;col<mat.glm.numrow;col++){ matinv->cont[EXM_aim(mat.glm,row2,col)]=matinv->cont[EXM_aim(mat.glm,row2,col)]+matinv->cont[EXM_aim(mat.glm,row,col)]*fact; } for(col=row;col<mat.glm.numrow;col++){ mattmp.cont[EXM_aim(mat.glm,row2,col)]=mattmp.cont[EXM_aim(mat.glm,row2,col)]+mattmp.cont[EXM_aim(mat.glm,row,col)]*fact; } mattmp.cont[EXM_aim(mat.glm,row2,row)]=0.0e0; }//forward substitution complete } //backward substitution start for(row=mat.glm.numrow-1;row>=1;row--){ //multiply fact over matinv for(row2=row-1;row2>=0;row2--){ assert(mattmp.cont[EXM_aim(mat.glm,row,row)]!=0.0e0); fact=-mattmp.cont[EXM_aim(mat.glm,row2,row)]/mattmp.cont[EXM_aim(mat.glm,row,row)]; for(col=0;col<mat.glm.numrow;col++){ matinv->cont[EXM_aim(mat.glm,row2,col)]=matinv->cont[EXM_aim(mat.glm,row2,col)]+matinv->cont[EXM_aim(mat.glm,row,col)]*fact; } } } //devide matinv by diagonal of mattmp for(row=0;row<mat.glm.numrow;row++){ for(col=0;col<mat.glm.numrow;col++){ assert(mattmp.cont[EXM_aim(mat.glm,row,row)]!=0.0e0); matinv->cont[EXM_aim(mat.glm,row,col)]=matinv->cont[EXM_aim(mat.glm,row,col)]/mattmp.cont[EXM_aim(mat.glm,row,row)]; } }//backward substitution complete //EXM_display_matrix(mattmp); } else{ printf("matrix cannot be inverted\n"); printf("number of rows not equal to number of columns \n"); } EXM_free_matrix(&mattmp); } void EXM_invert_matrix(EXM_mat_t mat, EXM_mat_t *matinv){ //EXM_invert_matrix_gaussian_elimination(mat,matinv); EXM_invert_matrix_partial_pivoting(mat,matinv); } void EXM_invert_matrix_analytical(EXM_mat_t mat, EXM_mat_t *matinv){ double den; if ((mat.glm.numrow==mat.glm.numcol) && (mat.glm.numrow<4)) { EXM_reinit_matrix(matinv,mat.glm.numrow,mat.glm.numcol); if (mat.glm.numrow==1){ den=mat.cont[EXM_aim(mat.glm,0,0)]; assert(den!=0.0); matinv->cont[EXM_aim(matinv->glm,0,0)]=1.0e0/den; } if (mat.glm.numrow==2){ den=mat.cont[EXM_aim(mat.glm,0,0)]*mat.cont[EXM_aim(mat.glm,1,1)] -mat.cont[EXM_aim(mat.glm,0,1)]*mat.cont[EXM_aim(mat.glm,1,0)]; assert(den!=0.0); matinv->cont[EXM_aim(matinv->glm,0,0)]=mat.cont[EXM_aim(mat.glm,1,1)]/den; matinv->cont[EXM_aim(matinv->glm,0,1)]=-mat.cont[EXM_aim(mat.glm,0,1)]/den; matinv->cont[EXM_aim(matinv->glm,1,0)]=-mat.cont[EXM_aim(mat.glm,1,0)]/den; matinv->cont[EXM_aim(matinv->glm,1,1)]=mat.cont[EXM_aim(mat.glm,0,0)]/den; } if (mat.glm.numrow==3){ den=mat.cont[EXM_aim(mat.glm,0,0)]*mat.cont[EXM_aim(mat.glm,1,1)]*mat.cont[EXM_aim(mat.glm,2,2)] -mat.cont[EXM_aim(mat.glm,0,0)]*mat.cont[EXM_aim(mat.glm,1,2)]*mat.cont[EXM_aim(mat.glm,2,1)] -mat.cont[EXM_aim(mat.glm,1,0)]*mat.cont[EXM_aim(mat.glm,0,1)]*mat.cont[EXM_aim(mat.glm,2,2)] +mat.cont[EXM_aim(mat.glm,1,0)]*mat.cont[EXM_aim(mat.glm,0,2)]*mat.cont[EXM_aim(mat.glm,2,1)] +mat.cont[EXM_aim(mat.glm,2,0)]*mat.cont[EXM_aim(mat.glm,0,1)]*mat.cont[EXM_aim(mat.glm,1,2)] -mat.cont[EXM_aim(mat.glm,2,0)]*mat.cont[EXM_aim(mat.glm,0,2)]*mat.cont[EXM_aim(mat.glm,1,1)]; assert(den!=0.0); matinv->cont[EXM_aim(mat.glm,0,0)]=(mat.cont[EXM_aim(mat.glm,1,1)]*mat.cont[EXM_aim(mat.glm,2,2)]-mat.cont[EXM_aim(mat.glm,1,2)]*mat.cont[EXM_aim(mat.glm,2,1)])/den; matinv->cont[EXM_aim(mat.glm,0,1)]=(mat.cont[EXM_aim(mat.glm,2,1)]*mat.cont[EXM_aim(mat.glm,0,2)]-mat.cont[EXM_aim(mat.glm,2,2)]*mat.cont[EXM_aim(mat.glm,0,1)])/den; matinv->cont[EXM_aim(mat.glm,0,2)]=(mat.cont[EXM_aim(mat.glm,0,1)]*mat.cont[EXM_aim(mat.glm,1,2)]-mat.cont[EXM_aim(mat.glm,0,2)]*mat.cont[EXM_aim(mat.glm,1,1)])/den; matinv->cont[EXM_aim(mat.glm,1,0)]=(mat.cont[EXM_aim(mat.glm,1,2)]*mat.cont[EXM_aim(mat.glm,2,0)]-mat.cont[EXM_aim(mat.glm,1,0)]*mat.cont[EXM_aim(mat.glm,2,2)])/den; matinv->cont[EXM_aim(mat.glm,1,1)]=(mat.cont[EXM_aim(mat.glm,2,2)]*mat.cont[EXM_aim(mat.glm,0,0)]-mat.cont[EXM_aim(mat.glm,2,0)]*mat.cont[EXM_aim(mat.glm,0,2)])/den; matinv->cont[EXM_aim(mat.glm,1,2)]=(mat.cont[EXM_aim(mat.glm,0,2)]*mat.cont[EXM_aim(mat.glm,1,0)]-mat.cont[EXM_aim(mat.glm,0,0)]*mat.cont[EXM_aim(mat.glm,1,2)])/den; matinv->cont[EXM_aim(mat.glm,2,0)]=(mat.cont[EXM_aim(mat.glm,1,0)]*mat.cont[EXM_aim(mat.glm,2,1)]-mat.cont[EXM_aim(mat.glm,1,1)]*mat.cont[EXM_aim(mat.glm,2,0)])/den; matinv->cont[EXM_aim(mat.glm,2,1)]=(mat.cont[EXM_aim(mat.glm,2,0)]*mat.cont[EXM_aim(mat.glm,0,1)]-mat.cont[EXM_aim(mat.glm,2,1)]*mat.cont[EXM_aim(mat.glm,0,0)])/den; matinv->cont[EXM_aim(mat.glm,2,2)]=(mat.cont[EXM_aim(mat.glm,0,0)]*mat.cont[EXM_aim(mat.glm,1,1)]-mat.cont[EXM_aim(mat.glm,0,1)]*mat.cont[EXM_aim(mat.glm,1,0)])/den; } } else { printf("mat.contrix cannot be inverted\n"); printf("number of rows not equal to number of columns \n"); } } double rad(double angle){ double tmp; tmp=angle*pi/180.0e0; return(tmp); } double deg(double angle){ double tmp; tmp=angle/pi*180.0e0; return(tmp); } /* find orthogonal vector to the three points pa, pb and pc in the xyz frame of reference */ void EXM_find_orthogonal_vector(EXM_vec3D_t pa, EXM_vec3D_t pb, EXM_vec3D_t pc, EXM_vec3D_t orthovect){ EXM_vec3D_t dp1,dp2; long cnt; for (cnt=0; cnt<3; cnt++){ dp1[cnt]=pa[cnt]-pc[cnt]; dp2[cnt]=pb[cnt]-pc[cnt]; } orthovect[0]=dp1[1]*dp2[2]-dp1[2]*dp2[1]; orthovect[1]=dp1[2]*dp2[0]-dp1[0]*dp2[2]; orthovect[2]=dp1[0]*dp2[1]-dp1[1]*dp2[0]; } /* find plane A*x+B*y+C*z=D from orthogonal vector and one point on plane p0 */ void EXM_find_plane(EXM_vec3D_t orthovect, EXM_vec3D_t p0, double *A, double *B, double *C, double *D){ *A=orthovect[0]; *B=orthovect[1]; *C=orthovect[2]; *D=(*A)*p0[0]+(*B)*p0[1]+(*C)*p0[2]; } /* find pp, a point on the plane A-B-C-D which also lies on the line composed of vect and p0 */ void EXM_find_point_in_plane_on_vector(EXM_vec3D_t vect, EXM_vec3D_t p0, double A, double B, double C, double D, EXM_vec3D_t pp){ double t; long cnt; assert(A*vect[0]+B*vect[1]+C*vect[2]!=0.0e0); t=(D-A*p0[0]-B*p0[1]-C*p0[2])/(A*vect[0]+B*vect[1]+C*vect[2]); for (cnt=0; cnt<3; cnt++) pp[cnt]=p0[cnt]+vect[cnt]*t; } /* the plane is defined by points pa,pb and pc while the point to be mirrored is pp_o. The mirrored point is pp_m; pp_p is the point on the plane nearest to pp_o, midway between pp_o and pp_m */ void EXM_mirror_point_wrt_plane(EXM_vec3D_t pa, EXM_vec3D_t pb, EXM_vec3D_t pc, EXM_vec3D_t pp_o, EXM_vec3D_t pp_m){ EXM_vec3D_t orthovect; double A,B,C,D; EXM_vec3D_t pp_p; long cnt; EXM_find_orthogonal_vector(pa,pb,pc,orthovect); EXM_find_plane(orthovect, pa, &A, &B, &C, &D); EXM_find_point_in_plane_on_vector(orthovect, pp_o, A, B, C, D, pp_p); for (cnt=0; cnt<3; cnt++) pp_m[cnt]=2.0e0*pp_p[cnt]-pp_o[cnt]; } void EXM_display_vector(EXM_vec3D_t pp){ printf("x=%E y=%E z=%E \n",pp[0],pp[1],pp[2]); } double EXM_dot_product(EXM_vec3D_t vec1, EXM_vec3D_t vec2){ double sum; long dim; sum=0.0e0; for (dim=0; dim<3; dim++){ sum=sum+vec1[dim]*vec2[dim]; } return(sum); } void EXM_cross_product(EXM_vec3D_t vec1, EXM_vec3D_t vec2, EXM_vec3D_t prod){ prod[0]=vec1[1]*vec2[2]-vec1[2]*vec2[1]; prod[1]=vec1[2]*vec2[0]-vec1[0]*vec2[2]; prod[2]=vec1[0]*vec2[1]-vec1[1]*vec2[0]; } double EXM_vector_magnitude(EXM_vec3D_t vec){ long dim; double sum; sum=0.0e0; for (dim=0; dim<3; dim++){ sum=sum+vec[dim]*vec[dim]; } sum=sqrt(sum); return(sum); } double EXM_angle_between_vectors(EXM_vec3D_t vec1, EXM_vec3D_t vec2){ double theta; theta=acos(EXM_dot_product(vec1,vec2)/EXM_vector_magnitude(vec1)/EXM_vector_magnitude(vec2)); return(theta); } double EXM_area_quadrilateral(EXM_vec3D_t A, EXM_vec3D_t B, EXM_vec3D_t C, EXM_vec3D_t D){ EXM_vec3D_t x,y,z; double theta,phi,area; long dim; for (dim=0; dim<3; dim++){ x[dim]=A[dim]-B[dim]; y[dim]=C[dim]-B[dim]; z[dim]=D[dim]-B[dim]; } theta=EXM_angle_between_vectors(y,z); phi=EXM_angle_between_vectors(x,y); area=0.5e0*EXM_vector_magnitude(y)*(EXM_vector_magnitude(z)*fabs(sin(theta))+EXM_vector_magnitude(x)*fabs(sin(phi))); return(area); } /* numerically differentiate FUNCT (which returns dx/dt) from t1 to t2, starting from x1, and returning x2 */ double EXM_numerical_differentiation(double(*FUNCT)(void *, double, double), void *arg_ptr, long METHOD, long n, double x1, double t1, double t2, long *error){ double x,dt,t; double x_1,x_2,x_3; long cnt; *error=0; dt=(t2-t1)/(double)n; x=x1; t=t1; if (METHOD==EXM_NUMDIFF_FORWARDEULER) for (cnt=0; cnt<n; cnt++) { x+=dt*(*FUNCT)(arg_ptr,x,t); t+=dt; } if (METHOD==EXM_NUMDIFF_RUNGEKUTTA) for (cnt=0; cnt<n; cnt++) { x_1=x+0.5*dt*(*FUNCT)(arg_ptr,x,t); x_2=x+0.5*dt*(*FUNCT)(arg_ptr,x_1,t+0.5*dt); x_3=x+dt*(*FUNCT)(arg_ptr,x_2,t+0.5*dt); x+=(x_1-x)/3.0 +(x_2-x)*2.0/3.0 +(x_3-x)/3.0 +dt/6.0*(*FUNCT)(arg_ptr,x_2,t+dt); t+=dt; } if (METHOD==EXM_NUMDIFF_IMPROVEDEULER) for (cnt=0; cnt<n; cnt++) { x+=0.5*dt*(*FUNCT)(arg_ptr,x,t) +0.5*dt*(*FUNCT)(arg_ptr,x+dt*(*FUNCT)(arg_ptr,x,t),t+dt); t+=dt; } if (METHOD==EXM_NUMDIFF_MODIFIEDEULER) for (cnt=0; cnt<n; cnt++) { x+=dt*(*FUNCT)(arg_ptr,x+0.5e0*dt*(*FUNCT)(arg_ptr,x,t),t+dt*0.5); t+=dt; } return(x); } double EXM_numerical_integration(double(*FUNCT)(void *, double), void *arg_ptr, long METHOD, long n, double x1, double x2, long *error){ double f,f1,f2,f3,x,sum,dx; sum=0.0; *error=0; dx=(x2-x1)/(double)n; if (METHOD==EXM_NUMINTEG_RECTANGLES) { sum=0.0e0; for (x=x1+dx*0.5e0; x<x2; x+=dx){ f=(*FUNCT)(arg_ptr,x); sum+=f*dx; } } if (METHOD==EXM_NUMINTEG_POLY2) { /* integrate using second degree polynomials */ f1=(*FUNCT)(arg_ptr,x1); f2=(*FUNCT)(arg_ptr,x1+dx); f3=(*FUNCT)(arg_ptr,x1+2.0*dx); sum=dx*(27.0/24.0*f2+9.0/24.0*f1); for (x=x1+2.0*dx; x<x2-1.5*dx; x+=dx){ f1=f2; f2=f3; f3=(*FUNCT)(arg_ptr,x+dx); sum+=dx*(f1/24.0+11.0/12.0*f2+f3/24.0); } f1=f2; f2=f3; f3=(*FUNCT)(arg_ptr,x2); sum+=dx*(27.0/24.0*f2+9.0/24.0*f3); } return(sum); } /* numerically integrate the function FUNCT(x) between x=x1 and x=x2, returning the value of the integral */ void EXM_numerical_integration_vector(void(*FUNCT)(void *, double, EXM_vec3D_t vector), void *arg_ptr, long METHOD, long n, double x1, double x2, long *error, EXM_vec3D_t sum){ double x,dx; long dim; EXM_vec3D_t f,f1,f2,f3; for (dim=0; dim<3; dim++) sum[dim]=0.0; *error=0; dx=(x2-x1)/(double)n; if (METHOD==EXM_NUMINTEG_RECTANGLES) { for (dim=0; dim<3; dim++) sum[dim]=0.0; for (x=x1+dx*0.5e0; x<x2; x+=dx){ (*FUNCT)(arg_ptr,x,f); for (dim=0; dim<3; dim++) sum[dim]+=f[dim]*dx; } } if (METHOD==EXM_NUMINTEG_POLY2) { /* integrate using second degree polynomials */ (*FUNCT)(arg_ptr,x1,f1); (*FUNCT)(arg_ptr,x1+dx,f2); (*FUNCT)(arg_ptr,x1+2.0*dx,f3); for (dim=0; dim<3; dim++) sum[dim]=dx*(27.0/24.0*f2[dim]+9.0/24.0*f1[dim]); for (x=x1+2.0*dx; x<x2-1.5*dx; x+=dx){ for (dim=0; dim<3; dim++) { f1[dim]=f2[dim]; f2[dim]=f3[dim]; } (*FUNCT)(arg_ptr,x+dx,f3); for (dim=0; dim<3; dim++) sum[dim]+=dx*(f1[dim]/24.0+11.0/12.0*f2[dim]+f3[dim]/24.0); } for (dim=0; dim<3; dim++){ f1[dim]=f2[dim]; f2[dim]=f3[dim]; } (*FUNCT)(arg_ptr,x2,f3); for (dim=0; dim<3; dim++) sum[dim]+=dx*(27.0/24.0*f2[dim]+9.0/24.0*f3[dim]); } } /* find b at each node given f and x on all nodes from i=0 to i=N-1 note: *b must have been malloced and given enough memory space prior to calling this function*/ void EXM_find_spline(long N, double *x, double *f, double *b){ EXM_pdmaline_t *pdma; double dxim1,dxip0,dfim1,dfip0; long n; pdma=(EXM_pdmaline_t *)malloc(N*sizeof(EXM_pdmaline_t)); /* do inner nodes first */ for (n=1; n<N-1; n++){ dxim1=x[n]-x[n-1]; dxip0=x[n+1]-x[n]; dfim1=f[n]-f[n-1]; dfip0=f[n+1]-f[n]; pdma[n].val[0]=0.0; pdma[n].val[1]=dxim1; pdma[n].val[2]=2.0*(dxim1+dxip0); pdma[n].val[3]=dxip0; pdma[n].val[4]=0.0; assert(dxip0!=0.0); assert(dxim1!=0.0); pdma[n].val[5]=3.0*(dfip0/dxip0-dfim1/dxim1); } /* do left bdry node */ pdma[0].val[0]=0.0; pdma[0].val[1]=0.0; pdma[0].val[2]=-(x[2]-x[1]); pdma[0].val[3]=(x[1]-x[0])+(x[2]-x[1]); pdma[0].val[4]=-(x[1]-x[0]); pdma[0].val[5]=0.0; /* do right bdry node */ pdma[N-1].val[0]=-(x[N-1]-x[N-2]); pdma[N-1].val[1]=(x[N-2]-x[N-3])+(x[N-1]-x[N-2]); pdma[N-1].val[2]=-(x[N-2]-x[N-3]); pdma[N-1].val[3]=0.0; pdma[N-1].val[4]=0.0; pdma[N-1].val[5]=0.0; EXM_solve_PDMA(pdma, N); for (n=0; n<N; n++) { assert(pdma[n].val[2]!=0.0); b[n]=pdma[n].val[5]/pdma[n].val[2]; } } /* returns f at thisx given x,f,b at each data point */ double EXM_f_from_spline(long N, double *x, double *f, double *b, double thisx){ long i; double thisf,di,ci,bi,ai,dxi; /* first find i that is such that x[i]<=thisx<=x[i+1] */ i=-1; do { i++; } while(i<(N-1) && !(x[i]<=thisx && x[i+1]>=thisx)); if (i>=N-1){ EXM_fatal_error("Couldn't find an interval for x=%E in EXM_f_from_spline.",thisx); } assert(i<N-1); dxi=x[i+1]-x[i]; ai=(b[i+1]-b[i])/(3.0*dxi); bi=b[i]; ci=(f[i+1]-f[i])/dxi-b[i]*dxi-(b[i+1]-b[i])/3.0*dxi; di=f[i]; thisf=ai*(thisx-x[i])*(thisx-x[i])*(thisx-x[i])+bi*(thisx-x[i])*(thisx-x[i])+ci*(thisx-x[i])+di; return(thisf); } #define EOS 0 /* insert str1 into str2 at the position pos; make sure *str2 has enough memory allocated */ char *strins(char *str1, char *str2, long pos){ long len1,len2,i; len1=(long)strlen(str1); len2=(long)strlen(str2); for (i=len2; i>=pos; i--) (str2)[i+len1]=(str2)[i]; for (i=0; i<len1; i++) (str2)[pos+i]=str1[i]; (str2)[len2+len1]=EOS; return str2; } /* add line breaks without breaking words with width the maximum number of characters per line */ char *strwrp(char *str, int width){ long cnt,cntbreak; bool CONTINUE; CONTINUE=TRUE; cntbreak=0; cnt=0; do { cnt++; if (str[cnt]=='\n') cntbreak=cnt; if (cnt-cntbreak>width){ cntbreak=cnt; do { cntbreak--; } while(str[cntbreak]!=' ' && str[cntbreak]!='-' && cntbreak>0); if (cntbreak>0){ if (str[cntbreak]=='-') { strins("\n",str,cntbreak+1); cntbreak++; } str[cntbreak]='\n'; cnt+=1; } else { // problem breaking line.. CONTINUE=FALSE; } } } while (CONTINUE && cnt<strlen(str)-1); return str; } char *strrep(char *str, char *orig, char *repl) { char *p; char *strtmp; strtmp=(char *)malloc(sizeof(char)*(strlen(str)+strlen(repl)+2)); if(!(p = strstr(str, orig))) return str; strncpy(strtmp, str, p-str); strtmp[p-str] = EOS; sprintf(strtmp+(p-str), "%s%s", repl, p+strlen(orig)); strcpy(str,strtmp); free(strtmp); return str; } /* add indent spaces to second and subsequent lines; make sure str has enough memory allocated */ char *strind(char *str, int indent){ long cnt,cnt2; static char whitespace[2]; strcpy(whitespace," "); if (indent<0){ /* hang indent */ cnt=0; do { cnt++; if (str[cnt]=='\n' && str[cnt+1]!=EOS) { for (cnt2=0; cnt2<(-indent); cnt2++) strins(whitespace,str,cnt+1); cnt-=indent; } } while (str[cnt]!=EOS); } else { /* indent */ for (cnt=0; cnt<indent; cnt++) strins(whitespace,str,0); } return str; } /* add line breaks without breaking words with width the maximum number of characters per line and indent the number of indented characters (either negative or positive) */ char *strwrpind(char *str, int width, int indent){ long cnt,cnt2,cntbreak; bool CONTINUE; static char whitespace[2]; strcpy(whitespace," "); if (indent>0){ for (cnt=0; cnt<indent; cnt++) strins(whitespace,str,0); } CONTINUE=TRUE; cntbreak=0; cnt=0; do { cnt++; if (str[cnt]=='\n') cntbreak=cnt; if (cnt-cntbreak>width-1){ cntbreak=cnt; do { cntbreak--; } while(str[cntbreak]!=' ' && str[cntbreak]!='-' && cntbreak>0); if (cntbreak>0){ if (str[cntbreak]=='-') { strins("\n",str,cntbreak+1); cntbreak++; } str[cntbreak]='\n'; cnt++; if (indent<0){ // do the hang indent here for (cnt2=0; cnt2<-indent; cnt2++){ strins(whitespace,str,cntbreak+1); } } } else { // problem breaking line.. CONTINUE=FALSE; } } } while (CONTINUE && cnt<strlen(str)-1); return str; } void find_terminal_window_size(int *width, int *height){ struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); *width=w.ws_col; *height=w.ws_row; } double avg_harmonic(double arg1, double arg2){ double ret; if (arg1==0.0) EXM_fatal_error("Problem: arg1 is zero in avg_harmonic()."); if (arg2==0.0) EXM_fatal_error("Problem: arg2 is zero in avg_harmonic()."); if (arg1<0.0) EXM_fatal_error("Problem: arg1 is negative in avg_harmonic()."); if (arg2<0.0) EXM_fatal_error("Problem: arg2 is negative in avg_harmonic()."); ret=2.0/(1.0/arg1+1.0/arg2); return(ret); } static int argrank(int argc, char **argv, char *arg){ int cnt,tmp; bool FOUND; tmp=0; FOUND=FALSE; for (cnt=1; cnt<argc; cnt++){ if (strcmp(argv[cnt],arg) == 0) { tmp=cnt; if (!FOUND) FOUND=TRUE; else EXM_fatal_error("The flag %s can not be called twice.",arg); } } return(tmp); } int process_flag_string(int argc, char **argv, char *flag, char **arg){ int RET; int flagrank; flagrank=argrank(argc,argv,flag); if (flagrank!=0) { if (argc<=flagrank+1) EXM_fatal_error("Missing argument after flag %s.",flag); *arg=(char *)realloc(*arg,(2+(long)strlen(argv[flagrank+1]))*sizeof(char)); strcpy(*arg,argv[flagrank+1]); strcpy(argv[flagrank+0],"\0"); strcpy(argv[flagrank+1],"\0"); RET=2; } else { RET=0; } return(RET); } int process_flag_int(int argc, char **argv, char *flag, int *arg){ int RET; int flagrank; int eos=EOS; flagrank=argrank(argc,argv,flag); if (flagrank!=0) { if (argc<=flagrank+1) EXM_fatal_error("Missing argument after flag %s.",flag); if (sscanf(argv[flagrank+1], "%d%n", arg,&eos)!=1 || argv[flagrank+1][eos]!=EOS) { EXM_fatal_error("Expecting integer argument after %s flag.",flag); } strcpy(argv[flagrank+0],"\0"); strcpy(argv[flagrank+1],"\0"); RET=2; } else { RET=0; } return(RET); } int process_flag_double(int argc, char **argv, char *flag, double *arg){ int RET; int flagrank; int eos=EOS; flagrank=argrank(argc,argv,flag); if (flagrank!=0) { if (argc<=flagrank+1) EXM_fatal_error("Missing argument after flag %s.",flag); if (sscanf(argv[flagrank+1], "%lf%n", arg,&eos)!=1 || argv[flagrank+1][eos]!=EOS) { EXM_fatal_error("Expecting integer argument after %s flag.",flag); } strcpy(argv[flagrank+0],"\0"); strcpy(argv[flagrank+1],"\0"); RET=2; } else { RET=0; } return(RET); } int process_flag_int_multiple(int argc, char **argv, char *flag, int **arg){ int RET,cnt; int flagrank; int eos=EOS; bool CONTINUE; flagrank=argrank(argc,argv,flag); if (flagrank!=0) { if (argc<=flagrank+1) EXM_fatal_error("Missing argument after flag %s.",flag); cnt=0; CONTINUE=TRUE; do { cnt++; *arg=(int *)realloc(*arg,(cnt+2)*sizeof(int)); if ((flagrank+cnt)>=argc || sscanf(argv[flagrank+cnt], "%d%n", &((*arg)[cnt-1]),&eos)!=1 || argv[flagrank+cnt][eos]!=EOS) CONTINUE=FALSE; else CONTINUE=TRUE; } while(CONTINUE); RET=cnt; for (cnt=0; cnt<RET; cnt++) strcpy(argv[flagrank+cnt],"\0"); } else { RET=0; } return(RET); } int process_flag_double_multiple(int argc, char **argv, char *flag, double **arg){ int RET,cnt; int flagrank; bool CONTINUE; flagrank=argrank(argc,argv,flag); if (flagrank!=0) { if (argc<=flagrank+1) EXM_fatal_error("Missing argument after flag %s.",flag); cnt=0; CONTINUE=TRUE; do { cnt++; *arg=(double *)realloc(*arg,(cnt+2)*sizeof(double)); if ((flagrank+cnt)>=argc || sscanf(argv[flagrank+cnt], "%lg", &((*arg)[cnt-1]))!=1) CONTINUE=FALSE; else CONTINUE=TRUE; } while(CONTINUE); RET=cnt; for (cnt=0; cnt<RET; cnt++) strcpy(argv[flagrank+cnt],"\0"); } else { RET=0; } return(RET); } int process_flag(int argc, char **argv, char *flag){ int RET; int flagrank; flagrank=argrank(argc,argv,flag); if (flagrank!=0) { strcpy(argv[flagrank],"\0"); RET=1; } else { RET=0; } return(RET); } int find_remaining_options(int argc, char **argv, char **options){ long cnt; int RET; RET=0; *options=(char *)realloc(*options,sizeof(char)); (*options)[0]=EOS; /* start cnt at 1 to exclude the executable */ for (cnt=1; cnt<argc; cnt++){ if ((argv[cnt])[0]!='\0'){ RET++; *options=(char *)realloc(*options,(2+strlen(*options)+strlen(argv[cnt]))*sizeof(char)); strcat(*options,argv[cnt]); strcat(*options," "); } } return(RET); } double min3(double val1, double val2, double val3){ return(min(val1,min(val2,val3))); } double max3(double val1, double val2, double val3){ return(max(val1,max(val2,val3))); } double notzero(double val, double sub){ if (val==0.0) val=sub; return(val); } double minmod(double x, double y){ double tmp; tmp=sign(x)*max(0.0e0,min(fabs(x),sign(x)*y)); return(tmp); } double minmod_old(double val1, double val2){ double ret; if (fabs(val1)>fabs(val2)) ret=val2; else ret=val1; if (val1*val2<0.0) ret=0.0; return(ret); } double minmod3(double x, double y, double z){ double tmp; tmp=sign(x)*max(0.0e0,min(sign(x)*z,min(fabs(x),sign(x)*y))); return(tmp); } double maxmag(double x, double y){ double ret; if (fabs(x)>fabs(y)) ret=x; else ret=y; return(ret); }
GB_unop__identity_fc64_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_fc64_uint64) // op(A') function: GB (_unop_tran__identity_fc64_uint64) // C type: GxB_FC64_t // A type: uint64_t // cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0) // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \ 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_FC64 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fc64_uint64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const uint64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // 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 (uint64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; 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] ; GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fc64_uint64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
fci_contract_nosym.c
/* * Paticle permutation symmetry for 2e Hamiltonian only * h2e[i,j,k,l] == h2e[k,l,i,j] * h2e[i,j,k,l] =/= h2e[j,i,k,l] =/= h2e[i,j,l,k] ... */ #include <stdlib.h> #include <string.h> //#include <omp.h> #include "config.h" #include "vhf/fblas.h" #include "fci.h" #define MIN(X,Y) ((X)<(Y)?(X):(Y)) #define CSUMTHR 1e-28 #define STRB_BLKSIZE 112 double FCI_t1ci_sf(double *ci0, double *t1, int bcount, int stra_id, int strb_id, int norb, int na, int nb, int nlinka, int nlinkb, _LinkT *clink_indexa, _LinkT *clink_indexb); void FCIcontract_a_1e_nosym(double *h1e, double *ci0, double *ci1, int norb, int nstra, int nstrb, int nlinka, int nlinkb, int *link_indexa, int *link_indexb) { int j, k, i, a, sign; size_t str0, str1; double *pci0, *pci1; double tmp; _LinkT *tab; _LinkT *clink = malloc(sizeof(_LinkT) * nlinka * nstra); FCIcompress_link(clink, link_indexa, norb, nstra, nlinka); for (str0 = 0; str0 < nstra; str0++) { tab = clink + str0 * nlinka; for (j = 0; j < nlinka; j++) { a = EXTRACT_CRE (tab[j]); // propagate from t1 to bra, through a^+ i i = EXTRACT_DES (tab[j]); str1 = EXTRACT_ADDR(tab[j]); sign = EXTRACT_SIGN(tab[j]); pci0 = ci0 + str0 * nstrb; pci1 = ci1 + str1 * nstrb; tmp = sign * h1e[a*norb+i]; for (k = 0; k < nstrb; k++) { pci1[k] += tmp * pci0[k]; } } } free(clink); } void FCIcontract_b_1e_nosym(double *h1e, double *ci0, double *ci1, int norb, int nstra, int nstrb, int nlinka, int nlinkb, int *link_indexa, int *link_indexb) { int j, k, i, a, sign; size_t str0, str1; double *pci1; double tmp; _LinkT *tab; _LinkT *clink = malloc(sizeof(_LinkT) * nlinkb * nstrb); FCIcompress_link(clink, link_indexb, norb, nstrb, nlinkb); for (str0 = 0; str0 < nstra; str0++) { pci1 = ci1 + str0 * nstrb; for (k = 0; k < nstrb; k++) { tab = clink + k * nlinkb; tmp = ci0[str0*nstrb+k]; for (j = 0; j < nlinkb; j++) { a = EXTRACT_CRE (tab[j]); i = EXTRACT_DES (tab[j]); str1 = EXTRACT_ADDR(tab[j]); sign = EXTRACT_SIGN(tab[j]); pci1[str1] += sign * tmp * h1e[a*norb+i]; } } } free(clink); } static void spread_a_t1(double *ci1, double *t1, int bcount, int stra_id, int strb_id, int norb, int nstrb, int nlinka, _LinkT *clink_indexa) { ci1 += strb_id; const int nnorb = norb * norb; int j, k, i, a, str1, sign; const _LinkT *tab = clink_indexa + stra_id * nlinka; double *cp0, *cp1; for (j = 0; j < nlinka; j++) { a = EXTRACT_CRE (tab[j]); i = EXTRACT_DES (tab[j]); str1 = EXTRACT_ADDR(tab[j]); sign = EXTRACT_SIGN(tab[j]); cp0 = t1 + a*norb+i; // propagate from t1 to bra, through a^+ i cp1 = ci1 + str1*(size_t)nstrb; if (sign > 0) { for (k = 0; k < bcount; k++) { cp1[k] += cp0[k*nnorb]; } } else { for (k = 0; k < bcount; k++) { cp1[k] -= cp0[k*nnorb]; } } } } static void spread_b_t1(double *ci1, double *t1, int bcount, int stra_id, int strb_id, int norb, int nstrb, int nlinkb, _LinkT *clink_indexb) { const int nnorb = norb * norb; int j, i, a, str0, str1, sign; const _LinkT *tab = clink_indexb + strb_id * nlinkb; double *pci = ci1 + stra_id * (size_t)nstrb; for (str0 = 0; str0 < bcount; str0++) { for (j = 0; j < nlinkb; j++) { a = EXTRACT_CRE (tab[j]); i = EXTRACT_DES (tab[j]); str1 = EXTRACT_ADDR(tab[j]); sign = EXTRACT_SIGN(tab[j]); // propagate from t1 to bra, through a^+ i pci[str1] += sign * t1[a*norb+i]; } t1 += nnorb; tab += nlinkb; } } static void ctr_rhf2e_kern(double *eri, double *ci0, double *ci1, double *ci1buf, double *t1buf, int bcount_for_spread_a, int ncol_ci1buf, int bcount, int stra_id, int strb_id, int norb, int na, int nb, int nlinka, int nlinkb, _LinkT *clink_indexa, _LinkT *clink_indexb) { const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; const int nnorb = norb * norb; double *t1 = t1buf; double *vt1 = t1buf + nnorb*bcount; double csum; csum = FCI_t1ci_sf(ci0, t1, bcount, stra_id, strb_id, norb, na, nb, nlinka, nlinkb, clink_indexa, clink_indexb); if (csum > CSUMTHR) { dgemm_(&TRANS_N, &TRANS_N, &nnorb, &bcount, &nnorb, &D1, eri, &nnorb, t1, &nnorb, &D0, vt1, &nnorb); spread_b_t1(ci1, vt1, bcount, stra_id, strb_id, norb, nb, nlinkb, clink_indexb); spread_a_t1(ci1buf, vt1, bcount_for_spread_a, stra_id, 0, norb, ncol_ci1buf, nlinka, clink_indexa); } } static void axpy2d(double *out, double *in, int count, int no, int ni) { int i, j; for (i = 0; i < count; i++) { for (j = 0; j < ni; j++) { out[i*no+j] += in[i*ni+j]; } } } void FCIcontract_2es1(double *eri, double *ci0, double *ci1, int norb, int na, int nb, int nlinka, int nlinkb, int *link_indexa, int *link_indexb) { _LinkT *clinka = malloc(sizeof(_LinkT) * nlinka * na); _LinkT *clinkb = malloc(sizeof(_LinkT) * nlinkb * nb); FCIcompress_link(clinka, link_indexa, norb, na, nlinka); FCIcompress_link(clinkb, link_indexb, norb, nb, nlinkb); memset(ci1, 0, sizeof(double)*na*nb); #pragma omp parallel default(none) \ shared(eri, ci0, ci1, norb, na, nb, nlinka, nlinkb, \ clinka, clinkb) { int strk, ib, blen; double *t1buf = malloc(sizeof(double) * STRB_BLKSIZE*norb*norb*2); double *ci1buf = malloc(sizeof(double) * na*STRB_BLKSIZE); for (ib = 0; ib < nb; ib += STRB_BLKSIZE) { blen = MIN(STRB_BLKSIZE, nb-ib); memset(ci1buf, 0, sizeof(double) * na*blen); #pragma omp for schedule(static) for (strk = 0; strk < na; strk++) { ctr_rhf2e_kern(eri, ci0, ci1, ci1buf, t1buf, blen, blen, blen, strk, ib, norb, na, nb, nlinka, nlinkb, clinka, clinkb); } #pragma omp critical axpy2d(ci1+ib, ci1buf, na, nb, blen); } free(ci1buf); free(t1buf); } free(clinka); free(clinkb); }
transfer.c
#include <math.h> #include <stdlib.h> #include <fastpm/libfastpm.h> #include <fastpm/logging.h> #include "pmpfft.h" void fastpm_apply_smoothing_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, double sml) { #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); int d; int i; double *kernel[3]; for(d = 0; d < 3; d ++) { kernel[d] = malloc(sizeof(double) * pm->Nmesh[d]); for(i = 0; i < pm->Nmesh[d]; i ++) { double kk = kiter.kk[d][i]; kernel[d][i] = exp(- 0.5 * kk * sml * sml); } } for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { int dir; double smth = 1.0; for(dir = 0; dir < 3; dir++) smth *= kernel[dir][kiter.iabs[dir]]; to[kiter.ind + 0] = from[kiter.ind + 0] * smth; to[kiter.ind + 1] = from[kiter.ind + 1] * smth; } for(d = 0; d < 3; d ++) { free(kernel[d]); } } } void fastpm_apply_lowpass_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, double kth) { double kth2 = kth * kth; #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { int dir; double smth = 1.0; double kk = 0; for(dir = 0; dir < 3; dir++) { kk += kiter.kk[dir][kiter.iabs[dir]]; } if(kk < kth2) smth = 1; else smth = 0; to[kiter.ind + 0] = from[kiter.ind + 0] * smth; to[kiter.ind + 1] = from[kiter.ind + 1] * smth; } } } static double sinc_unnormed(double x) { if(x < 1e-5 && x > -1e-5) { double x2 = x * x; return 1.0 - x2 / 6. + x2 * x2 / 120.; } else { return sin(x) / x; } } void fastpm_apply_decic_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to) { #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); int d; int i; double *kernel[3]; for(d = 0; d < 3; d ++) { kernel[d] = malloc(sizeof(double) * pm->Nmesh[d]); for(i = 0; i < pm->Nmesh[d]; i ++) { double w = kiter.k[d][i] * pm->BoxSize[d] / pm->Nmesh[d]; double cic = sinc_unnormed(0.5 * w); /* Watchout: this does divide by sinc, not sinc 2, */ kernel[d][i] = 1.0 / pow(cic, 2); } } for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { int dir; double smth = 1.0; for(dir = 0; dir < 3; dir++) smth *= kernel[dir][kiter.iabs[dir]]; /* - i k[d] */ to[kiter.ind + 0] = from[kiter.ind + 0] * smth; to[kiter.ind + 1] = from[kiter.ind + 1] * smth; } for(d = 0; d < 3; d ++) { free(kernel[d]); } } } void fastpm_apply_diff_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, int dir) { ptrdiff_t * Nmesh = pm_nmesh(pm); #pragma omp parallel { PMKIter kiter; for(pm_kiter_init(pm, &kiter); !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { double k_finite = kiter.k_finite[dir][kiter.iabs[dir]]; /* i k[d] */ if( kiter.iabs[0] == (Nmesh[0] - kiter.iabs[0]) % Nmesh[0] && kiter.iabs[1] == (Nmesh[1] - kiter.iabs[1]) % Nmesh[1] && kiter.iabs[2] == (Nmesh[2] - kiter.iabs[2]) % Nmesh[2] ) { /* We are at the nyquist and the diff operator shall be zero; * otherwise the force is not real! */ to[kiter.ind + 0] = 0; to[kiter.ind + 1] = 0; } { FastPMFloat tmp[2]; tmp[0] = - from[kiter.ind + 1] * (k_finite); tmp[1] = from[kiter.ind + 0] * (k_finite); to[kiter.ind + 0] = tmp[0]; to[kiter.ind + 1] = tmp[1]; } } } } void fastpm_apply_laplace_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, int order) { /* order = 0: 1 / kk gives an IC that agrees with linear theory better * at intermidiate scales (desi-cosmosim email archives). * than * order = 1: 1 / sinc(kk) used in original FastPM; * */ #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); float ** kklist [3] = {kiter.kk, kiter.kk_finite, kiter.kk_finite2}; for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { int d; double kk_finite = 0; for(d = 0; d < 3; d++) { kk_finite += kklist[order][d][kiter.iabs[d]]; } ptrdiff_t ind = kiter.ind; /* 1 / k2 */ if(LIKELY(kk_finite != 0)) { to[ind + 0] = from[ind + 0] * (1 / kk_finite); to[ind + 1] = from[ind + 1] * (1 / kk_finite); } else { to[ind + 0] = 0; to[ind + 1] = 0; } } } } void fastpm_apply_any_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, fastpm_fkfunc func, void * data) { #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { int dir; double smth = 1.0; double kk = 0; for(dir = 0; dir < 3; dir++) { kk += kiter.kk[dir][kiter.iabs[dir]]; } double k = sqrt(kk); smth = func(k, data); to[kiter.ind + 0] = from[kiter.ind + 0] * smth; to[kiter.ind + 1] = from[kiter.ind + 1] * smth; } } } void fastpm_apply_multiply_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, double value) { ptrdiff_t i; #pragma omp parallel for for(i = 0; i < pm_allocsize(pm); i ++) { to[i] = from[i] * value; } } void fastpm_apply_normalize_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to) { double Norm = 0; #pragma omp parallel reduction(+: Norm) { PMKIter kiter; pm_kiter_init(pm, &kiter); for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { int dir; double kk = 0; for(dir = 0; dir < 3; dir++) { kk += kiter.kk[dir][kiter.iabs[dir]]; } if(kk == 0) { Norm += from[kiter.ind + 0]; } } } MPI_Allreduce(MPI_IN_PLACE, &Norm, 1, MPI_DOUBLE, MPI_SUM, pm_comm(pm)); if(Norm == 0) { fastpm_raise(-1, "It makes no sense to normalize a field with a mean of zero."); } fastpm_apply_multiply_transfer(pm, from, to, 1 / Norm); } void fastpm_apply_c2r_weight_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to) { ptrdiff_t * Nmesh = pm_nmesh(pm); #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { /* usually each mode in the complex array moves its dual mode too, */ double weight = 2.0; /* but if my dual is myself, then I am used once */ if( kiter.iabs[0] == (Nmesh[0] - kiter.iabs[0]) % Nmesh[0] && kiter.iabs[1] == (Nmesh[1] - kiter.iabs[1]) % Nmesh[1] && kiter.iabs[2] == (Nmesh[2] - kiter.iabs[2]) % Nmesh[2] ) { weight = 1.0; /* fastpm_ilog(0, "weight == 1 mode found at %td %td %td\n", kiter.iabs[0], kiter.iabs[1], kiter.iabs[2]); */ } to[kiter.ind + 0] = weight * from[kiter.ind + 0]; to[kiter.ind + 1] = weight * from[kiter.ind + 1]; } } } void fastpm_apply_modify_mode_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, ptrdiff_t * mode, double value) { fastpm_apply_set_mode_transfer(pm, from, to, mode, value, 0); } /* method == 0 for override, method == 1 for add; * always use get_mode_transfer to check the result -- this doesn't guarentee setting the mode * to the value (because not all modes are free. * */ void fastpm_apply_set_mode_transfer(PM * pm, FastPMFloat * from, FastPMFloat * to, ptrdiff_t * mode, double value, int method) { ptrdiff_t * Nmesh = pm_nmesh(pm); if( mode[0] == (Nmesh[0] - mode[0]) % Nmesh[0] && mode[1] == (Nmesh[1] - mode[1]) % Nmesh[1] && mode[2] == (Nmesh[2] - mode[2]) % Nmesh[2] ) { if(mode[3] == 1) { /* These modes are purely real, thus we can not set the imag part to non-zero */ method = 0; value = 0; } } #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { to[kiter.ind + 0] = from[kiter.ind + 0]; to[kiter.ind + 1] = from[kiter.ind + 1]; if(( kiter.iabs[0] == mode[0] && kiter.iabs[1] == mode[1] && kiter.iabs[2] == mode[2] )) { if(method == 0) to[kiter.ind + mode[3]] = value; else to[kiter.ind + mode[3]] += value; } if(( kiter.iabs[0] == (Nmesh[0] - mode[0]) % Nmesh[0] && kiter.iabs[1] == (Nmesh[1] - mode[1]) % Nmesh[1] && kiter.iabs[2] == (Nmesh[2] - mode[2]) % Nmesh[2] )) { /* conjugate plane */ if(method == 0) to[kiter.ind + mode[3]] = value * ((mode[3] == 0)?1:-1); else to[kiter.ind + mode[3]] += value * ((mode[3] == 0)?1:-1); } } } } double fastpm_apply_get_mode_transfer(PM * pm, FastPMFloat * from, ptrdiff_t * mode) { double result = 0.0; #pragma omp parallel { PMKIter kiter; pm_kiter_init(pm, &kiter); for(; !pm_kiter_stop(&kiter); pm_kiter_next(&kiter)) { if(( kiter.iabs[0] == mode[0] && kiter.iabs[1] == mode[1] && kiter.iabs[2] == mode[2] )) { result = from[kiter.ind + mode[3]]; } } } MPI_Allreduce(MPI_IN_PLACE, &result, 1, MPI_DOUBLE, MPI_SUM, pm_comm(pm)); return result; }
pr38704.c
// RUN: %libomptarget-compile-run-and-check-aarch64-unknown-linux-gnu // RUN: %libomptarget-compile-run-and-check-powerpc64-ibm-linux-gnu // RUN: %libomptarget-compile-run-and-check-powerpc64le-ibm-linux-gnu // RUN: %libomptarget-compile-run-and-check-x86_64-pc-linux-gnu // Clang 6.0 doesn't use the new map interface, undefined behavior when // the compiler emits "old" interface code for structures. // UNSUPPORTED: clang-6 #include <stdio.h> #include <stdlib.h> typedef struct { int *ptr1; int *ptr2; } StructWithPtrs; int main(int argc, char *argv[]) { StructWithPtrs s, s2; s.ptr1 = malloc(sizeof(int)); s.ptr2 = malloc(2 * sizeof(int)); s2.ptr1 = malloc(sizeof(int)); s2.ptr2 = malloc(2 * sizeof(int)); #pragma omp target enter data map(to: s2.ptr2[0:1]) #pragma omp target map(s.ptr1[0:1], s.ptr2[0:2]) { s.ptr1[0] = 1; s.ptr2[0] = 2; s.ptr2[1] = 3; } #pragma omp target exit data map(from: s2.ptr1[0:1], s2.ptr2[0:1]) // CHECK: s.ptr1[0] = 1 // CHECK: s.ptr2[0] = 2 // CHECK: s.ptr2[1] = 3 printf("s.ptr1[0] = %d\n", s.ptr1[0]); printf("s.ptr2[0] = %d\n", s.ptr2[0]); printf("s.ptr2[1] = %d\n", s.ptr2[1]); free(s.ptr1); free(s.ptr2); free(s2.ptr1); free(s2.ptr2); return 0; }
nr_sgx_direct.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 <stdio.h> #include <string.h> #include <assert.h> #include <math.h> //#include <omp.h> #include "config.h" #include "cint.h" #include "nr_direct.h" #define MAX(I,J) ((I) > (J) ? (I) : (J)) #define MIN(I,J) ((I) < (J) ? (I) : (J)) typedef struct { int ncomp; int v_dims[3]; double *data; } SGXJKArray; typedef struct { SGXJKArray *(*allocate)(int *shls_slice, int *ao_loc, int ncomp, int ngrids); //void (*contract)(double *eri, double *dm, SGXJKArray *vjk, // int i0, int i1, int j0, int j1); void (*contract)(double *eri, double *dm, SGXJKArray *vjk, int i0, int i1, int j0, int j1, int* inds, int ngrids); void (*set0)(SGXJKArray *, int); void (*send)(SGXJKArray *, int, double *); void (*finalize)(SGXJKArray *, double *); void (*sanity_check)(int *shls_slice); } SGXJKOperator; int GTOmax_shell_dim(const int *ao_loc, const int *shls_slice, int ncenter); int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env); #define BLKSIZE 312 // for grids integrals only int _max_cache_size_sgx(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env) { int i, n; int i0 = shls_slice[0]; int i1 = shls_slice[1]; for (i = 1; i < ncenter; i++) { i0 = MIN(i0, shls_slice[i*2 ]); i1 = MAX(i1, shls_slice[i*2+1]); } int shls[4]; int cache_size = 0; for (i = i0; i < i1; i++) { shls[0] = i; shls[1] = i; shls[2] = 0; shls[3] = BLKSIZE; n = (*intor)(NULL, NULL, shls, atm, natm, bas, nbas, env, NULL, NULL); cache_size = MAX(cache_size, n); } return cache_size; } #define DECLARE_ALL \ const int *atm = envs->atm; \ const int *bas = envs->bas; \ double *env = envs->env; \ const int natm = envs->natm; \ const int nbas = envs->nbas; \ const int *ao_loc = envs->ao_loc; \ const int *shls_slice = envs->shls_slice; \ const CINTOpt *cintopt = envs->cintopt; \ const int ioff = ao_loc[shls_slice[0]]; \ const int joff = ao_loc[shls_slice[2]]; \ int i0, j0, i1, j1, ish, jsh, idm; \ ish = shls[0]; \ jsh = shls[1]; int SGXnr_pj_prescreen(int *shls, CVHFOpt *opt, int *atm, int *bas, double *env) { if (!opt) { return 1; } int i = shls[0]; int j = shls[1]; int k = shls[2]; int n = opt->nbas; int nk = opt->ngrids; assert(opt->q_cond); assert(opt->dm_cond); assert(i < n); assert(j < n); assert(k < nk); return opt->q_cond[i*n+j] * MAX(fabs(opt->dm_cond[j*nk+k]), fabs(opt->dm_cond[i*nk+k])) > opt->direct_scf_cutoff; } void SGXdot_nrk(int (*intor)(), SGXJKOperator **jkop, SGXJKArray **vjk, double **dms, double *buf, double *cache, int n_dm, int* shls, CVHFOpt *vhfopt, IntorEnvs *envs, double* all_grids, int tot_grids) { DECLARE_ALL; i0 = ao_loc[ish ] - ioff; j0 = ao_loc[jsh ] - joff; i1 = ao_loc[ish+1] - ioff; j1 = ao_loc[jsh+1] - joff; int tmp_ngrids = 0; int k; int* inds = (int*) malloc(tot_grids*sizeof(int)); double *grids = env + (size_t) env[PTR_GRIDS]; if (vhfopt != NULL && vhfopt->dm_cond != NULL) { for (k = 0; k < tot_grids; k++) { shls[2] = k; if (SGXnr_pj_prescreen(shls, vhfopt, atm, bas, env)) { grids[3*tmp_ngrids+0] = all_grids[3*k+0]; grids[3*tmp_ngrids+1] = all_grids[3*k+1]; grids[3*tmp_ngrids+2] = all_grids[3*k+2]; inds[tmp_ngrids] = k; tmp_ngrids++; } } env[NGRIDS] = tmp_ngrids; } else { for (k = 0; k < tot_grids; k++) { shls[2] = k; grids[3*tmp_ngrids+0] = all_grids[3*k+0]; grids[3*tmp_ngrids+1] = all_grids[3*k+1]; grids[3*tmp_ngrids+2] = all_grids[3*k+2]; inds[tmp_ngrids] = k; tmp_ngrids++; } env[NGRIDS] = tmp_ngrids; } int grid0, grid1; const int dims[] = {ao_loc[ish+1]-ao_loc[ish], ao_loc[jsh+1]-ao_loc[jsh], tmp_ngrids}; for (grid0 = 0; grid0 < tmp_ngrids; grid0 += BLKSIZE) { grid1 = MIN(grid0 + BLKSIZE, tmp_ngrids); shls[2] = grid0; shls[3] = grid1; (*intor)(buf+grid0, dims, shls, atm, natm, bas, nbas, env, cintopt, cache); } //(*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, cintopt, cache); for (idm = 0; idm < n_dm; idm++) { jkop[idm]->contract(buf, dms[idm], vjk[idm], i0, i1, j0, j1, inds, tmp_ngrids); } free(inds); } void SGXnr_direct_drv(int (*intor)(), void (*fdot)(), SGXJKOperator **jkop, double **dms, double **vjk, int n_dm, int ncomp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, CVHFOpt *vhfopt, int *atm, int natm, int *bas, int nbas, double *env, int env_size, int aosym) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; int nish = ish1 - ish0; int di = GTOmax_shell_dim(ao_loc, shls_slice, 2); int cache_size = _max_cache_size_sgx(intor, shls_slice, 2, atm, natm, bas, nbas, env); int npair; if (aosym == 2) { npair = nish * (nish+1) / 2; } else { npair = nish * nish; } int (*fprescreen)(); if (vhfopt) { fprescreen = vhfopt->fprescreen; } else { fprescreen = CVHFnoscreen; } int ngrids = (int) env[NGRIDS]; double* all_grids = env+(size_t)env[PTR_GRIDS]; #pragma omp parallel default(none) firstprivate(ish0, jsh0) \ shared(intor, fdot, jkop, ao_loc, shls_slice, \ dms, vjk, n_dm, ncomp, nbas, vhfopt, \ atm, bas, env, natm, \ nish, di, cache_size, fprescreen, \ aosym, npair, cintopt, env_size, \ ngrids, all_grids) { int i, ij, ish, jsh; int shls[4]; double* tmp_env = (double*) malloc(env_size * sizeof(double)); for (i = 0; i < env_size; i++) { tmp_env[i] = env[i]; } IntorEnvs envs = {natm, nbas, atm, bas, tmp_env, shls_slice, ao_loc, NULL, cintopt, ncomp}; SGXJKArray *v_priv[n_dm]; for (i = 0; i < n_dm; i++) { v_priv[i] = jkop[i]->allocate(shls_slice, ao_loc, ncomp, ngrids); } double *buf = malloc(sizeof(double) * ngrids*di*di*ncomp); double *cache = malloc(sizeof(double) * cache_size); #pragma omp for nowait schedule(dynamic, 1) for (ij = 0; ij < npair; ij++) { if (aosym == 2) { ish = (int)(sqrt(2*ij+.25) - .5 + 1e-7); jsh = ij - ish*(ish+1)/2; } else { ish = ij / nish; jsh = ij % nish; } shls[0] = ish + ish0; shls[1] = jsh + jsh0; if ((*fprescreen)(shls, vhfopt, atm, bas, env)) { (*fdot)(intor, jkop, v_priv, dms, buf, cache, n_dm, shls, vhfopt, &envs, all_grids, ngrids); } } #pragma omp critical { for (i = 0; i < n_dm; i++) { jkop[i]->finalize(v_priv[i], vjk[i]); } } free(buf); free(cache); free(tmp_env); } } void SGXsetnr_direct_scf(CVHFOpt *opt, int (*intor)(), CINTOpt *cintopt, int *ao_loc, int *atm, int natm, int *bas, int nbas, double *env) { if (opt->q_cond) { free(opt->q_cond); } nbas = opt->nbas; double *q_cond = (double *)malloc(sizeof(double) * nbas*nbas); opt->q_cond = q_cond; int shls_slice[] = {0, nbas}; int cache_size = GTOmax_cache_size(intor, shls_slice, 1, atm, natm, bas, nbas, env); #pragma omp parallel default(none) \ shared(intor, q_cond, ao_loc, atm, natm, bas, nbas, env, cache_size) { double qtmp, tmp; int ij, i, j, di, dj, ish, jsh; int shls[2]; di = 0; for (ish = 0; ish < nbas; ish++) { dj = ao_loc[ish+1] - ao_loc[ish]; di = MAX(di, dj); } double *cache = malloc(sizeof(double) * (di*di + cache_size)); double *buf = cache + cache_size; #pragma omp for schedule(dynamic, 4) for (ij = 0; ij < nbas*(nbas+1)/2; ij++) { ish = (int)(sqrt(2*ij+.25) - .5 + 1e-7); jsh = ij - ish*(ish+1)/2; if (bas(ATOM_OF,ish) == bas(ATOM_OF,jsh)) { // If two shells are on the same center, their // overlap integrals may be zero due to symmetry. // But their contributions to sgX integrals should // be recognized. q_cond[ish*nbas+jsh] = 1; q_cond[jsh*nbas+ish] = 1; continue; } shls[0] = ish; shls[1] = jsh; qtmp = 1e-100; if (0 != (*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, NULL, cache)) { di = ao_loc[ish+1] - ao_loc[ish]; dj = ao_loc[jsh+1] - ao_loc[jsh]; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { tmp = fabs(buf[i+di*j]); qtmp = MAX(qtmp, tmp); } } } q_cond[ish*nbas+jsh] = qtmp; q_cond[jsh*nbas+ish] = qtmp; } free(cache); } } void SGXsetnr_direct_scf_dm(CVHFOpt *opt, double *dm, int nset, int *ao_loc, int *atm, int natm, int *bas, int nbas, double *env, int ngrids) { nbas = opt->nbas; if (opt->dm_cond) { free(opt->dm_cond); } opt->dm_cond = (double *)malloc(sizeof(double) * nbas*ngrids); // nbas in the input arguments may different to opt->nbas. // Use opt->nbas because it is used in the prescreen function memset(opt->dm_cond, 0, sizeof(double)*nbas*ngrids); opt->ngrids = ngrids; const size_t nao = ao_loc[nbas] - ao_loc[0]; double dmax; size_t i, j, jsh, iset; double *pdm; for (i = 0; i < ngrids; i++) { for (jsh = 0; jsh < nbas; jsh++) { dmax = 0; for (iset = 0; iset < nset; iset++) { pdm = dm + nao*ngrids*iset; for (j = ao_loc[jsh]; j < ao_loc[jsh+1]; j++) { dmax = MAX(dmax, fabs(pdm[i*nao+j])); } } opt->dm_cond[jsh*ngrids+i] = dmax; } } } int SGXnr_ovlp_prescreen(int *shls, CVHFOpt *opt, int *atm, int *bas, double *env) { if (!opt) { return 1; } int i = shls[0]; int j = shls[1]; int n = opt->nbas; assert(opt->q_cond); assert(i < n); assert(j < n); return opt->q_cond[i*n+j] > opt->direct_scf_cutoff; } #define JTYPE1 1 #define JTYPE2 2 #define KTYPE1 3 #define ALLOCATE(label, task) \ static SGXJKArray *SGXJKOperator_allocate_##label(int *shls_slice, int *ao_loc, \ int ncomp, int ngrids) \ { \ SGXJKArray *jkarray = malloc(sizeof(SGXJKArray)); \ jkarray->v_dims[0] = ao_loc[shls_slice[1]] - ao_loc[shls_slice[0]]; \ jkarray->v_dims[1] = ao_loc[shls_slice[3]] - ao_loc[shls_slice[2]]; \ jkarray->v_dims[2] = ngrids; \ if (task == JTYPE1) { \ jkarray->data = calloc(ncomp * jkarray->v_dims[2], sizeof(double)); \ } else if (task == JTYPE2) { \ jkarray->data = calloc(ncomp * jkarray->v_dims[0] \ * jkarray->v_dims[1], sizeof(double)); \ } else { \ jkarray->data = calloc(ncomp * jkarray->v_dims[0] \ * jkarray->v_dims[2], sizeof(double)); \ } \ jkarray->ncomp = ncomp; \ return jkarray; \ } \ static void SGXJKOperator_set0_##label(SGXJKArray *jkarray, int k) \ { } \ static void SGXJKOperator_send_##label(SGXJKArray *jkarray, int k, double *out) \ { } \ static void SGXJKOperator_final_##label(SGXJKArray *jkarray, double *out) \ { \ int i, k, icomp; \ int ni = jkarray->v_dims[0]; \ double *data = jkarray->data; \ int ngrids = jkarray->v_dims[2]; \ if (task == JTYPE1) { \ for (i = 0; i < jkarray->ncomp; i++) { \ for (k = 0; k < ngrids; k++) { \ out[i*ngrids+k] += data[i*ngrids+k]; \ } } \ } else if (task == JTYPE2) { \ for (i = 0; i < jkarray->ncomp * jkarray->v_dims[0] * jkarray->v_dims[1]; i++) { \ out[i] += data[i]; \ } \ } else { \ for (icomp = 0; icomp < jkarray->ncomp; icomp++) { \ for (i = 0; i < ni; i++) { \ for (k = 0; k < ngrids; k++) { \ out[i*ngrids+k] += data[i*ngrids+k]; \ } } \ out += ngrids * ni; \ data += ngrids * ni; \ } \ } \ SGXJKOperator_deallocate(jkarray); \ } #define ADD_OP(fname, task, type) \ ALLOCATE(fname, task) \ SGXJKOperator SGX##fname = {SGXJKOperator_allocate_##fname, fname, \ SGXJKOperator_set0_##fname, SGXJKOperator_send_##fname, \ SGXJKOperator_final_##fname, \ SGXJKOperator_sanity_check_##type} static void SGXJKOperator_deallocate(SGXJKArray *jkarray) { free(jkarray->data); free(jkarray); } static void SGXJKOperator_sanity_check_s1(int *shls_slice) { } static void SGXJKOperator_sanity_check_s2(int *shls_slice) { if (!((shls_slice[0] == shls_slice[2]) && (shls_slice[1] == shls_slice[3]))) { fprintf(stderr, "Fail at s2\n"); exit(1); }; } static void nrs1_ijg_ji_g(double *eri, double *dm, SGXJKArray *out, int i0, int i1, int j0, int j1, int* inds, int pngrids) { const int ncol = out->v_dims[0]; int i, j, k, icomp; double *data = out->data; int ij = 0; for (icomp = 0; icomp < out->ncomp; icomp++) { for (j = j0; j < j1; j++) { for (i = i0; i < i1; i++, ij++) { for (k = 0; k < pngrids; k++) { data[inds[k]] += eri[ij*pngrids+k] * dm[j*ncol+i]; } } } data += out->v_dims[2]; } } ADD_OP(nrs1_ijg_ji_g, JTYPE1, s1); static void nrs2_ijg_ji_g(double *eri, double *dm, SGXJKArray *out, int i0, int i1, int j0, int j1, int* inds, int pngrids) { if (i0 == j0) { return nrs1_ijg_ji_g(eri, dm, out, i0, i1, j0, j1, inds, pngrids); } const int ncol = out->v_dims[0]; int i, j, k, icomp; double *data = out->data; int ij = 0; for (icomp = 0; icomp < out->ncomp; icomp++) { for (j = j0; j < j1; j++) { for (i = i0; i < i1; i++, ij++) { for (k = 0; k < pngrids; k++) { data[inds[k]] += eri[ij*pngrids+k] * (dm[j*ncol+i] + dm[i*ncol+j]); } } } data += out->v_dims[2]; } } ADD_OP(nrs2_ijg_ji_g, JTYPE1, s2); static void nrs1_ijg_g_ij(double *eri, double *dm, SGXJKArray *out, int i0, int i1, int j0, int j1, int* inds, int pngrids) { int ni = out->v_dims[0]; int nj = out->v_dims[1]; int i, j, k, icomp; double *data = out->data; int ij = 0; for (icomp = 0; icomp < out->ncomp; icomp++) { for (j = j0; j < j1; j++) { for (i = i0; i < i1; i++, ij++) { for (k = 0; k < pngrids; k++) { data[i*nj+j] += eri[ij*pngrids+k] * dm[inds[k]]; } } } data += ni * nj; } } ADD_OP(nrs1_ijg_g_ij, JTYPE2, s1); SGXJKOperator SGXnrs2_ijg_g_ij = {SGXJKOperator_allocate_nrs1_ijg_g_ij, nrs1_ijg_g_ij, SGXJKOperator_set0_nrs1_ijg_g_ij, SGXJKOperator_send_nrs1_ijg_g_ij, SGXJKOperator_final_nrs1_ijg_g_ij, SGXJKOperator_sanity_check_s2}; static void nrs1_ijg_gj_gi(double *eri, double *dm, SGXJKArray *out, int i0, int i1, int j0, int j1, int* inds, int pngrids) { double *data = out->data; int i, j, k, icomp; const int ngrids = out->v_dims[2]; int ij = 0; for (icomp = 0; icomp < out->ncomp; icomp++) { for (j = j0; j < j1; j++) { for (i = i0; i < i1; i++, ij++) { for (k = 0; k < pngrids; k++) { data[i*ngrids+inds[k]] += eri[ij*pngrids+k] * dm[j*ngrids+inds[k]]; } } } data += out->v_dims[0] * out->v_dims[2]; } } ADD_OP(nrs1_ijg_gj_gi, KTYPE1, s1); static void nrs2_ijg_gj_gi(double *eri, double *dm, SGXJKArray *out, int i0, int i1, int j0, int j1, int* inds, int pngrids) { if (i0 == j0) { return nrs1_ijg_gj_gi(eri, dm, out, i0, i1, j0, j1, inds, pngrids); } double *data = out->data; const int ngrids = out->v_dims[2]; int i, j, k, icomp; int ij = 0; for (icomp = 0; icomp < out->ncomp; icomp++) { for (j = j0; j < j1; j++) { for (i = i0; i < i1; i++, ij++) { for (k = 0; k < pngrids; k++) { data[i*ngrids+inds[k]] += eri[ij*pngrids+k] * dm[j*ngrids+inds[k]]; } for (k = 0; k < pngrids; k++) { data[j*ngrids+inds[k]] += eri[ij*pngrids+k] * dm[i*ngrids+inds[k]]; } } } data += out->v_dims[0] * out->v_dims[2]; } } ADD_OP(nrs2_ijg_gj_gi, KTYPE1, s2);
workspace.h
#ifndef Workspace_H #define Workspace_H #include "logger.h" #include "matrix.h" #include "Printer.h" namespace puma { class Workspace { public: // --- Start Constructors --- // Workspace(long x, long y, long z, short val, double voxelLength) { log = new puma::Logger(); matrix.resize(x,y,z,val); log->emptyLog(); this->voxelLength = voxelLength; printer = new puma::Printer(); } Workspace(long x, long y, long z, double voxelLength) { log = new puma::Logger(); matrix.resize(x,y,z,0); log->emptyLog(); this->voxelLength = voxelLength; printer = new puma::Printer(); } explicit Workspace(double voxelLength) { log = new puma::Logger(); matrix.resize(0,0,0,0); log->emptyLog(); this->voxelLength = voxelLength; printer = new puma::Printer(); } Workspace() { log = new puma::Logger(); matrix.resize(0,0,0,0); log->emptyLog(); this->voxelLength = 1e-6; printer = new puma::Printer(); } explicit Workspace(Workspace *other) { log = new puma::Logger(); matrix.copy(&other->matrix); log->emptyLog(); this->voxelLength = 1e-6; printer = new puma::Printer(); } explicit Workspace(const puma::Vec3<long>& shape) { log = new puma::Logger(); matrix.resize(shape.x,shape.y,shape.z,0); log->emptyLog(); this->voxelLength = 1e-6; printer = new puma::Printer(); } Workspace(long x, long y, long z, short val, double voxelLength, Logger *otherLog) { log = otherLog; matrix.resize(x,y,z,val); this->voxelLength = voxelLength; myLogger = false; printer = new puma::Printer(); } Workspace(long x, long y, long z, double voxelLength, Logger *otherLog) { log = otherLog; matrix.resize(x,y,z,0); this->voxelLength = voxelLength; myLogger = false; printer = new puma::Printer(); } Workspace(double voxelLength, Logger *otherLog) { log = otherLog; matrix.resize(0,0,0,0); this->voxelLength = voxelLength; myLogger = false; printer = new puma::Printer(); } explicit Workspace(Logger *otherLog) { log = otherLog; matrix.resize(0,0,0,0); this->voxelLength = 1e-6; myLogger = false; printer = new puma::Printer(); } Workspace(Workspace *other, Logger *otherLog) { log = otherLog; matrix.copy(&other->matrix); this->voxelLength = 1e-6; myLogger = false; printer = new puma::Printer(); } Workspace(const puma::Vec3<long>& shape, Logger *otherLog) { log = otherLog; matrix.resize(shape.x,shape.y,shape.z,0); this->voxelLength = 1e-6; myLogger = false; printer = new puma::Printer(); } Workspace(long x, long y, long z, short val, double voxelLength, bool logBool) { log = new puma::Logger(logBool); matrix.resize(x,y,z,val); log->emptyLog(); this->voxelLength = voxelLength; myLogger = false; printer = new puma::Printer(); } Workspace(long x, long y, long z, double voxelLength, bool logBool) { log = new puma::Logger(logBool); matrix.resize(x,y,z,0); log->emptyLog(); this->voxelLength = voxelLength; myLogger = false; printer = new puma::Printer(); } Workspace(double voxelLength, bool logBool) { log = new puma::Logger(logBool); matrix.resize(0,0,0,0); log->emptyLog(); this->voxelLength = voxelLength; myLogger = false; printer = new puma::Printer(); } explicit Workspace(bool logBool) { log = new puma::Logger(logBool); matrix.resize(0,0,0,0); log->emptyLog(); this->voxelLength = 1e-6; myLogger = false; printer = new puma::Printer(); } Workspace(Workspace *other, bool logBool) { log = new puma::Logger(logBool); matrix.copy(&other->matrix); log->emptyLog(); this->voxelLength = 1e-6; myLogger = false; printer = new puma::Printer(); } Workspace(const puma::Vec3<long>& shape, bool logBool) { log = new puma::Logger(logBool); matrix.resize(shape.x,shape.y,shape.z,0); log->emptyLog(); this->voxelLength = 1e-6; myLogger = false; printer = new puma::Printer(); } Workspace(const puma::Vec3<long>& shape, double voxelLength, bool logBool) { log = new puma::Logger(logBool); matrix.resize(shape.x,shape.y,shape.z,0); log->emptyLog(); this->voxelLength = voxelLength; myLogger = false; printer = new puma::Printer(); } ~Workspace() { if(myLogger) { delete log; } if(myPrinter) { delete printer; } } // --- End Constructors --- // // --- Start Variables --- // puma::Matrix<short> matrix; puma::Logger *log; puma::Printer *printer; bool myPrinter{true}; bool myLogger{true}; double voxelLength; // --- End Variables --- // // --- Start Functions --- // void newWorkspace(double voxelLength) { matrix.resize(0,0,0,0); log->emptyLog(); this->voxelLength = voxelLength; } void setLogLocation(std::string log_location) { log->emptyLog(log_location); } void setPrinter(puma::Printer *print) { std::cout << "Printer changed to user input" << std::endl; printer = print; myPrinter = false; } void newPrinter() { std::cout << "Printer returned to default" << std::endl; printer = new puma::Printer(); myPrinter = true; } short operator() (long i, long j, long k) { return matrix(i,j,k); } short& at(long i) { return matrix.at(i); } short& at(long i, long j, long k) { return matrix.at(i,j,k); } short& at_safe(long i) { return matrix.at_safe(i); } short& at_safe(long i, long j, long k) { return matrix.at_safe(i,j,k); } long size() { return matrix.size(); } long X() { return matrix.X(); } long Y() { return matrix.Y(); } long Z() { return matrix.Z(); } puma::Vec3<long> shape() { return puma::Vec3<long>(matrix.X(),matrix.Y(),matrix.Z()); } puma::Vec3<long> getShape() { return puma::Vec3<long>(matrix.X(),matrix.Y(),matrix.Z()); } long getLength() { return matrix.size(); } long getSize() { return matrix.size(); } long getX() { return matrix.X(); } long getY() { return matrix.Y(); } long getZ() { return matrix.Z(); } short min() { return matrix.min(); } short max() { return matrix.max(); } double average() { return matrix.average(); } bool crop(long x1, long x2, long y1, long y2, long z1, long z2) { return matrix.crop(x1,x2,y1,y2,z1,z2); } void setSize(long X, long Y, long Z) { if( !( X>0 && Y>0 && Z>0 ) ) { std::cout << "Invalid size. X, Y, and Z must be >0" << std::endl; return; } matrix.resize(X,Y,Z,0); } void resize(long X, long Y, long Z) { if( !( X>0 && Y>0 && Z>0 ) ) { std::cout << "Invalid size. X, Y, and Z must be >0" << std::endl; return; } matrix.resize(X,Y,Z,0); } void setMaterialID(puma::Cutoff cutoff, int identifier) { if(identifier < 0) { return; } if(identifier > 1000) { return; } int X = (int)matrix.X(); int Y = (int)matrix.Y(); int Z = (int)matrix.Z(); #pragma omp parallel for for(long i=0; i<X; i++) { for(long j=0; j<Y; j++) { for(long k=0; k<Z; k++) { short value = matrix(i,j,k); if(value <= cutoff.second && value >= cutoff.first) { matrix(i,j,k) = identifier; } } } } } void setMaterialID(Workspace *other, puma::Cutoff cutoff, int identifier) { if(identifier < 0) { return; } if(identifier > 1000) { return; } int X = (int)matrix.X(); int Y = (int)matrix.Y(); int Z = (int)matrix.Z(); #pragma omp parallel for for(long i=0; i<X; i++) { for(long j=0; j<Y; j++) { for(long k=0; k<Z; k++) { short value = other->matrix(i,j,k); if(value <= cutoff.second && value >= cutoff.first) { matrix(i,j,k) = identifier; } } } } } // --- End Functions --- // }; } #endif // Workspace
millionaire_with_equality.h
/* Authors: Mayank Rathee Copyright: Copyright (c) 2020 Microsoft Research 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. */ #ifndef MILLIONAIRE_WITH_EQ_H__ #define MILLIONAIRE_WITH_EQ_H__ #include "Millionaire/millionaire.h" #include "OT/emp-ot.h" #include "utils/emp-tool.h" #include <cmath> class MillionaireWithEquality { public: sci::IOPack *iopack; sci::OTPack *otpack; TripleGenerator *triple_gen; MillionaireProtocol *mill; int party; int l, r, log_alpha, beta, beta_pow; int num_digits, num_triples, log_num_digits; uint8_t mask_beta, mask_r; MillionaireWithEquality(int party, sci::IOPack *iopack, sci::OTPack *otpack, int bitlength = 32, int radix_base = MILL_PARAM) { this->party = party; this->iopack = iopack; this->otpack = otpack; this->mill = new MillionaireProtocol(party, iopack, otpack, bitlength, radix_base); this->triple_gen = mill->triple_gen; configure(bitlength, radix_base); } void configure(int bitlength, int radix_base = MILL_PARAM) { assert(radix_base <= 8); assert(bitlength <= 64); this->l = bitlength; this->beta = radix_base; this->num_digits = ceil((double)l / beta); this->r = l % beta; this->log_alpha = sci::bitlen(num_digits) - 1; this->log_num_digits = log_alpha + 1; this->num_triples = 2 * num_digits - 2; if (beta == 8) this->mask_beta = -1; else this->mask_beta = (1 << beta) - 1; this->mask_r = (1 << r) - 1; this->beta_pow = 1 << beta; } ~MillionaireWithEquality() { delete mill; } void bitlen_lt_beta(uint8_t *res_cmp, uint8_t *res_eq, uint64_t *data, int num_cmps, int bitlength, bool greater_than = true, int radix_base = MILL_PARAM) { uint8_t N = 1 << bitlength; uint8_t mask = N - 1; if (party == sci::ALICE) { sci::PRG128 prg; prg.random_data(res_cmp, num_cmps * sizeof(uint8_t)); prg.random_data(res_eq, num_cmps * sizeof(uint8_t)); uint8_t **leaf_messages = new uint8_t *[num_cmps]; for (int i = 0; i < num_cmps; i++) { res_cmp[i] &= 1; res_eq[i] &= 1; leaf_messages[i] = new uint8_t[N]; this->mill->set_leaf_ot_messages(leaf_messages[i], (data[i] & mask), N, res_cmp[i], res_eq[i], greater_than, true); } if (bitlength > 1) { otpack->kkot[bitlength - 1]->send(leaf_messages, num_cmps, 2); } else { otpack->iknp_straight->send(leaf_messages, num_cmps, 2); } for (int i = 0; i < num_cmps; i++) delete[] leaf_messages[i]; delete[] leaf_messages; } else { // party == BOB uint8_t *choice = new uint8_t[num_cmps]; for (int i = 0; i < num_cmps; i++) { choice[i] = data[i] & mask; } if (bitlength > 1) { otpack->kkot[bitlength - 1]->recv(res_cmp, choice, num_cmps, 2); } else { otpack->iknp_straight->recv(res_cmp, choice, num_cmps, 2); } for (int i = 0; i < num_cmps; i++) { res_eq[i] = res_cmp[i] & 1; res_cmp[i] >>= 1; } delete[] choice; } return; } void compare_with_eq(uint8_t *res_cmp, uint8_t *res_eq, uint64_t *data, int num_cmps, int bitlength, bool greater_than = true, int radix_base = MILL_PARAM) { configure(bitlength, radix_base); if (bitlength <= beta) { bitlen_lt_beta(res_cmp, res_eq, data, num_cmps, bitlength, greater_than, radix_base); return; } int old_num_cmps = num_cmps; // num_cmps should be a multiple of 8 num_cmps = ceil(num_cmps / 8.0) * 8; // padding with 0s if data dim not multiple of 8 uint64_t *data_ext; if (old_num_cmps == num_cmps) data_ext = data; else { data_ext = new uint64_t[num_cmps]; memcpy(data_ext, data, old_num_cmps * sizeof(uint64_t)); memset(data_ext + old_num_cmps, 0, (num_cmps - old_num_cmps) * sizeof(uint64_t)); } uint8_t *digits; // num_digits * num_cmps uint8_t *leaf_res_cmp; // num_digits * num_cmps uint8_t *leaf_res_eq; // num_digits * num_cmps digits = new uint8_t[num_digits * num_cmps]; leaf_res_cmp = new uint8_t[num_digits * num_cmps]; leaf_res_eq = new uint8_t[num_digits * num_cmps]; // Extract radix-digits from data for (int i = 0; i < num_digits; i++) // Stored from LSB to MSB for (int j = 0; j < num_cmps; j++) if ((i == num_digits - 1) && (r != 0)) digits[i * num_cmps + j] = (uint8_t)(data_ext[j] >> i * beta) & mask_r; else digits[i * num_cmps + j] = (uint8_t)(data_ext[j] >> i * beta) & mask_beta; // ====================== // Set leaf OT messages now if (party == sci::ALICE) { uint8_t * *leaf_ot_messages; // (num_digits * num_cmps) X beta_pow (=2^beta) leaf_ot_messages = new uint8_t *[num_digits * num_cmps]; for (int i = 0; i < num_digits * num_cmps; i++) leaf_ot_messages[i] = new uint8_t[beta_pow]; // Set Leaf OT messages triple_gen->prg->random_bool((bool *)leaf_res_cmp, num_digits * num_cmps); triple_gen->prg->random_bool((bool *)leaf_res_eq, num_digits * num_cmps); for (int i = 0; i < num_digits; i++) { for (int j = 0; j < num_cmps; j++) { if (i == (num_digits - 1) && (r > 0)) { this->mill->set_leaf_ot_messages( leaf_ot_messages[i * num_cmps + j], digits[i * num_cmps + j], 1ULL << r, leaf_res_cmp[i * num_cmps + j], leaf_res_eq[i * num_cmps + j], greater_than); } else { this->mill->set_leaf_ot_messages( leaf_ot_messages[i * num_cmps + j], digits[i * num_cmps + j], beta_pow, leaf_res_cmp[i * num_cmps + j], leaf_res_eq[i * num_cmps + j], greater_than); } } } // Perform Leaf OTs with comparison and equality if (r == 1) { // All branches except r otpack->kkot[beta - 1]->send(leaf_ot_messages, num_cmps * (num_digits - 1), 2); // r branch otpack->iknp_straight->send( leaf_ot_messages + num_cmps * (num_digits - 1), num_cmps, 2); } else if (r != 0) { // All branches except r otpack->kkot[beta - 1]->send(leaf_ot_messages, num_cmps * (num_digits - 1), 2); // r branch otpack->kkot[r - 1]->send( leaf_ot_messages + num_cmps * (num_digits - 1), num_cmps, 2); } else { // All branches including r, r is 0 otpack->kkot[beta - 1]->send(leaf_ot_messages, num_cmps * (num_digits), 2); } // Cleanup for (int i = 0; i < num_digits * num_cmps; i++) delete[] leaf_ot_messages[i]; delete[] leaf_ot_messages; } else // party = sci::BOB { // Perform Leaf OTs if (r == 1) { // All branches except r otpack->kkot[beta - 1]->recv(leaf_res_cmp, digits, num_cmps * (num_digits - 1), 2); // r branch otpack->iknp_straight->recv(leaf_res_cmp + num_cmps * (num_digits - 1), digits + num_cmps * (num_digits - 1), num_cmps, 2); } else if (r != 0) { // All branches except r otpack->kkot[beta - 1]->recv(leaf_res_cmp, digits, num_cmps * (num_digits - 1), 2); // r branch otpack->kkot[r - 1]->recv(leaf_res_cmp + num_cmps * (num_digits - 1), digits + num_cmps * (num_digits - 1), num_cmps, 2); } else { // All branches including r, r is 0 otpack->kkot[beta - 1]->recv(leaf_res_cmp, digits, num_cmps * (num_digits), 2); } // Extract equality result from leaf_res_cmp for (int i = 0; i < num_digits * num_cmps; i++) { leaf_res_eq[i] = leaf_res_cmp[i] & 1; leaf_res_cmp[i] >>= 1; } } traverse_and_compute_ANDs(num_cmps, leaf_res_eq, leaf_res_cmp); for (int i = 0; i < old_num_cmps; i++) { res_cmp[i] = leaf_res_cmp[i]; res_eq[i] = leaf_res_eq[i]; } // Cleanup if (old_num_cmps != num_cmps) delete[] data_ext; delete[] digits; delete[] leaf_res_cmp; delete[] leaf_res_eq; } /************************************************************************************************** * AND computation related functions **************************************************************************************************/ void traverse_and_compute_ANDs(int num_cmps, uint8_t *leaf_res_eq, uint8_t *leaf_res_cmp) { Triple triples_corr((num_triples)*num_cmps, true, num_cmps); // Generate required Bit-Triples triple_gen->generate(party, &triples_corr, _8KKOT); // Combine leaf OT results in a bottom-up fashion int counter_triples_used = 0, old_counter_triples_used = 0; uint8_t *ei = new uint8_t[(num_triples * num_cmps) / 8]; uint8_t *fi = new uint8_t[(num_triples * num_cmps) / 8]; uint8_t *e = new uint8_t[(num_triples * num_cmps) / 8]; uint8_t *f = new uint8_t[(num_triples * num_cmps) / 8]; for (int i = 1; i < num_digits; i *= 2) { // i denotes the distance between 2 nodes which should be // ANDed together for (int j = 0; j < num_digits and j + i < num_digits; j += 2 * i) { // j=0 is LSD and j=num_digits-1 is MSD // CMP_j: Use 1 triple for opening e = a + cmp_j and f = b + eq_j+i. this->mill->AND_step_1( ei + (2 * counter_triples_used * num_cmps) / 8, fi + (2 * counter_triples_used * num_cmps) / 8, leaf_res_cmp + j * num_cmps, leaf_res_eq + (j + i) * num_cmps, (triples_corr.ai) + (2 * counter_triples_used * num_cmps) / 8, (triples_corr.bi) + (2 * counter_triples_used * num_cmps) / 8, num_cmps); // EQ_j: Use 1 triple for opening e = a + eq_j and f = b + eq_j+i. this->mill->AND_step_1( ei + ((2 * counter_triples_used + 1) * num_cmps) / 8, fi + ((2 * counter_triples_used + 1) * num_cmps) / 8, leaf_res_eq + j * num_cmps, leaf_res_eq + (j + i) * num_cmps, (triples_corr.ai) + ((2 * counter_triples_used + 1) * num_cmps) / 8, (triples_corr.bi) + ((2 * counter_triples_used + 1) * num_cmps) / 8, num_cmps); counter_triples_used++; } int offset = (2 * old_counter_triples_used * num_cmps) / 8; int size_used = (2 * (counter_triples_used - old_counter_triples_used) * num_cmps) / 8; #pragma omp parallel num_threads(2) { if (omp_get_thread_num() == 1) { if (party == sci::ALICE) { iopack->io_rev->recv_data(e + offset, size_used); iopack->io_rev->recv_data(e + offset, size_used); iopack->io_rev->recv_data(f + offset, size_used); iopack->io_rev->recv_data(f + offset, size_used); } else { // party == sci::BOB iopack->io_rev->send_data(ei + offset, size_used); iopack->io_rev->send_data(ei + offset, size_used); iopack->io_rev->send_data(fi + offset, size_used); iopack->io_rev->send_data(fi + offset, size_used); } } else { if (party == sci::ALICE) { iopack->io->send_data(ei + offset, size_used); iopack->io->send_data(ei + offset, size_used); iopack->io->send_data(fi + offset, size_used); iopack->io->send_data(fi + offset, size_used); } else { // party == sci::BOB iopack->io->recv_data(e + offset, size_used); iopack->io->recv_data(e + offset, size_used); iopack->io->recv_data(f + offset, size_used); iopack->io->recv_data(f + offset, size_used); } } } // Reconstruct e and f for (int i = 0; i < size_used; i++) { e[i + offset] ^= ei[i + offset]; f[i + offset] ^= fi[i + offset]; } counter_triples_used = old_counter_triples_used; // Step 2 of AND computation for (int j = 0; j < num_digits and j + i < num_digits; j += 2 * i) { // j=0 is LSD and j=num_digits-1 is MSD // CMP_j: Use 1 triple compute cmp_j AND eq_j+i. this->mill->AND_step_2( leaf_res_cmp + j * num_cmps, e + (2 * counter_triples_used * num_cmps) / 8, f + (2 * counter_triples_used * num_cmps) / 8, nullptr, // not used in function nullptr, // not used in function (triples_corr.ai) + (2 * counter_triples_used * num_cmps) / 8, (triples_corr.bi) + (2 * counter_triples_used * num_cmps) / 8, (triples_corr.ci) + (2 * counter_triples_used * num_cmps) / 8, num_cmps); // EQ_j: Use 1 triple compute eq_j AND eq_j+i. this->mill->AND_step_2( leaf_res_eq + j * num_cmps, e + ((2 * counter_triples_used + 1) * num_cmps) / 8, f + ((2 * counter_triples_used + 1) * num_cmps) / 8, nullptr, // not used in function nullptr, // not used in function (triples_corr.ai) + ((2 * counter_triples_used + 1) * num_cmps) / 8, (triples_corr.bi) + ((2 * counter_triples_used + 1) * num_cmps) / 8, (triples_corr.ci) + ((2 * counter_triples_used + 1) * num_cmps) / 8, num_cmps); for (int k = 0; k < num_cmps; k++) { leaf_res_cmp[j * num_cmps + k] ^= leaf_res_cmp[(j + i) * num_cmps + k]; } counter_triples_used++; } old_counter_triples_used = counter_triples_used; } assert(2 * counter_triples_used == num_triples); // cleanup delete[] ei; delete[] fi; delete[] e; delete[] f; } }; #endif // MILLIONAIRE_WITH_EQ_H__
omp_test_nest_lock.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include "omp_testsuite.h" static omp_nest_lock_t lck; int test_omp_test_nest_lock() { int nr_threads_in_single = 0; int result = 0; int nr_iterations = 0; int i; omp_init_nest_lock (&lck); #pragma omp parallel shared(lck) { #pragma omp for for (i = 0; i < LOOPCOUNT; i++) { /*omp_set_lock(&lck);*/ while(!omp_test_nest_lock (&lck)) {}; #pragma omp flush nr_threads_in_single++; #pragma omp flush nr_iterations++; nr_threads_in_single--; result = result + nr_threads_in_single; omp_unset_nest_lock (&lck); } } omp_destroy_nest_lock (&lck); return ((result == 0) && (nr_iterations == LOOPCOUNT)); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_test_nest_lock()) { num_failed++; } } return num_failed; }
nodal_residualbased_elimination_builder_and_solver_for_FSI.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_FOR_FSI) #define KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_FOR_FSI /* 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 NodalResidualBasedEliminationBuilderAndSolverForFSI * @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 NodalResidualBasedEliminationBuilderAndSolverForFSI : public BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(NodalResidualBasedEliminationBuilderAndSolverForFSI); 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. */ NodalResidualBasedEliminationBuilderAndSolverForFSI( typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>(pNewLinearSystemSolver) { // KRATOS_INFO("NodalResidualBasedEliminationBuilderAndSolverForFSI") << "Using the standard builder and solver " << std::endl; } /** Destructor. */ ~NodalResidualBasedEliminationBuilderAndSolverForFSI() 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 SetMaterialPropertiesToSolid( ModelPart::NodeIterator itNode, double &density, double &deviatoricCoeff, double &volumetricCoeff, double timeInterval, double nodalVolume) { density = itNode->FastGetSolutionStepValue(SOLID_DENSITY); double youngModulus = itNode->FastGetSolutionStepValue(YOUNG_MODULUS); double poissonRatio = itNode->FastGetSolutionStepValue(POISSON_RATIO); //deviatoricCoeff=deltaT*secondLame deviatoricCoeff = timeInterval * youngModulus / (1.0 + poissonRatio) * 0.5; //volumetricCoeff=bulk*deltaT=deltaT*(firstLame+2*secondLame/3) volumetricCoeff = timeInterval * poissonRatio * youngModulus / ((1.0 + poissonRatio) * (1.0 - 2.0 * poissonRatio)) + 2.0 * deviatoricCoeff / 3.0; } void BuildSolidNodally( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &A, TSystemVectorType &b, double hybridCoeff) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //contributions to the system LocalSystemMatrixType solidLHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType solidRHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different terms Element::EquationIdVectorType solidEquationId; 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; double theta = 1.0; array_1d<double, 3> Acc(3, 0.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; double dynamics = 1.0; //dynamics=0.0; // static problem without intertial effects /* #pragma omp parallel */ // { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(), NodesBegin, NodesEnd); double numNodesForExternalForce = 0; double nodalExternalForce = 0; bool belytsckoCase = false; bool cooksMembraneCase = false; if (cooksMembraneCase == true) { for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { double posX = itNode->X0(); if (posX > 47.999 && posX < 48.001) { numNodesForExternalForce += 1.0; } } if (numNodesForExternalForce > 0) { nodalExternalForce = 1.0 / numNodesForExternalForce; } } if (belytsckoCase == true) { for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { double posX = itNode->X0(); if (posX > 24.999 && posX < 25.001) { numNodesForExternalForce += 1.0; } } if (numNodesForExternalForce > 0) { nodalExternalForce = 40.0 / numNodesForExternalForce; } } for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { if (itNode->Is(SOLID)) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); Vector solidNodalSFDneighboursId = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS_ORDER); // const unsigned int neighSize = neighb_nodes.size()+1; const unsigned int neighSize = solidNodalSFDneighboursId.size(); const double nodalVolume = itNode->FastGetSolutionStepValue(SOLID_NODAL_VOLUME); if (neighSize > 1 && nodalVolume > 0) { const unsigned int localSize = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS).size(); if (solidLHS_Contribution.size1() != localSize) solidLHS_Contribution.resize(localSize, localSize, false); //false says not to preserve existing storage!! if (solidRHS_Contribution.size() != localSize) solidRHS_Contribution.resize(localSize, false); //false says not to preserve existing storage!! if (solidEquationId.size() != localSize) solidEquationId.resize(localSize, false); solidLHS_Contribution = ZeroMatrix(localSize, localSize); solidRHS_Contribution = ZeroVector(localSize); this->SetMaterialPropertiesToSolid(itNode, density, deviatoricCoeff, volumetricCoeff, timeInterval, nodalVolume); firstRow = 0; firstCol = 0; if (dimension == 2) { //////////////////////////// LHS TERMS ////////////////////////////// solidLHS_Contribution(0, 0) += nodalVolume * density * 2.0 * dynamics / timeInterval; solidLHS_Contribution(1, 1) += nodalVolume * density * 2.0 * dynamics / timeInterval; //////////////////////////// RHS TERMS ////////////////////////////// //-------- DYNAMIC FORCES TERM -------// Acc = 2.0 * (itNode->FastGetSolutionStepValue(VELOCITY, 0) - itNode->FastGetSolutionStepValue(VELOCITY, 1)) / timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION, 0); solidRHS_Contribution[0] += -nodalVolume * density * Acc[0] * dynamics; solidRHS_Contribution[1] += -nodalVolume * density * Acc[1] * dynamics; //-------- 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; solidRHS_Contribution[0] += nodalVolume * density * VolumeAcceleration[0]; solidRHS_Contribution[1] += nodalVolume * density * VolumeAcceleration[1]; ///////////////LOAD CONDITIONS FOR BELYTSCHKO CASE // if(itNode->X0()>24.999){ // solidRHS_Contribution[1]+=40.0/2.0; // mesh 4 (1 element per edge) //solidRHS_Contribution[1]+=40.0/3.0; // mesh 2 (2 element per edge) //solidRHS_Contribution[1]+=40.0/5.0; // mesh 1 (4 element per edge) //solidRHS_Contribution[1]+=40.0/9.0; // mesh 0.5 (8 element per edge) // solidRHS_Contribution[1]+=40.0/17.0; // mesh 0.25 (16 element per edge) // solidRHS_Contribution[1]+=40.0/33.0; // mesh 0.125 (32 element per edge) //solidRHS_Contribution[1]+=40.0/65.0; // mesh 0.0625 (64 element per edge) //} if (belytsckoCase == true) { if (itNode->X0() > 24.999 && itNode->X0() < 25.001) { solidRHS_Contribution[1] += nodalExternalForce; } } if (cooksMembraneCase == true) { if (itNode->X0() > 47.999 && itNode->X0() < 48.001) { solidRHS_Contribution[1] += nodalExternalForce; } } //-------- INTERNAL FORCES TERM -------// array_1d<double, 3> Sigma(3, 0.0); Sigma = itNode->FastGetSolutionStepValue(SOLID_NODAL_CAUCHY_STRESS); const unsigned int xDofPos = itNode->GetDofPosition(VELOCITY_X); solidEquationId[0] = itNode->GetDof(VELOCITY_X, xDofPos).EquationId(); solidEquationId[1] = itNode->GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); for (unsigned int i = 0; i < neighSize; i++) { dNdXi = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstCol + 1]; solidRHS_Contribution[firstCol] += -nodalVolume * (dNdXi * Sigma[0] + dNdYi * Sigma[2]) * hybridCoeff; solidRHS_Contribution[firstCol + 1] += -nodalVolume * (dNdYi * Sigma[1] + dNdXi * Sigma[2]) * hybridCoeff; for (unsigned int j = 0; j < neighSize; j++) { dNdXj = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstRow]; dNdYj = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstRow + 1]; solidLHS_Contribution(firstRow, firstCol) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdXi + dNdYj * dNdYi * deviatoricCoeff) * theta * hybridCoeff; solidLHS_Contribution(firstRow, firstCol + 1) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdYi + dNdYj * dNdXi * deviatoricCoeff) * theta * hybridCoeff; solidLHS_Contribution(firstRow + 1, firstCol) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdXi + dNdXj * dNdYi * deviatoricCoeff) * theta * hybridCoeff; solidLHS_Contribution(firstRow + 1, firstCol + 1) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdYi + dNdXj * dNdXi * deviatoricCoeff) * theta * hybridCoeff; firstRow += 2; } firstRow = 0; firstCol += 2; unsigned int indexNode = i + 1; if (itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true && indexNode < neighSize) { unsigned int other_neigh_nodes_id = solidNodalSFDneighboursId[indexNode]; // std::cout<<"other_neigh_nodes_id= "<<other_neigh_nodes_id<<" within "<<nodalSFDneighboursId<<std::endl; for (unsigned int k = 0; k < neighb_nodes.size(); k++) { unsigned int neigh_nodes_id = neighb_nodes[k].Id(); // std::cout<<" neigh_nodes_id= "<< neigh_nodes_id<<std::endl; if (neigh_nodes_id == other_neigh_nodes_id) { solidEquationId[firstCol] = neighb_nodes[k].GetDof(VELOCITY_X, xDofPos).EquationId(); solidEquationId[firstCol + 1] = neighb_nodes[k].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); break; } } } else if (i < neighb_nodes.size()) { solidEquationId[firstCol] = neighb_nodes[i].GetDof(VELOCITY_X, xDofPos).EquationId(); solidEquationId[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 ////////////////////////////// solidLHS_Contribution(0, 0) += nodalVolume * density * 2.0 / timeInterval; solidLHS_Contribution(1, 1) += nodalVolume * density * 2.0 / timeInterval; solidLHS_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); solidRHS_Contribution[0] += -nodalVolume * density * Acc[0]; solidRHS_Contribution[1] += -nodalVolume * density * Acc[1]; solidRHS_Contribution[2] += -nodalVolume * density * Acc[2]; //-------- EXTERNAL FORCES TERM -------// array_1d<double, 3> &VolumeAcceleration = itNode->FastGetSolutionStepValue(VOLUME_ACCELERATION); solidRHS_Contribution[0] += nodalVolume * density * VolumeAcceleration[0]; solidRHS_Contribution[1] += nodalVolume * density * VolumeAcceleration[1]; solidRHS_Contribution[2] += nodalVolume * density * VolumeAcceleration[2]; ///////////////LOAD CONDITIONS FOR BELITSCHKO CASE // if(itNode->X0()>24.999){ // // solidRHS_Contribution[1]+=40.0/2.0; // mesh 4 (1 element per edge) // // solidRHS_Contribution[1]+=40.0/3.0; // mesh 2 (2 element per edge) // // solidRHS_Contribution[1]+=40.0/5.0; // mesh 1 (4 element per edge) // solidRHS_Contribution[1]+=40.0/27.0; // mesh 0.5 (8 element per edge, 2 per width) // // solidRHS_Contribution[1]+=40.0/17.0; // mesh 0.25 (16 element per edge) // // solidRHS_Contribution[1]+=40.0/33.0; // mesh 0.125 (32 element per edge) // // solidRHS_Contribution[1]+=40.0/65.0; // mesh 0.0625 (64 element per edge) // } //-------- INTERNAL FORCES TERM -------// array_1d<double, 6> Sigma(6, 0.0); Sigma = itNode->FastGetSolutionStepValue(SOLID_NODAL_CAUCHY_STRESS); // if(itNode->FastGetSolutionStepValue(INTERFACE_NODE)==true){ // Sigma=itNode->FastGetSolutionStepValue(SOLID_NODAL_CAUCHY_STRESS); // } const unsigned int xDofPos = itNode->GetDofPosition(VELOCITY_X); solidEquationId[0] = itNode->GetDof(VELOCITY_X, xDofPos).EquationId(); solidEquationId[1] = itNode->GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); solidEquationId[2] = itNode->GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); for (unsigned int i = 0; i < neighSize; i++) { dNdXi = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstCol]; dNdYi = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstCol + 1]; dNdZi = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstCol + 2]; solidRHS_Contribution[firstCol] += -nodalVolume * (dNdXi * Sigma[0] + dNdYi * Sigma[3] + dNdZi * Sigma[4]); solidRHS_Contribution[firstCol + 1] += -nodalVolume * (dNdYi * Sigma[1] + dNdXi * Sigma[3] + dNdZi * Sigma[5]); solidRHS_Contribution[firstCol + 2] += -nodalVolume * (dNdZi * Sigma[2] + dNdXi * Sigma[4] + dNdYi * Sigma[5]); for (unsigned int j = 0; j < neighSize; j++) { dNdXj = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstRow]; dNdYj = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstRow + 1]; dNdZj = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS)[firstRow + 2]; solidLHS_Contribution(firstRow, firstCol) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdXi + (dNdYj * dNdYi + dNdZj * dNdZi) * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow, firstCol + 1) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdYi + dNdYj * dNdXi * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow, firstCol + 2) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdXj * dNdZi + dNdZj * dNdXi * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow + 1, firstCol) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdXi + dNdXj * dNdYi * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow + 1, firstCol + 1) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdYi + (dNdXj * dNdXi + dNdZj * dNdZi) * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow + 1, firstCol + 2) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdYj * dNdZi + dNdZj * dNdYi * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow + 2, firstCol) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdZj * dNdXi + dNdXj * dNdZi * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow + 2, firstCol + 1) += nodalVolume * ((nTwoThirds * deviatoricCoeff + volumetricCoeff) * dNdZj * dNdYi + dNdYj * dNdZi * deviatoricCoeff) * theta; solidLHS_Contribution(firstRow + 2, firstCol + 2) += nodalVolume * ((FourThirds * deviatoricCoeff + volumetricCoeff) * dNdZj * dNdZi + (dNdXj * dNdXi + dNdYj * dNdYi) * deviatoricCoeff) * theta; firstRow += 3; } firstRow = 0; firstCol += 3; unsigned int indexNode = i + 1; if (itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true && indexNode < neighSize) { unsigned int other_neigh_nodes_id = solidNodalSFDneighboursId[indexNode]; // std::cout<<"other_neigh_nodes_id= "<<other_neigh_nodes_id<<" within "<<nodalSFDneighboursId<<std::endl; for (unsigned int k = 0; k < neighb_nodes.size(); k++) { unsigned int neigh_nodes_id = neighb_nodes[k].Id(); // std::cout<<" neigh_nodes_id= "<< neigh_nodes_id<<std::endl; if (neigh_nodes_id == other_neigh_nodes_id) { solidEquationId[firstCol] = neighb_nodes[k].GetDof(VELOCITY_X, xDofPos).EquationId(); solidEquationId[firstCol + 1] = neighb_nodes[k].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); solidEquationId[firstCol + 2] = neighb_nodes[k].GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); break; } } } else if (i < neighb_nodes.size()) { solidEquationId[firstCol] = neighb_nodes[i].GetDof(VELOCITY_X, xDofPos).EquationId(); solidEquationId[firstCol + 1] = neighb_nodes[i].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); solidEquationId[firstCol + 2] = neighb_nodes[i].GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); } } } #ifdef _OPENMP Assemble(A, b, solidLHS_Contribution, solidRHS_Contribution, solidEquationId, mlock_array); #else Assemble(A, b, solidLHS_Contribution, solidRHS_Contribution, solidEquationId); #endif } } } // } KRATOS_CATCH("") } 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) { if ((itNode->Is(FLUID) && itNode->IsNot(SOLID)) || itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true) { 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); // if(itNode->FastGetSolutionStepValue(INTERFACE_NODE)==true){ // // std::cout<<"density,deviatoricCoeff,volumetricCoeff "<<density<<" "<<deviatoricCoeff<<" "<<volumetricCoeff<<std::endl; // std::cout<<"INTERFACE nodalVolume "<<nodalVolume<<std::endl; // }else{ // std::cout<<"nodalVolume "<<nodalVolume<<std::endl; // } 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); // if(itNode->FastGetSolutionStepValue(INTERFACE_NODE)==true){ // Sigma=itNode->FastGetSolutionStepValue(SOLID_NODAL_CAUCHY_STRESS); // } if (itNode->IsNot(SOLID) || itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true) { 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; unsigned int indexNode = i + 1; if (itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true && indexNode < neighSize) { unsigned int other_neigh_nodes_id = nodalSFDneighboursId[indexNode]; // std::cout<<"other_neigh_nodes_id= "<<other_neigh_nodes_id<<" within "<<nodalSFDneighboursId<<std::endl; for (unsigned int k = 0; k < neighb_nodes.size(); k++) { unsigned int neigh_nodes_id = neighb_nodes[k].Id(); // std::cout<<" neigh_nodes_id= "<< neigh_nodes_id<<std::endl; if (neigh_nodes_id == other_neigh_nodes_id) { EquationId[firstCol] = neighb_nodes[k].GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[firstCol + 1] = neighb_nodes[k].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); break; } } } else 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); // if(itNode->FastGetSolutionStepValue(INTERFACE_NODE)==true){ // Sigma=itNode->FastGetSolutionStepValue(SOLID_NODAL_CAUCHY_STRESS); // } if (itNode->IsNot(SOLID) || itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true) { 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; unsigned int indexNode = i + 1; if (itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true && indexNode < neighSize) { unsigned int other_neigh_nodes_id = nodalSFDneighboursId[indexNode]; // std::cout<<"other_neigh_nodes_id= "<<other_neigh_nodes_id<<" within "<<nodalSFDneighboursId<<std::endl; for (unsigned int k = 0; k < neighb_nodes.size(); k++) { unsigned int neigh_nodes_id = neighb_nodes[k].Id(); // std::cout<<" neigh_nodes_id= "<< neigh_nodes_id<<std::endl; if (neigh_nodes_id == other_neigh_nodes_id) { EquationId[firstCol] = neighb_nodes[k].GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[firstCol + 1] = neighb_nodes[k].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); EquationId[firstCol + 2] = neighb_nodes[k].GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); break; } } } else 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("NodalResidualBasedEliminationBuilderAndSolverForFSI", 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("NodalResidualBasedEliminationBuilderAndSolverForFSI", rModelPart.GetCommunicator().MyPID() == 0) << "ATTENTION! setting the RHS to zero!" << std::endl; } // Prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedEliminationBuilderAndSolverForFSI", 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; double hybridCoeff = 1.0; // 0.5: half nodal - half elemental; 1.0 all nodal; 0.0 all elemental BuildSolidNodally(pScheme, rModelPart, A, b, hybridCoeff); if (hybridCoeff < 0.99999999) { BuildElementally(pScheme, rModelPart, A, b); } 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("") } void BuildElementally( typename TSchemeType::Pointer pScheme, ModelPart &rModelPart, TSystemMatrixType &rA, TSystemVectorType &rb) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; //getting the elements from the model const int nelements = static_cast<int>(rModelPart.Elements().size()); //getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); const ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo(); ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin(); ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); //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; const double start_build = OpenMPUtils::GetCurrentTime(); // assemble all elements #pragma omp parallel firstprivate(nelements, nconditions, LHS_Contribution, RHS_Contribution, EquationId) { #pragma omp for schedule(guided, 512) nowait for (int k = 0; k < nelements; k++) { ModelPart::ElementsContainerType::iterator it = el_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool element_is_active = true; if ((it)->IsDefined(ACTIVE)) element_is_active = (it)->Is(ACTIVE); if (element_is_active) { //calculate elemental contribution pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution #ifdef USE_LOCKS_IN_ASSEMBLY AssembleElementally(rA, rb, LHS_Contribution, RHS_Contribution, EquationId, mLockArray); #else AssembleElementally(rA, rb, LHS_Contribution, RHS_Contribution, EquationId); #endif } } #pragma omp for schedule(guided, 512) for (int k = 0; k < nconditions; k++) { ModelPart::ConditionsContainerType::iterator it = cond_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool condition_is_active = true; if ((it)->IsDefined(ACTIVE)) condition_is_active = (it)->Is(ACTIVE); if (condition_is_active) { //calculate elemental contribution pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); #ifdef USE_LOCKS_IN_ASSEMBLY AssembleElementally(rA, rb, LHS_Contribution, RHS_Contribution, EquationId, mLockArray); #else AssembleElementally(rA, rb, LHS_Contribution, RHS_Contribution, EquationId); #endif } } } const double stop_build = OpenMPUtils::GetCurrentTime(); KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolver", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "System build time: " << stop_build - start_build << std::endl; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0) << "Finished building" << std::endl; KRATOS_CATCH("") } void AssembleElementally( TSystemMatrixType &rA, TSystemVectorType &rb, const LocalSystemMatrixType &rLHSContribution, const LocalSystemVectorType &rRHSContribution, const Element::EquationIdVectorType &rEquationId #ifdef USE_LOCKS_IN_ASSEMBLY , std::vector<omp_lock_t> &rLockArray #endif ) { unsigned int local_size = rLHSContribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = rEquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { #ifdef USE_LOCKS_IN_ASSEMBLY omp_set_lock(&rLockArray[i_global]); b[i_global] += rRHSContribution(i_local); #else double &r_a = rb[i_global]; const double &v_a = rRHSContribution(i_local); #pragma omp atomic r_a += v_a; #endif AssembleRowContributionFreeDofs(rA, rLHSContribution, i_global, i_local, rEquationId); #ifdef USE_LOCKS_IN_ASSEMBLY omp_unset_lock(&rLockArray[i_global]); #endif } //note that computation of reactions is not performed here! } } /** * @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("NodalResidualBasedEliminationBuilderAndSolverForFSI", 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) { auto it_elem = pElements.begin() + i; const IndexType this_thread_id = OpenMPUtils::ThisThread(); // Gets list of Dof involved on every element pScheme->GetDofList(*it_elem, 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) { auto it_cond = pConditions.begin() + i; const IndexType this_thread_id = OpenMPUtils::ThisThread(); // Gets list of Dof involved on every element pScheme->GetDofList(*it_cond, 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("NodalResidualBasedEliminationBuilderAndSolverForFSI", 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); ConstructMatrixStructureForFSI(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); ConstructMatrixStructureForFSI(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("") } inline void AssembleRowContributionFreeDofs( TSystemMatrixType &rA, const Matrix &rALocal, const IndexType i, const IndexType i_local, const Element::EquationIdVectorType &EquationId) { double *values_vector = rA.value_data().begin(); std::size_t *index1_vector = rA.index1_data().begin(); std::size_t *index2_vector = rA.index2_data().begin(); const std::size_t left_limit = index1_vector[i]; // Find the first entry // We iterate over the equation ids until we find the first equation id to be considered // We count in which component we find an ID std::size_t last_pos = 0; std::size_t last_found = 0; std::size_t counter = 0; for (std::size_t j = 0; j < EquationId.size(); ++j) { ++counter; const std::size_t j_global = EquationId[j]; if (j_global < BaseType::mEquationSystemSize) { last_pos = ForwardFind(j_global, left_limit, index2_vector); last_found = j_global; break; } } // If the counter is equal to the size of the EquationID vector that means that only one dof will be considered, if the number is greater means that all the dofs are fixed. If the number is below means that at we have several dofs free to be considered if (counter <= EquationId.size()) { #ifndef USE_LOCKS_IN_ASSEMBLY double &r_a = values_vector[last_pos]; const double &v_a = rALocal(i_local, counter - 1); #pragma omp atomic r_a += v_a; #else values_vector[last_pos] += rALocal(i_local, counter - 1); #endif // Now find all of the other entries std::size_t pos = 0; for (std::size_t j = counter; j < EquationId.size(); ++j) { std::size_t id_to_find = EquationId[j]; if (id_to_find < BaseType::mEquationSystemSize) { if (id_to_find > last_found) pos = ForwardFind(id_to_find, last_pos + 1, index2_vector); else if (id_to_find < last_found) pos = BackwardFind(id_to_find, last_pos - 1, index2_vector); else pos = last_pos; #ifndef USE_LOCKS_IN_ASSEMBLY double &r = values_vector[pos]; const double &v = rALocal(i_local, j); #pragma omp atomic r += v; #else values_vector[pos] += Alocal(i_local, j); #endif last_found = id_to_find; last_pos = pos; } } } } inline std::size_t ForwardFind(const std::size_t id_to_find, const std::size_t start, const std::size_t *index_vector) { std::size_t pos = start; while (id_to_find != index_vector[pos]) pos++; return pos; } inline std::size_t BackwardFind(const std::size_t id_to_find, const std::size_t start, const std::size_t *index_vector) { std::size_t pos = start; while (id_to_find != index_vector[pos]) pos--; return pos; } //************************************************************************** //************************************************************************** /** * @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("NodalResidualBasedEliminationBuilderAndSolverForFSI", 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 ConstructMatrixStructureForFSI( 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) { if (itNode->Is(SOLID)) { const unsigned int localSize = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS).size(); const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); Vector nodalSFDneighboursId = itNode->FastGetSolutionStepValue(SOLID_NODAL_SFD_NEIGHBOURS_ORDER); const unsigned int neighSize = nodalSFDneighboursId.size(); 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(); if (itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); for (unsigned int i = 0; i < neighb_nodes.size(); i++) { unsigned int indexNode = i + 1; if (indexNode < neighSize) { unsigned int other_neigh_nodes_id = nodalSFDneighboursId[indexNode]; firstCol += dimension; for (unsigned int k = 0; k < neighb_nodes.size(); k++) { unsigned int neigh_nodes_id = neighb_nodes[k].Id(); if (neigh_nodes_id == other_neigh_nodes_id) { EquationId[firstCol] = neighb_nodes[k].GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[firstCol + 1] = neighb_nodes[k].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); if (dimension == 3) { EquationId[firstCol + 2] = neighb_nodes[k].GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); } break; } } } } } else { 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(); } } } } if ((itNode->Is(FLUID) && itNode->IsNot(SOLID)) || itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true) { 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); const unsigned int neighSize = nodalSFDneighboursId.size(); 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(); if (itNode->FastGetSolutionStepValue(INTERFACE_NODE) == true) { NodeWeakPtrVectorType &neighb_nodes = itNode->GetValue(NEIGHBOUR_NODES); for (unsigned int i = 0; i < neighb_nodes.size(); i++) { unsigned int indexNode = i + 1; if (indexNode < neighSize) { unsigned int other_neigh_nodes_id = nodalSFDneighboursId[indexNode]; firstCol += dimension; for (unsigned int k = 0; k < neighb_nodes.size(); k++) { unsigned int neigh_nodes_id = neighb_nodes[k].Id(); if (neigh_nodes_id == other_neigh_nodes_id) { EquationId[firstCol] = neighb_nodes[k].GetDof(VELOCITY_X, xDofPos).EquationId(); EquationId[firstCol + 1] = neighb_nodes[k].GetDof(VELOCITY_Y, xDofPos + 1).EquationId(); if (dimension == 3) { EquationId[firstCol + 2] = neighb_nodes[k].GetDof(VELOCITY_Z, xDofPos + 2).EquationId(); } break; } } } } } else { 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->EquationId(*i_condition, 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 NodalResidualBasedEliminationBuilderAndSolverForFSI */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_NODAL_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_FOR_FSI defined */
io.c
#include "allvars.h" #include "io.h" void ReadInputFile(char *filename) { #define DOUBLE 1 #define STRING 2 #define INT 3 #define MAXTAGS 300 int i,j,nt; int id[MAXTAGS]; void *addr[MAXTAGS]; char tag[MAXTAGS][50]; FILE *fd; char buf[MAXCHAR],buf1[MAXCHAR]; char buf2[MAXCHAR],buf3[MAXCHAR]; char fname[MAXCHAR]; nt = 0; strcpy(tag[nt],"BoxSize"); addr[nt] = &BoxSize; id[nt++] = DOUBLE; strcpy(tag[nt],"MaxRadiusSearch"); addr[nt] = &MaxRadiusSearch; id[nt++] = DOUBLE; strcpy(tag[nt],"DeltaThreshold"); addr[nt] = &DeltaThreshold; id[nt++] = DOUBLE; strcpy(tag[nt],"DeltaSeed"); addr[nt] = &DeltaSeed; id[nt++] = DOUBLE; strcpy(tag[nt],"OverlapTol"); addr[nt] = &OverlapTol; id[nt++] = DOUBLE; strcpy(tag[nt],"FormatTracers"); addr[nt] = &FormatTracers; id[nt++] = INT; strcpy(tag[nt],"NumFiles"); addr[nt] = &NumFiles; id[nt++] = INT; strcpy(tag[nt],"FileTracers"); addr[nt] = FileTracers; id[nt++] = STRING; strcpy(tag[nt],"FileVoids"); addr[nt] = FileVoids; id[nt++] = STRING; strcpy(tag[nt],"ScalePos"); addr[nt] = &ScalePos; id[nt++] = DOUBLE; strcpy(tag[nt],"ScaleVel"); addr[nt] = &ScaleVel; id[nt++] = DOUBLE; strcpy(tag[nt],"OMPcores"); addr[nt] = &OMPcores; id[nt++] = INT; strcpy(tag[nt],"RadIncrement"); addr[nt] = &RadIncrement; id[nt++] = DOUBLE; strcpy(tag[nt],"NumRanWalk"); addr[nt] = &NumRanWalk; id[nt++] = INT; strcpy(tag[nt],"FracRadius"); addr[nt] = &FracRadius; id[nt++] = DOUBLE; strcpy(tag[nt],"RSDist"); addr[nt] = &RSDist; id[nt++] = INT; strcpy(tag[nt],"Redshift"); addr[nt] = &Redshift; id[nt++] = DOUBLE; strcpy(tag[nt],"OmegaMatter"); addr[nt] = &OmegaMatter; id[nt++] = DOUBLE; strcpy(tag[nt],"OmegaLambda"); addr[nt] = &OmegaLambda; id[nt++] = DOUBLE; strcpy(tag[nt],"Hubble"); addr[nt] = &Hubble; id[nt++] = DOUBLE; strcpy(tag[nt],"GDist"); addr[nt] = &GDist; id[nt++] = INT; strcpy(tag[nt],"FidOmegaMatter"); addr[nt] = &FidOmegaMatter; id[nt++] = DOUBLE; strcpy(tag[nt],"FidOmegaLambda"); addr[nt] = &FidOmegaLambda; id[nt++] = DOUBLE; strcpy(tag[nt],"FidHubble"); addr[nt] = &FidHubble; id[nt++] = DOUBLE; strcpy(tag[nt],"WriteProfiles"); addr[nt] = &WriteProfiles; id[nt++] = INT; strcpy(tag[nt],"MinProfileDist"); addr[nt] = &MinProfileDist; id[nt++] = DOUBLE; strcpy(tag[nt],"MaxProfileDist"); addr[nt] = &MaxProfileDist; id[nt++] = DOUBLE; strcpy(tag[nt],"NumProfileBins"); addr[nt] = &NumProfileBins; id[nt++] = INT; strcpy(tag[nt],"PathProfiles"); addr[nt] = PathProfiles; id[nt++] = STRING; strcpy(tag[nt],"InnerShellVel"); addr[nt] = &InnerShellVel; id[nt++] = DOUBLE; strcpy(tag[nt],"OuterShellVel"); addr[nt] = &OuterShellVel; id[nt++] = DOUBLE; fd = SafeOpen(filename,"r"); sprintf(fname,"%s.log",filename); logfile = SafeOpen(fname,"w"); fprintf(logfile,"\n CONFIGURATION PARAMETERS USED \n\n"); while (!feof(fd)) { buf[0] = 0; fgets(buf, 200, fd); if (sscanf(buf, "%s%s%s", buf1, buf2, buf3) < 2) continue; if (buf1[0] == '%') continue; for (i = 0, j = -1; i < nt; i++) { if (strcmp(buf1, tag[i]) == 0) { j = i; tag[i][0] = 0; break; } } if (j >= 0) { switch (id[j]) { case DOUBLE: *((double *) addr[j]) = atof(buf2); fprintf(logfile, " %-35s%g\n", buf1, *((double *) addr[j])); break; case STRING: strcpy((char *)addr[j], buf2); fprintf(logfile, " %-35s%s\n", buf1, buf2); break; case INT: *((int *) addr[j]) = atoi(buf2); fprintf(logfile, " %-35s%d\n", buf1, *((int *) addr[j])); break; } } else { fprintf(stdout, "Error in file %s: Tag '%s' not allowed or multiple defined. \n", filename, buf1); fflush(stdout); exit(EXIT_FAILURE); } } fclose(fd); for (i=0; i<nt; i++) { if (*tag[i]) { fprintf(stdout, "Error. Missing value for tag '%s' in parameter file '%s'.\n", tag[i], filename); fflush(stdout); exit(EXIT_FAILURE); } } fflush(logfile); #undef DOUBLE #undef STRING #undef INT #undef MAXTAGS } void ReadTracers() { int i; FILE *fd; double Volume; clock_t t; fprintf(logfile,"\n READING TRACERS \n"); t = clock(); switch (FormatTracers) { case 0: fprintf(logfile," | Reading ASCII format \n"); ReadTracers_ASCII(); break; case 1: fprintf(logfile," | Reading GADGET-1 format \n"); ReadTracers_GADGET1(); break; case 2: fprintf(logfile," | Reading GADGET-2 format \n"); ReadTracers_GADGET2(); break; case 3: fprintf(logfile," | Reading BINARY format \n"); ReadTracers_BINARY(); } LBox[0] = BoxSize; LBox[1] = BoxSize; LBox[2] = BoxSize; if (RSDist == 1) RedshiftSpaceDistortions(); if (GDist == 1) GeometricalDistortions(); Volume = LBox[0]*LBox[1]*LBox[2]; MeanNumTrac = (double)NumTrac/Volume; MeanSeparation = cbrt(Volume/(double)NumTrac); fprintf(logfile," | Number of tracers = %d \n",NumTrac); fprintf(logfile," | Size of the box: x-axis = %f \n",LBox[0]); fprintf(logfile," | y-axis = %f \n",LBox[1]); fprintf(logfile," | z-axis = %f \n",LBox[2]); fprintf(logfile," | Mean number density [h³/Mpc³] = %e \n",MeanNumTrac); fprintf(logfile," | Mean separation [Mpc/h] = %e \n",MeanSeparation); StepName.push_back("Reading tracers"); StepTime.push_back(Time(t,1)); } void ReadTracers_ASCII() { int i; FILE *fd; NumTrac = CountLines(FileTracers); Tracer = (struct tracers *) malloc(NumTrac*sizeof(struct tracers)); fd = SafeOpen(FileTracers,"r"); for (i=0; i<NumTrac; i++) { fscanf(fd,"%f %f %f %f %f %f \n",&Tracer[i].Pos[0],&Tracer[i].Pos[1],&Tracer[i].Pos[2], &Tracer[i].Vel[0],&Tracer[i].Vel[1],&Tracer[i].Vel[2]); Tracer[i].Pos[0] *= ScalePos; Tracer[i].Pos[1] *= ScalePos; Tracer[i].Pos[2] *= ScalePos; Tracer[i].Vel[0] *= ScaleVel; Tracer[i].Vel[1] *= ScaleVel; Tracer[i].Vel[2] *= ScaleVel; } fclose(fd); } void ReadTracers_BINARY() { int i; FILE *fd; fd = SafeOpen(FileTracers,"r"); fread(&NumTrac,sizeof(int),1,fd); Tracer = (struct tracers *) malloc(NumTrac*sizeof(struct tracers)); for (i=0; i<NumTrac; i++) { fread(&Tracer[i].Pos[0],sizeof(float),3,fd); fread(&Tracer[i].Vel[0],sizeof(float),3,fd); Tracer[i].Pos[0] *= ScalePos; Tracer[i].Pos[1] *= ScalePos; Tracer[i].Pos[2] *= ScalePos; Tracer[i].Vel[0] *= ScaleVel; Tracer[i].Vel[1] *= ScaleVel; Tracer[i].Vel[2] *= ScaleVel; } fclose(fd); } void ReadTracers_GADGET1() { struct GadgetHeader { int Npart[6]; double Mass[6]; double Time; double Redshift; int Flag_1; int Flag_2; int NpartTotal[6]; int Flag_3; int NumFiles; double BoxSize; double Omega0; double OmegaLambda; double HubbleParam; char fill[96]; } Header; int i,j,k,SkipBlock,dummy,Np,id,NC; float pos[3],vel[3]; FILE *f1,*f2,*f3; char snapshot[MAXCHAR]; if (NumFiles == 1) sprintf(snapshot,"%s",FileTracers); else sprintf(snapshot,"%s.0",FileTracers); f1 = SafeOpen(snapshot,"r"); fread(&dummy,sizeof(int),1,f1); fread(&Header,sizeof(struct GadgetHeader),1,f1); fclose(f1); NumTrac = Header.NpartTotal[1]; if (Header.BoxSize*ScalePos != BoxSize || Header.NumFiles != NumFiles) { fprintf(stdout,"\nError. Missmatch with Gadget header.\n"); fprintf(stdout,"BoxSize = %f (%f in inputfile)\n",Header.BoxSize*ScalePos,BoxSize); fprintf(stdout,"NumFiles = %d (%d in inputfile)\n",Header.NumFiles,NumFiles); fflush(stdout); exit(EXIT_FAILURE); } if ((RSDist == 1 || GDist == 1) && (Header.Omega0 != OmegaMatter || Header.OmegaLambda != OmegaLambda || Header.Redshift != Redshift || Header.HubbleParam*100.0 != Hubble)) { fprintf(stdout,"\nError. Missmatch with Gadget header.\n"); fprintf(stdout,"OmegaMatter = %f (%f in inputfile)\n",Header.Omega0,OmegaMatter); fprintf(stdout,"OmegaLambda = %f (%f in inputfile)\n",Header.OmegaLambda,OmegaLambda); fprintf(stdout,"Hubble = %f (%f in inputfile)\n",Header.HubbleParam*100.0,Hubble); fprintf(stdout,"Redshift = %f (%f in inputfile)\n",Header.Redshift,Redshift); fflush(stdout); exit(EXIT_FAILURE); } Tracer = (struct tracers *) malloc(NumTrac*sizeof(struct tracers)); if (NumFiles < OMPcores) NC = NumFiles; else NC = OMPcores; #pragma omp parallel for default(none) schedule(static) num_threads(NC) \ private(i,snapshot,f1,f2,f3,Np,Header,SkipBlock,pos,vel,id,j,k,dummy) \ shared(Tracer,ScalePos,ScaleVel,stdout,NumFiles,FileTracers) for (i=0; i<NumFiles; i++) { if (NumFiles == 1) sprintf(snapshot,"%s",FileTracers); else sprintf(snapshot,"%s.%d",FileTracers,i); f1 = SafeOpen(snapshot,"r"); // Pos f2 = SafeOpen(snapshot,"r"); // Vel f3 = SafeOpen(snapshot,"r"); // ID fread(&dummy,sizeof(int),1,f1); fread(&Header,sizeof(struct GadgetHeader),1,f1); fread(&dummy,sizeof(int),1,f1); fread(&dummy,sizeof(int),1,f1); Np = Header.Npart[1]; SkipBlock = sizeof(int) + sizeof(struct GadgetHeader) + sizeof(int) + sizeof(int) + 3*sizeof(float)*Np + 2*sizeof(int); fseek(f2,SkipBlock,SEEK_CUR); SkipBlock = sizeof(int) + sizeof(struct GadgetHeader) + sizeof(int) + sizeof(int) + 3*sizeof(float)*Np + sizeof(int) + sizeof(int) + 3*sizeof(float)*Np + 2*sizeof(int); fseek(f3,SkipBlock,SEEK_CUR); for (j=0; j<Np; j++) { fread(pos,sizeof(float),3,f1); fread(vel,sizeof(float),3,f2); fread(&id,sizeof(float),1,f3); id--; for (k=0; k<3; k++) { Tracer[id].Pos[k] = pos[k]*ScalePos; Tracer[id].Vel[k] = vel[k]*sqrt(Header.Time)*ScaleVel; } } fclose(f1); fclose(f2); fclose(f3); } } void ReadTracers_GADGET2() { struct GadgetHeader { int Npart[6]; double Mass[6]; double Time; double Redshift; int Flag_1; int Flag_2; int NpartTotal[6]; int Flag_3; int NumFiles; double BoxSize; double Omega0; double OmegaLambda; double HubbleParam; char fill[96]; } Header; int i,j,k,SkipBlock,SizeBlock,dummy,Np,NC; int *Nstart,*NpFile,id; float pos[3],vel[3]; FILE *f1,*f2; char snapshot[MAXCHAR],key[5],buffer[5]; Nstart = (int *) malloc(NumFiles*sizeof(int)); NpFile = (int *) malloc(NumFiles*sizeof(int)); for (i=0; i<NumFiles; i++) { if (NumFiles == 1) sprintf(snapshot,"%s",FileTracers); else sprintf(snapshot,"%s.%d",FileTracers,i); f1 = SafeOpen(snapshot,"r"); strcpy(key,"HEAD\0"); do { fread(&dummy,sizeof(int),1,f1); fread(buffer,4*sizeof(char),1,f1); buffer[4]='\0'; fread(&SizeBlock,sizeof(int),1,f1); if (strcmp(key,buffer) == 0) break; fseek(f1,SizeBlock+sizeof(int),SEEK_CUR); } while(1); fread(&dummy,sizeof(int),1,f1); fread(&dummy,sizeof(int),1,f1); fread(&Header,sizeof(struct GadgetHeader),1,f1); fclose(f1); NpFile[i] = Header.Npart[1]; } NumTrac = Header.NpartTotal[1]; if (Header.BoxSize*ScalePos != BoxSize || Header.NumFiles != NumFiles) { fprintf(stdout,"\nError. Missmatch with Gadget header.\n"); fprintf(stdout,"BoxSize = %f (%f in inputfile)\n",Header.BoxSize*ScalePos,BoxSize); fprintf(stdout,"NumFiles = %d (%d in inputfile)\n",Header.NumFiles,NumFiles); fflush(stdout); exit(EXIT_FAILURE); } if ((RSDist == 1 || GDist == 1) && (Header.Omega0 != OmegaMatter || Header.OmegaLambda != OmegaLambda || Header.Redshift != Redshift || Header.HubbleParam*100.0 != Hubble)) { fprintf(stdout,"\nError. Missmatch with Gadget header.\n"); fprintf(stdout,"OmegaMatter = %f (%f in inputfile)\n",Header.Omega0,OmegaMatter); fprintf(stdout,"OmegaLambda = %f (%f in inputfile)\n",Header.OmegaLambda,OmegaLambda); fprintf(stdout,"Hubble = %f (%f in inputfile)\n",Header.HubbleParam*100.0,Hubble); fprintf(stdout,"Redshift = %f (%f in inputfile)\n",Header.Redshift,Redshift); fflush(stdout); exit(EXIT_FAILURE); } Tracer = (struct tracers *) malloc(NumTrac*sizeof(struct tracers)); for (i=0; i<NumFiles; i++) { Nstart[i] = 0; for (j=0; j<i; j++) Nstart[i] += NpFile[j]; } if (NumFiles < OMPcores) NC = NumFiles; else NC = OMPcores; #pragma omp parallel for default(none) schedule(static) num_threads(NC) \ private(i,snapshot,f1,f2,Np,Header,SkipBlock,pos,vel,id,j,k,dummy,key, \ buffer,SizeBlock) \ shared(Tracer,ScalePos,ScaleVel,stdout,NumFiles,FileTracers,Nstart) for (i=0; i<NumFiles; i++) { if (NumFiles == 1) sprintf(snapshot,"%s",FileTracers); else sprintf(snapshot,"%s.%d",FileTracers,i); f1 = SafeOpen(snapshot,"r"); // Pos f2 = SafeOpen(snapshot,"r"); // Vel strcpy(key,"HEAD\0"); do { fread(&dummy,sizeof(int),1,f1); fread(buffer,4*sizeof(char),1,f1); buffer[4]='\0'; fread(&SizeBlock,sizeof(int),1,f1); if (strcmp(key,buffer) == 0) break; fseek(f1,SizeBlock+sizeof(int),SEEK_CUR); } while(1); fread(&dummy,sizeof(int),1,f1); fread(&dummy,sizeof(int),1,f1); fread(&Header,sizeof(struct GadgetHeader),1,f1); fread(&dummy,sizeof(int),1,f1); Np = Header.Npart[1]; strcpy(key,"POS \0"); do { fread(&dummy,sizeof(int),1,f1); fread(buffer,4*sizeof(char),1,f1); buffer[4]='\0'; fread(&SizeBlock,sizeof(int),1,f1); if (strcmp(key,buffer) == 0) break; fseek(f1,SizeBlock+sizeof(int),SEEK_CUR); } while(1); fread(&dummy,sizeof(int),1,f1); fread(&dummy,sizeof(int),1,f1); strcpy(key,"VEL \0"); do { fread(&dummy,sizeof(int),1,f2); fread(buffer,4*sizeof(char),1,f2); buffer[4]='\0'; fread(&SizeBlock,sizeof(int),1,f2); if (strcmp(key,buffer) == 0) break; fseek(f2,SizeBlock+sizeof(int),SEEK_CUR); } while(1); fread(&dummy,sizeof(int),1,f2); fread(&dummy,sizeof(int),1,f2); //fseek(f1,sizeof(float)*Header.Npart[1]*3,SEEK_CUR); //fseek(f2,sizeof(float)*Header.Npart[1]*3,SEEK_CUR); id = Nstart[i]; for (j=0; j<Np; j++) { fread(pos,sizeof(float),3,f1); fread(vel,sizeof(float),3,f2); for (k=0; k<3; k++) { Tracer[id].Pos[k] = pos[k]*ScalePos; Tracer[id].Vel[k] = vel[k]*sqrt(Header.Time)*ScaleVel; } id++; } fclose(f1); fclose(f2); } free(Nstart); free(NpFile); } void RedshiftSpaceDistortions() { int i; double Hubble_z; double RSDFactor; fprintf(logfile," | Applying redshift-space distortions: LOS = z-axis, POS = xy-plane\n"); Cosmo.OmM = OmegaMatter; Cosmo.OmL = OmegaLambda; Cosmo.OmK = (1.0 - OmegaMatter - OmegaLambda); Cosmo.Red = Redshift; if (Redshift == 0.0) { RSDFactor = 1.0/100.0; } else { Hubble_z = 100.0*E(Cosmo.Red); RSDFactor = (1.0 + Redshift)/Hubble_z; } fprintf(logfile," | RSD factor = (1+z)/H(z) = %f [h⁻¹Mpc/(km/s)]\n",RSDFactor); fflush(logfile); for (i=0; i<NumTrac; i++) { Tracer[i].Pos[2] += Tracer[i].Vel[2]*RSDFactor; if (Tracer[i].Pos[2] < 0.0 ) Tracer[i].Pos[2] += LBox[2]; if (Tracer[i].Pos[2] > LBox[2]) Tracer[i].Pos[2] -= LBox[2]; } } void GeometricalDistortions() { int i; double Hubble_z,Distance_z; double FidHubble_z,FidDistance_z; double GDFactor_LOS,GDFactor_POS; fprintf(logfile," | Applying fiducial cosmology distortions: LOS = z-axis, POS = xy-plane\n"); Cosmo.Red = Redshift; Cosmo.OmM = OmegaMatter; Cosmo.OmL = OmegaLambda; Cosmo.OmK = 1.0 - Cosmo.OmM - Cosmo.OmL; Cosmo.Hub = Hubble; fprintf(logfile," | True cosmology: (OmM,OmL,OmK,H0) = (%4.2f,%4.2f,%4.2f,%4.2f)\n", Cosmo.OmM,Cosmo.OmL,Cosmo.OmK,Cosmo.Hub); Hubble_z = Cosmo.Hub*E(Cosmo.Red); Distance_z = AngularDistance(Cosmo.Red); Cosmo.OmM = FidOmegaMatter; Cosmo.OmL = FidOmegaLambda; Cosmo.OmK = 1.0 - Cosmo.OmM - Cosmo.OmL; Cosmo.Hub = FidHubble; fprintf(logfile," | Fiducial cosmology: (OmM,OmL,OmK,H0) = (%4.2f,%4.2f,%4.2f,%4.2f)\n", Cosmo.OmM,Cosmo.OmL,Cosmo.OmK,Cosmo.Hub); FidHubble_z = Cosmo.Hub*E(Cosmo.Red); FidDistance_z = AngularDistance(Cosmo.Red); GDFactor_LOS = Hubble_z/FidHubble_z; GDFactor_POS = FidDistance_z/Distance_z; fprintf(logfile," | GD factor: LOS = H(z)/FidH(z) = %f \n",GDFactor_LOS); fprintf(logfile," | POS = FidD(z)/D(z) = %f \n",GDFactor_POS); fflush(logfile); LBox[0] *= GDFactor_POS; LBox[1] *= GDFactor_POS; LBox[2] *= GDFactor_LOS; for (i=0; i<NumTrac; i++) { Tracer[i].Pos[0] *= GDFactor_POS; Tracer[i].Pos[1] *= GDFactor_POS; Tracer[i].Pos[2] *= GDFactor_LOS; } } void WriteVoids() { int i; FILE *fd; clock_t t; fprintf(logfile,"\n WRITTING VOID CATALOGUE \n"); t = clock(); fd = SafeOpen(FileVoids,"w"); float dx[3],disp; int k; for (i=0; i<NumVoid; i++) { if (Void[i].ToF) { fprintf(fd," %8.5f %12.6f %12.6f %12.6f %12.6f %12.6f %12.6f %12.6f %12.6f %12.6f %5d\n", Void[i].Rad,Void[i].Pos[0],Void[i].Pos[1],Void[i].Pos[2],Void[i].Vel[0],Void[i].Vel[1], Void[i].Vel[2],Void[i].Delta,Void[i].Dtype,Void[i].Poisson,Void[i].Nran); } } fclose(fd); StepName.push_back("Writting void catalogue"); StepTime.push_back(Time(t,1)); }
bml_import_csr_typed.c
#include "../../macros.h" #include "../../typed.h" #include "../bml_allocate.h" #include "../bml_logger.h" #include "../bml_types.h" #include "bml_allocate_csr.h" #include "bml_import_csr.h" #include "bml_types_csr.h" #include "bml_setters_csr.h" #include <complex.h> #include <math.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /** Convert a dense matrix into a bml csr matrix. * * \ingroup convert_group * * \param N The number of rows/columns * \param matrix_precision The real precision * \param A The dense matrix * \return The bml matrix */ bml_matrix_csr_t * TYPED_FUNC(bml_import_from_dense_csr) (bml_dense_order_t order, int N, void *A, double threshold, int M, bml_distribution_mode_t distrib_mode) { bml_matrix_csr_t *csr_A = TYPED_FUNC(bml_zero_matrix_csr) (N, M, distrib_mode); REAL_T *dense_A = (REAL_T *) A; #pragma omp parallel for shared(dense_A) for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { REAL_T A_ij; switch (order) { case dense_row_major: A_ij = dense_A[ROWMAJOR(i, j, N, N)]; break; case dense_column_major: A_ij = dense_A[COLMAJOR(i, j, N, N)]; break; default: LOG_ERROR("unknown order\n"); break; } if (is_above_threshold(A_ij, threshold)) { TYPED_FUNC(csr_set_row_element_new) (csr_A->data_[i], j, &A_ij); } } } return csr_A; }
GB_binop__isle_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__isle_int64 // A.*B function (eWiseMult): GB_AemultB__isle_int64 // A*D function (colscale): GB_AxD__isle_int64 // D*A function (rowscale): GB_DxB__isle_int64 // C+=B function (dense accum): GB_Cdense_accumB__isle_int64 // C+=b function (dense accum): GB_Cdense_accumb__isle_int64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isle_int64 // C=scalar+B GB_bind1st__isle_int64 // C=scalar+B' GB_bind1st_tran__isle_int64 // C=A+scalar GB_bind2nd__isle_int64 // C=A'+scalar GB_bind2nd_tran__isle_int64 // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x <= y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISLE || GxB_NO_INT64 || GxB_NO_ISLE_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__isle_int64 ( 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__isle_int64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__isle_int64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__isle_int64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__isle_int64 ( 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 int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__isle_int64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__isle_int64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__isle_int64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = Bx [p] ; Cx [p] = (x <= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__isle_int64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = Ax [p] ; Cx [p] = (aij <= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB_bind1st_tran__isle_int64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // 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) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB_bind2nd_tran__isle_int64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bli_axpyv_opt_var1.c
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of The University of Texas at Austin nor the names of its contributors may be used to endorse or promote products derived derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "blis.h" void bli_daxpyv_opt_var1 ( conj_t conjx, dim_t n, double* restrict alpha, double* restrict x, inc_t incx, double* restrict y, inc_t incy, cntx_t* cntx ) { if ( bli_zero_dim1( n ) ) return; // If there is anything that would interfere with our use of aligned // vector loads/stores, call the reference implementation. bool_t use_ref = FALSE; if ( incx != 1 || incy != 1 || bli_is_unaligned_to( x, 32 ) || bli_is_unaligned_to( y, 32 ) ) { use_ref = TRUE; } // Call the reference implementation if needed. if ( use_ref == TRUE ) { BLIS_DAXPYV_KERNEL_REF( conjx, n, alpha, x, incx, y, incy, cntx ); return; } dim_t n_run = n / 4; dim_t n_left = n % 4; vector4double xv, yv, zv; vector4double alphav = vec_lds( 0 * sizeof(double), (double*)alpha ); #pragma omp parallel for for ( dim_t i = 0; i < n_run; i++ ) { xv = vec_lda( 0 * sizeof(double), &x[i*4] ); yv = vec_lda( 0 * sizeof(double), &y[i*4] ); zv = vec_madd( alphav, xv, yv ); vec_sta( zv, 0 * sizeof(double), &y[i*4] ); } for ( dim_t i = 0; i < n_left; i++ ) { y[4*n_run + i] += *alpha * x[4*n_run + i]; } }
sw_traco.h
void sw_traco(){ printf("- traco [16x16x16 - \n\n"); int c1,c2,c3,c4,c5,c6,c7,c8,c9,c11,c10,c12,c13,c14,c15; #pragma omp parallel for for( c1 = 0; c1 <= (N - 1)/16; c1 += 1) for( c3 = 0; c3 <= (N - 1) / 16; c3 += 1) for( c5 = 16 * c1 + 1; c5 <= min(N, 16 * c1 + 16); c5 += 1) for( c7 = 16 * c3 + 1; c7 <= min(N, 16 * c3 + 16); c7 += 1){ m1[c5][c7] = INT_MIN; m2[c5][c7] = INT_MIN; } for( c1 = 0; c1 <= floord(N - 1, 8); c1 += 1) #pragma omp parallel for schedule(dynamic, 1) shared(c1) private(c3,c4,c7,c9,c10,c5,c11) for( c3 = max(0, c1 - (N + 15) / 16 + 1); c3 <= min(c1, (N - 1) / 16); c3 += 1) for( c4 = 0; c4 <= 2; c4 += 1) { if (c4 == 2) { for( c7 = 16 * c1 - 16 * c3 + 1; c7 <= min(N, 16 * c1 - 16 * c3 + 16); c7 += 1) for( c9 = 16 * c3 + 1; c9 <= min(N, 16 * c3 + 16); c9 += 1) { for( c10 = max(0, 16 * c1 - 16 * c3 - c7 + 2); c10 <= min(1, -16 * c3 + c9 - 1); c10 += 1) { if (c10 == 1) { for( c11 = 1; c11 <= c9; c11 += 1) m2[c7][c9] = MAX(m2[c7][c9] + H[c7][c9-c11], W[c11]); } else for( c11 = 1; c11 <= c7; c11 += 1) m1[c7][c9] = MAX(m1[c7][c9] + H[c7-c11][c9], W[c11]); } H[c7][c9] = MAX(0, MAX(H[c7-1][c9-1] + s(a[c7],b[c9]), MAX(m1[c7][c9], m2[c7][c9]))); } } else if (c4 == 1) { for( c5 = 0; c5 <= c3; c5 += 1) for( c7 = 16 * c1 - 16 * c3 + 1; c7 <= min(N, 16 * c1 - 16 * c3 + 16); c7 += 1) for( c11 = 16 * c5 + 1; c11 <= min(16 * c3 + 1, 16 * c5 + 16); c11 += 1) m2[c7][(16*c3+1)] = MAX(m2[c7][(16*c3+1)], H[c7][(16*c3+1)-c11] + W[c11]); } else for( c5 = 0; c5 <= c1 - c3; c5 += 1) for( c9 = 16 * c3 + 1; c9 <= min(N, 16 * c3 + 16); c9 += 1) for( c11 = 16 * c5 + 1; c11 <= min(16 * c1 - 16 * c3 + 1, 16 * c5 + 16); c11 += 1) m1[(16*c1-16*c3+1)][c9] = MAX(m1[(16*c1-16*c3+1)][c9], H[(16*c1-16*c3+1)-c11][c9] + W[c11]); } /* for (i=1; i <=N; i++) for (j=1; j <=N; j++){ // Block S m1[i][j] = INT_MIN; for (k=1; k <=i; k++) m1[i][j] = MAX(m1[i][j] ,H[i-k][j] + W[k]); m2[i][j] = INT_MIN; for (k=1; k <=j; k++) m2[i][j] = MAX(m2[i][j] ,H[i][j-k] + W[k]); H[i][j] = MAX(0, MAX( H[i-1][j-1] + s(a[i], b[i]), MAX(m1[i][j], m2[i][j]))); } */ }
accuracy_cython.c
/* Generated by Cython 0.23.4 */ /* BEGIN: Cython Metadata { "distutils": { "extra_compile_args": [ "-fopenmp" ], "extra_link_args": [ "-fopenmp" ] } } END: Cython Metadata */ #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. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_23_4" #include <stddef.h> #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 #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif #if !defined(CYTHON_USE_PYLONG_INTERNALS) && CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x02070000 #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #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_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #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 #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 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_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #elif CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #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 #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #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 #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__glove__metrics__accuracy_cython #define __PYX_HAVE_API__glove__metrics__accuracy_cython #include "pythread.h" #include "string.h" #include "stdlib.h" #include "stdio.h" #include "pystate.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif #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) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) && defined (_M_X64) #define __Pyx_sst_abs(value) _abs64(value) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(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); #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; 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; static const char *__pyx_f[] = { "glove/metrics/accuracy_cython.pyx", "stringsource", }; struct __pyx_memoryview_obj; typedef struct { struct __pyx_memoryview_obj *memview; char *data; Py_ssize_t shape[8]; Py_ssize_t strides[8]; Py_ssize_t suboffsets[8]; } __Pyx_memviewslice; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __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; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; #include <pythread.h> #ifndef CYTHON_ATOMICS #define CYTHON_ATOMICS 1 #endif #define __pyx_atomic_int_type int #if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 ||\ (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) &&\ !defined(__i386__) #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) #ifdef __PYX_DEBUG_ATOMICS #warning "Using GNU atomics" #endif #elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 #include <Windows.h> #undef __pyx_atomic_int_type #define __pyx_atomic_int_type LONG #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) #ifdef __PYX_DEBUG_ATOMICS #pragma message ("Using MSVC atomics") #endif #elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) #ifdef __PYX_DEBUG_ATOMICS #warning "Using Intel atomics" #endif #else #undef CYTHON_ATOMICS #define CYTHON_ATOMICS 0 #ifdef __PYX_DEBUG_ATOMICS #warning "Not using atomics" #endif #endif typedef volatile __pyx_atomic_int_type __pyx_atomic_int; #if CYTHON_ATOMICS #define __pyx_add_acquisition_count(memview)\ __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) #define __pyx_sub_acquisition_count(memview)\ __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) #else #define __pyx_add_acquisition_count(memview)\ __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #define __pyx_sub_acquisition_count(memview)\ __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #endif /*--- Type declarations ---*/ struct __pyx_array_obj; struct __pyx_MemviewEnum_obj; struct __pyx_memoryview_obj; struct __pyx_memoryviewslice_obj; /* "View.MemoryView":101 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_array_obj { PyObject_HEAD char *data; Py_ssize_t len; char *format; int ndim; Py_ssize_t *_shape; Py_ssize_t *_strides; Py_ssize_t itemsize; PyObject *mode; PyObject *_format; void (*callback_free_data)(void *); int free_data; int dtype_is_object; }; /* "View.MemoryView":271 * * @cname('__pyx_MemviewEnum') * cdef class Enum(object): # <<<<<<<<<<<<<< * cdef object name * def __init__(self, name): */ struct __pyx_MemviewEnum_obj { PyObject_HEAD PyObject *name; }; /* "View.MemoryView":304 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< * * cdef object obj */ struct __pyx_memoryview_obj { PyObject_HEAD struct __pyx_vtabstruct_memoryview *__pyx_vtab; PyObject *obj; PyObject *_size; PyObject *_array_interface; PyThread_type_lock lock; __pyx_atomic_int acquisition_count[2]; __pyx_atomic_int *acquisition_count_aligned_p; Py_buffer view; int flags; int dtype_is_object; __Pyx_TypeInfo *typeinfo; }; /* "View.MemoryView":923 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< * "Internal class for passing memoryview slices to Python" * */ struct __pyx_memoryviewslice_obj { struct __pyx_memoryview_obj __pyx_base; __Pyx_memviewslice from_slice; PyObject *from_object; PyObject *(*to_object_func)(char *); int (*to_dtype_func)(char *, PyObject *); }; /* "View.MemoryView":304 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< * * cdef object obj */ struct __pyx_vtabstruct_memoryview { char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); }; static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; /* "View.MemoryView":923 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< * "Internal class for passing memoryview slices to Python" * */ struct __pyx_vtabstruct__memoryviewslice { struct __pyx_vtabstruct_memoryview __pyx_base; }; static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; /* --- Runtime support code (head) --- */ #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); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #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, acquire_gil) #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 #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif static PyObject *__Pyx_GetBuiltinName(PyObject *name); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); 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); #define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d #define __Pyx_MEMVIEW_DIRECT 1 #define __Pyx_MEMVIEW_PTR 2 #define __Pyx_MEMVIEW_FULL 4 #define __Pyx_MEMVIEW_CONTIG 8 #define __Pyx_MEMVIEW_STRIDED 16 #define __Pyx_MEMVIEW_FOLLOW 32 #define __Pyx_IS_C_CONTIG 1 #define __Pyx_IS_F_CONTIG 2 static int __Pyx_init_memviewslice( struct __pyx_memoryview_obj *memview, int ndim, __Pyx_memviewslice *memviewslice, int memview_is_new_reference); static CYTHON_INLINE int __pyx_add_acquisition_count_locked( __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); #define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) #define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) #define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) #define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); #include <string.h> static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals #else #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals #endif #define UNARY_NEG_WOULD_OVERFLOW(x)\ (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); #define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ __Pyx_GetItemInt_Generic(o, to_py_func(i)))) #define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len)) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); Py_SIZE(list) = len+1; return 0; } return PyList_Append(list, x); } #else #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace)\ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) #endif static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { #if CYTHON_COMPILING_IN_CPYTHON PyObject* none = _PyList_Extend((PyListObject*)L, v); if (unlikely(!none)) return -1; Py_DECREF(none); return 0; #else return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); #endif } #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); Py_SIZE(list) = len+1; return 0; } return PyList_Append(list, x); } #else #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, int full_traceback, int nogil); #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); static int __Pyx_SetVtable(PyObject *dict, void *vtable); typedef struct { int code_line; PyCodeObject* code_object; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #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 static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); static int __Pyx_ValidateAndInit_memviewslice( int *axes_specs, int c_or_f_flag, int buf_flags, int ndim, __Pyx_TypeInfo *dtype, __Pyx_BufFmt_StackElem stack[], __Pyx_memviewslice *memviewslice, PyObject *original_obj); static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *); static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *); static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *); static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_int(PyObject *); static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *); static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, char order, int ndim); static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize); static __Pyx_memviewslice __pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, const char *mode, int ndim, size_t sizeof_dtype, int contig_flag, int dtype_is_object); static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ /* Module declarations from 'glove.metrics.accuracy_cython' */ static PyTypeObject *__pyx_array_type = 0; static PyTypeObject *__pyx_MemviewEnum_type = 0; static PyTypeObject *__pyx_memoryview_type = 0; static PyTypeObject *__pyx_memoryviewslice_type = 0; static PyObject *generic = 0; static PyObject *strided = 0; static PyObject *indirect = 0; static PyObject *contiguous = 0; static PyObject *indirect_contiguous = 0; static double __pyx_f_5glove_7metrics_15accuracy_cython_dot(__Pyx_memviewslice, __Pyx_memviewslice, int); /*proto*/ static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ static void *__pyx_align_pointer(void *, size_t); /*proto*/ static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ static PyObject *_unellipsify(PyObject *, int); /*proto*/ static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; #define __Pyx_MODULE_NAME "glove.metrics.accuracy_cython" int __pyx_module_is_main_glove__metrics__accuracy_cython = 0; /* Implementation of 'glove.metrics.accuracy_cython' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_Ellipsis; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_id; static PyObject *__pyx_builtin_IndexError; static char __pyx_k_O[] = "O"; static char __pyx_k_c[] = "c"; static char __pyx_k_i[] = "i"; static char __pyx_k_j[] = "j"; static char __pyx_k_k[] = "k"; static char __pyx_k_id[] = "id"; static char __pyx_k_obj[] = "obj"; static char __pyx_k_base[] = "base"; static char __pyx_k_main[] = "__main__"; static char __pyx_k_mode[] = "mode"; static char __pyx_k_name[] = "name"; static char __pyx_k_ndim[] = "ndim"; static char __pyx_k_pack[] = "pack"; static char __pyx_k_size[] = "size"; static char __pyx_k_step[] = "step"; static char __pyx_k_stop[] = "stop"; static char __pyx_k_test[] = "__test__"; static char __pyx_k_ASCII[] = "ASCII"; static char __pyx_k_class[] = "__class__"; static char __pyx_k_error[] = "error"; static char __pyx_k_flags[] = "flags"; static char __pyx_k_input[] = "input"; static char __pyx_k_range[] = "range"; static char __pyx_k_score[] = "score"; static char __pyx_k_shape[] = "shape"; static char __pyx_k_start[] = "start"; static char __pyx_k_encode[] = "encode"; static char __pyx_k_format[] = "format"; static char __pyx_k_import[] = "__import__"; static char __pyx_k_inputs[] = "inputs"; static char __pyx_k_name_2[] = "__name__"; static char __pyx_k_struct[] = "struct"; static char __pyx_k_unpack[] = "unpack"; static char __pyx_k_fortran[] = "fortran"; static char __pyx_k_memview[] = "memview"; static char __pyx_k_wordvec[] = "wordvec"; static char __pyx_k_Ellipsis[] = "Ellipsis"; static char __pyx_k_expected[] = "expected"; static char __pyx_k_itemsize[] = "itemsize"; static char __pyx_k_TypeError[] = "TypeError"; static char __pyx_k_enumerate[] = "enumerate"; static char __pyx_k_skip_word[] = "skip_word"; static char __pyx_k_IndexError[] = "IndexError"; static char __pyx_k_ValueError[] = "ValueError"; static char __pyx_k_no_threads[] = "no_threads"; static char __pyx_k_no_wordvec[] = "no_wordvec"; static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static char __pyx_k_violations[] = "violations"; static char __pyx_k_MemoryError[] = "MemoryError"; static char __pyx_k_wordvec_norm[] = "wordvec_norm"; static char __pyx_k_no_components[] = "no_components"; static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; static char __pyx_k_allocate_buffer[] = "allocate_buffer"; static char __pyx_k_dtype_is_object[] = "dtype_is_object"; static char __pyx_k_rank_violations[] = "rank_violations"; static char __pyx_k_no_input_vectors[] = "no_input_vectors"; static char __pyx_k_score_of_expected[] = "score_of_expected"; static char __pyx_k_strided_and_direct[] = "<strided and direct>"; static char __pyx_k_strided_and_indirect[] = "<strided and indirect>"; static char __pyx_k_contiguous_and_direct[] = "<contiguous and direct>"; static char __pyx_k_MemoryView_of_r_object[] = "<MemoryView of %r object>"; static char __pyx_k_MemoryView_of_r_at_0x_x[] = "<MemoryView of %r at 0x%x>"; static char __pyx_k_compute_rank_violations[] = "compute_rank_violations"; static char __pyx_k_contiguous_and_indirect[] = "<contiguous and indirect>"; static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; static char __pyx_k_glove_metrics_accuracy_cython[] = "glove.metrics.accuracy_cython"; static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; static char __pyx_k_home_maciej_Dropbox_code_glove[] = "/home/maciej/Dropbox/code/glove-python/glove/metrics/accuracy_cython.pyx"; static char __pyx_k_strided_and_direct_or_indirect[] = "<strided and direct or indirect>"; static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; static char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; static PyObject *__pyx_n_s_ASCII; static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; static PyObject *__pyx_kp_s_Cannot_index_with_type_s; static PyObject *__pyx_n_s_Ellipsis; static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; static PyObject *__pyx_n_s_IndexError; static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; static PyObject *__pyx_n_s_MemoryError; static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; static PyObject *__pyx_kp_s_MemoryView_of_r_object; static PyObject *__pyx_n_b_O; static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; static PyObject *__pyx_n_s_TypeError; static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_allocate_buffer; static PyObject *__pyx_n_s_base; static PyObject *__pyx_n_s_c; static PyObject *__pyx_n_u_c; static PyObject *__pyx_n_s_class; static PyObject *__pyx_n_s_compute_rank_violations; static PyObject *__pyx_kp_s_contiguous_and_direct; static PyObject *__pyx_kp_s_contiguous_and_indirect; static PyObject *__pyx_n_s_dtype_is_object; static PyObject *__pyx_n_s_encode; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_error; static PyObject *__pyx_n_s_expected; static PyObject *__pyx_n_s_flags; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_fortran; static PyObject *__pyx_n_u_fortran; static PyObject *__pyx_n_s_glove_metrics_accuracy_cython; static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; static PyObject *__pyx_kp_s_home_maciej_Dropbox_code_glove; static PyObject *__pyx_n_s_i; static PyObject *__pyx_n_s_id; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_input; static PyObject *__pyx_n_s_inputs; static PyObject *__pyx_n_s_itemsize; static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; static PyObject *__pyx_n_s_j; static PyObject *__pyx_n_s_k; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_memview; static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_name; static PyObject *__pyx_n_s_name_2; static PyObject *__pyx_n_s_ndim; static PyObject *__pyx_n_s_no_components; static PyObject *__pyx_n_s_no_input_vectors; static PyObject *__pyx_n_s_no_threads; static PyObject *__pyx_n_s_no_wordvec; static PyObject *__pyx_n_s_obj; static PyObject *__pyx_n_s_pack; static PyObject *__pyx_n_s_pyx_getbuffer; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_rank_violations; static PyObject *__pyx_n_s_score; static PyObject *__pyx_n_s_score_of_expected; static PyObject *__pyx_n_s_shape; static PyObject *__pyx_n_s_size; static PyObject *__pyx_n_s_skip_word; static PyObject *__pyx_n_s_start; static PyObject *__pyx_n_s_step; static PyObject *__pyx_n_s_stop; static PyObject *__pyx_kp_s_strided_and_direct; static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; static PyObject *__pyx_kp_s_strided_and_indirect; static PyObject *__pyx_n_s_struct; static PyObject *__pyx_n_s_test; static PyObject *__pyx_kp_s_unable_to_allocate_array_data; static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; static PyObject *__pyx_n_s_unpack; static PyObject *__pyx_n_s_violations; static PyObject *__pyx_n_s_wordvec; static PyObject *__pyx_n_s_wordvec_norm; static PyObject *__pyx_pf_5glove_7metrics_15accuracy_cython_compute_rank_violations(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_wordvec, __Pyx_memviewslice __pyx_v_wordvec_norm, __Pyx_memviewslice __pyx_v_input, __Pyx_memviewslice __pyx_v_expected, __Pyx_memviewslice __pyx_v_inputs, __Pyx_memviewslice __pyx_v_rank_violations, CYTHON_UNUSED int __pyx_v_no_threads); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_neg_1; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; static PyObject *__pyx_tuple__9; static PyObject *__pyx_slice__10; static PyObject *__pyx_slice__11; static PyObject *__pyx_slice__12; static PyObject *__pyx_tuple__13; static PyObject *__pyx_tuple__14; static PyObject *__pyx_tuple__16; static PyObject *__pyx_tuple__17; static PyObject *__pyx_tuple__18; static PyObject *__pyx_tuple__19; static PyObject *__pyx_tuple__20; static PyObject *__pyx_codeobj__15; /* "glove/metrics/accuracy_cython.pyx":7 * * * cdef double dot(double[::1] x, # <<<<<<<<<<<<<< * double[::1] y, * int dim) nogil: */ static double __pyx_f_5glove_7metrics_15accuracy_cython_dot(__Pyx_memviewslice __pyx_v_x, __Pyx_memviewslice __pyx_v_y, int __pyx_v_dim) { int __pyx_v_i; double __pyx_v_result; double __pyx_r; int __pyx_t_1; int __pyx_t_2; Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; /* "glove/metrics/accuracy_cython.pyx":12 * * cdef int i * cdef double result = 0.0 # <<<<<<<<<<<<<< * * for i in range(dim): */ __pyx_v_result = 0.0; /* "glove/metrics/accuracy_cython.pyx":14 * cdef double result = 0.0 * * for i in range(dim): # <<<<<<<<<<<<<< * result += x[i] * y[i] * */ __pyx_t_1 = __pyx_v_dim; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "glove/metrics/accuracy_cython.pyx":15 * * for i in range(dim): * result += x[i] * y[i] # <<<<<<<<<<<<<< * * return result */ __pyx_t_3 = __pyx_v_i; __pyx_t_4 = __pyx_v_i; __pyx_v_result = (__pyx_v_result + ((*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_x.data) + __pyx_t_3)) ))) * (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_y.data) + __pyx_t_4)) ))))); } /* "glove/metrics/accuracy_cython.pyx":17 * result += x[i] * y[i] * * return result # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_result; goto __pyx_L0; /* "glove/metrics/accuracy_cython.pyx":7 * * * cdef double dot(double[::1] x, # <<<<<<<<<<<<<< * double[::1] y, * int dim) nogil: */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "glove/metrics/accuracy_cython.pyx":20 * * * def compute_rank_violations(double[:, ::1] wordvec, # <<<<<<<<<<<<<< * double[::1] wordvec_norm, * double[:, ::1] input, */ /* Python wrapper */ static PyObject *__pyx_pw_5glove_7metrics_15accuracy_cython_1compute_rank_violations(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_5glove_7metrics_15accuracy_cython_compute_rank_violations[] = "\n Compute the rank violations\n of the expected words in the word analogy task.\n "; static PyMethodDef __pyx_mdef_5glove_7metrics_15accuracy_cython_1compute_rank_violations = {"compute_rank_violations", (PyCFunction)__pyx_pw_5glove_7metrics_15accuracy_cython_1compute_rank_violations, METH_VARARGS|METH_KEYWORDS, __pyx_doc_5glove_7metrics_15accuracy_cython_compute_rank_violations}; static PyObject *__pyx_pw_5glove_7metrics_15accuracy_cython_1compute_rank_violations(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_wordvec = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_wordvec_norm = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_input = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_expected = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_inputs = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_rank_violations = { 0, 0, { 0 }, { 0 }, { 0 } }; CYTHON_UNUSED int __pyx_v_no_threads; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("compute_rank_violations (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_wordvec,&__pyx_n_s_wordvec_norm,&__pyx_n_s_input,&__pyx_n_s_expected,&__pyx_n_s_inputs,&__pyx_n_s_rank_violations,&__pyx_n_s_no_threads,0}; PyObject* values[7] = {0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_wordvec)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_wordvec_norm)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_rank_violations", 1, 7, 7, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_input)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_rank_violations", 1, 7, 7, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_expected)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_rank_violations", 1, 7, 7, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_inputs)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_rank_violations", 1, 7, 7, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rank_violations)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_rank_violations", 1, 7, 7, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_no_threads)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("compute_rank_violations", 1, 7, 7, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "compute_rank_violations") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 7) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); } __pyx_v_wordvec = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(values[0]); if (unlikely(!__pyx_v_wordvec.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_wordvec_norm = __Pyx_PyObject_to_MemoryviewSlice_dc_double(values[1]); if (unlikely(!__pyx_v_wordvec_norm.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_input = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(values[2]); if (unlikely(!__pyx_v_input.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_expected = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[3]); if (unlikely(!__pyx_v_expected.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_inputs = __Pyx_PyObject_to_MemoryviewSlice_d_dc_int(values[4]); if (unlikely(!__pyx_v_inputs.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_rank_violations = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[5]); if (unlikely(!__pyx_v_rank_violations.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_no_threads = __Pyx_PyInt_As_int(values[6]); if (unlikely((__pyx_v_no_threads == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("compute_rank_violations", 1, 7, 7, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("glove.metrics.accuracy_cython.compute_rank_violations", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_5glove_7metrics_15accuracy_cython_compute_rank_violations(__pyx_self, __pyx_v_wordvec, __pyx_v_wordvec_norm, __pyx_v_input, __pyx_v_expected, __pyx_v_inputs, __pyx_v_rank_violations, __pyx_v_no_threads); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_5glove_7metrics_15accuracy_cython_compute_rank_violations(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_wordvec, __Pyx_memviewslice __pyx_v_wordvec_norm, __Pyx_memviewslice __pyx_v_input, __Pyx_memviewslice __pyx_v_expected, __Pyx_memviewslice __pyx_v_inputs, __Pyx_memviewslice __pyx_v_rank_violations, CYTHON_UNUSED int __pyx_v_no_threads) { int __pyx_v_i; int __pyx_v_j; int __pyx_v_k; CYTHON_UNUSED int __pyx_v_no_input_vectors; int __pyx_v_no_wordvec; int __pyx_v_skip_word; int __pyx_v_no_components; int __pyx_v_violations; double __pyx_v_score_of_expected; double __pyx_v_score; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; Py_ssize_t __pyx_t_5; __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; Py_ssize_t __pyx_t_7; Py_ssize_t __pyx_t_8; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; Py_ssize_t __pyx_t_12; Py_ssize_t __pyx_t_13; int __pyx_t_14; Py_ssize_t __pyx_t_15; Py_ssize_t __pyx_t_16; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("compute_rank_violations", 0); /* "glove/metrics/accuracy_cython.pyx":37 * cdef double score_of_expected, score * * no_input_vectors = input.shape[0] # <<<<<<<<<<<<<< * no_wordvec = wordvec.shape[0] * no_components = wordvec.shape[1] */ __pyx_v_no_input_vectors = (__pyx_v_input.shape[0]); /* "glove/metrics/accuracy_cython.pyx":38 * * no_input_vectors = input.shape[0] * no_wordvec = wordvec.shape[0] # <<<<<<<<<<<<<< * no_components = wordvec.shape[1] * */ __pyx_v_no_wordvec = (__pyx_v_wordvec.shape[0]); /* "glove/metrics/accuracy_cython.pyx":39 * no_input_vectors = input.shape[0] * no_wordvec = wordvec.shape[0] * no_components = wordvec.shape[1] # <<<<<<<<<<<<<< * * with nogil: */ __pyx_v_no_components = (__pyx_v_wordvec.shape[1]); /* "glove/metrics/accuracy_cython.pyx":41 * no_components = wordvec.shape[1] * * with nogil: # <<<<<<<<<<<<<< * for i in prange(no_input_vectors, num_threads=no_threads, * schedule='dynamic'): */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { /* "glove/metrics/accuracy_cython.pyx":42 * * with nogil: * for i in prange(no_input_vectors, num_threads=no_threads, # <<<<<<<<<<<<<< * schedule='dynamic'): * */ __pyx_t_1 = __pyx_v_no_input_vectors; if (1 == 0) abort(); { int __pyx_parallel_temp0 = 0xbad0bad0; int __pyx_parallel_temp1 = 0xbad0bad0; int __pyx_parallel_temp2 = 0xbad0bad0; double __pyx_parallel_temp3 = __PYX_NAN(); double __pyx_parallel_temp4 = __PYX_NAN(); int __pyx_parallel_temp5 = 0xbad0bad0; int __pyx_parallel_temp6 = 0xbad0bad0; const char *__pyx_parallel_filename = NULL; int __pyx_parallel_lineno = 0, __pyx_parallel_clineno = 0; PyObject *__pyx_parallel_exc_type = NULL, *__pyx_parallel_exc_value = NULL, *__pyx_parallel_exc_tb = NULL; int __pyx_parallel_why; __pyx_parallel_why = 0; #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) (x) #define unlikely(x) (x) #endif __pyx_t_3 = (__pyx_t_1 - 0) / 1; if (__pyx_t_3 > 0) { #ifdef _OPENMP #pragma omp parallel num_threads(__pyx_v_no_threads) private(__pyx_t_8, __pyx_t_10, __pyx_t_9, __pyx_t_15, __pyx_t_16, __pyx_t_13, __pyx_t_7, __pyx_t_12, __pyx_t_5, __pyx_t_14, __pyx_t_11) firstprivate(__pyx_t_4, __pyx_t_6) private(__pyx_filename, __pyx_lineno, __pyx_clineno) shared(__pyx_parallel_why, __pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb) #endif /* _OPENMP */ { #ifdef _OPENMP #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif Py_BEGIN_ALLOW_THREADS #endif /* _OPENMP */ #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_skip_word) lastprivate(__pyx_v_k) firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) lastprivate(__pyx_v_score_of_expected) lastprivate(__pyx_v_score) lastprivate(__pyx_v_violations) lastprivate(__pyx_v_j) schedule(dynamic) #endif /* _OPENMP */ for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){ if (__pyx_parallel_why < 2) { __pyx_v_i = 0 + 1 * __pyx_t_2; /* Initialize private variables to invalid values */ __pyx_v_skip_word = ((int)0xbad0bad0); __pyx_v_k = ((int)0xbad0bad0); __pyx_v_score_of_expected = ((double)__PYX_NAN()); __pyx_v_score = ((double)__PYX_NAN()); __pyx_v_violations = ((int)0xbad0bad0); __pyx_v_j = ((int)0xbad0bad0); /* "glove/metrics/accuracy_cython.pyx":46 * * # Compute the score of the expected word. * score_of_expected = (dot(input[i], # <<<<<<<<<<<<<< * wordvec[expected[i]], * no_components) */ __pyx_t_4.data = __pyx_v_input.data; __pyx_t_4.memview = __pyx_v_input.memview; __PYX_INC_MEMVIEW(&__pyx_t_4, 0); { Py_ssize_t __pyx_tmp_idx = __pyx_v_i; Py_ssize_t __pyx_tmp_shape = __pyx_v_input.shape[0]; Py_ssize_t __pyx_tmp_stride = __pyx_v_input.strides[0]; if (0 && (__pyx_tmp_idx < 0)) __pyx_tmp_idx += __pyx_tmp_shape; if (0 && (__pyx_tmp_idx < 0 || __pyx_tmp_idx >= __pyx_tmp_shape)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_IndexError, "Index out of bounds (axis 0)"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_t_4.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_4.shape[0] = __pyx_v_input.shape[1]; __pyx_t_4.strides[0] = __pyx_v_input.strides[1]; __pyx_t_4.suboffsets[0] = -1; __pyx_t_5 = __pyx_v_i; /* "glove/metrics/accuracy_cython.pyx":47 * # Compute the score of the expected word. * score_of_expected = (dot(input[i], * wordvec[expected[i]], # <<<<<<<<<<<<<< * no_components) * / wordvec_norm[expected[i]]) */ __pyx_t_6.data = __pyx_v_wordvec.data; __pyx_t_6.memview = __pyx_v_wordvec.memview; __PYX_INC_MEMVIEW(&__pyx_t_6, 0); { Py_ssize_t __pyx_tmp_idx = (*((int *) ( /* dim=0 */ (__pyx_v_expected.data + __pyx_t_5 * __pyx_v_expected.strides[0]) ))); Py_ssize_t __pyx_tmp_shape = __pyx_v_wordvec.shape[0]; Py_ssize_t __pyx_tmp_stride = __pyx_v_wordvec.strides[0]; if (0 && (__pyx_tmp_idx < 0)) __pyx_tmp_idx += __pyx_tmp_shape; if (0 && (__pyx_tmp_idx < 0 || __pyx_tmp_idx >= __pyx_tmp_shape)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_IndexError, "Index out of bounds (axis 0)"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_t_6.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_6.shape[0] = __pyx_v_wordvec.shape[1]; __pyx_t_6.strides[0] = __pyx_v_wordvec.strides[1]; __pyx_t_6.suboffsets[0] = -1; __pyx_t_7 = __pyx_v_i; /* "glove/metrics/accuracy_cython.pyx":49 * wordvec[expected[i]], * no_components) * / wordvec_norm[expected[i]]) # <<<<<<<<<<<<<< * * # Compute all other scores and count */ __pyx_t_8 = (*((int *) ( /* dim=0 */ (__pyx_v_expected.data + __pyx_t_7 * __pyx_v_expected.strides[0]) ))); __pyx_v_score_of_expected = (__pyx_f_5glove_7metrics_15accuracy_cython_dot(__pyx_t_4, __pyx_t_6, __pyx_v_no_components) / (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_wordvec_norm.data) + __pyx_t_8)) )))); __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0); __PYX_XDEC_MEMVIEW(&__pyx_t_6, 0); /* "glove/metrics/accuracy_cython.pyx":53 * # Compute all other scores and count * # rank violations. * violations = 0 # <<<<<<<<<<<<<< * * for j in range(no_wordvec): */ __pyx_v_violations = 0; /* "glove/metrics/accuracy_cython.pyx":55 * violations = 0 * * for j in range(no_wordvec): # <<<<<<<<<<<<<< * * # Words from the input do not */ __pyx_t_9 = __pyx_v_no_wordvec; for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { __pyx_v_j = __pyx_t_10; /* "glove/metrics/accuracy_cython.pyx":59 * # Words from the input do not * # count as violations. * skip_word = 0 # <<<<<<<<<<<<<< * for k in range(4): * if inputs[i, k] == j: */ __pyx_v_skip_word = 0; /* "glove/metrics/accuracy_cython.pyx":60 * # count as violations. * skip_word = 0 * for k in range(4): # <<<<<<<<<<<<<< * if inputs[i, k] == j: * skip_word = 1 */ for (__pyx_t_11 = 0; __pyx_t_11 < 4; __pyx_t_11+=1) { __pyx_v_k = __pyx_t_11; /* "glove/metrics/accuracy_cython.pyx":61 * skip_word = 0 * for k in range(4): * if inputs[i, k] == j: # <<<<<<<<<<<<<< * skip_word = 1 * break */ __pyx_t_12 = __pyx_v_i; __pyx_t_13 = __pyx_v_k; __pyx_t_14 = (((*((int *) ( /* dim=1 */ ((char *) (((int *) ( /* dim=0 */ (__pyx_v_inputs.data + __pyx_t_12 * __pyx_v_inputs.strides[0]) )) + __pyx_t_13)) ))) == __pyx_v_j) != 0); if (__pyx_t_14) { /* "glove/metrics/accuracy_cython.pyx":62 * for k in range(4): * if inputs[i, k] == j: * skip_word = 1 # <<<<<<<<<<<<<< * break * */ __pyx_v_skip_word = 1; /* "glove/metrics/accuracy_cython.pyx":63 * if inputs[i, k] == j: * skip_word = 1 * break # <<<<<<<<<<<<<< * * if skip_word == 1: */ goto __pyx_L13_break; /* "glove/metrics/accuracy_cython.pyx":61 * skip_word = 0 * for k in range(4): * if inputs[i, k] == j: # <<<<<<<<<<<<<< * skip_word = 1 * break */ } } __pyx_L13_break:; /* "glove/metrics/accuracy_cython.pyx":65 * break * * if skip_word == 1: # <<<<<<<<<<<<<< * continue * */ __pyx_t_14 = ((__pyx_v_skip_word == 1) != 0); if (__pyx_t_14) { /* "glove/metrics/accuracy_cython.pyx":66 * * if skip_word == 1: * continue # <<<<<<<<<<<<<< * * score = (dot(input[i], */ goto __pyx_L10_continue; /* "glove/metrics/accuracy_cython.pyx":65 * break * * if skip_word == 1: # <<<<<<<<<<<<<< * continue * */ } /* "glove/metrics/accuracy_cython.pyx":68 * continue * * score = (dot(input[i], # <<<<<<<<<<<<<< * wordvec[j], * no_components) */ __pyx_t_6.data = __pyx_v_input.data; __pyx_t_6.memview = __pyx_v_input.memview; __PYX_INC_MEMVIEW(&__pyx_t_6, 0); { Py_ssize_t __pyx_tmp_idx = __pyx_v_i; Py_ssize_t __pyx_tmp_shape = __pyx_v_input.shape[0]; Py_ssize_t __pyx_tmp_stride = __pyx_v_input.strides[0]; if (0 && (__pyx_tmp_idx < 0)) __pyx_tmp_idx += __pyx_tmp_shape; if (0 && (__pyx_tmp_idx < 0 || __pyx_tmp_idx >= __pyx_tmp_shape)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_IndexError, "Index out of bounds (axis 0)"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_t_6.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_6.shape[0] = __pyx_v_input.shape[1]; __pyx_t_6.strides[0] = __pyx_v_input.strides[1]; __pyx_t_6.suboffsets[0] = -1; __pyx_t_4.data = __pyx_v_wordvec.data; /* "glove/metrics/accuracy_cython.pyx":69 * * score = (dot(input[i], * wordvec[j], # <<<<<<<<<<<<<< * no_components) * / wordvec_norm[j]) */ __pyx_t_4.memview = __pyx_v_wordvec.memview; __PYX_INC_MEMVIEW(&__pyx_t_4, 0); { Py_ssize_t __pyx_tmp_idx = __pyx_v_j; Py_ssize_t __pyx_tmp_shape = __pyx_v_wordvec.shape[0]; Py_ssize_t __pyx_tmp_stride = __pyx_v_wordvec.strides[0]; if (0 && (__pyx_tmp_idx < 0)) __pyx_tmp_idx += __pyx_tmp_shape; if (0 && (__pyx_tmp_idx < 0 || __pyx_tmp_idx >= __pyx_tmp_shape)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_IndexError, "Index out of bounds (axis 0)"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_t_4.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_4.shape[0] = __pyx_v_wordvec.shape[1]; __pyx_t_4.strides[0] = __pyx_v_wordvec.strides[1]; __pyx_t_4.suboffsets[0] = -1; __pyx_t_15 = __pyx_v_j; /* "glove/metrics/accuracy_cython.pyx":71 * wordvec[j], * no_components) * / wordvec_norm[j]) # <<<<<<<<<<<<<< * * if score >= score_of_expected: */ __pyx_v_score = (__pyx_f_5glove_7metrics_15accuracy_cython_dot(__pyx_t_6, __pyx_t_4, __pyx_v_no_components) / (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_wordvec_norm.data) + __pyx_t_15)) )))); __PYX_XDEC_MEMVIEW(&__pyx_t_6, 0); __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0); /* "glove/metrics/accuracy_cython.pyx":73 * / wordvec_norm[j]) * * if score >= score_of_expected: # <<<<<<<<<<<<<< * violations = violations + 1 * */ __pyx_t_14 = ((__pyx_v_score >= __pyx_v_score_of_expected) != 0); if (__pyx_t_14) { /* "glove/metrics/accuracy_cython.pyx":74 * * if score >= score_of_expected: * violations = violations + 1 # <<<<<<<<<<<<<< * * # Update the average rank with the rank */ __pyx_v_violations = (__pyx_v_violations + 1); /* "glove/metrics/accuracy_cython.pyx":73 * / wordvec_norm[j]) * * if score >= score_of_expected: # <<<<<<<<<<<<<< * violations = violations + 1 * */ } __pyx_L10_continue:; } /* "glove/metrics/accuracy_cython.pyx":78 * # Update the average rank with the rank * # of this example. * rank_violations[i] = violations # <<<<<<<<<<<<<< */ __pyx_t_16 = __pyx_v_i; *((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_rank_violations.data) + __pyx_t_16)) )) = __pyx_v_violations; goto __pyx_L18; __pyx_L8_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #ifdef _OPENMP #pragma omp flush(__pyx_parallel_exc_type) #endif /* _OPENMP */ if (!__pyx_parallel_exc_type) { __Pyx_ErrFetch(&__pyx_parallel_exc_type, &__pyx_parallel_exc_value, &__pyx_parallel_exc_tb); __pyx_parallel_filename = __pyx_filename; __pyx_parallel_lineno = __pyx_lineno; __pyx_parallel_clineno = __pyx_clineno; __Pyx_GOTREF(__pyx_parallel_exc_type); } #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_parallel_why = 4; goto __pyx_L17; __pyx_L17:; #ifdef _OPENMP #pragma omp critical(__pyx_parallel_lastprivates0) #endif /* _OPENMP */ { __pyx_parallel_temp0 = __pyx_v_skip_word; __pyx_parallel_temp1 = __pyx_v_k; __pyx_parallel_temp2 = __pyx_v_i; __pyx_parallel_temp3 = __pyx_v_score_of_expected; __pyx_parallel_temp4 = __pyx_v_score; __pyx_parallel_temp5 = __pyx_v_violations; __pyx_parallel_temp6 = __pyx_v_j; } __pyx_L18:; #ifdef _OPENMP #pragma omp flush(__pyx_parallel_why) #endif /* _OPENMP */ } } #ifdef _OPENMP Py_END_ALLOW_THREADS #else { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #endif /* _OPENMP */ /* Clean up any temporaries */ __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0); __PYX_XDEC_MEMVIEW(&__pyx_t_6, 0); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif #ifndef _OPENMP } #endif /* _OPENMP */ } } if (__pyx_parallel_exc_type) { /* This may have been overridden by a continue, break or return in another thread. Prefer the error. */ __pyx_parallel_why = 4; } if (__pyx_parallel_why) { __pyx_v_skip_word = __pyx_parallel_temp0; __pyx_v_k = __pyx_parallel_temp1; __pyx_v_i = __pyx_parallel_temp2; __pyx_v_score_of_expected = __pyx_parallel_temp3; __pyx_v_score = __pyx_parallel_temp4; __pyx_v_violations = __pyx_parallel_temp5; __pyx_v_j = __pyx_parallel_temp6; switch (__pyx_parallel_why) { case 3: goto __pyx_L3_return; case 4: { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_GIVEREF(__pyx_parallel_exc_type); __Pyx_ErrRestore(__pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb); __pyx_filename = __pyx_parallel_filename; __pyx_lineno = __pyx_parallel_lineno; __pyx_clineno = __pyx_parallel_clineno; #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } goto __pyx_L4_error; } } } #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #endif } /* "glove/metrics/accuracy_cython.pyx":41 * no_components = wordvec.shape[1] * * with nogil: # <<<<<<<<<<<<<< * for i in prange(no_input_vectors, num_threads=no_threads, * schedule='dynamic'): */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L3_return: { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L0; } __pyx_L4_error: { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L1_error; } __pyx_L5:; } } /* "glove/metrics/accuracy_cython.pyx":20 * * * def compute_rank_violations(double[:, ::1] wordvec, # <<<<<<<<<<<<<< * double[::1] wordvec_norm, * double[:, ::1] input, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __PYX_XDEC_MEMVIEW(&__pyx_t_4, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); __Pyx_AddTraceback("glove.metrics.accuracy_cython.compute_rank_violations", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_wordvec, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_wordvec_norm, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_input, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_expected, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_inputs, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_rank_violations, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":118 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* Python wrapper */ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_shape = 0; Py_ssize_t __pyx_v_itemsize; PyObject *__pyx_v_format = 0; PyObject *__pyx_v_mode = 0; int __pyx_v_allocate_buffer; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; PyObject* values[5] = {0,0,0,0,0}; values[3] = ((PyObject *)__pyx_n_s_c); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); if (value) { values[3] = value; kw_args--; } } case 4: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); if (value) { values[4] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_shape = ((PyObject*)values[0]); __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_format = values[2]; __pyx_v_mode = values[3]; if (values[4]) { __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { /* "View.MemoryView":119 * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< * * cdef int idx */ __pyx_v_allocate_buffer = ((int)1); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); /* "View.MemoryView":118 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { int __pyx_v_idx; Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_dim; PyObject **__pyx_v_p; char __pyx_v_order; int __pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; char *__pyx_t_6; int __pyx_t_7; Py_ssize_t __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF(__pyx_v_format); /* "View.MemoryView":125 * cdef PyObject **p * * self.ndim = <int> len(shape) # <<<<<<<<<<<<<< * self.itemsize = itemsize * */ if (unlikely(__pyx_v_shape == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_self->ndim = ((int)__pyx_t_1); /* "View.MemoryView":126 * * self.ndim = <int> len(shape) * self.itemsize = itemsize # <<<<<<<<<<<<<< * * if not self.ndim: */ __pyx_v_self->itemsize = __pyx_v_itemsize; /* "View.MemoryView":128 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":129 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 129; __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 = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":128 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ } /* "View.MemoryView":131 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":132 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 132; __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 = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":131 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ } /* "View.MemoryView":134 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ __pyx_t_2 = PyBytes_Check(__pyx_v_format); __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":135 * * if not isinstance(format, bytes): * format = format.encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":134 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ } /* "View.MemoryView":136 * if not isinstance(format, bytes): * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< * self.format = self._format * */ if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_5 = __pyx_v_format; __Pyx_INCREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __Pyx_GOTREF(__pyx_v_self->_format); __Pyx_DECREF(__pyx_v_self->_format); __pyx_v_self->_format = ((PyObject*)__pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":137 * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string * self.format = self._format # <<<<<<<<<<<<<< * * */ __pyx_t_6 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_6) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 137; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_self->format = __pyx_t_6; /* "View.MemoryView":140 * * * self._shape = <Py_ssize_t *> PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< * self._strides = self._shape + self.ndim * */ __pyx_v_self->_shape = ((Py_ssize_t *)PyMem_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); /* "View.MemoryView":141 * * self._shape = <Py_ssize_t *> PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< * * if not self._shape: */ __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); /* "View.MemoryView":143 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":144 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __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 = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":143 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ } /* "View.MemoryView":147 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ __pyx_t_7 = 0; __pyx_t_5 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_5); __pyx_t_1 = 0; for (;;) { if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_5)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_5, __pyx_t_1); __Pyx_INCREF(__pyx_t_3); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_3 = PySequence_ITEM(__pyx_t_5, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); #endif __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_dim = __pyx_t_8; __pyx_v_idx = __pyx_t_7; __pyx_t_7 = (__pyx_t_7 + 1); /* "View.MemoryView":148 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); if (__pyx_t_4) { /* "View.MemoryView":149 * for idx, dim in enumerate(shape): * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< * self._shape[idx] = dim * */ __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); __pyx_t_3 = 0; __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __Pyx_Raise(__pyx_t_9, 0, 0, 0); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":148 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ } /* "View.MemoryView":150 * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim # <<<<<<<<<<<<<< * * cdef char order */ (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; /* "View.MemoryView":147 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ } __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":153 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":154 * cdef char order * if mode == 'fortran': * order = b'F' # <<<<<<<<<<<<<< * self.mode = u'fortran' * elif mode == 'c': */ __pyx_v_order = 'F'; /* "View.MemoryView":155 * if mode == 'fortran': * order = b'F' * self.mode = u'fortran' # <<<<<<<<<<<<<< * elif mode == 'c': * order = b'C' */ __Pyx_INCREF(__pyx_n_u_fortran); __Pyx_GIVEREF(__pyx_n_u_fortran); __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_fortran; /* "View.MemoryView":153 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ goto __pyx_L10; } /* "View.MemoryView":156 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":157 * self.mode = u'fortran' * elif mode == 'c': * order = b'C' # <<<<<<<<<<<<<< * self.mode = u'c' * else: */ __pyx_v_order = 'C'; /* "View.MemoryView":158 * elif mode == 'c': * order = b'C' * self.mode = u'c' # <<<<<<<<<<<<<< * else: * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) */ __Pyx_INCREF(__pyx_n_u_c); __Pyx_GIVEREF(__pyx_n_u_c); __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_c; /* "View.MemoryView":156 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ goto __pyx_L10; } /* "View.MemoryView":160 * self.mode = u'c' * else: * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< * * self.len = fill_contig_strides_array(self._shape, self._strides, */ /*else*/ { __pyx_t_5 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 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 = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L10:; /* "View.MemoryView":162 * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) * * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< * itemsize, self.ndim, order) * */ __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); /* "View.MemoryView":165 * itemsize, self.ndim, order) * * self.free_data = allocate_buffer # <<<<<<<<<<<<<< * self.dtype_is_object = format == b'O' * if allocate_buffer: */ __pyx_v_self->free_data = __pyx_v_allocate_buffer; /* "View.MemoryView":166 * * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< * if allocate_buffer: * */ __pyx_t_5 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_self->dtype_is_object = __pyx_t_4; /* "View.MemoryView":167 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ __pyx_t_4 = (__pyx_v_allocate_buffer != 0); if (__pyx_t_4) { /* "View.MemoryView":170 * * * self.data = <char *>malloc(self.len) # <<<<<<<<<<<<<< * if not self.data: * raise MemoryError("unable to allocate array data.") */ __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); /* "View.MemoryView":171 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":172 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __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 = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":171 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ } /* "View.MemoryView":174 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< * p = <PyObject **> self.data * for i in range(self.len / itemsize): */ __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_4) { /* "View.MemoryView":175 * * if self.dtype_is_object: * p = <PyObject **> self.data # <<<<<<<<<<<<<< * for i in range(self.len / itemsize): * p[i] = Py_None */ __pyx_v_p = ((PyObject **)__pyx_v_self->data); /* "View.MemoryView":176 * if self.dtype_is_object: * p = <PyObject **> self.data * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< * p[i] = Py_None * Py_INCREF(Py_None) */ if (unlikely(__pyx_v_itemsize == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize); for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { __pyx_v_i = __pyx_t_8; /* "View.MemoryView":177 * p = <PyObject **> self.data * for i in range(self.len / itemsize): * p[i] = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ (__pyx_v_p[__pyx_v_i]) = Py_None; /* "View.MemoryView":178 * for i in range(self.len / itemsize): * p[i] = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * @cname('getbuffer') */ Py_INCREF(Py_None); } /* "View.MemoryView":174 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< * p = <PyObject **> self.data * for i in range(self.len / itemsize): */ } /* "View.MemoryView":167 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":118 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_format); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":181 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * cdef int bufmode = -1 * if self.mode == u"c": */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_bufmode; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; char *__pyx_t_4; Py_ssize_t __pyx_t_5; int __pyx_t_6; Py_ssize_t *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "View.MemoryView":182 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 # <<<<<<<<<<<<<< * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS */ __pyx_v_bufmode = -1; /* "View.MemoryView":183 * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 * if self.mode == u"c": # <<<<<<<<<<<<<< * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": */ __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":184 * cdef int bufmode = -1 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS */ __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); /* "View.MemoryView":183 * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 * if self.mode == u"c": # <<<<<<<<<<<<<< * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": */ goto __pyx_L3; } /* "View.MemoryView":185 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": # <<<<<<<<<<<<<< * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): */ __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":186 * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") */ __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); /* "View.MemoryView":185 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": # <<<<<<<<<<<<<< * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): */ } __pyx_L3:; /* "View.MemoryView":187 * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): # <<<<<<<<<<<<<< * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data */ __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":188 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 188; __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 = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":187 * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): # <<<<<<<<<<<<<< * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data */ } /* "View.MemoryView":189 * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data # <<<<<<<<<<<<<< * info.len = self.len * info.ndim = self.ndim */ __pyx_t_4 = __pyx_v_self->data; __pyx_v_info->buf = __pyx_t_4; /* "View.MemoryView":190 * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data * info.len = self.len # <<<<<<<<<<<<<< * info.ndim = self.ndim * info.shape = self._shape */ __pyx_t_5 = __pyx_v_self->len; __pyx_v_info->len = __pyx_t_5; /* "View.MemoryView":191 * info.buf = self.data * info.len = self.len * info.ndim = self.ndim # <<<<<<<<<<<<<< * info.shape = self._shape * info.strides = self._strides */ __pyx_t_6 = __pyx_v_self->ndim; __pyx_v_info->ndim = __pyx_t_6; /* "View.MemoryView":192 * info.len = self.len * info.ndim = self.ndim * info.shape = self._shape # <<<<<<<<<<<<<< * info.strides = self._strides * info.suboffsets = NULL */ __pyx_t_7 = __pyx_v_self->_shape; __pyx_v_info->shape = __pyx_t_7; /* "View.MemoryView":193 * info.ndim = self.ndim * info.shape = self._shape * info.strides = self._strides # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = self.itemsize */ __pyx_t_7 = __pyx_v_self->_strides; __pyx_v_info->strides = __pyx_t_7; /* "View.MemoryView":194 * info.shape = self._shape * info.strides = self._strides * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = self.itemsize * info.readonly = 0 */ __pyx_v_info->suboffsets = NULL; /* "View.MemoryView":195 * info.strides = self._strides * info.suboffsets = NULL * info.itemsize = self.itemsize # <<<<<<<<<<<<<< * info.readonly = 0 * */ __pyx_t_5 = __pyx_v_self->itemsize; __pyx_v_info->itemsize = __pyx_t_5; /* "View.MemoryView":196 * info.suboffsets = NULL * info.itemsize = self.itemsize * info.readonly = 0 # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ __pyx_v_info->readonly = 0; /* "View.MemoryView":198 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":199 * * if flags & PyBUF_FORMAT: * info.format = self.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_4 = __pyx_v_self->format; __pyx_v_info->format = __pyx_t_4; /* "View.MemoryView":198 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ goto __pyx_L5; } /* "View.MemoryView":201 * info.format = self.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.obj = self */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L5:; /* "View.MemoryView":203 * info.format = NULL * * info.obj = self # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "View.MemoryView":181 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * cdef int bufmode = -1 * if self.mode == u"c": */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.array.__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_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":207 * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< * if self.callback_free_data != NULL: * self.callback_free_data(self.data) */ /* Python wrapper */ static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":208 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< * self.callback_free_data(self.data) * elif self.free_data: */ __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":209 * def __dealloc__(array self): * if self.callback_free_data != NULL: * self.callback_free_data(self.data) # <<<<<<<<<<<<<< * elif self.free_data: * if self.dtype_is_object: */ __pyx_v_self->callback_free_data(__pyx_v_self->data); /* "View.MemoryView":208 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< * self.callback_free_data(self.data) * elif self.free_data: */ goto __pyx_L3; } /* "View.MemoryView":210 * if self.callback_free_data != NULL: * self.callback_free_data(self.data) * elif self.free_data: # <<<<<<<<<<<<<< * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, */ __pyx_t_1 = (__pyx_v_self->free_data != 0); if (__pyx_t_1) { /* "View.MemoryView":211 * self.callback_free_data(self.data) * elif self.free_data: * if self.dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) */ __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":212 * elif self.free_data: * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< * self._strides, self.ndim, False) * free(self.data) */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); /* "View.MemoryView":211 * self.callback_free_data(self.data) * elif self.free_data: * if self.dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) */ } /* "View.MemoryView":214 * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) * free(self.data) # <<<<<<<<<<<<<< * PyMem_Free(self._shape) * */ free(__pyx_v_self->data); /* "View.MemoryView":210 * if self.callback_free_data != NULL: * self.callback_free_data(self.data) * elif self.free_data: # <<<<<<<<<<<<<< * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, */ } __pyx_L3:; /* "View.MemoryView":215 * self._strides, self.ndim, False) * free(self.data) * PyMem_Free(self._shape) # <<<<<<<<<<<<<< * * property memview: */ PyMem_Free(__pyx_v_self->_shape); /* "View.MemoryView":207 * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< * if self.callback_free_data != NULL: * self.callback_free_data(self.data) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":219 * property memview: * @cname('get_memview') * def __get__(self): # <<<<<<<<<<<<<< * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE */ /* Python wrapper */ static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ static PyObject *get_memview(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":221 * def __get__(self): * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< * return memoryview(self, flags, self.dtype_is_object) * */ __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); /* "View.MemoryView":222 * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":219 * property memview: * @cname('get_memview') * def __get__(self): # <<<<<<<<<<<<<< * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":225 * * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) * */ /* Python wrapper */ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getattr__", 0); /* "View.MemoryView":226 * * def __getattr__(self, attr): * return getattr(self.memview, attr) # <<<<<<<<<<<<<< * * def __getitem__(self, item): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":225 * * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":228 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< * return self.memview[item] * */ /* Python wrapper */ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":229 * * def __getitem__(self, item): * return self.memview[item] # <<<<<<<<<<<<<< * * def __setitem__(self, item, value): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 229; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 229; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":228 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< * return self.memview[item] * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":231 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* Python wrapper */ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); /* "View.MemoryView":232 * * def __setitem__(self, item, value): * self.memview[item] = value # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":231 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":236 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< * char *mode, char *buf): * cdef array result */ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { struct __pyx_array_obj *__pyx_v_result = 0; struct __pyx_array_obj *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("array_cwrapper", 0); /* "View.MemoryView":240 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":241 * * if buf == NULL: * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), */ __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":240 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ goto __pyx_L3; } /* "View.MemoryView":243 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ /*else*/ { __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_3 = 0; /* "View.MemoryView":244 * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) # <<<<<<<<<<<<<< * result.data = buf * */ __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":243 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 243; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":245 * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) * result.data = buf # <<<<<<<<<<<<<< * * return result */ __pyx_v_result->data = __pyx_v_buf; } __pyx_L3:; /* "View.MemoryView":247 * result.data = buf * * return result # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":236 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< * char *mode, char *buf): * cdef array result */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":273 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< * self.name = name * def __repr__(self): */ /* Python wrapper */ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_name = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); } __pyx_v_name = values[0]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__", 0); /* "View.MemoryView":274 * cdef object name * def __init__(self, name): * self.name = name # <<<<<<<<<<<<<< * def __repr__(self): * return self.name */ __Pyx_INCREF(__pyx_v_name); __Pyx_GIVEREF(__pyx_v_name); __Pyx_GOTREF(__pyx_v_self->name); __Pyx_DECREF(__pyx_v_self->name); __pyx_v_self->name = __pyx_v_name; /* "View.MemoryView":273 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< * self.name = name * def __repr__(self): */ /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":275 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< * return self.name * */ /* Python wrapper */ static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__", 0); /* "View.MemoryView":276 * self.name = name * def __repr__(self): * return self.name # <<<<<<<<<<<<<< * * cdef generic = Enum("<strided and direct or indirect>") */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->name); __pyx_r = __pyx_v_self->name; goto __pyx_L0; /* "View.MemoryView":275 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< * return self.name * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":290 * * @cname('__pyx_align_pointer') * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory */ static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { Py_intptr_t __pyx_v_aligned_p; size_t __pyx_v_offset; void *__pyx_r; int __pyx_t_1; /* "View.MemoryView":292 * cdef void *align_pointer(void *memory, size_t alignment) nogil: * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory # <<<<<<<<<<<<<< * cdef size_t offset * */ __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); /* "View.MemoryView":296 * * with cython.cdivision(True): * offset = aligned_p % alignment # <<<<<<<<<<<<<< * * if offset > 0: */ __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); /* "View.MemoryView":298 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ __pyx_t_1 = ((__pyx_v_offset > 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":299 * * if offset > 0: * aligned_p += alignment - offset # <<<<<<<<<<<<<< * * return <void *> aligned_p */ __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); /* "View.MemoryView":298 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ } /* "View.MemoryView":301 * aligned_p += alignment - offset * * return <void *> aligned_p # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview') */ __pyx_r = ((void *)__pyx_v_aligned_p); goto __pyx_L0; /* "View.MemoryView":290 * * @cname('__pyx_align_pointer') * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":319 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< * self.obj = obj * self.flags = flags */ /* Python wrapper */ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_obj = 0; int __pyx_v_flags; int __pyx_v_dtype_is_object; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); if (value) { values[2] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_obj = values[0]; __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} if (values[2]) { __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_dtype_is_object = ((int)0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 319; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); /* "View.MemoryView":320 * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj # <<<<<<<<<<<<<< * self.flags = flags * if type(self) is memoryview or obj is not None: */ __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); __Pyx_GOTREF(__pyx_v_self->obj); __Pyx_DECREF(__pyx_v_self->obj); __pyx_v_self->obj = __pyx_v_obj; /* "View.MemoryView":321 * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj * self.flags = flags # <<<<<<<<<<<<<< * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) */ __pyx_v_self->flags = __pyx_v_flags; /* "View.MemoryView":322 * self.obj = obj * self.flags = flags * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: */ __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)__pyx_memoryview_type)); __pyx_t_3 = (__pyx_t_2 != 0); if (!__pyx_t_3) { } else { __pyx_t_1 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } __pyx_t_3 = (__pyx_v_obj != Py_None); __pyx_t_2 = (__pyx_t_3 != 0); __pyx_t_1 = __pyx_t_2; __pyx_L4_bool_binop_done:; if (__pyx_t_1) { /* "View.MemoryView":323 * self.flags = flags * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None */ __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":324 * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: # <<<<<<<<<<<<<< * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) */ __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":325 * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; /* "View.MemoryView":326 * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * self.lock = PyThread_allocate_lock() */ Py_INCREF(Py_None); /* "View.MemoryView":324 * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: # <<<<<<<<<<<<<< * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) */ } /* "View.MemoryView":322 * self.obj = obj * self.flags = flags * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: */ } /* "View.MemoryView":328 * Py_INCREF(Py_None) * * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< * if self.lock == NULL: * raise MemoryError */ __pyx_v_self->lock = PyThread_allocate_lock(); /* "View.MemoryView":329 * * self.lock = PyThread_allocate_lock() * if self.lock == NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":330 * self.lock = PyThread_allocate_lock() * if self.lock == NULL: * raise MemoryError # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ PyErr_NoMemory(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 330; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":329 * * self.lock = PyThread_allocate_lock() * if self.lock == NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ } /* "View.MemoryView":332 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = self.view.format == b'O' * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":333 * * if flags & PyBUF_FORMAT: * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< * else: * self.dtype_is_object = dtype_is_object */ __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_v_self->dtype_is_object = __pyx_t_1; /* "View.MemoryView":332 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = self.view.format == b'O' * else: */ goto __pyx_L8; } /* "View.MemoryView":335 * self.dtype_is_object = self.view.format == b'O' * else: * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( */ /*else*/ { __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; } __pyx_L8:; /* "View.MemoryView":337 * self.dtype_is_object = dtype_is_object * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< * <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) * self.typeinfo = NULL */ __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); /* "View.MemoryView":339 * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( * <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) * self.typeinfo = NULL # <<<<<<<<<<<<<< * * def __dealloc__(memoryview self): */ __pyx_v_self->typeinfo = NULL; /* "View.MemoryView":319 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< * self.obj = obj * self.flags = flags */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":341 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* Python wrapper */ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":342 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * */ __pyx_t_1 = (__pyx_v_self->obj != Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":343 * def __dealloc__(memoryview self): * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< * * if self.lock != NULL: */ __Pyx_ReleaseBuffer((&__pyx_v_self->view)); /* "View.MemoryView":342 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * */ } /* "View.MemoryView":345 * __Pyx_ReleaseBuffer(&self.view) * * if self.lock != NULL: # <<<<<<<<<<<<<< * PyThread_free_lock(self.lock) * */ __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":346 * * if self.lock != NULL: * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< * * cdef char *get_item_pointer(memoryview self, object index) except NULL: */ PyThread_free_lock(__pyx_v_self->lock); /* "View.MemoryView":345 * __Pyx_ReleaseBuffer(&self.view) * * if self.lock != NULL: # <<<<<<<<<<<<<< * PyThread_free_lock(self.lock) * */ } /* "View.MemoryView":341 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":348 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf */ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { Py_ssize_t __pyx_v_dim; char *__pyx_v_itemp; PyObject *__pyx_v_idx = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; Py_ssize_t __pyx_t_3; PyObject *(*__pyx_t_4)(PyObject *); PyObject *__pyx_t_5 = NULL; Py_ssize_t __pyx_t_6; char *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_item_pointer", 0); /* "View.MemoryView":350 * cdef char *get_item_pointer(memoryview self, object index) except NULL: * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf # <<<<<<<<<<<<<< * * for dim, idx in enumerate(index): */ __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); /* "View.MemoryView":352 * cdef char *itemp = <char *> self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< * itemp = pybuffer_index(&self.view, itemp, idx, dim) * */ __pyx_t_1 = 0; if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; __pyx_t_4 = NULL; } else { __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } for (;;) { if (likely(!__pyx_t_4)) { if (likely(PyList_CheckExact(__pyx_t_2))) { if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); #endif } else { if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); #endif } } else { __pyx_t_5 = __pyx_t_4(__pyx_t_2); if (unlikely(!__pyx_t_5)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_5); } __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); __pyx_t_5 = 0; __pyx_v_dim = __pyx_t_1; __pyx_t_1 = (__pyx_t_1 + 1); /* "View.MemoryView":353 * * for dim, idx in enumerate(index): * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< * * return itemp */ __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 353; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_itemp = __pyx_t_7; /* "View.MemoryView":352 * cdef char *itemp = <char *> self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< * itemp = pybuffer_index(&self.view, itemp, idx, dim) * */ } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":355 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_itemp; goto __pyx_L0; /* "View.MemoryView":348 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_idx); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":358 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< * if index is Ellipsis: * return self */ /* Python wrapper */ static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_indices = NULL; char *__pyx_v_itemp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; char *__pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":359 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":360 * def __getitem__(memoryview self, object index): * if index is Ellipsis: * return self # <<<<<<<<<<<<<< * * have_slices, indices = _unellipsify(index, self.view.ndim) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __pyx_r = ((PyObject *)__pyx_v_self); goto __pyx_L0; /* "View.MemoryView":359 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ } /* "View.MemoryView":362 * return self * * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * cdef char *itemp */ __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; #if CYTHON_COMPILING_IN_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); #else __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_have_slices = __pyx_t_4; __pyx_t_4 = 0; __pyx_v_indices = __pyx_t_5; __pyx_t_5 = 0; /* "View.MemoryView":365 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 365; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_2) { /* "View.MemoryView":366 * cdef char *itemp * if have_slices: * return memview_slice(self, indices) # <<<<<<<<<<<<<< * else: * itemp = self.get_item_pointer(indices) */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":365 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ } /* "View.MemoryView":368 * return memview_slice(self, indices) * else: * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< * return self.convert_item_to_object(itemp) * */ /*else*/ { __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_itemp = __pyx_t_6; /* "View.MemoryView":369 * else: * itemp = self.get_item_pointer(indices) * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< * * def __setitem__(memoryview self, object index, object value): */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":358 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< * if index is Ellipsis: * return self */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_have_slices); __Pyx_XDECREF(__pyx_v_indices); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":371 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * have_slices, index = _unellipsify(index, self.view.ndim) * */ /* Python wrapper */ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_obj = NULL; int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); /* "View.MemoryView":372 * * def __setitem__(memoryview self, object index, object value): * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * if have_slices: */ __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (likely(__pyx_t_1 != Py_None)) { PyObject* sequence = __pyx_t_1; #if CYTHON_COMPILING_IN_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(__pyx_t_3); #else __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_have_slices = __pyx_t_2; __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":374 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":375 * * if have_slices: * obj = self.is_slice(value) # <<<<<<<<<<<<<< * if obj: * self.setitem_slice_assignment(self[index], obj) */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_obj = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":376 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":377 * obj = self.is_slice(value) * if obj: * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< * else: * self.setitem_slice_assign_scalar(self[index], value) */ __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":376 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ goto __pyx_L4; } /* "View.MemoryView":379 * self.setitem_slice_assignment(self[index], obj) * else: * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< * else: * self.setitem_indexed(index, value) */ /*else*/ { __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L4:; /* "View.MemoryView":374 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ goto __pyx_L3; } /* "View.MemoryView":381 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< * * cdef is_slice(self, obj): */ /*else*/ { __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L3:; /* "View.MemoryView":371 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * have_slices, index = _unellipsify(index, self.view.ndim) * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_have_slices); __Pyx_XDECREF(__pyx_v_obj); __Pyx_XDECREF(__pyx_v_index); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":383 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< * if not isinstance(obj, memoryview): * try: */ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_slice", 0); __Pyx_INCREF(__pyx_v_obj); /* "View.MemoryView":384 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":385 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ { __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); __Pyx_XGOTREF(__pyx_t_5); /*try:*/ { /* "View.MemoryView":386 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":387 * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) # <<<<<<<<<<<<<< * except TypeError: * return None */ __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 387; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_7); /* "View.MemoryView":386 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":385 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ } __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L11_try_end; __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":388 * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) * except TypeError: # <<<<<<<<<<<<<< * return None * */ __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); if (__pyx_t_9) { __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 388; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":389 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< * * return obj */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; goto __pyx_L7_except_return; } goto __pyx_L6_except_error; __pyx_L6_except_error:; /* "View.MemoryView":385 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L1_error; __pyx_L7_except_return:; __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L0; __pyx_L11_try_end:; } /* "View.MemoryView":384 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, */ } /* "View.MemoryView":391 * return None * * return obj # <<<<<<<<<<<<<< * * cdef setitem_slice_assignment(self, dst, src): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_obj); __pyx_r = __pyx_v_obj; goto __pyx_L0; /* "View.MemoryView":383 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< * if not isinstance(obj, memoryview): * try: */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_obj); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":393 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice dst_slice * cdef __Pyx_memviewslice src_slice */ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { __Pyx_memviewslice __pyx_v_dst_slice; __Pyx_memviewslice __pyx_v_src_slice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); /* "View.MemoryView":397 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":398 * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< * src.ndim, dst.ndim, self.dtype_is_object) * */ if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":399 * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":397 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":393 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice dst_slice * cdef __Pyx_memviewslice src_slice */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":401 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< * cdef int array[128] * cdef void *tmp = NULL */ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { int __pyx_v_array[0x80]; void *__pyx_v_tmp; void *__pyx_v_item; __Pyx_memviewslice *__pyx_v_dst_slice; __Pyx_memviewslice __pyx_v_tmp_slice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_t_3; int __pyx_t_4; char const *__pyx_t_5; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); /* "View.MemoryView":403 * cdef setitem_slice_assign_scalar(self, memoryview dst, value): * cdef int array[128] * cdef void *tmp = NULL # <<<<<<<<<<<<<< * cdef void *item * */ __pyx_v_tmp = NULL; /* "View.MemoryView":408 * cdef __Pyx_memviewslice *dst_slice * cdef __Pyx_memviewslice tmp_slice * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< * * if <size_t>self.view.itemsize > sizeof(array): */ __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); /* "View.MemoryView":410 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if <size_t>self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: */ __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); if (__pyx_t_1) { /* "View.MemoryView":411 * * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< * if tmp == NULL: * raise MemoryError */ __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); /* "View.MemoryView":412 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":413 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ PyErr_NoMemory(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 413; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":412 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ } /* "View.MemoryView":414 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< * else: * item = <void *> array */ __pyx_v_item = __pyx_v_tmp; /* "View.MemoryView":410 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if <size_t>self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: */ goto __pyx_L3; } /* "View.MemoryView":416 * item = tmp * else: * item = <void *> array # <<<<<<<<<<<<<< * * try: */ /*else*/ { __pyx_v_item = ((void *)__pyx_v_array); } __pyx_L3:; /* "View.MemoryView":418 * item = <void *> array * * try: # <<<<<<<<<<<<<< * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value */ /*try:*/ { /* "View.MemoryView":419 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":420 * try: * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value # <<<<<<<<<<<<<< * else: * self.assign_item_from_object(<char *> item, value) */ (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); /* "View.MemoryView":419 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ goto __pyx_L8; } /* "View.MemoryView":422 * (<PyObject **> item)[0] = <PyObject *> value * else: * self.assign_item_from_object(<char *> item, value) # <<<<<<<<<<<<<< * * */ /*else*/ { __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 422; __pyx_clineno = __LINE__; goto __pyx_L6_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L8:; /* "View.MemoryView":426 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, */ __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":427 * * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, * item, self.dtype_is_object) */ __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 427; __pyx_clineno = __LINE__; goto __pyx_L6_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":426 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, */ } /* "View.MemoryView":428 * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< * item, self.dtype_is_object) * finally: */ __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); } /* "View.MemoryView":431 * item, self.dtype_is_object) * finally: * PyMem_Free(tmp) # <<<<<<<<<<<<<< * * cdef setitem_indexed(self, index, value): */ /*finally:*/ { /*normal exit:*/{ PyMem_Free(__pyx_v_tmp); goto __pyx_L7; } /*exception exit:*/{ __pyx_L6_error:; __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); __Pyx_XGOTREF(__pyx_t_6); __Pyx_XGOTREF(__pyx_t_7); __Pyx_XGOTREF(__pyx_t_8); __Pyx_XGOTREF(__pyx_t_9); __Pyx_XGOTREF(__pyx_t_10); __Pyx_XGOTREF(__pyx_t_11); __pyx_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; { PyMem_Free(__pyx_v_tmp); } if (PY_MAJOR_VERSION >= 3) { __Pyx_XGIVEREF(__pyx_t_9); __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); } __Pyx_XGIVEREF(__pyx_t_6); __Pyx_XGIVEREF(__pyx_t_7); __Pyx_XGIVEREF(__pyx_t_8); __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; goto __pyx_L1_error; } __pyx_L7:; } /* "View.MemoryView":401 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< * cdef int array[128] * cdef void *tmp = NULL */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":433 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) */ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { char *__pyx_v_itemp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations char *__pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_indexed", 0); /* "View.MemoryView":434 * * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< * self.assign_item_from_object(itemp, value) * */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_itemp = __pyx_t_1; /* "View.MemoryView":435 * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< * * cdef convert_item_to_object(self, char *itemp): */ __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":433 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":437 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { PyObject *__pyx_v_struct = NULL; PyObject *__pyx_v_bytesitem = 0; PyObject *__pyx_v_result = NULL; 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; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; Py_ssize_t __pyx_t_8; PyObject *__pyx_t_9 = NULL; size_t __pyx_t_10; int __pyx_t_11; int __pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":440 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef bytes bytesitem * */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":443 * cdef bytes bytesitem * * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< * try: * result = struct.unpack(self.view.format, bytesitem) */ __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":444 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ { __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); /*try:*/ { /* "View.MemoryView":445 * bytesitem = itemp[:self.view.itemsize] * try: * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< * except struct.error: * raise ValueError("Unable to convert item to object") */ __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; __pyx_t_8 = 0; if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_7)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_7); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); __pyx_t_8 = 1; } } __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_7) { __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; } __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); __Pyx_INCREF(__pyx_v_bytesitem); __Pyx_GIVEREF(__pyx_v_bytesitem); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); __pyx_t_6 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":444 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ } /* "View.MemoryView":449 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ /*else:*/ { __pyx_t_10 = strlen(__pyx_v_self->view.format); __pyx_t_11 = ((__pyx_t_10 == 1) != 0); if (__pyx_t_11) { /* "View.MemoryView":450 * else: * if len(self.view.format) == 1: * return result[0] # <<<<<<<<<<<<<< * return result * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 450; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L6_except_return; /* "View.MemoryView":449 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ } /* "View.MemoryView":451 * if len(self.view.format) == 1: * return result[0] * return result # <<<<<<<<<<<<<< * * cdef assign_item_from_object(self, char *itemp, object value): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_result); __pyx_r = __pyx_v_result; goto __pyx_L6_except_return; } __pyx_L3_error:; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":446 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< * raise ValueError("Unable to convert item to object") * else: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_12 = PyErr_ExceptionMatches(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_12) { __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_9); /* "View.MemoryView":447 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "View.MemoryView":444 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); goto __pyx_L1_error; __pyx_L6_except_return:; __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); goto __pyx_L0; } /* "View.MemoryView":437 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_struct); __Pyx_XDECREF(__pyx_v_bytesitem); __Pyx_XDECREF(__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":453 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { PyObject *__pyx_v_struct = NULL; char __pyx_v_c; PyObject *__pyx_v_bytesvalue = 0; Py_ssize_t __pyx_v_i; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; Py_ssize_t __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; char *__pyx_t_10; char *__pyx_t_11; char *__pyx_t_12; char *__pyx_t_13; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":456 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef char c * cdef bytes bytesvalue */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":461 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ __pyx_t_2 = PyTuple_Check(__pyx_v_value); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { /* "View.MemoryView":462 * * if isinstance(value, tuple): * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< * else: * bytesvalue = struct.pack(self.view.format, value) */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":461 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ goto __pyx_L3; } /* "View.MemoryView":464 * bytesvalue = struct.pack(self.view.format, *value) * else: * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< * * for i, c in enumerate(bytesvalue): */ /*else*/ { __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = NULL; __pyx_t_7 = 0; if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_6))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_6, function); __pyx_t_7 = 1; } } __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); if (__pyx_t_5) { __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; } __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_v_value); __Pyx_GIVEREF(__pyx_v_value); PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); __pyx_t_1 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; /* "View.MemoryView":466 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_7 = 0; if (unlikely(__pyx_v_bytesvalue == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 466; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __Pyx_INCREF(__pyx_v_bytesvalue); __pyx_t_9 = __pyx_v_bytesvalue; __pyx_t_11 = PyBytes_AS_STRING(__pyx_t_9); __pyx_t_12 = (__pyx_t_11 + PyBytes_GET_SIZE(__pyx_t_9)); for (__pyx_t_13 = __pyx_t_11; __pyx_t_13 < __pyx_t_12; __pyx_t_13++) { __pyx_t_10 = __pyx_t_13; __pyx_v_c = (__pyx_t_10[0]); /* "View.MemoryView":467 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ __pyx_v_i = __pyx_t_7; /* "View.MemoryView":466 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_7 = (__pyx_t_7 + 1); /* "View.MemoryView":467 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; } __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; /* "View.MemoryView":453 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_8); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_struct); __Pyx_XDECREF(__pyx_v_bytesvalue); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":470 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_STRIDES: * info.shape = self.view.shape */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; Py_ssize_t *__pyx_t_2; char *__pyx_t_3; void *__pyx_t_4; int __pyx_t_5; Py_ssize_t __pyx_t_6; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "View.MemoryView":471 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { /* "View.MemoryView":472 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: * info.shape = self.view.shape # <<<<<<<<<<<<<< * else: * info.shape = NULL */ __pyx_t_2 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_2; /* "View.MemoryView":471 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ goto __pyx_L3; } /* "View.MemoryView":474 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_STRIDES: */ /*else*/ { __pyx_v_info->shape = NULL; } __pyx_L3:; /* "View.MemoryView":476 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { /* "View.MemoryView":477 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< * else: * info.strides = NULL */ __pyx_t_2 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_2; /* "View.MemoryView":476 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ goto __pyx_L4; } /* "View.MemoryView":479 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_INDIRECT: */ /*else*/ { __pyx_v_info->strides = NULL; } __pyx_L4:; /* "View.MemoryView":481 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); if (__pyx_t_1) { /* "View.MemoryView":482 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< * else: * info.suboffsets = NULL */ __pyx_t_2 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_2; /* "View.MemoryView":481 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ goto __pyx_L5; } /* "View.MemoryView":484 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ /*else*/ { __pyx_v_info->suboffsets = NULL; } __pyx_L5:; /* "View.MemoryView":486 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":487 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_3 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_3; /* "View.MemoryView":486 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ goto __pyx_L6; } /* "View.MemoryView":489 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.buf = self.view.buf */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L6:; /* "View.MemoryView":491 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize */ __pyx_t_4 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_4; /* "View.MemoryView":492 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< * info.itemsize = self.view.itemsize * info.len = self.view.len */ __pyx_t_5 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_5; /* "View.MemoryView":493 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< * info.len = self.view.len * info.readonly = 0 */ __pyx_t_6 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_6; /* "View.MemoryView":494 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< * info.readonly = 0 * info.obj = self */ __pyx_t_6 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_6; /* "View.MemoryView":495 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = 0 # <<<<<<<<<<<<<< * info.obj = self * */ __pyx_v_info->readonly = 0; /* "View.MemoryView":496 * info.len = self.view.len * info.readonly = 0 * info.obj = self # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "View.MemoryView":470 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_STRIDES: * info.shape = self.view.shape */ /* function exit code */ __pyx_r = 0; 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_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":503 * property T: * @cname('__pyx_memoryview_transpose') * def __get__(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* Python wrapper */ static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":504 * @cname('__pyx_memoryview_transpose') * def __get__(self): * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< * transpose_memslice(&result.from_slice) * return result */ __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":505 * def __get__(self): * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< * return result * */ __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":506 * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) * return result # <<<<<<<<<<<<<< * * property base: */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":503 * property T: * @cname('__pyx_memoryview_transpose') * def __get__(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":510 * property base: * @cname('__pyx_memoryview__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.obj * */ /* Python wrapper */ static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":511 * @cname('__pyx_memoryview__get__base') * def __get__(self): * return self.obj # <<<<<<<<<<<<<< * * property shape: */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->obj); __pyx_r = __pyx_v_self->obj; goto __pyx_L0; /* "View.MemoryView":510 * property base: * @cname('__pyx_memoryview__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.obj * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":515 * property shape: * @cname('__pyx_memoryview_get_shape') * def __get__(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_length; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":516 * @cname('__pyx_memoryview_get_shape') * def __get__(self): * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< * * property strides: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { __pyx_t_2 = __pyx_t_4; __pyx_v_length = (__pyx_t_2[0]); __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":515 * property shape: * @cname('__pyx_memoryview_get_shape') * def __get__(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":520 * property strides: * @cname('__pyx_memoryview_get_strides') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_stride; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":521 * @cname('__pyx_memoryview_get_strides') * def __get__(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":523 * if self.view.strides == NULL: * * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":521 * @cname('__pyx_memoryview_get_strides') * def __get__(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ } /* "View.MemoryView":525 * raise ValueError("Buffer view does not expose strides") * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< * * property suboffsets: */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { __pyx_t_3 = __pyx_t_5; __pyx_v_stride = (__pyx_t_3[0]); __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_6; __pyx_t_6 = 0; goto __pyx_L0; /* "View.MemoryView":520 * property strides: * @cname('__pyx_memoryview_get_strides') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":529 * property suboffsets: * @cname('__pyx_memoryview_get_suboffsets') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; Py_ssize_t *__pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":530 * @cname('__pyx_memoryview_get_suboffsets') * def __get__(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":531 * def __get__(self): * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__9, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":530 * @cname('__pyx_memoryview_get_suboffsets') * def __get__(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ } /* "View.MemoryView":533 * return (-1,) * self.view.ndim * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< * * property ndim: */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { __pyx_t_4 = __pyx_t_6; __pyx_v_suboffset = (__pyx_t_4[0]); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":529 * property suboffsets: * @cname('__pyx_memoryview_get_suboffsets') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":537 * property ndim: * @cname('__pyx_memoryview_get_ndim') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { 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("__get__", 0); /* "View.MemoryView":538 * @cname('__pyx_memoryview_get_ndim') * def __get__(self): * return self.view.ndim # <<<<<<<<<<<<<< * * property itemsize: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":537 * property ndim: * @cname('__pyx_memoryview_get_ndim') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":542 * property itemsize: * @cname('__pyx_memoryview_get_itemsize') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { 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("__get__", 0); /* "View.MemoryView":543 * @cname('__pyx_memoryview_get_itemsize') * def __get__(self): * return self.view.itemsize # <<<<<<<<<<<<<< * * property nbytes: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":542 * property itemsize: * @cname('__pyx_memoryview_get_itemsize') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":547 * property nbytes: * @cname('__pyx_memoryview_get_nbytes') * def __get__(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":548 * @cname('__pyx_memoryview_get_nbytes') * def __get__(self): * return self.size * self.view.itemsize # <<<<<<<<<<<<<< * * property size: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 548; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":547 * property nbytes: * @cname('__pyx_memoryview_get_nbytes') * def __get__(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":552 * property size: * @cname('__pyx_memoryview_get_size') * def __get__(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_v_result = NULL; PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":553 * @cname('__pyx_memoryview_get_size') * def __get__(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ __pyx_t_1 = (__pyx_v_self->_size == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":554 * def __get__(self): * if self._size is None: * result = 1 # <<<<<<<<<<<<<< * * for length in self.view.shape[:self.view.ndim]: */ __Pyx_INCREF(__pyx_int_1); __pyx_v_result = __pyx_int_1; /* "View.MemoryView":556 * result = 1 * * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< * result *= length * */ __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { __pyx_t_3 = __pyx_t_5; __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 556; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); __pyx_t_6 = 0; /* "View.MemoryView":557 * * for length in self.view.shape[:self.view.ndim]: * result *= length # <<<<<<<<<<<<<< * * self._size = result */ __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 557; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); __pyx_t_6 = 0; } /* "View.MemoryView":559 * result *= length * * self._size = result # <<<<<<<<<<<<<< * * return self._size */ __Pyx_INCREF(__pyx_v_result); __Pyx_GIVEREF(__pyx_v_result); __Pyx_GOTREF(__pyx_v_self->_size); __Pyx_DECREF(__pyx_v_self->_size); __pyx_v_self->_size = __pyx_v_result; /* "View.MemoryView":553 * @cname('__pyx_memoryview_get_size') * def __get__(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ } /* "View.MemoryView":561 * self._size = result * * return self._size # <<<<<<<<<<<<<< * * def __len__(self): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->_size); __pyx_r = __pyx_v_self->_size; goto __pyx_L0; /* "View.MemoryView":552 * property size: * @cname('__pyx_memoryview_get_size') * def __get__(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_result); __Pyx_XDECREF(__pyx_v_length); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":563 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: * return self.view.shape[0] */ /* Python wrapper */ static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__len__", 0); /* "View.MemoryView":564 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":565 * def __len__(self): * if self.view.ndim >= 1: * return self.view.shape[0] # <<<<<<<<<<<<<< * * return 0 */ __pyx_r = (__pyx_v_self->view.shape[0]); goto __pyx_L0; /* "View.MemoryView":564 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ } /* "View.MemoryView":567 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< * * def __repr__(self): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":563 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: * return self.view.shape[0] */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":569 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) */ /* Python wrapper */ static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__repr__", 0); /* "View.MemoryView":570 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":571 * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) # <<<<<<<<<<<<<< * * def __str__(self): */ __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":570 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":569 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":573 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) * */ /* Python wrapper */ static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__str__", 0); /* "View.MemoryView":574 * * def __str__(self): * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":573 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":577 * * * def is_c_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* Python wrapper */ static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; 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("is_c_contig", 0); /* "View.MemoryView":580 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice, 'C', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); /* "View.MemoryView":581 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< * * def is_f_contig(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 581; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":577 * * * def is_c_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":583 * return slice_is_contig(mslice, 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* Python wrapper */ static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; 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("is_f_contig", 0); /* "View.MemoryView":586 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice, 'F', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); /* "View.MemoryView":587 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< * * def copy(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":583 * return slice_is_contig(mslice, 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":589 * return slice_is_contig(mslice, 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS */ /* Python wrapper */ static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_mslice; int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy", 0); /* "View.MemoryView":591 * def copy(self): * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< * * slice_copy(self, &mslice) */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); /* "View.MemoryView":593 * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS * * slice_copy(self, &mslice) # <<<<<<<<<<<<<< * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, * self.view.itemsize, */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); /* "View.MemoryView":594 * * slice_copy(self, &mslice) * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_C_CONTIGUOUS, */ __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":599 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< * * def copy_fortran(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":589 * return slice_is_contig(mslice, 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":601 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS */ /* Python wrapper */ static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_src; __Pyx_memviewslice __pyx_v_dst; int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy_fortran", 0); /* "View.MemoryView":603 * def copy_fortran(self): * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< * * slice_copy(self, &src) */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); /* "View.MemoryView":605 * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS * * slice_copy(self, &src) # <<<<<<<<<<<<<< * dst = slice_copy_contig(&src, "fortran", self.view.ndim, * self.view.itemsize, */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); /* "View.MemoryView":606 * * slice_copy(self, &src) * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_F_CONTIGUOUS, */ __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_dst = __pyx_t_1; /* "View.MemoryView":611 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":601 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":615 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo */ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { struct __pyx_memoryview_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); /* "View.MemoryView":616 * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< * result.typeinfo = typeinfo * return result */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 616; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 616; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 616; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_o); __Pyx_GIVEREF(__pyx_v_o); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 616; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":617 * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo # <<<<<<<<<<<<<< * return result * */ __pyx_v_result->typeinfo = __pyx_v_typeinfo; /* "View.MemoryView":618 * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo * return result # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_check') */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":615 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":621 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< * return isinstance(o, memoryview) * */ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("memoryview_check", 0); /* "View.MemoryView":622 * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): * return isinstance(o, memoryview) # <<<<<<<<<<<<<< * * cdef tuple _unellipsify(object index, int ndim): */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, __pyx_memoryview_type); __pyx_r = __pyx_t_1; goto __pyx_L0; /* "View.MemoryView":621 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< * return isinstance(o, memoryview) * */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":624 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< * """ * Replace all ellipses with full slices and fill incomplete indices with */ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { PyObject *__pyx_v_tup = NULL; PyObject *__pyx_v_result = NULL; int __pyx_v_have_slices; int __pyx_v_seen_ellipsis; CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; PyObject *__pyx_v_item = NULL; Py_ssize_t __pyx_v_nslices; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; Py_ssize_t __pyx_t_5; PyObject *(*__pyx_t_6)(PyObject *); PyObject *__pyx_t_7 = NULL; Py_ssize_t __pyx_t_8; int __pyx_t_9; int __pyx_t_10; PyObject *__pyx_t_11 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_unellipsify", 0); /* "View.MemoryView":629 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ __pyx_t_1 = PyTuple_Check(__pyx_v_index); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":630 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 630; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_index); __Pyx_GIVEREF(__pyx_v_index); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); __pyx_v_tup = __pyx_t_3; __pyx_t_3 = 0; /* "View.MemoryView":629 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ goto __pyx_L3; } /* "View.MemoryView":632 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< * * result = [] */ /*else*/ { __Pyx_INCREF(__pyx_v_index); __pyx_v_tup = __pyx_v_index; } __pyx_L3:; /* "View.MemoryView":634 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":635 * * result = [] * have_slices = False # <<<<<<<<<<<<<< * seen_ellipsis = False * for idx, item in enumerate(tup): */ __pyx_v_have_slices = 0; /* "View.MemoryView":636 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< * for idx, item in enumerate(tup): * if item is Ellipsis: */ __pyx_v_seen_ellipsis = 0; /* "View.MemoryView":637 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< * if item is Ellipsis: * if not seen_ellipsis: */ __Pyx_INCREF(__pyx_int_0); __pyx_t_3 = __pyx_int_0; if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; __pyx_t_6 = NULL; } else { __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } for (;;) { if (likely(!__pyx_t_6)) { if (likely(PyList_CheckExact(__pyx_t_4))) { if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); #endif } else { if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); #endif } } else { __pyx_t_7 = __pyx_t_6(__pyx_t_4); if (unlikely(!__pyx_t_7)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_7); } __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); __pyx_t_7 = 0; __Pyx_INCREF(__pyx_t_3); __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = __pyx_t_7; __pyx_t_7 = 0; /* "View.MemoryView":638 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) */ __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":639 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True */ __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":640 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { __Pyx_INCREF(__pyx_slice__10); __Pyx_GIVEREF(__pyx_slice__10); PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__10); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":641 * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True # <<<<<<<<<<<<<< * else: * result.append(slice(None)) */ __pyx_v_seen_ellipsis = 1; /* "View.MemoryView":639 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True */ goto __pyx_L7; } /* "View.MemoryView":643 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ /*else*/ { __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__11); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L7:; /* "View.MemoryView":644 * else: * result.append(slice(None)) * have_slices = True # <<<<<<<<<<<<<< * else: * if not isinstance(item, slice) and not PyIndex_Check(item): */ __pyx_v_have_slices = 1; /* "View.MemoryView":638 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) */ goto __pyx_L6; } /* "View.MemoryView":646 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ /*else*/ { __pyx_t_2 = PySlice_Check(__pyx_v_item); __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_10) { } else { __pyx_t_1 = __pyx_t_10; goto __pyx_L9_bool_binop_done; } __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); __pyx_t_1 = __pyx_t_10; __pyx_L9_bool_binop_done:; if (__pyx_t_1) { /* "View.MemoryView":647 * else: * if not isinstance(item, slice) and not PyIndex_Check(item): * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< * * have_slices = have_slices or isinstance(item, slice) */ __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_11); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; __Pyx_Raise(__pyx_t_7, 0, 0, 0); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 647; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":646 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ } /* "View.MemoryView":649 * raise TypeError("Cannot index with type '%s'" % type(item)) * * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< * result.append(item) * */ __pyx_t_10 = (__pyx_v_have_slices != 0); if (!__pyx_t_10) { } else { __pyx_t_1 = __pyx_t_10; goto __pyx_L11_bool_binop_done; } __pyx_t_10 = PySlice_Check(__pyx_v_item); __pyx_t_2 = (__pyx_t_10 != 0); __pyx_t_1 = __pyx_t_2; __pyx_L11_bool_binop_done:; __pyx_v_have_slices = __pyx_t_1; /* "View.MemoryView":650 * * have_slices = have_slices or isinstance(item, slice) * result.append(item) # <<<<<<<<<<<<<< * * nslices = ndim - len(result) */ __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L6:; /* "View.MemoryView":637 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< * if item is Ellipsis: * if not seen_ellipsis: */ } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":652 * result.append(item) * * nslices = ndim - len(result) # <<<<<<<<<<<<<< * if nslices: * result.extend([slice(None)] * nslices) */ __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); /* "View.MemoryView":653 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { /* "View.MemoryView":654 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { __Pyx_INCREF(__pyx_slice__12); __Pyx_GIVEREF(__pyx_slice__12); PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__12); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":653 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ } /* "View.MemoryView":656 * result.extend([slice(None)] * nslices) * * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): */ __Pyx_XDECREF(__pyx_r); if (!__pyx_v_have_slices) { } else { __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L14_bool_binop_done; } __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; __pyx_L14_bool_binop_done:; __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_4); __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_r = ((PyObject*)__pyx_t_7); __pyx_t_7 = 0; goto __pyx_L0; /* "View.MemoryView":624 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< * """ * Replace all ellipses with full slices and fill incomplete indices with */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_11); __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_tup); __Pyx_XDECREF(__pyx_v_result); __Pyx_XDECREF(__pyx_v_idx); __Pyx_XDECREF(__pyx_v_item); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":658 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: */ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t *__pyx_t_1; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); /* "View.MemoryView":659 * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") */ __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { __pyx_t_1 = __pyx_t_3; __pyx_v_suboffset = (__pyx_t_1[0]); /* "View.MemoryView":660 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_4) { /* "View.MemoryView":661 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 661; __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 = 661; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":660 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ } } /* "View.MemoryView":658 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":668 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< * cdef int new_ndim = 0, suboffset_dim = -1, dim * cdef bint negative_step */ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { int __pyx_v_new_ndim; int __pyx_v_suboffset_dim; int __pyx_v_dim; __Pyx_memviewslice __pyx_v_src; __Pyx_memviewslice __pyx_v_dst; __Pyx_memviewslice *__pyx_v_p_src; struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; __Pyx_memviewslice *__pyx_v_p_dst; int *__pyx_v_p_suboffset_dim; Py_ssize_t __pyx_v_start; Py_ssize_t __pyx_v_stop; Py_ssize_t __pyx_v_step; int __pyx_v_have_start; int __pyx_v_have_stop; int __pyx_v_have_step; PyObject *__pyx_v_index = NULL; struct __pyx_memoryview_obj *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; struct __pyx_memoryview_obj *__pyx_t_4; char *__pyx_t_5; int __pyx_t_6; Py_ssize_t __pyx_t_7; PyObject *(*__pyx_t_8)(PyObject *); PyObject *__pyx_t_9 = NULL; Py_ssize_t __pyx_t_10; int __pyx_t_11; Py_ssize_t __pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memview_slice", 0); /* "View.MemoryView":669 * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< * cdef bint negative_step * cdef __Pyx_memviewslice src, dst */ __pyx_v_new_ndim = 0; __pyx_v_suboffset_dim = -1; /* "View.MemoryView":676 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< * * cdef _memoryviewslice memviewsliceobj */ memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); /* "View.MemoryView":680 * cdef _memoryviewslice memviewsliceobj * * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< * * if isinstance(memview, _memoryviewslice): */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { PyErr_SetNone(PyExc_AssertionError); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 680; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "View.MemoryView":682 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":683 * * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview # <<<<<<<<<<<<<< * p_src = &memviewsliceobj.from_slice * else: */ if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 683; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":684 * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< * else: * slice_copy(memview, &src) */ __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); /* "View.MemoryView":682 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ goto __pyx_L3; } /* "View.MemoryView":686 * p_src = &memviewsliceobj.from_slice * else: * slice_copy(memview, &src) # <<<<<<<<<<<<<< * p_src = &src * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); /* "View.MemoryView":687 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< * * */ __pyx_v_p_src = (&__pyx_v_src); } __pyx_L3:; /* "View.MemoryView":693 * * * dst.memview = p_src.memview # <<<<<<<<<<<<<< * dst.data = p_src.data * */ __pyx_t_4 = __pyx_v_p_src->memview; __pyx_v_dst.memview = __pyx_t_4; /* "View.MemoryView":694 * * dst.memview = p_src.memview * dst.data = p_src.data # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __pyx_v_p_src->data; __pyx_v_dst.data = __pyx_t_5; /* "View.MemoryView":699 * * * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< * cdef int *p_suboffset_dim = &suboffset_dim * cdef Py_ssize_t start, stop, step */ __pyx_v_p_dst = (&__pyx_v_dst); /* "View.MemoryView":700 * * cdef __Pyx_memviewslice *p_dst = &dst * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< * cdef Py_ssize_t start, stop, step * cdef bint have_start, have_stop, have_step */ __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); /* "View.MemoryView":704 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< * if PyIndex_Check(index): * slice_memviewslice( */ __pyx_t_6 = 0; if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; __pyx_t_8 = NULL; } else { __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } for (;;) { if (likely(!__pyx_t_8)) { if (likely(PyList_CheckExact(__pyx_t_3))) { if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); #endif } else { if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); #endif } } else { __pyx_t_9 = __pyx_t_8(__pyx_t_3); if (unlikely(!__pyx_t_9)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_9); } __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); __pyx_t_9 = 0; __pyx_v_dim = __pyx_t_6; __pyx_t_6 = (__pyx_t_6 + 1); /* "View.MemoryView":705 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< * slice_memviewslice( * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], */ __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); if (__pyx_t_2) { /* "View.MemoryView":709 * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< * 0, 0, 0, # have_{start,stop,step} * False) */ __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":706 * for dim, index in enumerate(indices): * if PyIndex_Check(index): * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":705 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< * slice_memviewslice( * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], */ goto __pyx_L6; } /* "View.MemoryView":712 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 */ __pyx_t_2 = (__pyx_v_index == Py_None); __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":713 * False) * elif index is None: * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 */ (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; /* "View.MemoryView":714 * elif index is None: * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 */ (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; /* "View.MemoryView":715 * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< * new_ndim += 1 * else: */ (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; /* "View.MemoryView":716 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 # <<<<<<<<<<<<<< * else: * start = index.start or 0 */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); /* "View.MemoryView":712 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 */ goto __pyx_L6; } /* "View.MemoryView":718 * new_ndim += 1 * else: * start = index.start or 0 # <<<<<<<<<<<<<< * stop = index.stop or 0 * step = index.step or 0 */ /*else*/ { __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L7_bool_binop_done; } __pyx_t_10 = 0; __pyx_L7_bool_binop_done:; __pyx_v_start = __pyx_t_10; /* "View.MemoryView":719 * else: * start = index.start or 0 * stop = index.stop or 0 # <<<<<<<<<<<<<< * step = index.step or 0 * */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L9_bool_binop_done; } __pyx_t_10 = 0; __pyx_L9_bool_binop_done:; __pyx_v_stop = __pyx_t_10; /* "View.MemoryView":720 * start = index.start or 0 * stop = index.stop or 0 * step = index.step or 0 # <<<<<<<<<<<<<< * * have_start = index.start is not None */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 720; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 720; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 720; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L11_bool_binop_done; } __pyx_t_10 = 0; __pyx_L11_bool_binop_done:; __pyx_v_step = __pyx_t_10; /* "View.MemoryView":722 * step = index.step or 0 * * have_start = index.start is not None # <<<<<<<<<<<<<< * have_stop = index.stop is not None * have_step = index.step is not None */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_start = __pyx_t_1; /* "View.MemoryView":723 * * have_start = index.start is not None * have_stop = index.stop is not None # <<<<<<<<<<<<<< * have_step = index.step is not None * */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_stop = __pyx_t_1; /* "View.MemoryView":724 * have_start = index.start is not None * have_stop = index.stop is not None * have_step = index.step is not None # <<<<<<<<<<<<<< * * slice_memviewslice( */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_step = __pyx_t_1; /* "View.MemoryView":726 * have_step = index.step is not None * * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":732 * have_start, have_stop, have_step, * True) * new_ndim += 1 # <<<<<<<<<<<<<< * * if isinstance(memview, _memoryviewslice): */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); } __pyx_L6:; /* "View.MemoryView":704 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< * if PyIndex_Check(index): * slice_memviewslice( */ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":734 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":735 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, */ __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":736 * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< * memviewsliceobj.to_dtype_func, * memview.dtype_is_object) */ if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":737 * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< * memview.dtype_is_object) * else: */ if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 737; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":735 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, */ __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":734 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ } /* "View.MemoryView":740 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ /*else*/ { __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":741 * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 740; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); /* "View.MemoryView":740 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 740; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":668 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< * cdef int new_ndim = 0, suboffset_dim = -1, dim * cdef bint negative_step */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); __Pyx_XDECREF(__pyx_v_index); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":765 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, */ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { Py_ssize_t __pyx_v_new_shape; int __pyx_v_negative_step; int __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":785 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":787 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ __pyx_t_1 = ((__pyx_v_start < 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":788 * * if start < 0: * start += shape # <<<<<<<<<<<<<< * if not 0 <= start < shape: * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":787 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ } /* "View.MemoryView":789 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ __pyx_t_1 = (0 <= __pyx_v_start); if (__pyx_t_1) { __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); } __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":790 * start += shape * if not 0 <= start < shape: * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< * else: * */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":789 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ } /* "View.MemoryView":785 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ goto __pyx_L3; } /* "View.MemoryView":793 * else: * * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< * * if have_step and step == 0: */ /*else*/ { __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); if (__pyx_t_1) { } else { __pyx_t_2 = __pyx_t_1; goto __pyx_L6_bool_binop_done; } __pyx_t_1 = ((__pyx_v_step < 0) != 0); __pyx_t_2 = __pyx_t_1; __pyx_L6_bool_binop_done:; __pyx_v_negative_step = __pyx_t_2; /* "View.MemoryView":795 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) * */ __pyx_t_1 = (__pyx_v_have_step != 0); if (__pyx_t_1) { } else { __pyx_t_2 = __pyx_t_1; goto __pyx_L9_bool_binop_done; } __pyx_t_1 = ((__pyx_v_step == 0) != 0); __pyx_t_2 = __pyx_t_1; __pyx_L9_bool_binop_done:; if (__pyx_t_2) { /* "View.MemoryView":796 * * if have_step and step == 0: * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":795 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) * */ } /* "View.MemoryView":799 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { /* "View.MemoryView":800 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":801 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< * if start < 0: * start = 0 */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":802 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":803 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< * elif start >= shape: * if negative_step: */ __pyx_v_start = 0; /* "View.MemoryView":802 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ } /* "View.MemoryView":800 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ goto __pyx_L12; } /* "View.MemoryView":804 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":805 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":806 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = shape */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":805 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L14; } /* "View.MemoryView":808 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ /*else*/ { __pyx_v_start = __pyx_v_shape; } __pyx_L14:; /* "View.MemoryView":804 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ } __pyx_L12:; /* "View.MemoryView":799 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ goto __pyx_L11; } /* "View.MemoryView":810 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":811 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = 0 */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":810 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L15; } /* "View.MemoryView":813 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< * * if have_stop: */ /*else*/ { __pyx_v_start = 0; } __pyx_L15:; } __pyx_L11:; /* "View.MemoryView":815 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { /* "View.MemoryView":816 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":817 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< * if stop < 0: * stop = 0 */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); /* "View.MemoryView":818 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":819 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< * elif stop > shape: * stop = shape */ __pyx_v_stop = 0; /* "View.MemoryView":818 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ } /* "View.MemoryView":816 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ goto __pyx_L17; } /* "View.MemoryView":820 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":821 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ __pyx_v_stop = __pyx_v_shape; /* "View.MemoryView":820 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ } __pyx_L17:; /* "View.MemoryView":815 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ goto __pyx_L16; } /* "View.MemoryView":823 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":824 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< * else: * stop = shape */ __pyx_v_stop = -1L; /* "View.MemoryView":823 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ goto __pyx_L19; } /* "View.MemoryView":826 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< * * if not have_step: */ /*else*/ { __pyx_v_stop = __pyx_v_shape; } __pyx_L19:; } __pyx_L16:; /* "View.MemoryView":828 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":829 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< * * */ __pyx_v_step = 1; /* "View.MemoryView":828 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ } /* "View.MemoryView":833 * * with cython.cdivision(True): * new_shape = (stop - start) // step # <<<<<<<<<<<<<< * * if (stop - start) - step * new_shape: */ __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); /* "View.MemoryView":835 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); if (__pyx_t_2) { /* "View.MemoryView":836 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< * * if new_shape < 0: */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); /* "View.MemoryView":835 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ } /* "View.MemoryView":838 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":839 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< * * */ __pyx_v_new_shape = 0; /* "View.MemoryView":838 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ } /* "View.MemoryView":842 * * * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset */ (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); /* "View.MemoryView":843 * * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< * dst.suboffsets[new_ndim] = suboffset * */ (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; /* "View.MemoryView":844 * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< * * */ (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; } __pyx_L3:; /* "View.MemoryView":847 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":848 * * if suboffset_dim[0] < 0: * dst.data += start * stride # <<<<<<<<<<<<<< * else: * dst.suboffsets[suboffset_dim[0]] += start * stride */ __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); /* "View.MemoryView":847 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ goto __pyx_L23; } /* "View.MemoryView":850 * dst.data += start * stride * else: * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< * * if suboffset >= 0: */ /*else*/ { __pyx_t_3 = (__pyx_v_suboffset_dim[0]); (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); } __pyx_L23:; /* "View.MemoryView":852 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":853 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":854 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":855 * if not is_slice: * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset # <<<<<<<<<<<<<< * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " */ __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); /* "View.MemoryView":854 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ goto __pyx_L26; } /* "View.MemoryView":857 * dst.data = (<char **> dst.data)[0] + suboffset * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< * "must be indexed and not sliced", dim) * else: */ /*else*/ { /* "View.MemoryView":858 * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< * else: * suboffset_dim[0] = new_ndim */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 857; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L26:; /* "View.MemoryView":853 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ goto __pyx_L25; } /* "View.MemoryView":860 * "must be indexed and not sliced", dim) * else: * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< * * return 0 */ /*else*/ { (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; } __pyx_L25:; /* "View.MemoryView":852 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ } /* "View.MemoryView":862 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":765 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":868 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 */ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { Py_ssize_t __pyx_v_shape; Py_ssize_t __pyx_v_stride; Py_ssize_t __pyx_v_suboffset; Py_ssize_t __pyx_v_itemsize; char *__pyx_v_resultp; char *__pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("pybuffer_index", 0); /* "View.MemoryView":870 * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< * cdef Py_ssize_t itemsize = view.itemsize * cdef char *resultp */ __pyx_v_suboffset = -1L; /* "View.MemoryView":871 * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< * cdef char *resultp * */ __pyx_t_1 = __pyx_v_view->itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":874 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":875 * * if view.ndim == 0: * shape = view.len / itemsize # <<<<<<<<<<<<<< * stride = itemsize * else: */ if (unlikely(__pyx_v_itemsize == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 875; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 875; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize); /* "View.MemoryView":876 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< * else: * shape = view.shape[dim] */ __pyx_v_stride = __pyx_v_itemsize; /* "View.MemoryView":874 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ goto __pyx_L3; } /* "View.MemoryView":878 * stride = itemsize * else: * shape = view.shape[dim] # <<<<<<<<<<<<<< * stride = view.strides[dim] * if view.suboffsets != NULL: */ /*else*/ { __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); /* "View.MemoryView":879 * else: * shape = view.shape[dim] * stride = view.strides[dim] # <<<<<<<<<<<<<< * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] */ __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); /* "View.MemoryView":880 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":881 * stride = view.strides[dim] * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< * * if index < 0: */ __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); /* "View.MemoryView":880 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ } } __pyx_L3:; /* "View.MemoryView":883 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":884 * * if index < 0: * index += view.shape[dim] # <<<<<<<<<<<<<< * if index < 0: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) */ __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); /* "View.MemoryView":885 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":886 * index += view.shape[dim] * if index < 0: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * if index >= shape: */ __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 886; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 886; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 886; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 886; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 886; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":885 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ } /* "View.MemoryView":883 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ } /* "View.MemoryView":888 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":889 * * if index >= shape: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * resultp = bufp + index * stride */ __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 889; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 889; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __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 = 889; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 889; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 889; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":888 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ } /* "View.MemoryView":891 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * resultp = bufp + index * stride # <<<<<<<<<<<<<< * if suboffset >= 0: * resultp = (<char **> resultp)[0] + suboffset */ __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); /* "View.MemoryView":892 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":893 * resultp = bufp + index * stride * if suboffset >= 0: * resultp = (<char **> resultp)[0] + suboffset # <<<<<<<<<<<<<< * * return resultp */ __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); /* "View.MemoryView":892 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ } /* "View.MemoryView":895 * resultp = (<char **> resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_resultp; goto __pyx_L0; /* "View.MemoryView":868 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":901 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { int __pyx_v_ndim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; int __pyx_v_i; int __pyx_v_j; int __pyx_r; int __pyx_t_1; Py_ssize_t *__pyx_t_2; long __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":902 * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< * * cdef Py_ssize_t *shape = memslice.shape */ __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; __pyx_v_ndim = __pyx_t_1; /* "View.MemoryView":904 * cdef int ndim = memslice.memview.view.ndim * * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< * cdef Py_ssize_t *strides = memslice.strides * */ __pyx_t_2 = __pyx_v_memslice->shape; __pyx_v_shape = __pyx_t_2; /* "View.MemoryView":905 * * cdef Py_ssize_t *shape = memslice.shape * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< * * */ __pyx_t_2 = __pyx_v_memslice->strides; __pyx_v_strides = __pyx_t_2; /* "View.MemoryView":909 * * cdef int i, j * for i in range(ndim / 2): # <<<<<<<<<<<<<< * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] */ __pyx_t_3 = (__pyx_v_ndim / 2); for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":910 * cdef int i, j * for i in range(ndim / 2): * j = ndim - 1 - i # <<<<<<<<<<<<<< * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] */ __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); /* "View.MemoryView":911 * for i in range(ndim / 2): * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< * shape[i], shape[j] = shape[j], shape[i] * */ __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; /* "View.MemoryView":912 * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: */ __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; /* "View.MemoryView":914 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * */ __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L6_bool_binop_done; } __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L6_bool_binop_done:; if (__pyx_t_6) { /* "View.MemoryView":915 * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< * * return 1 */ __pyx_t_8 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 915; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":914 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * */ } } /* "View.MemoryView":917 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< * * */ __pyx_r = 1; goto __pyx_L0; /* "View.MemoryView":901 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = 0; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":934 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * */ /* Python wrapper */ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":935 * * def __dealloc__(self): * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< * * cdef convert_item_to_object(self, char *itemp): */ __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); /* "View.MemoryView":934 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":937 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * if self.to_object_func != NULL: * return self.to_object_func(itemp) */ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":938 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":939 * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: * return self.to_object_func(itemp) # <<<<<<<<<<<<<< * else: * return memoryview.convert_item_to_object(self, itemp) */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 939; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":938 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ } /* "View.MemoryView":941 * return self.to_object_func(itemp) * else: * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< * * cdef assign_item_from_object(self, char *itemp, object value): */ /*else*/ { __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } /* "View.MemoryView":937 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * if self.to_object_func != NULL: * return self.to_object_func(itemp) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":943 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) */ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":944 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< * self.to_dtype_func(itemp, value) * else: */ __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":945 * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< * else: * memoryview.assign_item_from_object(self, itemp, value) */ __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":944 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< * self.to_dtype_func(itemp, value) * else: */ goto __pyx_L3; } /* "View.MemoryView":947 * self.to_dtype_func(itemp, value) * else: * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< * * property base: */ /*else*/ { __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; /* "View.MemoryView":943 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":951 * property base: * @cname('__pyx_memoryviewslice__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* Python wrapper */ static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":952 * @cname('__pyx_memoryviewslice__get__base') * def __get__(self): * return self.from_object # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->from_object); __pyx_r = __pyx_v_self->from_object; goto __pyx_L0; /* "View.MemoryView":951 * property base: * @cname('__pyx_memoryviewslice__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":958 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< * int ndim, * object (*to_object_func)(char *), */ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; __Pyx_TypeInfo *__pyx_t_4; Py_buffer __pyx_t_5; Py_ssize_t *__pyx_t_6; Py_ssize_t *__pyx_t_7; Py_ssize_t *__pyx_t_8; Py_ssize_t __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_fromslice", 0); /* "View.MemoryView":966 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); if (__pyx_t_1) { /* "View.MemoryView":967 * * if <PyObject *> memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; /* "View.MemoryView":966 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ } /* "View.MemoryView":972 * * * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< * * result.from_slice = memviewslice */ __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":974 * result = _memoryviewslice(None, 0, dtype_is_object) * * result.from_slice = memviewslice # <<<<<<<<<<<<<< * __PYX_INC_MEMVIEW(&memviewslice, 1) * */ __pyx_v_result->from_slice = __pyx_v_memviewslice; /* "View.MemoryView":975 * * result.from_slice = memviewslice * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< * * result.from_object = (<memoryview> memviewslice.memview).base */ __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); /* "View.MemoryView":977 * __PYX_INC_MEMVIEW(&memviewslice, 1) * * result.from_object = (<memoryview> memviewslice.memview).base # <<<<<<<<<<<<<< * result.typeinfo = memviewslice.memview.typeinfo * */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __Pyx_GOTREF(__pyx_v_result->from_object); __Pyx_DECREF(__pyx_v_result->from_object); __pyx_v_result->from_object = __pyx_t_2; __pyx_t_2 = 0; /* "View.MemoryView":978 * * result.from_object = (<memoryview> memviewslice.memview).base * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< * * result.view = memviewslice.memview.view */ __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; /* "View.MemoryView":980 * result.typeinfo = memviewslice.memview.typeinfo * * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim */ __pyx_t_5 = __pyx_v_memviewslice.memview->view; __pyx_v_result->__pyx_base.view = __pyx_t_5; /* "View.MemoryView":981 * * result.view = memviewslice.memview.view * result.view.buf = <void *> memviewslice.data # <<<<<<<<<<<<<< * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None */ __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); /* "View.MemoryView":982 * result.view = memviewslice.memview.view * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim # <<<<<<<<<<<<<< * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) */ __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; /* "View.MemoryView":983 * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; /* "View.MemoryView":984 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * result.flags = PyBUF_RECORDS */ Py_INCREF(Py_None); /* "View.MemoryView":986 * Py_INCREF(Py_None) * * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< * * result.view.shape = <Py_ssize_t *> result.from_slice.shape */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; /* "View.MemoryView":988 * result.flags = PyBUF_RECORDS * * result.view.shape = <Py_ssize_t *> result.from_slice.shape # <<<<<<<<<<<<<< * result.view.strides = <Py_ssize_t *> result.from_slice.strides * */ __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); /* "View.MemoryView":989 * * result.view.shape = <Py_ssize_t *> result.from_slice.shape * result.view.strides = <Py_ssize_t *> result.from_slice.strides # <<<<<<<<<<<<<< * * */ __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); /* "View.MemoryView":992 * * * result.view.suboffsets = NULL # <<<<<<<<<<<<<< * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: */ __pyx_v_result->__pyx_base.view.suboffsets = NULL; /* "View.MemoryView":993 * * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets */ __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { __pyx_t_6 = __pyx_t_8; __pyx_v_suboffset = (__pyx_t_6[0]); /* "View.MemoryView":994 * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break */ __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":995 * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets # <<<<<<<<<<<<<< * break * */ __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); /* "View.MemoryView":996 * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break # <<<<<<<<<<<<<< * * result.view.len = result.view.itemsize */ goto __pyx_L5_break; /* "View.MemoryView":994 * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break */ } } __pyx_L5_break:; /* "View.MemoryView":998 * break * * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< * for length in result.view.shape[:ndim]: * result.view.len *= length */ __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; /* "View.MemoryView":999 * * result.view.len = result.view.itemsize * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< * result.view.len *= length * */ __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { __pyx_t_6 = __pyx_t_8; __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 999; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":1000 * result.view.len = result.view.itemsize * for length in result.view.shape[:ndim]: * result.view.len *= length # <<<<<<<<<<<<<< * * result.to_object_func = to_object_func */ __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1000; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1000; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1000; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } /* "View.MemoryView":1002 * result.view.len *= length * * result.to_object_func = to_object_func # <<<<<<<<<<<<<< * result.to_dtype_func = to_dtype_func * */ __pyx_v_result->to_object_func = __pyx_v_to_object_func; /* "View.MemoryView":1003 * * result.to_object_func = to_object_func * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< * * return result */ __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; /* "View.MemoryView":1005 * result.to_dtype_func = to_dtype_func * * return result # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_get_slice_from_memoryview') */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":958 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< * int ndim, * object (*to_object_func)(char *), */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XDECREF(__pyx_v_length); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1008 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj */ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; __Pyx_memviewslice *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_slice_from_memview", 0); /* "View.MemoryView":1011 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1012 * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): * obj = memview # <<<<<<<<<<<<<< * return &obj.from_slice * else: */ if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1012; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":1013 * if isinstance(memview, _memoryviewslice): * obj = memview * return &obj.from_slice # <<<<<<<<<<<<<< * else: * slice_copy(memview, mslice) */ __pyx_r = (&__pyx_v_obj->from_slice); goto __pyx_L0; /* "View.MemoryView":1011 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ } /* "View.MemoryView":1015 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< * return mslice * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); /* "View.MemoryView":1016 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_slice_copy') */ __pyx_r = __pyx_v_mslice; goto __pyx_L0; } /* "View.MemoryView":1008 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0, 0); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_obj); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1019 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< * cdef int dim * cdef (Py_ssize_t*) shape, strides, suboffsets */ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { int __pyx_v_dim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; Py_ssize_t *__pyx_v_suboffsets; __Pyx_RefNannyDeclarations Py_ssize_t *__pyx_t_1; int __pyx_t_2; int __pyx_t_3; Py_ssize_t __pyx_t_4; __Pyx_RefNannySetupContext("slice_copy", 0); /* "View.MemoryView":1023 * cdef (Py_ssize_t*) shape, strides, suboffsets * * shape = memview.view.shape # <<<<<<<<<<<<<< * strides = memview.view.strides * suboffsets = memview.view.suboffsets */ __pyx_t_1 = __pyx_v_memview->view.shape; __pyx_v_shape = __pyx_t_1; /* "View.MemoryView":1024 * * shape = memview.view.shape * strides = memview.view.strides # <<<<<<<<<<<<<< * suboffsets = memview.view.suboffsets * */ __pyx_t_1 = __pyx_v_memview->view.strides; __pyx_v_strides = __pyx_t_1; /* "View.MemoryView":1025 * shape = memview.view.shape * strides = memview.view.strides * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< * * dst.memview = <__pyx_memoryview *> memview */ __pyx_t_1 = __pyx_v_memview->view.suboffsets; __pyx_v_suboffsets = __pyx_t_1; /* "View.MemoryView":1027 * suboffsets = memview.view.suboffsets * * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< * dst.data = <char *> memview.view.buf * */ __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); /* "View.MemoryView":1028 * * dst.memview = <__pyx_memoryview *> memview * dst.data = <char *> memview.view.buf # <<<<<<<<<<<<<< * * for dim in range(memview.view.ndim): */ __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); /* "View.MemoryView":1030 * dst.data = <char *> memview.view.buf * * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] */ __pyx_t_2 = __pyx_v_memview->view.ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_dim = __pyx_t_3; /* "View.MemoryView":1031 * * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 */ (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); /* "View.MemoryView":1032 * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 * */ (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); /* "View.MemoryView":1033 * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object') */ if ((__pyx_v_suboffsets != 0)) { __pyx_t_4 = (__pyx_v_suboffsets[__pyx_v_dim]); } else { __pyx_t_4 = -1L; } (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_4; } /* "View.MemoryView":1019 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< * cdef int dim * cdef (Py_ssize_t*) shape, strides, suboffsets */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":1036 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice */ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { __Pyx_memviewslice __pyx_v_memviewslice; 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("memoryview_copy", 0); /* "View.MemoryView":1039 * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< * return memoryview_copy_from_slice(memview, &memviewslice) * */ __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); /* "View.MemoryView":1040 * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object_from_slice') */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":1036 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1043 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< * """ * Create a new memoryview object from a given memoryview object and slice. */ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { PyObject *(*__pyx_v_to_object_func)(char *); int (*__pyx_v_to_dtype_func)(char *, PyObject *); PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *(*__pyx_t_3)(char *); int (*__pyx_t_4)(char *, PyObject *); PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); /* "View.MemoryView":1050 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1051 * * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: */ __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; __pyx_v_to_object_func = __pyx_t_3; /* "View.MemoryView":1052 * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< * else: * to_object_func = NULL */ __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; __pyx_v_to_dtype_func = __pyx_t_4; /* "View.MemoryView":1050 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func */ goto __pyx_L3; } /* "View.MemoryView":1054 * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: * to_object_func = NULL # <<<<<<<<<<<<<< * to_dtype_func = NULL * */ /*else*/ { __pyx_v_to_object_func = NULL; /* "View.MemoryView":1055 * else: * to_object_func = NULL * to_dtype_func = NULL # <<<<<<<<<<<<<< * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, */ __pyx_v_to_dtype_func = NULL; } __pyx_L3:; /* "View.MemoryView":1057 * to_dtype_func = NULL * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< * to_object_func, to_dtype_func, * memview.dtype_is_object) */ __Pyx_XDECREF(__pyx_r); /* "View.MemoryView":1059 * return memoryview_fromslice(memviewslice[0], memview.view.ndim, * to_object_func, to_dtype_func, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1057; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":1043 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< * """ * Create a new memoryview object from a given memoryview object and slice. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1065 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< * if arg < 0: * return -arg */ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { Py_ssize_t __pyx_r; int __pyx_t_1; /* "View.MemoryView":1066 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ __pyx_t_1 = ((__pyx_v_arg < 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":1067 * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: * return -arg # <<<<<<<<<<<<<< * else: * return arg */ __pyx_r = (-__pyx_v_arg); goto __pyx_L0; /* "View.MemoryView":1066 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ } /* "View.MemoryView":1069 * return -arg * else: * return arg # <<<<<<<<<<<<<< * * @cname('__pyx_get_best_slice_order') */ /*else*/ { __pyx_r = __pyx_v_arg; goto __pyx_L0; } /* "View.MemoryView":1065 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< * if arg < 0: * return -arg */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1072 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< * """ * Figure out the best memory access order for a given slice. */ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { int __pyx_v_i; Py_ssize_t __pyx_v_c_stride; Py_ssize_t __pyx_v_f_stride; char __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1077 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< * cdef Py_ssize_t f_stride = 0 * */ __pyx_v_c_stride = 0; /* "View.MemoryView":1078 * cdef int i * cdef Py_ssize_t c_stride = 0 * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< * * for i in range(ndim - 1, -1, -1): */ __pyx_v_f_stride = 0; /* "View.MemoryView":1080 * cdef Py_ssize_t f_stride = 0 * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] */ for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1L; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1081 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1082 * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< * break * */ __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1083 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * for i in range(ndim): */ goto __pyx_L4_break; /* "View.MemoryView":1081 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ } } __pyx_L4_break:; /* "View.MemoryView":1085 * break * * for i in range(ndim): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] */ __pyx_t_1 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1086 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1087 * for i in range(ndim): * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< * break * */ __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1088 * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): */ goto __pyx_L7_break; /* "View.MemoryView":1086 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ } } __pyx_L7_break:; /* "View.MemoryView":1090 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1091 * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): * return 'C' # <<<<<<<<<<<<<< * else: * return 'F' */ __pyx_r = 'C'; goto __pyx_L0; /* "View.MemoryView":1090 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ } /* "View.MemoryView":1093 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< * * @cython.cdivision(True) */ /*else*/ { __pyx_r = 'F'; goto __pyx_L0; } /* "View.MemoryView":1072 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< * """ * Figure out the best memory access order for a given slice. */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1096 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< * char *dst_data, Py_ssize_t *dst_strides, * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, */ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; Py_ssize_t __pyx_v_dst_extent; Py_ssize_t __pyx_v_src_stride; Py_ssize_t __pyx_v_dst_stride; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; /* "View.MemoryView":1103 * * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] */ __pyx_v_src_extent = (__pyx_v_src_shape[0]); /* "View.MemoryView":1104 * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t src_stride = src_strides[0] * cdef Py_ssize_t dst_stride = dst_strides[0] */ __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); /* "View.MemoryView":1105 * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t dst_stride = dst_strides[0] * */ __pyx_v_src_stride = (__pyx_v_src_strides[0]); /* "View.MemoryView":1106 * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< * * if ndim == 1: */ __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); /* "View.MemoryView":1108 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): */ __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":1109 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) */ __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L5_bool_binop_done; } __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L5_bool_binop_done; } /* "View.MemoryView":1110 * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): # <<<<<<<<<<<<<< * memcpy(dst_data, src_data, itemsize * dst_extent) * else: */ __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); if (__pyx_t_2) { __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); } __pyx_t_3 = (__pyx_t_2 != 0); __pyx_t_1 = __pyx_t_3; __pyx_L5_bool_binop_done:; /* "View.MemoryView":1109 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) */ if (__pyx_t_1) { /* "View.MemoryView":1111 * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); /* "View.MemoryView":1109 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) */ goto __pyx_L4; } /* "View.MemoryView":1113 * memcpy(dst_data, src_data, itemsize * dst_extent) * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * memcpy(dst_data, src_data, itemsize) * src_data += src_stride */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1114 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< * src_data += src_stride * dst_data += dst_stride */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); /* "View.MemoryView":1115 * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< * dst_data += dst_stride * else: */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); /* "View.MemoryView":1116 * memcpy(dst_data, src_data, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); } } __pyx_L4:; /* "View.MemoryView":1108 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): */ goto __pyx_L3; } /* "View.MemoryView":1118 * dst_data += dst_stride * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * _copy_strided_to_strided(src_data, src_strides + 1, * dst_data, dst_strides + 1, */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1119 * else: * for i in range(dst_extent): * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< * dst_data, dst_strides + 1, * src_shape + 1, dst_shape + 1, */ _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); /* "View.MemoryView":1123 * src_shape + 1, dst_shape + 1, * ndim - 1, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< * dst_data += dst_stride * */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); /* "View.MemoryView":1124 * ndim - 1, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, */ __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); } } __pyx_L3:; /* "View.MemoryView":1096 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< * char *dst_data, Py_ssize_t *dst_strides, * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, */ /* function exit code */ } /* "View.MemoryView":1126 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: */ static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { /* "View.MemoryView":1129 * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< * src.shape, dst.shape, ndim, itemsize) * */ _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); /* "View.MemoryView":1126 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: */ /* function exit code */ } /* "View.MemoryView":1133 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i */ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { int __pyx_v_i; Py_ssize_t __pyx_v_size; Py_ssize_t __pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1136 * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< * * for i in range(ndim): */ __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_size = __pyx_t_1; /* "View.MemoryView":1138 * cdef Py_ssize_t size = src.memview.view.itemsize * * for i in range(ndim): # <<<<<<<<<<<<<< * size *= src.shape[i] * */ __pyx_t_2 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1139 * * for i in range(ndim): * size *= src.shape[i] # <<<<<<<<<<<<<< * * return size */ __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); } /* "View.MemoryView":1141 * size *= src.shape[i] * * return size # <<<<<<<<<<<<<< * * @cname('__pyx_fill_contig_strides_array') */ __pyx_r = __pyx_v_size; goto __pyx_L0; /* "View.MemoryView":1133 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1144 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, * int ndim, char order) nogil: */ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { int __pyx_v_idx; Py_ssize_t __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1153 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ __pyx_t_1 = ((__pyx_v_order == 'F') != 0); if (__pyx_t_1) { /* "View.MemoryView":1154 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ __pyx_t_2 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_idx = __pyx_t_3; /* "View.MemoryView":1155 * if order == 'F': * for idx in range(ndim): * strides[idx] = stride # <<<<<<<<<<<<<< * stride = stride * shape[idx] * else: */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1156 * for idx in range(ndim): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< * else: * for idx in range(ndim - 1, -1, -1): */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } /* "View.MemoryView":1153 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ goto __pyx_L3; } /* "View.MemoryView":1158 * stride = stride * shape[idx] * else: * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ /*else*/ { for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1L; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; /* "View.MemoryView":1159 * else: * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride # <<<<<<<<<<<<<< * stride = stride * shape[idx] * */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1160 * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< * * return stride */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } } __pyx_L3:; /* "View.MemoryView":1162 * stride = stride * shape[idx] * * return stride # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_data_to_temp') */ __pyx_r = __pyx_v_stride; goto __pyx_L0; /* "View.MemoryView":1144 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, * int ndim, char order) nogil: */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1165 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *tmpslice, * char order, */ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { int __pyx_v_i; void *__pyx_v_result; size_t __pyx_v_itemsize; size_t __pyx_v_size; void *__pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; struct __pyx_memoryview_obj *__pyx_t_4; int __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1176 * cdef void *result * * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< * cdef size_t size = slice_get_size(src, ndim) * */ __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":1177 * * cdef size_t itemsize = src.memview.view.itemsize * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< * * result = malloc(size) */ __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); /* "View.MemoryView":1179 * cdef size_t size = slice_get_size(src, ndim) * * result = malloc(size) # <<<<<<<<<<<<<< * if not result: * _err(MemoryError, NULL) */ __pyx_v_result = malloc(__pyx_v_size); /* "View.MemoryView":1180 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1181 * result = malloc(size) * if not result: * _err(MemoryError, NULL) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1180 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ } /* "View.MemoryView":1184 * * * tmpslice.data = <char *> result # <<<<<<<<<<<<<< * tmpslice.memview = src.memview * for i in range(ndim): */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); /* "View.MemoryView":1185 * * tmpslice.data = <char *> result * tmpslice.memview = src.memview # <<<<<<<<<<<<<< * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] */ __pyx_t_4 = __pyx_v_src->memview; __pyx_v_tmpslice->memview = __pyx_t_4; /* "View.MemoryView":1186 * tmpslice.data = <char *> result * tmpslice.memview = src.memview * for i in range(ndim): # <<<<<<<<<<<<<< * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 */ __pyx_t_3 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1187 * tmpslice.memview = src.memview * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< * tmpslice.suboffsets[i] = -1 * */ (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); /* "View.MemoryView":1188 * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, */ (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; } /* "View.MemoryView":1190 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< * ndim, order) * */ __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); /* "View.MemoryView":1194 * * * for i in range(ndim): # <<<<<<<<<<<<<< * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 */ __pyx_t_3 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1195 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1196 * for i in range(ndim): * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< * * if slice_is_contig(src, order, ndim): */ (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; /* "View.MemoryView":1195 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ } } /* "View.MemoryView":1198 * tmpslice.strides[i] = 0 * * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1199 * * if slice_is_contig(src, order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) */ memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); /* "View.MemoryView":1198 * tmpslice.strides[i] = 0 * * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ goto __pyx_L9; } /* "View.MemoryView":1201 * memcpy(result, src.data, size) * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< * * return result */ /*else*/ { copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); } __pyx_L9:; /* "View.MemoryView":1203 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":1165 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *tmpslice, * char order, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = NULL; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1208 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % */ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_extents", 0); /* "View.MemoryView":1211 * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % * (i, extent1, extent2)) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err_dim') */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1211; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_3 = 0; /* "View.MemoryView":1210 * cdef int _err_extents(int i, Py_ssize_t extent1, * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< * (i, extent1, extent2)) * */ __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __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 = 1210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1208 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1214 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1215 * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err') */ __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_INCREF(__pyx_v_error); __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } if (!__pyx_t_2) { __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_1); } else { __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __pyx_t_2 = NULL; __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1214 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1218 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1219 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":1220 * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< * else: * raise error */ __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_error); __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } if (!__pyx_t_5) { __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_2); } else { __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1219 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ } /* "View.MemoryView":1222 * raise error(msg.decode('ascii')) * else: * raise error # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_contents') */ /*else*/ { __Pyx_Raise(__pyx_v_error, 0, 0, 0); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":1218 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1225 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { void *__pyx_v_tmpdata; size_t __pyx_v_itemsize; int __pyx_v_i; char __pyx_v_order; int __pyx_v_broadcasting; int __pyx_v_direct_copy; __Pyx_memviewslice __pyx_v_tmp; int __pyx_v_ndim; int __pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; void *__pyx_t_6; int __pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1233 * Check for overlapping memory and verify the shapes. * """ * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< * cdef size_t itemsize = src.memview.view.itemsize * cdef int i */ __pyx_v_tmpdata = NULL; /* "View.MemoryView":1234 * """ * cdef void *tmpdata = NULL * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< * cdef int i * cdef char order = get_best_order(&src, src_ndim) */ __pyx_t_1 = __pyx_v_src.memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":1236 * cdef size_t itemsize = src.memview.view.itemsize * cdef int i * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< * cdef bint broadcasting = False * cdef bint direct_copy = False */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); /* "View.MemoryView":1237 * cdef int i * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False # <<<<<<<<<<<<<< * cdef bint direct_copy = False * cdef __Pyx_memviewslice tmp */ __pyx_v_broadcasting = 0; /* "View.MemoryView":1238 * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False * cdef bint direct_copy = False # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice tmp * */ __pyx_v_direct_copy = 0; /* "View.MemoryView":1241 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: */ __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1242 * * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); /* "View.MemoryView":1241 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: */ goto __pyx_L3; } /* "View.MemoryView":1243 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&dst, dst_ndim, src_ndim) * */ __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1244 * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< * * cdef int ndim = max(src_ndim, dst_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); /* "View.MemoryView":1243 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&dst, dst_ndim, src_ndim) * */ } __pyx_L3:; /* "View.MemoryView":1246 * broadcast_leading(&dst, dst_ndim, src_ndim) * * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< * * for i in range(ndim): */ __pyx_t_3 = __pyx_v_dst_ndim; __pyx_t_4 = __pyx_v_src_ndim; if (((__pyx_t_3 > __pyx_t_4) != 0)) { __pyx_t_5 = __pyx_t_3; } else { __pyx_t_5 = __pyx_t_4; } __pyx_v_ndim = __pyx_t_5; /* "View.MemoryView":1248 * cdef int ndim = max(src_ndim, dst_ndim) * * for i in range(ndim): # <<<<<<<<<<<<<< * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: */ __pyx_t_5 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1249 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); if (__pyx_t_2) { /* "View.MemoryView":1250 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< * broadcasting = True * src.strides[i] = 0 */ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1251 * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: * broadcasting = True # <<<<<<<<<<<<<< * src.strides[i] = 0 * else: */ __pyx_v_broadcasting = 1; /* "View.MemoryView":1252 * if src.shape[i] == 1: * broadcasting = True * src.strides[i] = 0 # <<<<<<<<<<<<<< * else: * _err_extents(i, dst.shape[i], src.shape[i]) */ (__pyx_v_src.strides[__pyx_v_i]) = 0; /* "View.MemoryView":1250 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< * broadcasting = True * src.strides[i] = 0 */ goto __pyx_L7; } /* "View.MemoryView":1254 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< * * if src.suboffsets[i] >= 0: */ /*else*/ { __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L7:; /* "View.MemoryView":1249 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ } /* "View.MemoryView":1256 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Dimension %d is not direct", i) * */ __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":1257 * * if src.suboffsets[i] >= 0: * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< * * if slices_overlap(&src, &dst, ndim, itemsize): */ __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1256 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Dimension %d is not direct", i) * */ } } /* "View.MemoryView":1259 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * * if not slice_is_contig(&src, order, ndim): */ __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); if (__pyx_t_2) { /* "View.MemoryView":1261 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1262 * * if not slice_is_contig(&src, order, ndim): * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); /* "View.MemoryView":1261 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ } /* "View.MemoryView":1264 * order = get_best_order(&dst, ndim) * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< * src = tmp * */ __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1264; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_tmpdata = __pyx_t_6; /* "View.MemoryView":1265 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< * * if not broadcasting: */ __pyx_v_src = __pyx_v_tmp; /* "View.MemoryView":1259 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * * if not slice_is_contig(&src, order, ndim): */ } /* "View.MemoryView":1267 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1270 * * * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): */ __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1271 * * if slice_is_contig(&src, 'C', ndim): * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< * elif slice_is_contig(&src, 'F', ndim): * direct_copy = slice_is_contig(&dst, 'F', ndim) */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); /* "View.MemoryView":1270 * * * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): */ goto __pyx_L12; } /* "View.MemoryView":1272 * if slice_is_contig(&src, 'C', ndim): * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(&dst, 'F', ndim) * */ __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1273 * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< * * if direct_copy: */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); /* "View.MemoryView":1272 * if slice_is_contig(&src, 'C', ndim): * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(&dst, 'F', ndim) * */ } __pyx_L12:; /* "View.MemoryView":1275 * direct_copy = slice_is_contig(&dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ __pyx_t_2 = (__pyx_v_direct_copy != 0); if (__pyx_t_2) { /* "View.MemoryView":1277 * if direct_copy: * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1278 * * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) */ memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); /* "View.MemoryView":1279 * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * free(tmpdata) * return 0 */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1280 * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1281 * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * if order == 'F' == get_best_order(&dst, ndim): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1275 * direct_copy = slice_is_contig(&dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ } /* "View.MemoryView":1267 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1283 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ __pyx_t_2 = (__pyx_v_order == 'F'); if (__pyx_t_2) { __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); } __pyx_t_7 = (__pyx_t_2 != 0); if (__pyx_t_7) { /* "View.MemoryView":1286 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1287 * * transpose_memslice(&src) * transpose_memslice(&dst) # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1283 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1289 * transpose_memslice(&dst) * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * copy_strided_to_strided(&src, &dst, ndim, itemsize) * refcount_copying(&dst, dtype_is_object, ndim, True) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1290 * * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< * refcount_copying(&dst, dtype_is_object, ndim, True) * */ copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); /* "View.MemoryView":1291 * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * * free(tmpdata) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1293 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1294 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_broadcast_leading') */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1225 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1297 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { int __pyx_v_i; int __pyx_v_offset; int __pyx_t_1; int __pyx_t_2; /* "View.MemoryView":1301 * int ndim_other) nogil: * cdef int i * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< * * for i in range(ndim - 1, -1, -1): */ __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); /* "View.MemoryView":1303 * cdef int offset = ndim_other - ndim * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] */ for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1L; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1304 * * for i in range(ndim - 1, -1, -1): * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< * mslice.strides[i + offset] = mslice.strides[i] * mslice.suboffsets[i + offset] = mslice.suboffsets[i] */ (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); /* "View.MemoryView":1305 * for i in range(ndim - 1, -1, -1): * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * */ (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1306 * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< * * for i in range(offset): */ (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); } /* "View.MemoryView":1308 * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * * for i in range(offset): # <<<<<<<<<<<<<< * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] */ __pyx_t_1 = __pyx_v_offset; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "View.MemoryView":1309 * * for i in range(offset): * mslice.shape[i] = 1 # <<<<<<<<<<<<<< * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 */ (__pyx_v_mslice->shape[__pyx_v_i]) = 1; /* "View.MemoryView":1310 * for i in range(offset): * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< * mslice.suboffsets[i] = -1 * */ (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); /* "View.MemoryView":1311 * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * */ (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; } /* "View.MemoryView":1297 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ /* function exit code */ } /* "View.MemoryView":1319 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< * int ndim, bint inc) nogil: * */ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { int __pyx_t_1; /* "View.MemoryView":1323 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ __pyx_t_1 = (__pyx_v_dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":1324 * * if dtype_is_object: * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< * dst.strides, ndim, inc) * */ __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); /* "View.MemoryView":1323 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ } /* "View.MemoryView":1319 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< * int ndim, bint inc) nogil: * */ /* function exit code */ } /* "View.MemoryView":1328 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { __Pyx_RefNannyDeclarations #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); /* "View.MemoryView":1331 * Py_ssize_t *strides, int ndim, * bint inc) with gil: * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_refcount_objects_in_slice') */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); /* "View.MemoryView":1328 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ /* function exit code */ __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } /* "View.MemoryView":1334 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, bint inc): * cdef Py_ssize_t i */ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; int __pyx_t_3; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); /* "View.MemoryView":1338 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< * if ndim == 1: * if inc: */ __pyx_t_1 = (__pyx_v_shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "View.MemoryView":1339 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_3) { /* "View.MemoryView":1340 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ __pyx_t_3 = (__pyx_v_inc != 0); if (__pyx_t_3) { /* "View.MemoryView":1341 * if ndim == 1: * if inc: * Py_INCREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * Py_DECREF((<PyObject **> data)[0]) */ Py_INCREF((((PyObject **)__pyx_v_data)[0])); /* "View.MemoryView":1340 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ goto __pyx_L6; } /* "View.MemoryView":1343 * Py_INCREF((<PyObject **> data)[0]) * else: * Py_DECREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, */ /*else*/ { Py_DECREF((((PyObject **)__pyx_v_data)[0])); } __pyx_L6:; /* "View.MemoryView":1339 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ goto __pyx_L5; } /* "View.MemoryView":1345 * Py_DECREF((<PyObject **> data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, inc) * */ /*else*/ { /* "View.MemoryView":1346 * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, * ndim - 1, inc) # <<<<<<<<<<<<<< * * data += strides[0] */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); } __pyx_L5:; /* "View.MemoryView":1348 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } /* "View.MemoryView":1334 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, bint inc): * cdef Py_ssize_t i */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":1354 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< * size_t itemsize, void *item, * bint dtype_is_object) nogil: */ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { /* "View.MemoryView":1357 * size_t itemsize, void *item, * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1358 * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) */ __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); /* "View.MemoryView":1360 * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * * */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1354 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< * size_t itemsize, void *item, * bint dtype_is_object) nogil: */ /* function exit code */ } /* "View.MemoryView":1364 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_stride; Py_ssize_t __pyx_v_extent; int __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; /* "View.MemoryView":1368 * size_t itemsize, void *item) nogil: * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t extent = shape[0] * */ __pyx_v_stride = (__pyx_v_strides[0]); /* "View.MemoryView":1369 * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< * * if ndim == 1: */ __pyx_v_extent = (__pyx_v_shape[0]); /* "View.MemoryView":1371 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":1372 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< * memcpy(data, item, itemsize) * data += stride */ __pyx_t_2 = __pyx_v_extent; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1373 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< * data += stride * else: */ memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); /* "View.MemoryView":1374 * for i in range(extent): * memcpy(data, item, itemsize) * data += stride # <<<<<<<<<<<<<< * else: * for i in range(extent): */ __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } /* "View.MemoryView":1371 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ goto __pyx_L3; } /* "View.MemoryView":1376 * data += stride * else: * for i in range(extent): # <<<<<<<<<<<<<< * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) */ /*else*/ { __pyx_t_2 = __pyx_v_extent; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1377 * else: * for i in range(extent): * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, itemsize, item) * data += stride */ __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); /* "View.MemoryView":1379 * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) * data += stride # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } } __pyx_L3:; /* "View.MemoryView":1364 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ /* function exit code */ } static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_array_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_array_obj *)o); p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { Py_DECREF(o); o = 0; } return o; } static void __pyx_tp_dealloc_array(PyObject *o) { struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_array___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->mode); Py_CLEAR(p->_format); (*Py_TYPE(o)->tp_free)(o); } static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_array___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { PyObject *v = PyObject_GenericGetAttr(o, n); if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); v = __pyx_array___getattr__(o, n); } return v; } static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { return get_memview(o); } static PyMethodDef __pyx_methods_array[] = { {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_array[] = { {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_array = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ __pyx_sq_item_array, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_array = { 0, /*mp_length*/ __pyx_array___getitem__, /*mp_subscript*/ __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_array = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif __pyx_array_getbuffer, /*bf_getbuffer*/ 0, /*bf_releasebuffer*/ }; static PyTypeObject __pyx_type___pyx_array = { PyVarObject_HEAD_INIT(0, 0) "glove.metrics.accuracy_cython.array", /*tp_name*/ sizeof(struct __pyx_array_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_array, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ __pyx_tp_getattro_array, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_array, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_array, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_array, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_MemviewEnum_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_MemviewEnum_obj *)o); p->name = Py_None; Py_INCREF(Py_None); return o; } static void __pyx_tp_dealloc_Enum(PyObject *o) { struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); Py_CLEAR(p->name); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { int e; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; if (p->name) { e = (*v)(p->name, a); if (e) return e; } return 0; } static int __pyx_tp_clear_Enum(PyObject *o) { PyObject* tmp; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; tmp = ((PyObject*)p->name); p->name = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); return 0; } static PyMethodDef __pyx_methods_Enum[] = { {0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_MemviewEnum = { PyVarObject_HEAD_INIT(0, 0) "glove.metrics.accuracy_cython.Enum", /*tp_name*/ sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_Enum, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif __pyx_MemviewEnum___repr__, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_Enum, /*tp_traverse*/ __pyx_tp_clear_Enum, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_Enum, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ __pyx_MemviewEnum___init__, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_Enum, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_memoryview_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_memoryview_obj *)o); p->__pyx_vtab = __pyx_vtabptr_memoryview; p->obj = Py_None; Py_INCREF(Py_None); p->_size = Py_None; Py_INCREF(Py_None); p->_array_interface = Py_None; Py_INCREF(Py_None); p->view.obj = NULL; if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { Py_DECREF(o); o = 0; } return o; } static void __pyx_tp_dealloc_memoryview(PyObject *o) { struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_memoryview___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->obj); Py_CLEAR(p->_size); Py_CLEAR(p->_array_interface); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; if (p->obj) { e = (*v)(p->obj, a); if (e) return e; } if (p->_size) { e = (*v)(p->_size, a); if (e) return e; } if (p->_array_interface) { e = (*v)(p->_array_interface, a); if (e) return e; } if (p->view.obj) { e = (*v)(p->view.obj, a); if (e) return e; } return 0; } static int __pyx_tp_clear_memoryview(PyObject *o) { PyObject* tmp; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; tmp = ((PyObject*)p->obj); p->obj = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_size); p->_size = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_array_interface); p->_array_interface = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); Py_CLEAR(p->view.obj); return 0; } static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_memoryview___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_transpose(o); } static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview__get__base(o); } static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_shape(o); } static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_strides(o); } static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_suboffsets(o); } static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_ndim(o); } static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_itemsize(o); } static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_nbytes(o); } static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_size(o); } static PyMethodDef __pyx_methods_memoryview[] = { {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_memoryview[] = { {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_memoryview = { __pyx_memoryview___len__, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ __pyx_sq_item_memoryview, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_memoryview = { __pyx_memoryview___len__, /*mp_length*/ __pyx_memoryview___getitem__, /*mp_subscript*/ __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_memoryview = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif __pyx_memoryview_getbuffer, /*bf_getbuffer*/ 0, /*bf_releasebuffer*/ }; static PyTypeObject __pyx_type___pyx_memoryview = { PyVarObject_HEAD_INIT(0, 0) "glove.metrics.accuracy_cython.memoryview", /*tp_name*/ sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif __pyx_memoryview___repr__, /*tp_repr*/ 0, /*tp_as_number*/ &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ __pyx_memoryview___str__, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_memoryview, /*tp_traverse*/ __pyx_tp_clear_memoryview, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_memoryview, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_memoryview, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_memoryview, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_memoryviewslice_obj *p; PyObject *o = __pyx_tp_new_memoryview(t, a, k); if (unlikely(!o)) return 0; p = ((struct __pyx_memoryviewslice_obj *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; p->from_object = Py_None; Py_INCREF(Py_None); p->from_slice.memview = NULL; return o; } static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_memoryviewslice___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->from_object); PyObject_GC_Track(o); __pyx_tp_dealloc_memoryview(o); } static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; if (p->from_object) { e = (*v)(p->from_object, a); if (e) return e; } return 0; } static int __pyx_tp_clear__memoryviewslice(PyObject *o) { PyObject* tmp; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; __pyx_tp_clear_memoryview(o); tmp = ((PyObject*)p->from_object); p->from_object = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); __PYX_XDEC_MEMVIEW(&p->from_slice, 1); return 0; } static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryviewslice__get__base(o); } static PyMethodDef __pyx_methods__memoryviewslice[] = { {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_memoryviewslice = { PyVarObject_HEAD_INIT(0, 0) "glove.metrics.accuracy_cython._memoryviewslice", /*tp_name*/ sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif #if CYTHON_COMPILING_IN_PYPY __pyx_memoryview___repr__, /*tp_repr*/ #else 0, /*tp_repr*/ #endif 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ #if CYTHON_COMPILING_IN_PYPY __pyx_memoryview___str__, /*tp_str*/ #else 0, /*tp_str*/ #endif 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ "Internal class for passing memoryview slices to Python", /*tp_doc*/ __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ __pyx_tp_clear__memoryviewslice, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods__memoryviewslice, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets__memoryviewslice, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new__memoryviewslice, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "accuracy_cython", 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_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, {&__pyx_n_s_compute_rank_violations, __pyx_k_compute_rank_violations, sizeof(__pyx_k_compute_rank_violations), 0, 0, 1, 1}, {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, {&__pyx_n_s_expected, __pyx_k_expected, sizeof(__pyx_k_expected), 0, 0, 1, 1}, {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, {&__pyx_n_s_glove_metrics_accuracy_cython, __pyx_k_glove_metrics_accuracy_cython, sizeof(__pyx_k_glove_metrics_accuracy_cython), 0, 0, 1, 1}, {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, {&__pyx_kp_s_home_maciej_Dropbox_code_glove, __pyx_k_home_maciej_Dropbox_code_glove, sizeof(__pyx_k_home_maciej_Dropbox_code_glove), 0, 0, 1, 0}, {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_input, __pyx_k_input, sizeof(__pyx_k_input), 0, 0, 1, 1}, {&__pyx_n_s_inputs, __pyx_k_inputs, sizeof(__pyx_k_inputs), 0, 0, 1, 1}, {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, {&__pyx_n_s_no_components, __pyx_k_no_components, sizeof(__pyx_k_no_components), 0, 0, 1, 1}, {&__pyx_n_s_no_input_vectors, __pyx_k_no_input_vectors, sizeof(__pyx_k_no_input_vectors), 0, 0, 1, 1}, {&__pyx_n_s_no_threads, __pyx_k_no_threads, sizeof(__pyx_k_no_threads), 0, 0, 1, 1}, {&__pyx_n_s_no_wordvec, __pyx_k_no_wordvec, sizeof(__pyx_k_no_wordvec), 0, 0, 1, 1}, {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_rank_violations, __pyx_k_rank_violations, sizeof(__pyx_k_rank_violations), 0, 0, 1, 1}, {&__pyx_n_s_score, __pyx_k_score, sizeof(__pyx_k_score), 0, 0, 1, 1}, {&__pyx_n_s_score_of_expected, __pyx_k_score_of_expected, sizeof(__pyx_k_score_of_expected), 0, 0, 1, 1}, {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, {&__pyx_n_s_skip_word, __pyx_k_skip_word, sizeof(__pyx_k_skip_word), 0, 0, 1, 1}, {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, {&__pyx_n_s_violations, __pyx_k_violations, sizeof(__pyx_k_violations), 0, 0, 1, 1}, {&__pyx_n_s_wordvec, __pyx_k_wordvec, sizeof(__pyx_k_wordvec), 0, 0, 1, 1}, {&__pyx_n_s_wordvec_norm, __pyx_k_wordvec_norm, sizeof(__pyx_k_wordvec_norm), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 359; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 388; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 790; __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", 0); /* "View.MemoryView":129 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "View.MemoryView":132 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "View.MemoryView":135 * * if not isinstance(format, bytes): * format = format.encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_n_s_ASCII); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "View.MemoryView":144 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "View.MemoryView":172 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "View.MemoryView":188 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 188; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "View.MemoryView":447 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 447; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "View.MemoryView":523 * if self.view.strides == NULL: * * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "View.MemoryView":531 * def __get__(self): * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) */ __pyx_tuple__9 = PyTuple_New(1); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__9); __Pyx_INCREF(__pyx_int_neg_1); __Pyx_GIVEREF(__pyx_int_neg_1); PyTuple_SET_ITEM(__pyx_tuple__9, 0, __pyx_int_neg_1); __Pyx_GIVEREF(__pyx_tuple__9); /* "View.MemoryView":640 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_slice__10 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_slice__10); __Pyx_GIVEREF(__pyx_slice__10); /* "View.MemoryView":643 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ __pyx_slice__11 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_slice__11); __Pyx_GIVEREF(__pyx_slice__11); /* "View.MemoryView":654 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ __pyx_slice__12 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_slice__12); __Pyx_GIVEREF(__pyx_slice__12); /* "View.MemoryView":661 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 661; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); /* "glove/metrics/accuracy_cython.pyx":20 * * * def compute_rank_violations(double[:, ::1] wordvec, # <<<<<<<<<<<<<< * double[::1] wordvec_norm, * double[:, ::1] input, */ __pyx_tuple__14 = PyTuple_Pack(17, __pyx_n_s_wordvec, __pyx_n_s_wordvec_norm, __pyx_n_s_input, __pyx_n_s_expected, __pyx_n_s_inputs, __pyx_n_s_rank_violations, __pyx_n_s_no_threads, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_no_input_vectors, __pyx_n_s_no_wordvec, __pyx_n_s_skip_word, __pyx_n_s_no_components, __pyx_n_s_violations, __pyx_n_s_score_of_expected, __pyx_n_s_score); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__14); __Pyx_GIVEREF(__pyx_tuple__14); __pyx_codeobj__15 = (PyObject*)__Pyx_PyCode_New(7, 0, 17, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_maciej_Dropbox_code_glove, __pyx_n_s_compute_rank_violations, 20, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":278 * return self.name * * cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<< * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") */ __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__16); __Pyx_GIVEREF(__pyx_tuple__16); /* "View.MemoryView":279 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__17); __Pyx_GIVEREF(__pyx_tuple__17); /* "View.MemoryView":280 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__18)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__18); __Pyx_GIVEREF(__pyx_tuple__18); /* "View.MemoryView":283 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__19); __Pyx_GIVEREF(__pyx_tuple__19); /* "View.MemoryView":284 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__20)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__20); __Pyx_GIVEREF(__pyx_tuple__20); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { /* InitThreads.init */ #ifdef WITH_THREAD PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__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 initaccuracy_cython(void); /*proto*/ PyMODINIT_FUNC initaccuracy_cython(void) #else PyMODINIT_FUNC PyInit_accuracy_cython(void); /*proto*/ PyMODINIT_FUNC PyInit_accuracy_cython(void) #endif { PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __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_accuracy_cython(void)", 0); 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_CyFunction_USED if (__pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_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("accuracy_cython", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_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 (__Pyx_InitGlobals() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif if (__pyx_module_is_main_glove__metrics__accuracy_cython) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!PyDict_GetItemString(modules, "glove.metrics.accuracy_cython")) { if (unlikely(PyDict_SetItemString(modules, "glove.metrics.accuracy_cython", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ generic = Py_None; Py_INCREF(Py_None); strided = Py_None; Py_INCREF(Py_None); indirect = Py_None; Py_INCREF(Py_None); contiguous = Py_None; Py_INCREF(Py_None); indirect_contiguous = Py_None; Py_INCREF(Py_None); /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_array.tp_print = 0; __pyx_array_type = &__pyx_type___pyx_array; if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_MemviewEnum.tp_print = 0; __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_memoryview.tp_print = 0; if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_memoryview_type = &__pyx_type___pyx_memoryview; __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_memoryviewslice.tp_print = 0; if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 923; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; /*--- Type import code ---*/ /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /* "glove/metrics/accuracy_cython.pyx":20 * * * def compute_rank_violations(double[:, ::1] wordvec, # <<<<<<<<<<<<<< * double[::1] wordvec_norm, * double[:, ::1] input, */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_5glove_7metrics_15accuracy_cython_1compute_rank_violations, NULL, __pyx_n_s_glove_metrics_accuracy_cython); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_compute_rank_violations, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "glove/metrics/accuracy_cython.pyx":1 * #!python # <<<<<<<<<<<<<< * #cython: boundscheck=False, wraparound=False, cdivision=True, initializedcheck=False * */ __pyx_t_1 = PyDict_New(); 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 (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __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; /* "View.MemoryView":205 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * def __dealloc__(array self): */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 205; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_array_type); /* "View.MemoryView":278 * return self.name * * cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<< * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(generic); __Pyx_DECREF_SET(generic, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":279 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(strided); __Pyx_DECREF_SET(strided, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":280 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 280; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect); __Pyx_DECREF_SET(indirect, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":283 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(contiguous); __Pyx_DECREF_SET(contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":284 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect_contiguous); __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":498 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryview_type); /* "View.MemoryView":954 * return self.from_object * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 954; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 954; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryviewslice_type); /* "View.MemoryView":1364 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init glove.metrics.accuracy_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init glove.metrics.accuracy_cython"); } __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 static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } 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; ctx->is_valid_array = 0; ctx->struct_alignment = 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 int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } 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 'c': return "'char'"; case 'b': return "'signed 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 's': case 'p': return "a string"; 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': case 's': case 'p': 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': case 's': case 'p': 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, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': 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; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_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': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': 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, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } 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 (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __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 %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } 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; 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 CYTHON_INLINE PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number; int ndim = ctx->head->field->type->ndim; ; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } 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 '\r': case '\n': ++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': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++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; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } 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; } 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': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } case 's': 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; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) 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 (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_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 int __Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, int ndim, __Pyx_memviewslice *memviewslice, int memview_is_new_reference) { __Pyx_RefNannyDeclarations int i, retval=-1; Py_buffer *buf = &memview->view; __Pyx_RefNannySetupContext("init_memviewslice", 0); if (!buf) { PyErr_SetString(PyExc_ValueError, "buf is NULL."); goto fail; } else if (memviewslice->memview || memviewslice->data) { PyErr_SetString(PyExc_ValueError, "memviewslice is already initialized!"); goto fail; } if (buf->strides) { for (i = 0; i < ndim; i++) { memviewslice->strides[i] = buf->strides[i]; } } else { Py_ssize_t stride = buf->itemsize; for (i = ndim - 1; i >= 0; i--) { memviewslice->strides[i] = stride; stride *= buf->shape[i]; } } for (i = 0; i < ndim; i++) { memviewslice->shape[i] = buf->shape[i]; if (buf->suboffsets) { memviewslice->suboffsets[i] = buf->suboffsets[i]; } else { memviewslice->suboffsets[i] = -1; } } memviewslice->memview = memview; memviewslice->data = (char *)buf->buf; if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { Py_INCREF(memview); } retval = 0; goto no_fail; fail: memviewslice->memview = 0; memviewslice->data = 0; retval = -1; no_fail: __Pyx_RefNannyFinishContext(); return retval; } static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { va_list vargs; char msg[200]; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, fmt); #else va_start(vargs); #endif vsnprintf(msg, 200, fmt, vargs); Py_FatalError(msg); va_end(vargs); } static CYTHON_INLINE int __pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)++; PyThread_release_lock(lock); return result; } static CYTHON_INLINE int __pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)--; PyThread_release_lock(lock); return result; } static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int first_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (!memview || (PyObject *) memview == Py_None) return; if (__pyx_get_slice_count(memview) < 0) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); first_time = __pyx_add_acquisition_count(memview) == 0; if (first_time) { if (have_gil) { Py_INCREF((PyObject *) memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_INCREF((PyObject *) memview); PyGILState_Release(_gilstate); } } } static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int last_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (!memview ) { return; } else if ((PyObject *) memview == Py_None) { memslice->memview = NULL; return; } if (__pyx_get_slice_count(memview) <= 0) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); last_time = __pyx_sub_acquisition_count(memview) == 1; memslice->data = NULL; if (last_time) { if (have_gil) { Py_CLEAR(memslice->memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_CLEAR(memslice->memview); PyGILState_Release(_gilstate); } } else { memslice->memview = NULL; } } static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON 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); #else PyErr_Restore(type, value, tb); #endif } static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_COMPILING_IN_CPYTHON 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; #else PyErr_Fetch(type, value, tb); #endif } static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); } static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (likely(Py_TYPE(obj) == type)) return 1; #if PY_MAJOR_VERSION == 2 else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(PyObject_TypeCheck(obj, type))) return 1; } __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; 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; } } __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; 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)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } #if PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else 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; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else 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); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else if (s1 == s2) { return (equals == Py_EQ); } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { const char *ps1, *ps2; Py_ssize_t length = PyBytes_GET_SIZE(s1); if (length != PyBytes_GET_SIZE(s2)) return (equals == Py_NE); ps1 = PyBytes_AS_STRING(s1); ps2 = PyBytes_AS_STRING(s2); if (ps1[0] != ps2[0]) { return (equals == Py_NE); } else if (length == 1) { return (equals == Py_EQ); } else { int result = memcmp(ps1, ps2, (size_t)length); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { return (equals == Py_NE); } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { return (equals == Py_NE); } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } #endif } static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else #if PY_MAJOR_VERSION < 3 PyObject* owned_ref = NULL; #endif int s1_is_unicode, s2_is_unicode; if (s1 == s2) { goto return_eq; } s1_is_unicode = PyUnicode_CheckExact(s1); s2_is_unicode = PyUnicode_CheckExact(s2); #if PY_MAJOR_VERSION < 3 if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { owned_ref = PyUnicode_FromObject(s2); if (unlikely(!owned_ref)) return -1; s2 = owned_ref; s2_is_unicode = 1; } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { owned_ref = PyUnicode_FromObject(s1); if (unlikely(!owned_ref)) return -1; s1 = owned_ref; s1_is_unicode = 1; } else if (((!s2_is_unicode) & (!s1_is_unicode))) { return __Pyx_PyBytes_Equals(s1, s2, equals); } #endif if (s1_is_unicode & s2_is_unicode) { Py_ssize_t length; int kind; void *data1, *data2; if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) return -1; length = __Pyx_PyUnicode_GET_LENGTH(s1); if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { goto return_ne; } kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ); return_ne: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_NE); #endif } static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { #if CYTHON_COMPILING_IN_CPYTHON #if PY_MAJOR_VERSION >= 3 if (likely(PyUnicode_Check(n))) #else if (likely(PyString_Check(n))) #endif return __Pyx_PyObject_GetAttrStr(o, n); #endif return PyObject_GetAttr(o, n); } static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { Py_ssize_t length; if (unlikely((start < 0) | (stop < 0))) { size_t slen = strlen(cstring); if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { PyErr_SetString(PyExc_OverflowError, "c-string too long to convert to Python"); return NULL; } length = (Py_ssize_t) slen; if (start < 0) { start += length; if (start < 0) start = 0; } if (stop < 0) stop += length; } length = stop - start; if (unlikely(length <= 0)) return PyUnicode_FromUnicode(NULL, 0); cstring += start; if (decode_func) { return decode_func(cstring, length, errors); } else { return PyUnicode_Decode(cstring, length, encoding, errors); } } static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(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_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); #else PyErr_GetExcInfo(type, value, tb); #endif } static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(type, value, tb); #endif } static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { PyObject *local_type, *local_value, *local_tb; #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_COMPILING_IN_CPYTHON tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = *type; tstate->exc_value = *value; tstate->exc_traceback = *tb; #else PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_VERSION_HEX < 0x03030000 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif 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_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_VERSION_HEX < 0x03030000 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 module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (PyErr_ExceptionMatches(PyExc_OverflowError)) PyErr_Clear(); else return NULL; } } return m->sq_item(o, i); } } #else if (is_list || PySequence_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = (long)((unsigned long)a + b); if (likely((x^a) >= 0 || (x^b) >= 0)) return PyInt_FromLong(x); return PyLong_Type.tp_as_number->nb_add(op1, op2); } #endif #if CYTHON_USE_PYLONG_INTERNALS && PY_MAJOR_VERSION >= 3 if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; } case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; } case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; } case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; } case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; } case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; } default: return PyLong_Type.tp_as_number->nb_add(op1, op2); } } x = a + b; return PyLong_FromLong(x); long_long: llx = lla + llb; return PyLong_FromLongLong(llx); } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); double result; PyFPE_START_PROTECT("add", return NULL) result = ((double)a) + (double)b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } #endif static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, int full_traceback, CYTHON_UNUSED int nogil) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; #ifdef WITH_THREAD PyGILState_STATE state; if (nogil) state = PyGILState_Ensure(); #endif __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); if (full_traceback) { Py_XINCREF(old_exc); Py_XINCREF(old_val); Py_XINCREF(old_tb); __Pyx_ErrRestore(old_exc, old_val, old_tb); PyErr_PrintEx(1); } #if PY_MAJOR_VERSION < 3 ctx = PyString_FromString(name); #else ctx = PyUnicode_FromString(name); #endif __Pyx_ErrRestore(old_exc, old_val, old_tb); if (!ctx) { PyErr_WriteUnraisable(Py_None); } else { PyErr_WriteUnraisable(ctx); Py_DECREF(ctx); } #ifdef WITH_THREAD if (nogil) PyGILState_Release(state); #endif } #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = PyCFunction_GET_FUNCTION(func); self = PyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif static int __Pyx_SetVtable(PyObject *dict, void *vtable) { #if PY_VERSION_HEX >= 0x02070000 PyObject *ob = PyCapsule_New(vtable, 0, 0); #else PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); #endif if (!ob) goto bad; if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) goto bad; Py_DECREF(ob); return 0; bad: Py_XDECREF(ob); return -1; } static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #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_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __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,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' 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) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } Py_DECREF(obj); view->obj = NULL; } #endif static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) { int i; if (!a || !b) return 0; if (a == b) return 1; if (a->size != b->size || a->typegroup != b->typegroup || a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { if (a->typegroup == 'H' || b->typegroup == 'H') { return a->size == b->size; } else { return 0; } } if (a->ndim) { for (i = 0; i < a->ndim; i++) if (a->arraysize[i] != b->arraysize[i]) return 0; } if (a->typegroup == 'S') { if (a->flags != b->flags) return 0; if (a->fields || b->fields) { if (!(a->fields && b->fields)) return 0; for (i = 0; a->fields[i].type && b->fields[i].type; i++) { __Pyx_StructField *field_a = a->fields + i; __Pyx_StructField *field_b = b->fields + i; if (field_a->offset != field_b->offset || !__pyx_typeinfo_cmp(field_a->type, field_b->type)) return 0; } return !a->fields[i].type && !b->fields[i].type; } } return 1; } static int __pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) { if (buf->shape[dim] <= 1) return 1; if (buf->strides) { if (spec & __Pyx_MEMVIEW_CONTIG) { if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { if (buf->strides[dim] != sizeof(void *)) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly contiguous " "in dimension %d.", dim); goto fail; } } else if (buf->strides[dim] != buf->itemsize) { PyErr_SetString(PyExc_ValueError, "Buffer and memoryview are not contiguous " "in the same dimension."); goto fail; } } if (spec & __Pyx_MEMVIEW_FOLLOW) { Py_ssize_t stride = buf->strides[dim]; if (stride < 0) stride = -stride; if (stride < buf->itemsize) { PyErr_SetString(PyExc_ValueError, "Buffer and memoryview are not contiguous " "in the same dimension."); goto fail; } } } else { if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { PyErr_Format(PyExc_ValueError, "C-contiguous buffer is not contiguous in " "dimension %d", dim); goto fail; } else if (spec & (__Pyx_MEMVIEW_PTR)) { PyErr_Format(PyExc_ValueError, "C-contiguous buffer is not indirect in " "dimension %d", dim); goto fail; } else if (buf->suboffsets) { PyErr_SetString(PyExc_ValueError, "Buffer exposes suboffsets but no strides"); goto fail; } } return 1; fail: return 0; } static int __pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) { if (spec & __Pyx_MEMVIEW_DIRECT) { if (buf->suboffsets && buf->suboffsets[dim] >= 0) { PyErr_Format(PyExc_ValueError, "Buffer not compatible with direct access " "in dimension %d.", dim); goto fail; } } if (spec & __Pyx_MEMVIEW_PTR) { if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly accessible " "in dimension %d.", dim); goto fail; } } return 1; fail: return 0; } static int __pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) { int i; if (c_or_f_flag & __Pyx_IS_F_CONTIG) { Py_ssize_t stride = 1; for (i = 0; i < ndim; i++) { if (stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1) { PyErr_SetString(PyExc_ValueError, "Buffer not fortran contiguous."); goto fail; } stride = stride * buf->shape[i]; } } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { Py_ssize_t stride = 1; for (i = ndim - 1; i >- 1; i--) { if (stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1) { PyErr_SetString(PyExc_ValueError, "Buffer not C contiguous."); goto fail; } stride = stride * buf->shape[i]; } } return 1; fail: return 0; } static int __Pyx_ValidateAndInit_memviewslice( int *axes_specs, int c_or_f_flag, int buf_flags, int ndim, __Pyx_TypeInfo *dtype, __Pyx_BufFmt_StackElem stack[], __Pyx_memviewslice *memviewslice, PyObject *original_obj) { struct __pyx_memoryview_obj *memview, *new_memview; __Pyx_RefNannyDeclarations Py_buffer *buf; int i, spec = 0, retval = -1; __Pyx_BufFmt_Context ctx; int from_memoryview = __pyx_memoryview_check(original_obj); __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) original_obj)->typeinfo)) { memview = (struct __pyx_memoryview_obj *) original_obj; new_memview = NULL; } else { memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( original_obj, buf_flags, 0, dtype); new_memview = memview; if (unlikely(!memview)) goto fail; } buf = &memview->view; if (buf->ndim != ndim) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", ndim, buf->ndim); goto fail; } if (new_memview) { __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 (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } for (i = 0; i < ndim; i++) { spec = axes_specs[i]; if (!__pyx_check_strides(buf, i, ndim, spec)) goto fail; if (!__pyx_check_suboffsets(buf, i, ndim, spec)) goto fail; } if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) goto fail; if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, new_memview != NULL) == -1)) { goto fail; } retval = 0; goto no_fail; fail: Py_XDECREF(new_memview); retval = -1; no_fail: __Pyx_RefNannyFinishContext(); return retval; } static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, &__Pyx_TypeInfo_double, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, &__Pyx_TypeInfo_double, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, PyBUF_RECORDS, 1, &__Pyx_TypeInfo_int, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_int(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2, &__Pyx_TypeInfo_int, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1, &__Pyx_TypeInfo_int, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) digits[0]) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, char order, int ndim) { int i, index, step, start; Py_ssize_t itemsize = mvs->memview->view.itemsize; if (order == 'F') { step = 1; start = 0; } else { step = -1; start = ndim - 1; } for (i = 0; i < ndim; i++) { index = start + step * i; if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) return 0; itemsize *= mvs->shape[index]; } return 1; } static void __pyx_get_array_memory_extents(__Pyx_memviewslice *slice, void **out_start, void **out_end, int ndim, size_t itemsize) { char *start, *end; int i; start = end = slice->data; for (i = 0; i < ndim; i++) { Py_ssize_t stride = slice->strides[i]; Py_ssize_t extent = slice->shape[i]; if (extent == 0) { *out_start = *out_end = start; return; } else { if (stride > 0) end += stride * (extent - 1); else start += stride * (extent - 1); } } *out_start = start; *out_end = end + itemsize; } static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize) { void *start1, *end1, *start2, *end2; __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); return (start1 < end2) && (start2 < end1); } static __Pyx_memviewslice __pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, const char *mode, int ndim, size_t sizeof_dtype, int contig_flag, int dtype_is_object) { __Pyx_RefNannyDeclarations int i; __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; struct __pyx_memoryview_obj *from_memview = from_mvs->memview; Py_buffer *buf = &from_memview->view; PyObject *shape_tuple = NULL; PyObject *temp_int = NULL; struct __pyx_array_obj *array_obj = NULL; struct __pyx_memoryview_obj *memview_obj = NULL; __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); for (i = 0; i < ndim; i++) { if (from_mvs->suboffsets[i] >= 0) { PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " "indirect dimensions (axis %d)", i); goto fail; } } shape_tuple = PyTuple_New(ndim); if (unlikely(!shape_tuple)) { goto fail; } __Pyx_GOTREF(shape_tuple); for(i = 0; i < ndim; i++) { temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); if(unlikely(!temp_int)) { goto fail; } else { PyTuple_SET_ITEM(shape_tuple, i, temp_int); temp_int = NULL; } } array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); if (unlikely(!array_obj)) { goto fail; } __Pyx_GOTREF(array_obj); memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( (PyObject *) array_obj, contig_flag, dtype_is_object, from_mvs->memview->typeinfo); if (unlikely(!memview_obj)) goto fail; if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) goto fail; if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, dtype_is_object) < 0)) goto fail; goto no_fail; fail: __Pyx_XDECREF(new_mvs.memview); new_mvs.memview = NULL; new_mvs.data = NULL; no_fail: __Pyx_XDECREF(shape_tuple); __Pyx_XDECREF(temp_int); __Pyx_XDECREF(array_obj); __Pyx_RefNannyFinishContext(); return new_mvs; } static CYTHON_INLINE PyObject * __pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) { PyObject *cobj; #if PY_VERSION_HEX >= 0x02070000 cobj = PyCapsule_New(p, sig, NULL); #else cobj = PyCObject_FromVoidPtr(p, NULL); #endif return cobj; } static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { const char neg_one = (char) -1, const_zero = (char) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(char) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (char) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (char) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(char) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, -(sdigit) digits[0]) case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) case -2: if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -3: if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -4: if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; } #endif if (sizeof(char) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else char val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (char) -1; } } else { char val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (char) -1; val = __Pyx_PyInt_As_char(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to char"); return (char) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to char"); return (char) -1; } static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) digits[0]) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } 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); return PyErr_WarnEx(NULL, message, 1); } return 0; } 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 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; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } 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_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return __Pyx_NewRef(x); m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 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_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (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; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } 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) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
GB_unaryop__minv_uint64_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_uint64_uint8 // op(A') function: GB_tran__minv_uint64_uint8 // C type: uint64_t // A type: uint8_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 64) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 64) ; // casting #define GB_CASTING(z, x) \ uint64_t z = (uint64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT64 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint64_uint8 ( uint64_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint64_uint8 ( 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
laplace_par.h
#ifndef _LAPLACE_PAR_ #define _LAPLACE_PAR_ #include<omp.h> template<int SIZE> inline void initialize(double a[SIZE + 2][SIZE + 2], double b[SIZE + 2][SIZE + 2]) { //TODO implement your solution in here #pragma omp parallel for for (int i = 0; i < SIZE + 2; i++) for (int j = 0; j < SIZE + 2; j++) { a[i][j] = 0.0; b[i][j] = 0.0; } } template<int SIZE> inline void time_step(double a[SIZE + 2][SIZE + 2], double b[SIZE + 2][SIZE + 2], int n) { //TODO implement your solution in here if (n % 2 == 0) { #pragma omp parallel for for (int i = 1; i < SIZE + 1; i++) for (int j = 1; j < SIZE + 1; j++) b[i][j] = (a[i + 1][j] + a[i - 1][j] + a[i][j - 1] + a[i][j + 1]) *0.25; } else { #pragma omp parallel for for (int i = 1; i < SIZE + 1; i++) for (int j = 1; j < SIZE + 1; j++) a[i][j] = (b[i + 1][j] + b[i - 1][j] + b[i][j - 1] + b[i][j + 1])*0.25; } } #endif // !_LAPLACE_PAR_
vednnMaxPoolingBackward.c
#include <stdint.h> #include "vednnMaxPoolingBackward.h" #ifdef VEDNN_USE_OPENMP #include <stdint.h> #include <omp.h> extern int __vednn_omp_num_threads ; #endif static inline vednnError_t vednnMaxPoolingForward_wrapper( vednnMaxPoolBackward_t pFunc, const vednnTensorParam_t *pParamGradOut, const void *pDataGradOut, const vednnTensorParam_t *pParamOut, const void *pDataOut, const vednnTensorParam_t *pParamIn, const void *pDataIn, const vednnTensorParam_t *pParamGradIn, void *pDataGradIn, const vednnPoolingParam_t *pParamPool ) { #ifdef VEDNN_USE_OPENMP if ( __vednn_omp_num_threads == 1 ) { return pFunc(pParamGradOut, pDataGradOut, pParamOut, pDataOut, pParamIn, pDataIn, pParamGradIn, pDataGradIn, pParamPool ) ; } else { vednnError_t rc = VEDNN_SUCCESS ; #pragma omp parallel reduction(|:rc) { int64_t nthreads = omp_get_num_threads() ; int64_t threadid = omp_get_thread_num() ; int64_t allBatch = pParamGradOut->batch ; int64_t nBatch = allBatch / nthreads ; int64_t remain = allBatch % nthreads ; int64_t batchBegin = nBatch * threadid + ( threadid < remain ? threadid : remain ) ; int64_t myBatch = nBatch + ( threadid < remain ? 1 : 0 ) ; if( myBatch == 0 ) { rc |= VEDNN_SUCCESS ; } else { vednnTensorParam_t _pParamGradOut = *pParamGradOut ; _pParamGradOut.batch = myBatch ; vednnTensorParam_t _pParamOut = *pParamOut ; _pParamOut.batch = myBatch ; vednnTensorParam_t _pParamIn = *pParamIn ; _pParamIn.batch = myBatch ; vednnTensorParam_t _pParamGradIn = *pParamGradIn ; _pParamGradIn.batch = myBatch ; float* _pDataGradOut = ((float *)pDataGradOut) + batchBegin * pParamGradOut->channel * pParamGradOut->height * pParamGradOut->width ; float* _pDataOut = ((float *)pDataOut) + batchBegin * pParamOut->channel * pParamOut->height * pParamOut->width ; float* _pDataIn = ((float *)pDataIn) + batchBegin * pParamIn->channel * pParamIn->height * pParamIn->width ; float* _pDataGradIn = ((float *)pDataGradIn) + batchBegin * pParamGradIn->channel * pParamGradIn->height * pParamGradIn->width ; rc |= pFunc(&_pParamGradOut, (void*) _pDataGradOut, &_pParamOut, (void*) _pDataOut, &_pParamIn, (void*) _pDataIn, &_pParamGradIn, (void*) _pDataGradIn, pParamPool ) ; } } return rc ; } #else return pFunc(pParamGradOut, pDataGradOut, pParamOut, pDataOut, pParamIn, pDataIn, pParamGradIn, pDataGradIn, pParamPool ) ; #endif } /* ----------------------------------------------------------------------- */ vednnError_t vednnMaxPoolingBackward( const vednnTensorParam_t *pParamGradOut, const void *pDataGradOut, const vednnTensorParam_t *pParamOut, const void *pDataOut, const vednnTensorParam_t *pParamIn, const void *pDataIn, const vednnTensorParam_t *pParamGradIn, void *pDataGradIn, const vednnPoolingParam_t *pParamPool ) { // [todo] add variations if( pParamPool->padHeight == 0 && pParamPool->padWidth == 0 && pParamPool->strideHeight == pParamPool->windowHeight && pParamPool->strideWidth == pParamPool->windowWidth && pParamOut->height*pParamPool->strideHeight <= pParamIn->height && pParamOut->width*pParamPool->strideWidth == pParamIn->width ) { if( pParamOut->width <= 128 ) { if( (pParamPool->windowWidth & 0x01) == 0 && (((uint64_t)pDataIn) & 0x07) == 0 && (((uint64_t)pDataGradIn) & 0x07) == 0 ) { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingBackward_regular_ww2X_owU128_ialigned, pParamGradOut, pDataGradOut, pParamOut, pDataOut, pParamIn, pDataIn, pParamGradIn, pDataGradIn, pParamPool ) ; } else { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingBackward_regular_owU128, pParamGradOut, pDataGradOut, pParamOut, pDataOut, pParamIn, pDataIn, pParamGradIn, pDataGradIn, pParamPool ) ; } } else { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingBackward_regular, pParamGradOut, pDataGradOut, pParamOut, pDataOut, pParamIn, pDataIn, pParamGradIn, pDataGradIn, pParamPool ) ; } } else { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingBackward_default, pParamGradOut, pDataGradOut, pParamOut, pDataOut, pParamIn, pDataIn, pParamGradIn, pDataGradIn, pParamPool ) ; } }