source
stringlengths
3
92
c
stringlengths
26
2.25M
search.h
// -*- C++ -*- // Copyright (C) 2007-2017 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/search.h * @brief Parallel implementation base for std::search() and * std::search_n(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_SEARCH_H #define _GLIBCXX_PARALLEL_SEARCH_H 1 #include <bits/stl_algobase.h> #include <parallel/parallel.h> #include <parallel/equally_split.h> namespace __gnu_parallel { /** * @brief Precalculate __advances for Knuth-Morris-Pratt algorithm. * @param __elements Begin iterator of sequence to search for. * @param __length Length of sequence to search for. * @param __off Returned __offsets. */ template<typename _RAIter, typename _DifferenceTp> void __calc_borders(_RAIter __elements, _DifferenceTp __length, _DifferenceTp* __off) { typedef _DifferenceTp _DifferenceType; __off[0] = -1; if (__length > 1) __off[1] = 0; _DifferenceType __k = 0; for (_DifferenceType __j = 2; __j <= __length; __j++) { while ((__k >= 0) && !(__elements[__k] == __elements[__j-1])) __k = __off[__k]; __off[__j] = ++__k; } } // Generic parallel find algorithm (requires random access iterator). /** @brief Parallel std::search. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __end2 End iterator of second sequence. * @param __pred Find predicate. * @return Place of finding in first sequences. */ template<typename __RAIter1, typename __RAIter2, typename _Pred> __RAIter1 __search_template(__RAIter1 __begin1, __RAIter1 __end1, __RAIter2 __begin2, __RAIter2 __end2, _Pred __pred) { typedef std::iterator_traits<__RAIter1> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; _GLIBCXX_CALL((__end1 - __begin1) + (__end2 - __begin2)); _DifferenceType __pattern_length = __end2 - __begin2; // Pattern too short. if(__pattern_length <= 0) return __end1; // Last point to start search. _DifferenceType __input_length = (__end1 - __begin1) - __pattern_length; // Where is first occurrence of pattern? defaults to end. _DifferenceType __result = (__end1 - __begin1); _DifferenceType *__splitters; // Pattern too long. if (__input_length < 0) return __end1; omp_lock_t __result_lock; omp_init_lock(&__result_lock); _ThreadIndex __num_threads = std::max<_DifferenceType> (1, std::min<_DifferenceType>(__input_length, __get_max_threads())); _DifferenceType __advances[__pattern_length]; __calc_borders(__begin2, __pattern_length, __advances); # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __splitters = new _DifferenceType[__num_threads + 1]; __equally_split(__input_length, __num_threads, __splitters); } _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType __start = __splitters[__iam], __stop = __splitters[__iam + 1]; _DifferenceType __pos_in_pattern = 0; bool __found_pattern = false; while (__start <= __stop && !__found_pattern) { // Get new value of result. #pragma omp flush(__result) // No chance for this thread to find first occurrence. if (__result < __start) break; while (__pred(__begin1[__start + __pos_in_pattern], __begin2[__pos_in_pattern])) { ++__pos_in_pattern; if (__pos_in_pattern == __pattern_length) { // Found new candidate for result. omp_set_lock(&__result_lock); __result = std::min(__result, __start); omp_unset_lock(&__result_lock); __found_pattern = true; break; } } // Make safe jump. __start += (__pos_in_pattern - __advances[__pos_in_pattern]); __pos_in_pattern = (__advances[__pos_in_pattern] < 0 ? 0 : __advances[__pos_in_pattern]); } } //parallel omp_destroy_lock(&__result_lock); delete[] __splitters; // Return iterator on found element. return (__begin1 + __result); } } // end namespace #endif /* _GLIBCXX_PARALLEL_SEARCH_H */
3d7pt.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 7 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) /* 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])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (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); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][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] = 32; 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; const double alpha = 0.0876; const double beta = 0.0765; // 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); } } } #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 >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-7,8)),ceild(4*t2-Nz-12,16));t3<=min(min(min(floord(4*t2+Ny,16),floord(Nt+Ny-4,16)),floord(2*t1+Ny+1,16)),floord(4*t1-4*t2+Nz+Ny-1,16));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(4*t2-Nz-28,32)),ceild(16*t3-Ny-28,32));t4<=min(min(min(min(floord(4*t2+Nx,32),floord(Nt+Nx-4,32)),floord(2*t1+Nx+1,32)),floord(16*t3+Nx+12,32)),floord(4*t1-4*t2+Nz+Nx-1,32));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),16*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),16*t3+14),32*t4+30),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) { lbv=max(32*t4,t5+1); ubv=min(32*t4+31,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* 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(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* 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]); */ return 0; }
daxpy.c
/* * ======================================================================================= * * Author: Jan Eitzinger (je), jan.eitzinger@fau.de * Copyright (c) 2020 RRZE, University Erlangen-Nuremberg * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * ======================================================================================= */ #include <timing.h> double daxpy( double * restrict a, double * restrict b, double scalar, int N ) { double S, E; S = getTimeStamp(); #pragma omp parallel for schedule(static) for (int i=0; i<N; i++) { a[i] = a[i] + scalar * b[i]; } E = getTimeStamp(); return E-S; }
GB_binop__band_uint64.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__band_uint64) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_03__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__band_uint64) // A*D function (colscale): GB (_AxD__band_uint64) // D*A function (rowscale): GB (_DxB__band_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__band_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__band_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_uint64) // C=scalar+B GB (_bind1st__band_uint64) // C=scalar+B' GB (_bind1st_tran__band_uint64) // C=A+scalar GB (_bind2nd__band_uint64) // C=A'+scalar GB (_bind2nd_tran__band_uint64) // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x) & (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BAND || GxB_NO_UINT64 || GxB_NO_BAND_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__band_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__band_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__band_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__band_uint64) ( 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 uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__band_uint64) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__band_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 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__band_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_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__band_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_03__band_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_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__band_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__band_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 anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = Bx [p] ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__band_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 = 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) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB (_bind1st_tran__band_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 = Ax [pA] ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB (_bind2nd_tran__band_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
conv_kernel_mips.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) 2021, OPEN AI LAB * Author: qtang@openailab.com */ #include "conv_kernel_mips.h" #include "wino_conv_kernel_mips.h" #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "utility/sys_port.h" #include "utility/float.h" #include "utility/log.h" #include "device/cpu/cpu_node.h" #include "device/cpu/cpu_graph.h" #include "device/cpu/cpu_module.h" #include <string.h> #include <stdint.h> #include <stdlib.h> #include <math.h> #if __mips_msa #include <msa.h> #endif #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) static int get_private_mem_size(struct tensor* filter) { return filter->elem_num * filter->elem_size; // caution } static void interleave(struct tensor* filter, struct conv_priv_info* priv_info) { /* simply copy the data */ memcpy(priv_info->interleave_buffer, filter->data, filter->elem_num * filter->elem_size); } void im2col(float* data_img, float* data_col, int inh, int inw, int inc, int outh, int outw, int outc, int ksize_h, int ksize_w, int sh, int sw, int ph, int pw, int dh, int dw) { const int channels_col = ksize_h * ksize_w * inc; for (int c = 0; c < channels_col; ++c) { const int kw = c % ksize_w; int c_ = c / ksize_w; const int kh = c_ % ksize_h; c_ = c_ / ksize_h; const int im_col = kw * dw - pw; const int w_low = max(0, -im_col / sw + (-im_col % sw > 0)); const int w_high = min(outw, (inw - im_col) / sw + ((inw - im_col) % sw > 0)); for (int h = 0; h < outh; ++h) { const int im_row = kh * dh + h * sh - ph; float* out = data_col + (c * outh + h) * outw; const float* end = out + w_high; if (im_row >= 0 && im_row < inh) { float* in = data_img + inw * (im_row + inh * c_) + im_col + (w_low - 1) * sw; memset(out, 0, w_low * sizeof(float)); out += w_low; while (out < end) { in += sw; *(out++) = *in; } memset(out, 0, (outw - w_high) * sizeof(float)); } else { memset(out, 0, outw * sizeof(float)); } } } } static void im2col_ir(struct tensor* input, struct tensor* output, struct conv_priv_info* priv_info, struct conv_param* param, int n, int group) { int input_chan = param->input_channel / param->group; int image_size = input->dims[1] * input->dims[2] * input->dims[3]; int group_size = input_chan * input->dims[2] * input->dims[3]; void* input_base = input->data + (n * image_size + group * group_size) * input->elem_size; void* im2col_buf = priv_info->im2col_buffer; int input_zero = 0; if (input->data_type == TENGINE_DT_UINT8) input_zero = input->zero_point; im2col(input_base, im2col_buf, input->dims[2], input->dims[3], input_chan, output->dims[2], output->dims[3], output->dims[1] / param->group, param->kernel_h, param->kernel_w, param->stride_h, param->stride_w, param->pad_h0, param->pad_w0, param->dilation_h, param->dilation_w); } void input_pack4(int K, int N, float* pB, float* pB_t, int num_thread) { int nn_size = N >> 2; int remian_size_start = nn_size << 2; // [ch00, ch10, ch20, ch30, ch01, ch11, ch21, ch31, ch02, ch12, ch22, ch32, ch03, ch13, ch23, ch33 ....] #pragma omp parallel for num_threads(num_thread) for (int ii = 0; ii < nn_size; ii++) { int i = ii * 4; const float* img = pB + i; float* tmp = pB_t + (i / 4) * 4 * K; for (int j = 0; j < K; j++) { #if __mips_msa __msa_st_w(__msa_ld_w(img, 0), tmp, 0); #else tmp[0] = img[0]; tmp[1] = img[1]; tmp[2] = img[2]; tmp[3] = img[3]; #endif // __mips_msa tmp += 4; img += N; } } // [ch00, ch01, ch02, ch03 ....] #pragma omp parallel for num_threads(num_thread) for (int i = remian_size_start; i < N; i++) { const float* img = pB + i; float* tmp = pB_t + (i / 4 + i % 4) * 4 * K; for (int j = 0; j < K; j++) { tmp[0] = img[0]; tmp += 1; img += N; } } } // unloop output M, unloop N, packet 4x4, using intrinsic static void sgemm(int M, int N, int K, float* pA_t, float* pB_t, float* pC, int num_thread) { int nn_outch = 0; int remain_outch_start = 0; nn_outch = M >> 2; remain_outch_start = nn_outch << 2; // output ch0 - ch3 #pragma omp parallel for num_threads(num_thread) for (int pp=0; pp<nn_outch; pp++) { int i = pp * 4; float* output0 = pC + ( i )*N; float* output1 = pC + (i + 1) * N; float* output2 = pC + (i + 2) * N; float* output3 = pC + (i + 3) * N; int j = 0; for (; j + 3 < N; j += 4) { float* va = pA_t + (i / 4) * 4 * K; float* vb = pB_t + (j / 4) * 4 * K; #if __mips_msa v4f32 _sum0 = {0.f}; v4f32 _sum1 = {0.f}; v4f32 _sum2 = {0.f}; v4f32 _sum3 = {0.f}; for (int k = 0; k < K; k++) { // k0 __builtin_prefetch(vb + 32); __builtin_prefetch(va + 32); v4f32 _vb = (v4f32)__msa_ld_w(vb, 0); v4i32 _va0123 = __msa_ld_w(va, 0); _sum0 = __msa_fmadd_w(_sum0, _vb, (v4f32)__msa_splati_w(_va0123, 0)); // sum0 = (a00-a03) * k00 _sum1 = __msa_fmadd_w(_sum1, _vb, (v4f32)__msa_splati_w(_va0123, 1)); // sum1 = (a00-a03) * k10 _sum2 = __msa_fmadd_w(_sum2, _vb, (v4f32)__msa_splati_w(_va0123, 2)); // sum2 = (a00-a03) * k20 _sum3 = __msa_fmadd_w(_sum3, _vb, (v4f32)__msa_splati_w(_va0123, 3)); // sum3 = (a00-a03) * k30 va += 4; vb += 4; } __msa_st_w((v4i32)_sum0, output0, 0); __msa_st_w((v4i32)_sum1, output1, 0); __msa_st_w((v4i32)_sum2, output2, 0); __msa_st_w((v4i32)_sum3, output3, 0); #else float sum0[4] = {0}; float sum1[4] = {0}; float sum2[4] = {0}; float sum3[4] = {0}; for (int k = 0; k < K; k++) { for (int n = 0; n < 4; n++) { sum0[n] += va[0] * vb[n]; sum1[n] += va[1] * vb[n]; sum2[n] += va[2] * vb[n]; sum3[n] += va[3] * vb[n]; } va += 4; vb += 4; } for (int n = 0; n < 4; n++) { output0[n] = sum0[n]; output1[n] = sum1[n]; output2[n] = sum2[n]; output3[n] = sum3[n]; } #endif // __mips_msa output0 += 4; output1 += 4; output2 += 4; output3 += 4; } for (; j < N; j++) { float* va = pA_t + (i / 4) * 4 * K; float* vb = pB_t + (j / 4 + j % 4) * 4 * K; #if __mips_msa v4f32 _sum0_3 = {0.f}; v4f32 _sum0 = {0.f}; v4f32 _sum1 = {0.f}; v4f32 _sum2 = {0.f}; v4f32 _sum3 = {0.f}; int k = 0; for (; k + 3 < K; k = k + 4) { __builtin_prefetch(vb + 32); __builtin_prefetch(va + 128); v4i32 _vb0123 = __msa_ld_w(vb, 0); v4f32 _va0 = (v4f32)__msa_ld_w(va, 0); v4f32 _va1 = (v4f32)__msa_ld_w(va + 4, 0); v4f32 _va2 = (v4f32)__msa_ld_w(va + 8, 0); v4f32 _va3 = (v4f32)__msa_ld_w(va + 12, 0); _sum0 = __msa_fmadd_w(_sum0, _va0, (v4f32)__msa_splati_w(_vb0123, 0)); // sum0 += (k00-k30) * a00 _sum1 = __msa_fmadd_w(_sum1, _va1, (v4f32)__msa_splati_w(_vb0123, 1)); // sum1 += (k01-k31) * a10 _sum2 = __msa_fmadd_w(_sum2, _va2, (v4f32)__msa_splati_w(_vb0123, 2)); // sum2 += (k02-k32) * a20 _sum3 = __msa_fmadd_w(_sum3, _va3, (v4f32)__msa_splati_w(_vb0123, 3)); // sum3 += (k03-k33) * a30 va += 16; vb += 4; } _sum0 = __msa_fadd_w(_sum0, _sum1); _sum2 = __msa_fadd_w(_sum2, _sum3); _sum0_3 = __msa_fadd_w(_sum2, _sum0); // _sum0_3 = __msa_fadd_w(_sum0_3, _sum2); for (; k < K; k++) { v4f32 _vb0 = {vb[0], vb[0], vb[0], vb[0]}; v4f32 _va = (v4f32)__msa_ld_w(va, 0); _sum0_3 = __msa_fmadd_w(_sum0_3, _va, _vb0); // sum0 += (k00-k30) * a00 va += 4; vb += 1; } output0[0] = _sum0_3[0]; output1[0] = _sum0_3[1]; output2[0] = _sum0_3[2]; output3[0] = _sum0_3[3]; #else float sum0 = 0; float sum1 = 0; float sum2 = 0; float sum3 = 0; for (int k = 0; k < K; k++) { sum0 += va[0] * vb[0]; sum1 += va[1] * vb[0]; sum2 += va[2] * vb[0]; sum3 += va[3] * vb[0]; va += 4; vb += 1; } output0[0] = sum0; output1[0] = sum1; output2[0] = sum2; output3[0] = sum3; #endif // __mips_msa output0++; output1++; output2++; output3++; } } // output ch0 #pragma omp parallel for num_threads(num_thread) for (int i=remain_outch_start; i<M; i++) { float* output = pC + i * N; int j = 0; for (; j + 3 < N; j += 4) { float* va = pA_t + (i / 4 + i % 4) * 4 * K; float* vb = pB_t + (j / 4) * 4 * K; #if __mips_msa v4f32 _sum0 = {0.f}; int k = 0; for (; k + 3 < K; k = k + 4) { // k0 __builtin_prefetch(va + 32); __builtin_prefetch(vb + 128); v4i32 _va0123 = __msa_ld_w(va, 0); v4f32 _vb0 = (v4f32)__msa_ld_w(vb, 0); v4f32 _vb1 = (v4f32)__msa_ld_w(vb + 4, 0); v4f32 _vb2 = (v4f32)__msa_ld_w(vb + 8, 0); v4f32 _vb3 = (v4f32)__msa_ld_w(vb + 12, 0); _sum0 = __msa_fmadd_w(_sum0, _vb0, (v4f32)__msa_splati_w(_va0123, 0)); // sum0 = (a00-a03) * k00 _sum0 = __msa_fmadd_w(_sum0, _vb1, (v4f32)__msa_splati_w(_va0123, 1)); // sum0 += (a10-a13) * k01 _sum0 = __msa_fmadd_w(_sum0, _vb2, (v4f32)__msa_splati_w(_va0123, 2)); // sum0 += (a20-a23) * k02 _sum0 = __msa_fmadd_w(_sum0, _vb3, (v4f32)__msa_splati_w(_va0123, 3)); // sum0 += (a30-a33) * k03 va += 4; vb += 16; } for (; k < K; k++) { // k0 v4f32 _va0 = {va[0]}; v4f32 _vb0 = (v4f32)__msa_ld_w(vb, 0); _sum0 = __msa_fmadd_w(_sum0, _vb0, _va0); // sum0 = (a00-a03) * k00 va += 1; vb += 4; } __msa_st_w((v4i32)_sum0, output, 0); #else float sum[4] = {0}; for (int k = 0; k < K; k++) { for (int n = 0; n < 4; n++) { sum[n] += va[0] * vb[n]; } va += 1; vb += 4; } for (int n = 0; n < 4; n++) { output[n] = sum[n]; } #endif // __mips_msa output += 4; } for (; j < N; j++) { float* va = pA_t + (i / 4 + i % 4) * 4 * K; float* vb = pB_t + (j / 4 + j % 4) * 4 * K; int k = 0; #if __mips_msa v4f32 _sum0 = {0.f}; for (; k + 3 < K; k += 4) { __builtin_prefetch(vb + 32); __builtin_prefetch(va + 32); v4f32 _p0 = (v4f32)__msa_ld_w(vb, 0); v4f32 _k0 = (v4f32)__msa_ld_w(va, 0); _sum0 = __msa_fmadd_w(_sum0, _p0, _k0); va += 4; vb += 4; } float sum0 = _sum0[0] + _sum0[1] + _sum0[2] + _sum0[3]; #else float sum0 = 0.f; #endif // __mips_msa for (; k < K; k++) { sum0 += va[0] * vb[0]; va += 1; vb += 1; } output[0] = sum0; output++; } } } static void sgemm_fp32(struct tensor* input, struct tensor* filter, struct tensor* bias, struct tensor* output, struct conv_priv_info* priv_info, struct conv_param* param, int n, int group, int num_thread) { int kernel_size = param->kernel_h * param->kernel_w * param->input_channel / param->group; int outchan_g = param->output_channel / param->group; int out_h = output->dims[2]; int out_w = output->dims[3]; int out_image_size = output->dims[1] * output->dims[2] * output->dims[3]; float* interleave_fp32 = ( float* )priv_info->interleave_buffer_pack4 + outchan_g * group * kernel_size; float* im2col_pack4_fp32 = priv_info->im2col_buffer_pack4; float* output_fp32 = ( float* )output->data + n * out_image_size + outchan_g * group * out_h * out_w; float* bias_fp32 = NULL; if (bias) bias_fp32 = ( float* )bias->data + outchan_g * group; float* filter_sgemm = interleave_fp32; float* input_sgemm_pack4 = im2col_pack4_fp32; float* output_sgemm = output_fp32; sgemm(outchan_g, out_h * out_w, kernel_size, filter_sgemm, input_sgemm_pack4, output_sgemm, num_thread); // process bias if (bias) { for (int i = 0; i < outchan_g; i++) { for (int j = 0; j < out_h * out_w; j++) { int output_off = i * (out_h * out_w) + j; output_fp32[output_off] += bias_fp32[i]; } } } // process activation relu if (param->activation == 0) { for (int i = 0; i < outchan_g; i++) { for (int j = 0; j < out_h * out_w; j++) { int output_off = i * (out_h * out_w) + j; if (output_fp32[output_off] < 0) output_fp32[output_off] = 0; } } } // process activation relu6 if (param->activation > 0) { for (int i = 0; i < outchan_g; i++) { for (int j = 0; j < out_h * out_w; j++) { int output_off = i * (out_h * out_w) + j; if (output_fp32[output_off] < 0) output_fp32[output_off] = 0; if (output_fp32[output_off] > 6) output_fp32[output_off] = 6; } } } } /* check the conv wheather need to be using winograd */ static int winograd_support(struct conv_param* param, int in_h, int in_w) { int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int input_chan = param->input_channel; int output_chan = param->output_channel; int group = param->group; if (in_h <= 10 && in_w <= 10) return 0; if (group != 1 || kernel_h != 3 || kernel_w != 3 || stride_h != 1 || stride_w != 1 || dilation_h != 1 || dilation_w != 1 || input_chan < 16 || output_chan < 16) return 0; return 1; } int conv_hcl_get_shared_mem_size(struct tensor* input, struct tensor* output, struct conv_param* param) { int group = param->group; int input_chan = param->input_channel / group; int kernel_size = input_chan * param->kernel_h * param->kernel_w; int output_xy = output->dims[2] * output->dims[3]; int elem_size = input->elem_size; return elem_size * output_xy * kernel_size; } int conv_hcl_get_shared_pack4_mem_size(struct tensor* filter, struct tensor* output, struct conv_param* param) { int K = filter->elem_num / filter->dims[0]; int N = output->dims[2] * output->dims[3]; int elem_size = filter->elem_size; return (4 * K * (N / 4 + N % 4)) * elem_size; } int conv_hcl_get_interleave_pack4_size(int M, int K, struct tensor* filter) { int size = 4 * K * (M / 4 + M % 4) * filter->elem_size; return size; } void conv_hcl_interleave_pack4(int M, int K, struct conv_priv_info* priv_info) { float* pA = ( float* )priv_info->interleave_buffer; float* pA_t = ( float* )priv_info->interleave_buffer_pack4; int nn_outch = M >> 2; int remain_outch_start = nn_outch << 2; for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; const float* k0 = pA + (p + 0) * K; const float* k1 = pA + (p + 1) * K; const float* k2 = pA + (p + 2) * K; const float* k3 = pA + (p + 3) * K; float* ktmp = pA_t + (p / 4) * 4 * K; for (int q = 0; q < K; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp += 4; k0 += 1; k1 += 1; k2 += 1; k3 += 1; } } for (int p = remain_outch_start; p < M; p++) { const float* k0 = pA + (p + 0) * K; float* ktmp = pA_t + (p / 4 + p % 4) * 4 * K; for (int q = 0; q < K; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } int conv_hcl_prerun(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param) { int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; /* check winograd implement, only for conv3x3s1 */ priv_info->winograd = winograd_support(param, in_h, in_w); if (priv_info->winograd) { return wino_conv_hcl_prerun(input_tensor, filter_tensor, output_tensor, priv_info, param); } if (!priv_info->external_im2col_mem) { int mem_size = conv_hcl_get_shared_mem_size(input_tensor, output_tensor, param); void* mem = sys_malloc(mem_size); priv_info->im2col_buffer = mem; priv_info->im2col_buffer_size = mem_size; } if (!priv_info->external_im2col_pack4_mem) { int mem_size = conv_hcl_get_shared_pack4_mem_size(filter_tensor, output_tensor, param); void* mem = sys_malloc(mem_size); priv_info->im2col_buffer_pack4 = mem; priv_info->im2col_buffer_pack4_size = mem_size; } if (!priv_info->external_interleave_mem) { int mem_size = get_private_mem_size(filter_tensor); void* mem = sys_malloc(mem_size); priv_info->interleave_buffer = mem; priv_info->interleave_buffer_size = mem_size; } interleave(filter_tensor, priv_info); if (priv_info->external_interleave_pack4_mem) { int M = filter_tensor->dims[0]; int K = filter_tensor->elem_num / filter_tensor->dims[0]; int mem_size = conv_hcl_get_interleave_pack4_size(M, K, filter_tensor); void* mem = sys_malloc(mem_size); priv_info->interleave_buffer_pack4 = mem; priv_info->interleave_buffer_pack4_size = mem_size; conv_hcl_interleave_pack4(M, K, priv_info); if (!priv_info->external_interleave_mem && priv_info->interleave_buffer) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = NULL; } } return 0; } int conv_hcl_postrun(struct conv_priv_info* priv_info) { if (priv_info->winograd) { return wino_conv_hcl_postrun(priv_info); } if (priv_info->external_interleave_pack4_mem && !priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer_pack4); priv_info->interleave_buffer_pack4 = NULL; } if (!priv_info->external_im2col_mem && priv_info->im2col_buffer != NULL) { sys_free(priv_info->im2col_buffer); priv_info->im2col_buffer = NULL; } if (!priv_info->external_im2col_pack4_mem && priv_info->im2col_buffer_pack4 != NULL) { sys_free(priv_info->im2col_buffer_pack4); priv_info->im2col_buffer_pack4 = NULL; } if (priv_info->external_interleave_pack4_mem && priv_info->interleave_buffer_pack4 != NULL) { sys_free(priv_info->interleave_buffer_pack4); priv_info->interleave_buffer_pack4 = NULL; } return 0; } int conv_hcl_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param, int num_thread, int cpu_affinity) { int group = param->group; int type = input_tensor->data_type; if (priv_info->winograd) { return wino_conv_hcl_run(input_tensor, filter_tensor, bias_tensor, output_tensor, priv_info, param, num_thread, cpu_affinity); } for (int i = 0; i < input_tensor->dims[0]; i++) // batch size { for (int j = 0; j < group; j++) { im2col_ir(input_tensor, output_tensor, priv_info, param, i, j); int K = filter_tensor->elem_num / filter_tensor->dims[0]; int N = output_tensor->dims[2] * output_tensor->dims[3]; float* im2col_fp32 = priv_info->im2col_buffer; float* im2col_pack4_fp32 = priv_info->im2col_buffer_pack4; input_pack4(K, N, im2col_fp32, im2col_pack4_fp32, num_thread); if (type == TENGINE_DT_FP32) sgemm_fp32(input_tensor, filter_tensor, bias_tensor, output_tensor, priv_info, param, i, j, num_thread); } } return 0; } int conv_hcl_set_shared_mem(struct conv_priv_info* priv_info, void* mem, int mem_size) { priv_info->external_im2col_mem = 1; priv_info->im2col_buffer = mem; priv_info->im2col_buffer_size = mem_size; return 0; } int conv_hcl_set_shared_pack4_mem(struct conv_priv_info* priv_info, void* mem, int mem_size) { priv_info->external_im2col_pack4_mem = 1; priv_info->im2col_buffer_pack4 = mem; priv_info->im2col_buffer_pack4_size = mem_size; return 0; }
single.c
/* Copyright (C) 2005-2014 Free Software Foundation, Inc. C ontributed by Richard Henderson <r*th@redhat.com>. This file is part of the GNU OpenMP Library (libgomp). Libgomp 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. Libgomp 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/>. */ /* Copyright 2014 DEI - Universita' di Bologna author DEI - Universita' di Bologna Alessandro Capotondi - alessandro.capotondi@unibo.it info #pragma omp single implementation */ #include "libgomp.h" #define WS_NOT_INITED ( 0x0U ) void * gomp_single_copy_start(gomp_work_share_t *ws) { GOMP_WARN_NOT_SUPPORTED("#pragma omp single copyprivate"); return NULL; } void gomp_single_copy_end(gomp_work_share_t *ws, void *data) { GOMP_WARN_NOT_SUPPORTED("#pragma omp single copyprivate"); } /**************** APIs **************************/ int GOMP_single_start(void) { int ret = 0; uint32_t pid = get_proc_id(); gomp_team_t *team = (gomp_team_t *) CURR_TEAM(pid); gomp_work_share_t *ws; //NOTE ws return from this function already locked ret = gomp_work_share_start(&ws); /* Faster than a call to gomp_work_share_end_nowait() */ ws->completed++; if (ws->completed == team->nthreads) { ws->checkfirst = WS_NOT_INITED; #ifdef OMP_NOWAIT_SUPPORT gomp_free_work_share(ws->prev_ws); #endif } gomp_hal_unlock(&ws->lock); return ret; } void * GOMP_single_copy_start(void) { GOMP_WARN_NOT_SUPPORTED("#pragma omp single copyprivate"); return NULL; } void GOMP_single_copy_end(void *data) { GOMP_WARN_NOT_SUPPORTED("#pragma omp single copyprivate"); return; }
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include <deque> #include <memory> #include <string> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions FPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; void Act(SourceLocation PragmaLocation, PragmaClangSectionAction Action, StringLiteral* Name); }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value); // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispAttr::Mode> VtorDispStack; // #pragma pack. // Sentinel to represent when the stack is set to mac68k alignment. static const unsigned kMac68kAlignmentSentinel = ~0U; PragmaStack<unsigned> PackStack; // The current #pragma pack values and locations at each #include. struct PackIncludeState { unsigned CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<PackIncludeState, 8> PackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. The /// element type here is ExprWithCleanups::Object. SmallVector<BlockDecl*, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// A flag to indicate that we're in a context that permits abstract /// references to fields. This is really a bool AllowAbstractFieldReference; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// Whether we are in a decltype expression. bool IsDecltype; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// 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. std::unique_ptr<MangleNumberingContext> MangleNumbering; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), MangleNumbering(), ExprContext(ExprContext) {} /// Retrieve the mangling numbering context, used to consistently /// number constructs like lambdas for mangling. MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. /// /// \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: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the FP_CONTRACT state on entry/exit of compound /// statements. class FPContractStateRAII { public: FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } private: Sema& S; FPOptions OldFPFeaturesState; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getFPOptions() { return FPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. SemaDiagnosticBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class SemaDiagnosticBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op // in that case anwyay. SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; ~SemaDiagnosticBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First flush the underlying // DiagnosticBuilder data, and clear the diagnostic builder itself so it // won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. FlushCounts(); Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template<typename T> friend const SemaDiagnosticBuilder &operator<<( const SemaDiagnosticBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } }; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; void emitAndClearUnusedLocalTypedefWarnings(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Expr *E); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return !D->isHidden() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T) { return !RequireCompleteTypeImpl(Loc, T, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { NC_Unknown, NC_Error, NC_Keyword, NC_Type, NC_Expression, NC_NestedNameSpecifier, NC_TypeTemplate, NC_VarTemplate, NC_FunctionTemplate, NC_UndeclaredTemplate, }; class NameClassification { NameClassificationKind Kind; ExprResult Expr; TemplateName Template; ParsedType Type; 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) {} 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; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); 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 || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param 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, CorrectionCandidateCallback *CCC = nullptr); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); 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, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); DeclContext *getContainingDC(DeclContext *DC); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr *mergeAvailabilityAttr( NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, unsigned AttrSpellingListIndex); TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, TypeVisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex); VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex); UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex, StringRef Uuid); 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); CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex); MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true); ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL); bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, SourceRange OpRange = SourceRange()); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfOnlyViableOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfOnlyViableOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplate }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing); bool isKnownName(StringRef name); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr(Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(E, nullptr, Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(ER, nullptr, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult 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); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); // "({..})" // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// default constructor of a class will have, and whether the parameter /// will be const. ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD); /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl * startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Optional<std::pair<unsigned, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(Decl *D); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); 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, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbigiousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, AccessSpecifier access, QualType objectType); void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, SourceLocation TemplateKWLoc = SourceLocation(), AssumedTemplateKind *ATK = nullptr); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, ConceptDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnDependentTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); // Concepts Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression, UPPC_Block }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); VarDecl *getVarTemplateSpecialization( VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs, const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispAttr::Mode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, DeclaratorDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// FreePackedContext - Deallocate and null out PackContext. void FreePackedContext(); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(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); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, unsigned SpellingListIndex); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, Expr *MinBlocks, unsigned SpellingListIndex); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, unsigned SpellingListIndex, bool InInstantiation = false); void AddParameterABIAttr(SourceRange AttrRange, Decl *D, ParameterABI ABI, unsigned SpellingListIndex); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(SourceRange AttrRange, Decl *D, Expr *Min, Expr *Max, unsigned SpellingListIndex); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(SourceRange AttrRange, Decl *D, Expr *Min, Expr *Max, unsigned SpellingListIndex); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = Ext; } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. unsigned DeclareTargetNestingLevel = 0; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckForDelayedContext = true); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckCaller = true); /// Check if the expression is allowed to be used in expressions for the /// OpenMP devices. void checkOpenMPDeviceExpr(const Expr *E); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); public: /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); /// Called at the end of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, ArrayRef<OMPClause *> ClauseList); /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return DeclareTargetNestingLevel > 0; } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, OpenMPLinearClauseKind LinKind, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation DepLinMapLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause *ActOnOpenMPFromClause( ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This is DefaultFunctionArrayLvalueConversion, // except that it assumes the operand isn't of function or array // type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign = false); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit, ImplicitConversionSequence& ICS); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); virtual ~VerifyICEDiagnoser() { } }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr); /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// A partial call graph maintained during CUDA/OpenMP device code compilation /// to support deferred diagnostics. /// /// Functions are only added here if, at the time they're considered, they are /// not known-emitted. As soon as we discover that a function is /// known-emitted, we remove it and everything it transitively calls from this /// set and add those functions to DeviceKnownEmittedFns. llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, SourceLocation>> DeviceCallGraph; /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be /// deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class DeviceDiagBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); DeviceDiagBuilder(DeviceDiagBuilder &&D); DeviceDiagBuilder(const DeviceDiagBuilder &) = default; ~DeviceDiagBuilder(); /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (DeviceDiagBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a DeviceDiagBuilder yourself. operator bool() const { return ImmediateDiag.hasValue(); } template <typename T> friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Indicate that this function (and thus everything it transtively calls) /// will be codegen'ed, and emit any deferred diagnostics on this function and /// its (transitive) callees. void markKnownEmitted( Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, SourceLocation OrigLoc, const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas declared inside __device__ or __global__ functions inherit /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ /// functions become __host__ __device__ themselves. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); void CodeCompleteAfterIf(Scope *S); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; decltype(DelayedDllExportClasses) SavedDllExportClasses; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); SavedDllExportClasses.swap(S.DelayedDllExportClasses); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getRawEncoding()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
point_outlier.h
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004-2015 \/)\/ * * 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 VCG_TRI_OUTLIERS__H #define VCG_TRI_OUTLIERS__H #include <vcg/space/index/kdtree/kdtree.h> namespace vcg { namespace tri { template <class MeshType> class OutlierRemoval { public: typedef typename MeshType::ScalarType ScalarType; typedef typename vcg::KdTree<ScalarType> KdTreeType; typedef typename vcg::KdTree<ScalarType>::PriorityQueue PriorityQueue; /** Compute an outlier probability value for each vertex of the mesh using the approch in the paper "LoOP: Local Outlier Probabilities". The outlier probability is stored in the vertex attribute "outlierScore". It use the input kdtree to find the kNearest of each vertex. "LoOP: local outlier probabilities" by Hans-Peter Kriegel et al. Proceedings of the 18th ACM conference on Information and knowledge management */ static void ComputeLoOPScore(MeshType& mesh, KdTreeType& kdTree, int kNearest) { vcg::tri::RequireCompactness(mesh); typename MeshType::template PerVertexAttributeHandle<ScalarType> outlierScore = tri::Allocator<MeshType>:: template GetPerVertexAttribute<ScalarType>(mesh, std::string("outlierScore")); typename MeshType::template PerVertexAttributeHandle<ScalarType> sigma = tri::Allocator<MeshType>:: template GetPerVertexAttribute<ScalarType>(mesh, std::string("sigma")); typename MeshType::template PerVertexAttributeHandle<ScalarType> plof = tri::Allocator<MeshType>:: template GetPerVertexAttribute<ScalarType>(mesh, std::string("plof")); #pragma omp parallel for schedule(dynamic, 10) for (size_t i = 0; i < mesh.vert.size(); i++) { PriorityQueue queue; kdTree.doQueryK(mesh.vert[i].cP(), kNearest, queue); ScalarType sum = 0; for (int j = 0; j < queue.getNofElements(); j++) sum += queue.getWeight(j); sum /= (queue.getNofElements()); sigma[i] = sqrt(sum); } float mean = 0; #pragma omp parallel for reduction(+: mean) schedule(dynamic, 10) for (size_t i = 0; i < mesh.vert.size(); i++) { PriorityQueue queue; kdTree.doQueryK(mesh.vert[i].cP(), kNearest, queue); ScalarType sum = 0; for (int j = 0; j < queue.getNofElements(); j++) sum += sigma[queue.getIndex(j)]; sum /= (queue.getNofElements()); plof[i] = sigma[i] / sum - 1.0f; mean += plof[i] * plof[i]; } mean /= mesh.vert.size(); mean = sqrt(mean); #pragma omp parallel for schedule(dynamic, 10) for (size_t i = 0; i < mesh.vert.size(); i++) { ScalarType value = plof[i] / (mean * sqrt(2.0f)); double dem = 1.0 + 0.278393 * value; dem += 0.230389 * value * value; dem += 0.000972 * value * value * value; dem += 0.078108 * value * value * value * value; ScalarType op = max(0.0, 1.0 - 1.0 / dem); outlierScore[i] = op; } tri::Allocator<MeshType>::DeletePerVertexAttribute(mesh, std::string("sigma")); tri::Allocator<MeshType>::DeletePerVertexAttribute(mesh, std::string("plof")); }; /** Select all the vertex of the mesh with an outlier probability above the input threshold [0.0, 1.0]. */ static int SelectLoOPOutliers(MeshType& mesh, KdTreeType& kdTree, int kNearest, float threshold) { ComputeLoOPScore(mesh, kdTree, kNearest); int count = 0; typename MeshType:: template PerVertexAttributeHandle<ScalarType> outlierScore = tri::Allocator<MeshType>::template GetPerVertexAttribute<ScalarType>(mesh, std::string("outlierScore")); for (int i = 0; i < mesh.vert.size(); i++) { if (outlierScore[i] > threshold) { mesh.vert[i].SetS(); count++; } } return count; } /** Delete all the vertex of the mesh with an outlier probability above the input threshold [0.0, 1.0]. */ static int DeleteLoOPOutliers(MeshType& m, KdTreeType& kdTree, int kNearest, float threshold) { SelectLoOPOutliers(m,kdTree,kNearest,threshold); int ovn = m.vn; for(typename MeshType::VertexIterator vi=m.vert.begin();vi!=m.vert.end();++vi) if((*vi).IsS() ) tri::Allocator<MeshType>::DeleteVertex(m,*vi); tri::Allocator<MeshType>::CompactVertexVector(m); tri::Allocator<MeshType>::DeletePerVertexAttribute(m, std::string("outlierScore")); return m.vn - ovn; } }; } // end namespace tri } // end namespace vcg #endif // VCG_TRI_OUTLIERS_H
sparse_msg_filter.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE 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) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ #include "_hypre_struct_ls.h" #if 0 /*-------------------------------------------------------------------------- * hypre_SparseMSGFilterSetup *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilterSetup( hypre_StructMatrix *A, HYPRE_Int *num_grids, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump, hypre_StructVector *visitx, hypre_StructVector *visity, hypre_StructVector *visitz ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *A_dbox; hypre_Box *v_dbox; HYPRE_Int Ai; HYPRE_Int vi; HYPRE_Real *Ap; HYPRE_Real *vxp; HYPRE_Real *vyp; HYPRE_Real *vzp; HYPRE_Real lambdax; HYPRE_Real lambday; HYPRE_Real lambdaz; HYPRE_Real lambda_max; hypre_StructStencil *stencil; hypre_Index *stencil_shape; HYPRE_Int stencil_size; HYPRE_Int Astenc; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i, si, dir, k, l; /*---------------------------------------------------------- * Initialize some things *----------------------------------------------------------*/ stencil = hypre_StructMatrixStencil(A); stencil_shape = hypre_StructStencilShape(stencil); stencil_size = hypre_StructStencilSize(stencil); /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); l = lx + ly + lz; if ((l >= 1) && (l <= jump)) { k = 1 >> l; hypre_SetIndex3(stridev, (1 >> lx), (1 >> ly), (1 >> lz)); } else { k = 1; hypre_SetIndex3(stridev, 1, 1, 1); hypre_StructVectorSetConstantValues(visitx, 0.0); hypre_StructVectorSetConstantValues(visity, 0.0); hypre_StructVectorSetConstantValues(visitz, 0.0); } /*----------------------------------------------------- * Compute visit vectors *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructMatrixGrid(A)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visitx), i); vxp = hypre_StructVectorBoxData(visitx, i); vyp = hypre_StructVectorBoxData(visity, i); vzp = hypre_StructVectorBoxData(visitz, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructMatrixNDim(A), loop_size, A_dbox, start, stride, Ai, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,Ai,vi,lambdax,lambday,lambdaz,si,Ap,Astenc,lambda_max,dir) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(Ai, vi) { lambdax = 0.0; lambday = 0.0; lambdaz = 0.0; for (si = 0; si < stencil_size; si++) { Ap = hypre_StructMatrixBoxData(A, i, si); /* compute lambdax */ Astenc = hypre_IndexD(stencil_shape[si], 0); if (Astenc == 0) { lambdax += Ap[Ai]; } else { lambdax -= Ap[Ai]; } /* compute lambday */ Astenc = hypre_IndexD(stencil_shape[si], 1); if (Astenc == 0) { lambday += Ap[Ai]; } else { lambday -= Ap[Ai]; } /* compute lambdaz */ Astenc = hypre_IndexD(stencil_shape[si], 2); if (Astenc == 0) { lambdaz += Ap[Ai]; } else { lambdaz -= Ap[Ai]; } } lambdax *= lambdax; lambday *= lambday; lambdaz *= lambdaz; lambda_max = 0; dir = -1; if ((lx < num_grids[0] - 1) && (lambdax > lambda_max)) { lambda_max = lambdax; dir = 0; } if ((ly < num_grids[1] - 1) && (lambday > lambda_max)) { lambda_max = lambday; dir = 1; } if ((lz < num_grids[2] - 1) && (lambdaz > lambda_max)) { lambda_max = lambdaz; dir = 2; } if (dir == 0) { vxp[vi] = (HYPRE_Real) ( ((HYPRE_Int) vxp[vi]) | k ); } else if (dir == 1) { vyp[vi] = (HYPRE_Real) ( ((HYPRE_Int) vyp[vi]) | k ); } else if (dir == 2) { vzp[vi] = (HYPRE_Real) ( ((HYPRE_Int) vzp[vi]) | k ); } } hypre_BoxLoop2End(Ai, vi); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SparseMSGFilter *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilter( hypre_StructVector *visit, hypre_StructVector *e, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *e_dbox; hypre_Box *v_dbox; HYPRE_Int ei; HYPRE_Int vi; HYPRE_Real *ep; HYPRE_Real *vp; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i, k, l; /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); l = lx + ly + lz; if ((l >= 1) && (l <= jump)) { k = 1 >> l; hypre_SetIndex3(stridev, (1 >> lx), (1 >> ly), (1 >> lz)); } else { k = 1; hypre_SetIndex3(stridev, 1, 1, 1); } /*----------------------------------------------------- * Filter interpolated error *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructVectorGrid(e)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visit), i); ep = hypre_StructVectorBoxData(e, i); vp = hypre_StructVectorBoxData(visit, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructVectorNDim(e), loop_size, e_dbox, start, stride, ei, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,vi) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(ei, vi) { if ( !(((HYPRE_Int) vp[vi]) & k) ) { ep[ei] = 0.0; } } hypre_BoxLoop2End(ei, vi); } return ierr; } #else /*-------------------------------------------------------------------------- * hypre_SparseMSGFilterSetup *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilterSetup( hypre_StructMatrix *A, HYPRE_Int *num_grids, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump, hypre_StructVector *visitx, hypre_StructVector *visity, hypre_StructVector *visitz ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *A_dbox; hypre_Box *v_dbox; HYPRE_Int Ai; HYPRE_Int vi; HYPRE_Real *Ap; HYPRE_Real *vxp; HYPRE_Real *vyp; HYPRE_Real *vzp; HYPRE_Real lambdax; HYPRE_Real lambday; HYPRE_Real lambdaz; hypre_StructStencil *stencil; hypre_Index *stencil_shape; HYPRE_Int stencil_size; HYPRE_Int Astenc; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i, si; /*---------------------------------------------------------- * Initialize some things *----------------------------------------------------------*/ stencil = hypre_StructMatrixStencil(A); stencil_shape = hypre_StructStencilShape(stencil); stencil_size = hypre_StructStencilSize(stencil); /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); hypre_SetIndex3(stridev, 1, 1, 1); /*----------------------------------------------------- * Compute visit vectors *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructMatrixGrid(A)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visitx), i); vxp = hypre_StructVectorBoxData(visitx, i); vyp = hypre_StructVectorBoxData(visity, i); vzp = hypre_StructVectorBoxData(visitz, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructMatrixNDim(A), loop_size, A_dbox, start, stride, Ai, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,Ai,vi,lambdax,lambday,lambdaz,si,Ap,Astenc) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(Ai, vi) { lambdax = 0.0; lambday = 0.0; lambdaz = 0.0; for (si = 0; si < stencil_size; si++) { Ap = hypre_StructMatrixBoxData(A, i, si); /* compute lambdax */ Astenc = hypre_IndexD(stencil_shape[si], 0); if (Astenc == 0) { lambdax += Ap[Ai]; } else { lambdax -= Ap[Ai]; } /* compute lambday */ Astenc = hypre_IndexD(stencil_shape[si], 1); if (Astenc == 0) { lambday += Ap[Ai]; } else { lambday -= Ap[Ai]; } /* compute lambdaz */ Astenc = hypre_IndexD(stencil_shape[si], 2); if (Astenc == 0) { lambdaz += Ap[Ai]; } else { lambdaz -= Ap[Ai]; } } lambdax *= lambdax; lambday *= lambday; lambdaz *= lambdaz; vxp[vi] = lambdax / (lambdax + lambday + lambdaz); vyp[vi] = lambday / (lambdax + lambday + lambdaz); vzp[vi] = lambdaz / (lambdax + lambday + lambdaz); } hypre_BoxLoop2End(Ai, vi); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SparseMSGFilter *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SparseMSGFilter( hypre_StructVector *visit, hypre_StructVector *e, HYPRE_Int lx, HYPRE_Int ly, HYPRE_Int lz, HYPRE_Int jump ) { HYPRE_Int ierr = 0; hypre_BoxArray *compute_boxes; hypre_Box *compute_box; hypre_Box *e_dbox; hypre_Box *v_dbox; HYPRE_Int ei; HYPRE_Int vi; HYPRE_Real *ep; HYPRE_Real *vp; hypre_Index loop_size; hypre_Index cindex; hypre_IndexRef start; hypre_Index startv; hypre_Index stride; hypre_Index stridev; HYPRE_Int i; /*----------------------------------------------------- * Compute encoding digit and strides *-----------------------------------------------------*/ hypre_SetIndex3(stride, 1, 1, 1); hypre_SetIndex3(stridev, 1, 1, 1); /*----------------------------------------------------- * Filter interpolated error *-----------------------------------------------------*/ hypre_SetIndex3(cindex, 0, 0, 0); compute_boxes = hypre_StructGridBoxes(hypre_StructVectorGrid(e)); hypre_ForBoxI(i, compute_boxes) { compute_box = hypre_BoxArrayBox(compute_boxes, i); e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), i); v_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(visit), i); ep = hypre_StructVectorBoxData(e, i); vp = hypre_StructVectorBoxData(visit, i); start = hypre_BoxIMin(compute_box); hypre_StructMapCoarseToFine(start, cindex, stridev, startv); hypre_BoxGetSize(compute_box, loop_size); hypre_BoxLoop2Begin(hypre_StructVectorNDim(e), loop_size, e_dbox, start, stride, ei, v_dbox, startv, stridev, vi); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,vi) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(ei, vi) { ep[ei] *= vp[vi]; } hypre_BoxLoop2End(ei, vi); } return ierr; } #endif
MathTools.h
/** * \file * \author Thomas Fischer * \date 2010-01-13 * \brief Definition of math helper functions. * * \copyright * Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #ifndef MATHTOOLS_H_ #define MATHTOOLS_H_ #include <cmath> #include <limits> #include <vector> #ifdef _OPENMP #include <omp.h> #endif #include "TemplatePoint.h" namespace MathLib { /** * standard inner product in R^N * \param v0 array of type T representing the vector * \param v1 array of type T representing the vector * */ template<typename T, int N> inline T scalarProduct(T const * const v0, T const * const v1) { T res (v0[0] * v1[0]); #ifdef _OPENMP OPENMP_LOOP_TYPE k; #pragma omp parallel for reduction (+:res) for (k = 1; k<N; k++) { res += v0[k] * v1[k]; } #else for (std::size_t k(1); k < N; k++) res += v0[k] * v1[k]; #endif return res; } template <> inline double scalarProduct<double,3>(double const * const v0, double const * const v1) { double res (v0[0] * v1[0]); for (std::size_t k(1); k < 3; k++) res += v0[k] * v1[k]; return res; } template<typename T> inline T scalarProduct(T const * const v0, T const * const v1, unsigned n) { T res (v0[0] * v1[0]); #ifdef _OPENMP OPENMP_LOOP_TYPE k; #pragma omp parallel for reduction (+:res) #ifdef WIN32 #pragma warning ( push ) #pragma warning ( disable: 4018 ) #endif for (k = 1; k<n; k++) { res += v0[k] * v1[k]; } #ifdef WIN32 #pragma warning ( pop ) #endif #else for (std::size_t k(1); k < n; k++) res += v0[k] * v1[k]; #endif return res; } /** * computes the cross (or vector) product of the 3d vectors u and v * the result is given in the vector r */ void crossProd (const double u[3], const double v[3], double r[3]); /** * calcProjPntToLineAndDists computes the orthogonal projection * of a point p to the line described by the points a and b, * \f$g(\lambda) = a + \lambda (b - a)\f$, * the distance between p and the projected point * and the distances between the projected point and the end * points a, b of the line * \param p the (mesh) point * \param a first point of line * \param b second point of line * \param lambda the projected point described by the line equation above * \param d0 distance to the line point a * \returns the distance between p and the orthogonal projection of p */ double calcProjPntToLineAndDists(const double p[3], const double a[3], const double b[3], double &lambda, double &d0); template <typename POINT_T> typename POINT_T::FP_T sqrDist(POINT_T const& p0, POINT_T const& p1) { typename POINT_T::FP_T const v[3] = {p1[0]-p0[0], p1[1]-p0[1], p1[2]-p0[2]}; return MathLib::scalarProduct<typename POINT_T::FP_T,3>(v,v); } template <typename T, std::size_t DIM> bool operator==(TemplatePoint<T,DIM> const& a, TemplatePoint<T,DIM> const& b) { T const sqr_dist(sqrDist(a,b)); return (sqr_dist < pow(std::numeric_limits<T>::epsilon(),2)); } /** squared dist between double arrays p0 and p1 (size of arrays is 3) */ double sqrDist(const double* p0, const double* p1); /** Distance between points p0 and p1 in the maximum norm. */ template <typename T> T maxNormDist(const MathLib::TemplatePoint<T>* p0, const MathLib::TemplatePoint<T>* p1) { const T x = fabs((*p1)[0] - (*p0)[0]); const T y = fabs((*p1)[1] - (*p0)[1]); const T z = fabs((*p1)[2] - (*p0)[2]); return std::max(x, std::max(y, z)); } /** linear normalisation of val from [min, max] into [0,1] */ float normalize(float min, float max, float val); /** * Let \f$p_0, p_1, p_2 \in R^3\f$. The function getAngle * computes the angle between the edges \f$(p_0,p_1)\f$ and \f$(p_1,p_2)\f$ * @param p0 start point of edge 0 * @param p1 end point of edge 0 and start point of edge 1 * @param p2 end point of edge 1 * @return the angle between the edges */ double getAngle (const double p0[3], const double p1[3], const double p2[3]); /** * Calculates the area of a triangle. * The formula is A=.5*|u x v|, i.e. half of the area of the parallelogram specified by u=p0->p1 and v=p0->p2. */ double calcTriangleArea(const double* p0, const double* p1, const double* p2); /** * Calculates the volume of a tetrahedron. * The formula is V=1/6*|a(b x c)| with a=x1->x2, b=x1->x3 and c=x1->x4. */ double calcTetrahedronVolume(const double* x1, const double* x2, const double* x3, const double* x4); /** * simple power function that takes as a second argument an integer instead of a float * @param base basis of the expression * @param exp exponent of the expression * @return base^exp */ template <typename T> inline T fastpow (T base, std::size_t exp) { T result (base); if (exp == 0) result = static_cast<T>(1); for (std::size_t k(1); k < exp; k++) result *= base; return result; } /// 2D linear interpolation function (TODO adopted from geo_mathlib) void MPhi2D(double* vf, double r, double s); } // namespace #endif /* MATHTOOLS_H_ */
compatibility.h
// -*- C++ -*- // Copyright (C) 2007, 2008, 2009, 2010, 2012 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/compatibility.h * @brief Compatibility layer, mostly concerned with atomic operations. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_COMPATIBILITY_H #define _GLIBCXX_PARALLEL_COMPATIBILITY_H 1 #include <parallel/types.h> #include <parallel/base.h> #if defined(__SUNPRO_CC) && defined(__sparc) #include <sys/atomic.h> #endif #if !defined(_WIN32) || defined (__CYGWIN__) #include <sched.h> #endif #if defined(_MSC_VER) #include <Windows.h> #include <intrin.h> #undef max #undef min #endif #ifdef __MINGW32__ // Including <windows.h> will drag in all the windows32 names. Since // that can cause user code portability problems, we just declare the // one needed function here. extern "C" __attribute((dllimport)) void __attribute__((stdcall)) Sleep (unsigned long); #endif namespace __gnu_parallel { #if defined(__ICC) template<typename _MustBeInt = int> int32_t __faa32(int32_t* __x, int32_t __inc) { asm volatile("lock xadd %0,%1" : "=__r" (__inc), "=__m" (*__x) : "0" (__inc) : "memory"); return __inc; } #if defined(__x86_64) template<typename _MustBeInt = int> int64_t __faa64(int64_t* __x, int64_t __inc) { asm volatile("lock xadd %0,%1" : "=__r" (__inc), "=__m" (*__x) : "0" (__inc) : "memory"); return __inc; } #endif #endif // atomic functions only work on integers /** @brief Add a value to a variable, atomically. * * Implementation is heavily platform-dependent. * @param __ptr Pointer to a 32-bit signed integer. * @param __addend Value to add. */ inline int32_t __fetch_and_add_32(volatile int32_t* __ptr, int32_t __addend) { #if defined(__ICC) //x86 version return _InterlockedExchangeAdd((void*)__ptr, __addend); #elif defined(__ECC) //IA-64 version return _InterlockedExchangeAdd((void*)__ptr, __addend); #elif defined(__ICL) || defined(_MSC_VER) return _InterlockedExchangeAdd(reinterpret_cast<volatile long*>(__ptr), __addend); #elif defined(__GNUC__) return __atomic_fetch_add(__ptr, __addend, __ATOMIC_ACQ_REL); #elif defined(__SUNPRO_CC) && defined(__sparc) volatile int32_t __before, __after; do { __before = *__ptr; __after = __before + __addend; } while (atomic_cas_32((volatile unsigned int*)__ptr, __before, __after) != __before); return __before; #else //fallback, slow #pragma message("slow __fetch_and_add_32") int32_t __res; #pragma omp critical { __res = *__ptr; *(__ptr) += __addend; } return __res; #endif } /** @brief Add a value to a variable, atomically. * * Implementation is heavily platform-dependent. * @param __ptr Pointer to a 64-bit signed integer. * @param __addend Value to add. */ inline int64_t __fetch_and_add_64(volatile int64_t* __ptr, int64_t __addend) { #if defined(__ICC) && defined(__x86_64) //x86 version return __faa64<int>((int64_t*)__ptr, __addend); #elif defined(__ECC) //IA-64 version return _InterlockedExchangeAdd64((void*)__ptr, __addend); #elif defined(__ICL) || defined(_MSC_VER) #ifndef _WIN64 _GLIBCXX_PARALLEL_ASSERT(false); //not available in this case return 0; #else return _InterlockedExchangeAdd64(__ptr, __addend); #endif #elif defined(__GNUC__) && defined(__x86_64) return __atomic_fetch_add(__ptr, __addend, __ATOMIC_ACQ_REL); #elif defined(__GNUC__) && defined(__i386) && \ (defined(__i686) || defined(__pentium4) || defined(__athlon) \ || defined(__k8) || defined(__core2)) return __atomic_fetch_add(__ptr, __addend, __ATOMIC_ACQ_REL); #elif defined(__SUNPRO_CC) && defined(__sparc) volatile int64_t __before, __after; do { __before = *__ptr; __after = __before + __addend; } while (atomic_cas_64((volatile unsigned long long*)__ptr, __before, __after) != __before); return __before; #else //fallback, slow #if defined(__GNUC__) && defined(__i386) // XXX doesn'__t work with -march=native //#warning "please compile with -march=i686 or better" #endif #pragma message("slow __fetch_and_add_64") int64_t __res; #pragma omp critical { __res = *__ptr; *(__ptr) += __addend; } return __res; #endif } /** @brief Add a value to a variable, atomically. * * Implementation is heavily platform-dependent. * @param __ptr Pointer to a signed integer. * @param __addend Value to add. */ template<typename _Tp> inline _Tp __fetch_and_add(volatile _Tp* __ptr, _Tp __addend) { if (sizeof(_Tp) == sizeof(int32_t)) return (_Tp)__fetch_and_add_32((volatile int32_t*) __ptr, (int32_t)__addend); else if (sizeof(_Tp) == sizeof(int64_t)) return (_Tp)__fetch_and_add_64((volatile int64_t*) __ptr, (int64_t)__addend); else _GLIBCXX_PARALLEL_ASSERT(false); } #if defined(__ICC) template<typename _MustBeInt = int> inline int32_t __cas32(volatile int32_t* __ptr, int32_t __old, int32_t __nw) { int32_t __before; __asm__ __volatile__("lock; cmpxchgl %1,%2" : "=a"(__before) : "q"(__nw), "__m"(*(volatile long long*)(__ptr)), "0"(__old) : "memory"); return __before; } #if defined(__x86_64) template<typename _MustBeInt = int> inline int64_t __cas64(volatile int64_t *__ptr, int64_t __old, int64_t __nw) { int64_t __before; __asm__ __volatile__("lock; cmpxchgq %1,%2" : "=a"(__before) : "q"(__nw), "__m"(*(volatile long long*)(__ptr)), "0"(__old) : "memory"); return __before; } #endif #endif /** @brief Compare @c *__ptr and @c __comparand. If equal, let @c * *__ptr=__replacement and return @c true, return @c false otherwise. * * Implementation is heavily platform-dependent. * @param __ptr Pointer to 32-bit signed integer. * @param __comparand Compare value. * @param __replacement Replacement value. */ inline bool __compare_and_swap_32(volatile int32_t* __ptr, int32_t __comparand, int32_t __replacement) { #if defined(__ICC) //x86 version return _InterlockedCompareExchange((void*)__ptr, __replacement, __comparand) == __comparand; #elif defined(__ECC) //IA-64 version return _InterlockedCompareExchange((void*)__ptr, __replacement, __comparand) == __comparand; #elif defined(__ICL) || defined(_MSC_VER) return _InterlockedCompareExchange( reinterpret_cast<volatile long*>(__ptr), __replacement, __comparand) == __comparand; #elif defined(__GNUC__) return __atomic_compare_exchange_n(__ptr, &__comparand, __replacement, false, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); #elif defined(__SUNPRO_CC) && defined(__sparc) return atomic_cas_32((volatile unsigned int*)__ptr, __comparand, __replacement) == __comparand; #else #pragma message("slow __compare_and_swap_32") bool __res = false; #pragma omp critical { if (*__ptr == __comparand) { *__ptr = __replacement; __res = true; } } return __res; #endif } /** @brief Compare @c *__ptr and @c __comparand. If equal, let @c * *__ptr=__replacement and return @c true, return @c false otherwise. * * Implementation is heavily platform-dependent. * @param __ptr Pointer to 64-bit signed integer. * @param __comparand Compare value. * @param __replacement Replacement value. */ inline bool __compare_and_swap_64(volatile int64_t* __ptr, int64_t __comparand, int64_t __replacement) { #if defined(__ICC) && defined(__x86_64) //x86 version return __cas64<int>(__ptr, __comparand, __replacement) == __comparand; #elif defined(__ECC) //IA-64 version return _InterlockedCompareExchange64((void*)__ptr, __replacement, __comparand) == __comparand; #elif defined(__ICL) || defined(_MSC_VER) #ifndef _WIN64 _GLIBCXX_PARALLEL_ASSERT(false); //not available in this case return 0; #else return _InterlockedCompareExchange64(__ptr, __replacement, __comparand) == __comparand; #endif #elif defined(__GNUC__) && defined(__x86_64) return __atomic_compare_exchange_n(__ptr, &__comparand, __replacement, false, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); #elif defined(__GNUC__) && defined(__i386) && \ (defined(__i686) || defined(__pentium4) || defined(__athlon) \ || defined(__k8) || defined(__core2)) return __atomic_compare_exchange_n(__ptr, &__comparand, __replacement, false, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); #elif defined(__SUNPRO_CC) && defined(__sparc) return atomic_cas_64((volatile unsigned long long*)__ptr, __comparand, __replacement) == __comparand; #else #if defined(__GNUC__) && defined(__i386) // XXX -march=native //#warning "please compile with -march=i686 or better" #endif #pragma message("slow __compare_and_swap_64") bool __res = false; #pragma omp critical { if (*__ptr == __comparand) { *__ptr = __replacement; __res = true; } } return __res; #endif } /** @brief Compare @c *__ptr and @c __comparand. If equal, let @c * *__ptr=__replacement and return @c true, return @c false otherwise. * * Implementation is heavily platform-dependent. * @param __ptr Pointer to signed integer. * @param __comparand Compare value. * @param __replacement Replacement value. */ template<typename _Tp> inline bool __compare_and_swap(volatile _Tp* __ptr, _Tp __comparand, _Tp __replacement) { if (sizeof(_Tp) == sizeof(int32_t)) return __compare_and_swap_32((volatile int32_t*) __ptr, (int32_t)__comparand, (int32_t)__replacement); else if (sizeof(_Tp) == sizeof(int64_t)) return __compare_and_swap_64((volatile int64_t*) __ptr, (int64_t)__comparand, (int64_t)__replacement); else _GLIBCXX_PARALLEL_ASSERT(false); } /** @brief Yield the control to another thread, without waiting for the end to the time slice. */ inline void __yield() { #if defined (_WIN32) && !defined (__CYGWIN__) Sleep(0); #else sched_yield(); #endif } } // end namespace #endif /* _GLIBCXX_PARALLEL_COMPATIBILITY_H */
paint.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP AAA IIIII N N TTTTT % % P P A A I NN N T % % PPPP AAAAA I N N N T % % P A A I N NN T % % P A A IIIII N N T % % % % % % Methods to Paint on an Image % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/color-private.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o o d f i l l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FloodfillPaintImage() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. % However, in many cases two colors may differ by a small amount. The % fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now % interpreted as the same color for the purposes of the floodfill. % % The format of the FloodfillPaintImage method is: % % MagickBooleanType FloodfillPaintImage(Image *image, % const ChannelType channel,const DrawInfo *draw_info, % const MagickPixelPacket target,const ssize_t x_offset, % const ssize_t y_offset,const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o draw_info: the draw info. % % o target: the RGB value of the target color. % % o x_offset,y_offset: the starting location of the operation. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType FloodfillPaintImage(Image *image, const ChannelType channel,const DrawInfo *draw_info, const MagickPixelPacket *target,const ssize_t x_offset,const ssize_t y_offset, const MagickBooleanType invert) { #define MaxStacksize 524288UL #define PushSegmentStack(up,left,right,delta) \ { \ if (s >= (segment_stack+MaxStacksize)) \ ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \ else \ { \ if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \ { \ s->x1=(double) (left); \ s->y1=(double) (up); \ s->x2=(double) (right); \ s->y2=(double) (delta); \ s++; \ } \ } \ } CacheView *floodplane_view, *image_view; ExceptionInfo *exception; Image *floodplane_image; MagickBooleanType skip; MagickPixelPacket fill, pixel; MemoryInfo *segment_info; PixelPacket fill_color; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); exception=(&image->exception); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); if ((image->matte == MagickFalse) && (draw_info->fill.opacity != OpaqueOpacity)) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); /* Set floodfill state. */ floodplane_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); (void) SetImageAlphaChannel(floodplane_image,OpaqueAlphaChannel); segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack)); if (segment_info == (MemoryInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info); /* Push initial segment on stack. */ x=x_offset; y=y_offset; start=0; s=segment_stack; PushSegmentStack(y,x,x,1); PushSegmentStack(y+1,x,x,-1); GetMagickPixelPacket(image,&fill); GetMagickPixelPacket(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception); while (s > segment_stack) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception); q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewVirtualIndexQueue(image_view); p+=x1; q+=x1; for (x=x1; x >= 0; x--) { if (q->opacity == (Quantum) TransparentOpacity) break; SetMagickPixelPacket(image,p,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) == invert) break; q->opacity=(Quantum) TransparentOpacity; p--; q--; } if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y, image->columns-x,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for ( ; x < (ssize_t) image->columns; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; SetMagickPixelPacket(image,p,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) == invert) break; q->opacity=(Quantum) TransparentOpacity; p++; q++; } if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for ( ; x <= x2; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; SetMagickPixelPacket(image,p,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) != invert) break; p++; q++; } } start=x; } while (x <= x2); } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; /* Tile fill color onto floodplane. */ p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) { (void) GetFillColor(draw_info,x,y,&fill_color); SetMagickPixelPacket(image,&fill_color,(IndexPacket *) NULL,&fill); if (image->colorspace == CMYKColorspace) ConvertRGBToCMYK(&fill); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(fill.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(fill.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(fill.blue)); if (((channel & OpacityChannel) != 0) || (draw_info->fill.opacity != OpaqueOpacity)) SetPixelOpacity(q,ClampToQuantum(fill.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum(fill.index)); } p++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } floodplane_view=DestroyCacheView(floodplane_view); image_view=DestroyCacheView(image_view); segment_info=RelinquishVirtualMemory(segment_info); floodplane_image=DestroyImage(floodplane_image); return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GradientImage() applies a continuously smooth color transitions along a % vector from one color to another. % % Note, the interface of this method will change in the future to support % more than one transistion. % % The format of the GradientImage method is: % % MagickBooleanType GradientImage(Image *image,const GradientType type, % const SpreadMethod method,const PixelPacket *start_color, % const PixelPacket *stop_color) % % A description of each parameter follows: % % o image: the image. % % o type: the gradient type: linear or radial. % % o spread: the gradient spread meathod: pad, reflect, or repeat. % % o start_color: the start color. % % o stop_color: the stop color. % % This provides a good example of making use of the DrawGradientImage % function and the gradient structure in draw_info. % */ MagickExport MagickBooleanType GradientImage(Image *image, const GradientType type,const SpreadMethod method, const PixelPacket *start_color,const PixelPacket *stop_color) { const char *artifact; DrawInfo *draw_info; GradientInfo *gradient; MagickBooleanType status; register ssize_t i; /* Set gradient start-stop end points. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(start_color != (const PixelPacket *) NULL); assert(stop_color != (const PixelPacket *) NULL); draw_info=AcquireDrawInfo(); gradient=(&draw_info->gradient); gradient->type=type; gradient->bounding_box.width=image->columns; gradient->bounding_box.height=image->rows; artifact=GetImageArtifact(image,"gradient:bounding-box"); if (artifact != (const char *) NULL) (void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box); gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; artifact=GetImageArtifact(image,"gradient:direction"); if (artifact != (const char *) NULL) { GravityType direction; direction=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,artifact); switch (direction) { case NorthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case WestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case EastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case SouthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->rows-1; break; } case SouthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->columns-1; break; } case SouthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; break; } default: break; } } artifact=GetImageArtifact(image,"gradient:angle"); if (artifact != (const char *) NULL) gradient->angle=(MagickRealType) StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"gradient:vector"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", &gradient->gradient_vector.x1,&gradient->gradient_vector.y1, &gradient->gradient_vector.x2,&gradient->gradient_vector.y2); if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) && (GetImageArtifact(image,"gradient:direction") == (const char *) NULL) && (GetImageArtifact(image,"gradient:extent") == (const char *) NULL) && (GetImageArtifact(image,"gradient:vector") == (const char *) NULL)) if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0)) gradient->gradient_vector.x2=0.0; gradient->center.x=(double) gradient->gradient_vector.x2/2.0; gradient->center.y=(double) gradient->gradient_vector.y2/2.0; artifact=GetImageArtifact(image,"gradient:center"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x, &gradient->center.y); artifact=GetImageArtifact(image,"gradient:angle"); if ((type == LinearGradient) && (artifact != (const char *) NULL)) { double sine, cosine, distance; /* Reference https://drafts.csswg.org/css-images-3/#linear-gradients. */ sine=sin((double) DegreesToRadians(gradient->angle-90.0)); cosine=cos((double) DegreesToRadians(gradient->angle-90.0)); distance=fabs((double) (image->columns-1)*cosine)+ fabs((double) (image->rows-1)*sine); gradient->gradient_vector.x1=0.5*((image->columns-1)-distance*cosine); gradient->gradient_vector.y1=0.5*((image->rows-1)-distance*sine); gradient->gradient_vector.x2=0.5*((image->columns-1)+distance*cosine); gradient->gradient_vector.y2=0.5*((image->rows-1)+distance*sine); } gradient->radii.x=(double) MagickMax((image->columns-1),(image->rows-1))/2.0; gradient->radii.y=gradient->radii.x; artifact=GetImageArtifact(image,"gradient:extent"); if (artifact != (const char *) NULL) { if (LocaleCompare(artifact,"Circle") == 0) { gradient->radii.x=(double) (MagickMax((image->columns-1), (image->rows-1)))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Diagonal") == 0) { gradient->radii.x=(double) (sqrt((double) (image->columns-1)* (image->columns-1)+(image->rows-1)*(image->rows-1)))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Ellipse") == 0) { gradient->radii.x=(double) (image->columns-1)/2.0; gradient->radii.y=(double) (image->rows-1)/2.0; } if (LocaleCompare(artifact,"Maximum") == 0) { gradient->radii.x=(double) MagickMax((image->columns-1), (image->rows-1))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Minimum") == 0) { gradient->radii.x=(double) MagickMin((image->columns-1), (image->rows-1))/2.0; gradient->radii.y=gradient->radii.x; } } artifact=GetImageArtifact(image,"gradient:radii"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x, &gradient->radii.y); gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y); gradient->spread=method; /* Define the gradient to fill between the stops. */ gradient->number_stops=2; gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops, sizeof(*gradient->stops)); if (gradient->stops == (StopInfo *) NULL) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(gradient->stops,0,gradient->number_stops* sizeof(*gradient->stops)); for (i=0; i < (ssize_t) gradient->number_stops; i++) GetMagickPixelPacket(image,&gradient->stops[i].color); SetMagickPixelPacket(image,start_color,(IndexPacket *) NULL, &gradient->stops[0].color); gradient->stops[0].offset=0.0; SetMagickPixelPacket(image,stop_color,(IndexPacket *) NULL, &gradient->stops[1].color); gradient->stops[1].offset=1.0; /* Draw a gradient on the image. */ status=DrawGradientImage(image,draw_info); draw_info=DestroyDrawInfo(draw_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O i l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OilPaintImage() applies a special effect filter that simulates an oil % painting. Each pixel is replaced by the most frequent color occurring % in a circular region defined by radius. % % The format of the OilPaintImage method is: % % Image *OilPaintImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the circular neighborhood. % % o exception: return any errors or warnings in this structure. % */ static size_t **DestroyHistogramThreadSet(size_t **histogram) { register ssize_t i; assert(histogram != (size_t **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (histogram[i] != (size_t *) NULL) histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]); histogram=(size_t **) RelinquishMagickMemory(histogram); return(histogram); } static size_t **AcquireHistogramThreadSet(const size_t count) { register ssize_t i; size_t **histogram, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); histogram=(size_t **) AcquireQuantumMemory(number_threads, sizeof(*histogram)); if (histogram == (size_t **) NULL) return((size_t **) NULL); (void) memset(histogram,0,number_threads*sizeof(*histogram)); for (i=0; i < (ssize_t) number_threads; i++) { histogram[i]=(size_t *) AcquireQuantumMemory(count, sizeof(**histogram)); if (histogram[i] == (size_t *) NULL) return(DestroyHistogramThreadSet(histogram)); } return(histogram); } MagickExport Image *OilPaintImage(const Image *image,const double radius, ExceptionInfo *exception) { #define NumberPaintBins 256 #define OilPaintImageTag "OilPaint/Image" CacheView *image_view, *paint_view; Image *linear_image, *paint_image; MagickBooleanType status; MagickOffsetType progress; size_t **magick_restrict histograms, width; ssize_t y; /* Initialize painted image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth2D(radius,0.5); linear_image=CloneImage(image,0,0,MagickTrue,exception); paint_image=CloneImage(image,0,0,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (paint_image != (Image *) NULL) linear_image=DestroyImage(paint_image); return((Image *) NULL); } if (SetImageStorageClass(paint_image,DirectClass) == MagickFalse) { InheritException(exception,&paint_image->exception); linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); return((Image *) NULL); } histograms=AcquireHistogramThreadSet(NumberPaintBins); if (histograms == (size_t **) NULL) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Oil paint image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(linear_image,exception); paint_view=AcquireAuthenticCacheView(paint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(linear_image,paint_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict paint_indexes; register ssize_t x; register PixelPacket *magick_restrict q; register size_t *histogram; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (width/2L),linear_image->columns+width,width,exception); q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); paint_indexes=GetCacheViewAuthenticIndexQueue(paint_view); histogram=histograms[GetOpenMPThreadId()]; for (x=0; x < (ssize_t) linear_image->columns; x++) { register ssize_t i, u; size_t count; ssize_t j, k, v; /* Assign most frequent color. */ i=0; j=0; count=0; (void) memset(histogram,0,NumberPaintBins*sizeof(*histogram)); for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { k=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity( linear_image,p+u+i))); histogram[k]++; if (histogram[k] > count) { j=i+u; count=histogram[k]; } } i+=(ssize_t) (linear_image->columns+width); } *q=(*(p+j)); if (linear_image->colorspace == CMYKColorspace) SetPixelIndex(paint_indexes+x,GetPixelIndex(indexes+x+j)); p++; q++; } if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,OilPaintImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } paint_view=DestroyCacheView(paint_view); image_view=DestroyCacheView(image_view); histograms=DestroyHistogramThreadSet(histograms); linear_image=DestroyImage(linear_image); if (status == MagickFalse) paint_image=DestroyImage(paint_image); return(paint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p a q u e P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpaquePaintImage() changes any pixel that matches color with the color % defined by fill. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the OpaquePaintImage method is: % % MagickBooleanType OpaquePaintImage(Image *image, % const PixelPacket *target,const PixelPacket *fill, % const MagickBooleanType invert) % MagickBooleanType OpaquePaintImageChannel(Image *image, % const ChannelType channel,const PixelPacket *target, % const PixelPacket *fill,const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o target: the RGB value of the target color. % % o fill: the replacement color. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType OpaquePaintImage(Image *image, const MagickPixelPacket *target,const MagickPixelPacket *fill, const MagickBooleanType invert) { return(OpaquePaintImageChannel(image,CompositeChannels,target,fill,invert)); } MagickExport MagickBooleanType OpaquePaintImageChannel(Image *image, const ChannelType channel,const MagickPixelPacket *target, const MagickPixelPacket *fill,const MagickBooleanType invert) { #define OpaquePaintImageTag "Opaque/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket conform_fill, conform_target, zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (MagickPixelPacket *) NULL); assert(fill != (MagickPixelPacket *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); exception=(&image->exception); ConformMagickPixelPacket(image,fill,&conform_fill,exception); ConformMagickPixelPacket(image,target,&conform_target,exception); /* Make image color opaque. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,&conform_target) != invert) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(conform_fill.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(conform_fill.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(conform_fill.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(conform_fill.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToQuantum(conform_fill.index)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,OpaquePaintImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the TransparentPaintImage method is: % % MagickBooleanType TransparentPaintImage(Image *image, % const MagickPixelPacket *target,const Quantum opacity, % const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o target: the target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType TransparentPaintImage(Image *image, const MagickPixelPacket *target,const Quantum opacity, const MagickBooleanType invert) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (MagickPixelPacket *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); /* Make image color transparent. */ status=MagickTrue; progress=0; exception=(&image->exception); GetMagickPixelPacket(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); if (IsMagickColorSimilar(&pixel,target) != invert) q->opacity=opacity; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,TransparentPaintImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e C h r o m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImageChroma() changes the opacity value associated with any % pixel that matches color to the value defined by opacity. % % As there is one fuzz value for the all the channels, the % TransparentPaintImage() API is not suitable for the operations like chroma, % where the tolerance for similarity of two color component (RGB) can be % different, Thus we define this method take two target pixels (one % low and one hight) and all the pixels of an image which are lying between % these two pixels are made transparent. % % The format of the TransparentPaintImage method is: % % MagickBooleanType TransparentPaintImage(Image *image, % const MagickPixelPacket *low,const MagickPixelPacket *hight, % const Quantum opacity,const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o low: the low target color. % % o high: the high target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % */ MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image, const MagickPixelPacket *low,const MagickPixelPacket *high, const Quantum opacity,const MagickBooleanType invert) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(high != (MagickPixelPacket *) NULL); assert(low != (MagickPixelPacket *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,ResetAlphaChannel); /* Make image color transparent. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType match; MagickPixelPacket pixel; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); GetMagickPixelPacket(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); match=((pixel.red >= low->red) && (pixel.red <= high->red) && (pixel.green >= low->green) && (pixel.green <= high->green) && (pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue : MagickFalse; if (match != invert) q->opacity=opacity; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,TransparentPaintImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
region_layer.c
#include "region_layer.h" #include "activations.h" #include "blas.h" #include "box.h" #include "dark_cuda.h" #include "utils.h" #include <stdio.h> #include <assert.h> #include <string.h> #include <stdlib.h> #define DOABS 1 region_layer make_region_layer(int batch, int w, int h, int n, int classes, int coords, int max_boxes) { region_layer l = { (LAYER_TYPE)0 }; l.type = REGION; l.n = n; l.batch = batch; l.h = h; l.w = w; l.classes = classes; l.coords = coords; l.cost = (float*)xcalloc(1, sizeof(float)); l.biases = (float*)xcalloc(n * 2, sizeof(float)); l.bias_updates = (float*)xcalloc(n * 2, sizeof(float)); l.outputs = h*w*n*(classes + coords + 1); l.inputs = l.outputs; l.max_boxes = max_boxes; l.truths = max_boxes*(5); l.delta = (float*)xcalloc(batch * l.outputs, sizeof(float)); l.output = (float*)xcalloc(batch * l.outputs, sizeof(float)); int i; for(i = 0; i < n*2; ++i){ l.biases[i] = .5; } l.forward = forward_region_layer; l.backward = backward_region_layer; #ifdef GPU l.forward_gpu = forward_region_layer_gpu; l.backward_gpu = backward_region_layer_gpu; l.output_gpu = cuda_make_array(l.output, batch*l.outputs); l.delta_gpu = cuda_make_array(l.delta, batch*l.outputs); #endif fprintf(stderr, "detection\n"); srand(time(0)); return l; } void resize_region_layer(layer *l, int w, int h) { #ifdef GPU int old_w = l->w; int old_h = l->h; #endif l->w = w; l->h = h; l->outputs = h*w*l->n*(l->classes + l->coords + 1); l->inputs = l->outputs; l->output = (float*)xrealloc(l->output, l->batch * l->outputs * sizeof(float)); l->delta = (float*)xrealloc(l->delta, l->batch * l->outputs * sizeof(float)); #ifdef GPU if (old_w < w || old_h < h) { cuda_free(l->delta_gpu); cuda_free(l->output_gpu); l->delta_gpu = cuda_make_array(l->delta, l->batch*l->outputs); l->output_gpu = cuda_make_array(l->output, l->batch*l->outputs); } #endif } box get_region_box(float *x, float *biases, int n, int index, int i, int j, int w, int h) { box b; b.x = (i + logistic_activate(x[index + 0])) / w; b.y = (j + logistic_activate(x[index + 1])) / h; b.w = exp(x[index + 2]) * biases[2*n]; b.h = exp(x[index + 3]) * biases[2*n+1]; if(DOABS){ b.w = exp(x[index + 2]) * biases[2*n] / w; b.h = exp(x[index + 3]) * biases[2*n+1] / h; } return b; } float delta_region_box(box truth, float *x, float *biases, int n, int index, int i, int j, int w, int h, float *delta, float scale) { box pred = get_region_box(x, biases, n, index, i, j, w, h); float iou = box_iou(pred, truth); float tx = (truth.x*w - i); float ty = (truth.y*h - j); float tw = log(truth.w / biases[2*n]); float th = log(truth.h / biases[2*n + 1]); if(DOABS){ tw = log(truth.w*w / biases[2*n]); th = log(truth.h*h / biases[2*n + 1]); } delta[index + 0] = scale * (tx - logistic_activate(x[index + 0])) * logistic_gradient(logistic_activate(x[index + 0])); delta[index + 1] = scale * (ty - logistic_activate(x[index + 1])) * logistic_gradient(logistic_activate(x[index + 1])); delta[index + 2] = scale * (tw - x[index + 2]); delta[index + 3] = scale * (th - x[index + 3]); return iou; } void delta_region_class(float *output, float *delta, int index, int class_id, int classes, tree *hier, float scale, float *avg_cat, int focal_loss) { int i, n; if(hier){ float pred = 1; while(class_id >= 0){ pred *= output[index + class_id]; int g = hier->group[class_id]; int offset = hier->group_offset[g]; for(i = 0; i < hier->group_size[g]; ++i){ delta[index + offset + i] = scale * (0 - output[index + offset + i]); } delta[index + class_id] = scale * (1 - output[index + class_id]); class_id = hier->parent[class_id]; } *avg_cat += pred; } else { // Focal loss if (focal_loss) { // Focal Loss float alpha = 0.5; // 0.25 or 0.5 //float gamma = 2; // hardcoded in many places of the grad-formula int ti = index + class_id; float pt = output[ti] + 0.000000000000001F; // http://fooplot.com/#W3sidHlwZSI6MCwiZXEiOiItKDEteCkqKDIqeCpsb2coeCkreC0xKSIsImNvbG9yIjoiIzAwMDAwMCJ9LHsidHlwZSI6MTAwMH1d float grad = -(1 - pt) * (2 * pt*logf(pt) + pt - 1); // http://blog.csdn.net/linmingan/article/details/77885832 //float grad = (1 - pt) * (2 * pt*logf(pt) + pt - 1); // https://github.com/unsky/focal-loss for (n = 0; n < classes; ++n) { delta[index + n] = scale * (((n == class_id) ? 1 : 0) - output[index + n]); delta[index + n] *= alpha*grad; if (n == class_id) *avg_cat += output[index + n]; } } else { // default for (n = 0; n < classes; ++n) { delta[index + n] = scale * (((n == class_id) ? 1 : 0) - output[index + n]); if (n == class_id) *avg_cat += output[index + n]; } } } } float logit(float x) { return log(x/(1.-x)); } float tisnan(float x) { return (x != x); } static int entry_index(layer l, int batch, int location, int entry) { int n = location / (l.w*l.h); int loc = location % (l.w*l.h); return batch*l.outputs + n*l.w*l.h*(l.coords + l.classes + 1) + entry*l.w*l.h + loc; } void softmax_tree(float *input, int batch, int inputs, float temp, tree *hierarchy, float *output); void forward_region_layer(const region_layer l, network_state state) { int i,j,b,t,n; int size = l.coords + l.classes + 1; memcpy(l.output, state.input, l.outputs*l.batch*sizeof(float)); #ifndef GPU flatten(l.output, l.w*l.h, size*l.n, l.batch, 1); #endif for (b = 0; b < l.batch; ++b){ for(i = 0; i < l.h*l.w*l.n; ++i){ int index = size*i + b*l.outputs; l.output[index + 4] = logistic_activate(l.output[index + 4]); } } #ifndef GPU if (l.softmax_tree){ for (b = 0; b < l.batch; ++b){ for(i = 0; i < l.h*l.w*l.n; ++i){ int index = size*i + b*l.outputs; softmax_tree(l.output + index + 5, 1, 0, 1, l.softmax_tree, l.output + index + 5); } } } else if (l.softmax){ for (b = 0; b < l.batch; ++b){ for(i = 0; i < l.h*l.w*l.n; ++i){ int index = size*i + b*l.outputs; softmax(l.output + index + 5, l.classes, 1, l.output + index + 5, 1); } } } #endif if(!state.train) return; memset(l.delta, 0, l.outputs * l.batch * sizeof(float)); float avg_iou = 0; float recall = 0; float avg_cat = 0; float avg_obj = 0; float avg_anyobj = 0; int count = 0; int class_count = 0; *(l.cost) = 0; for (b = 0; b < l.batch; ++b) { if(l.softmax_tree){ int onlyclass_id = 0; for(t = 0; t < l.max_boxes; ++t){ box truth = float_to_box(state.truth + t*5 + b*l.truths); if(!truth.x) break; // continue; int class_id = state.truth[t*5 + b*l.truths + 4]; float maxp = 0; int maxi = 0; if(truth.x > 100000 && truth.y > 100000){ for(n = 0; n < l.n*l.w*l.h; ++n){ int index = size*n + b*l.outputs + 5; float scale = l.output[index-1]; float p = scale*get_hierarchy_probability(l.output + index, l.softmax_tree, class_id); if(p > maxp){ maxp = p; maxi = n; } } int index = size*maxi + b*l.outputs + 5; delta_region_class(l.output, l.delta, index, class_id, l.classes, l.softmax_tree, l.class_scale, &avg_cat, l.focal_loss); ++class_count; onlyclass_id = 1; break; } } if(onlyclass_id) continue; } for (j = 0; j < l.h; ++j) { for (i = 0; i < l.w; ++i) { for (n = 0; n < l.n; ++n) { int index = size*(j*l.w*l.n + i*l.n + n) + b*l.outputs; box pred = get_region_box(l.output, l.biases, n, index, i, j, l.w, l.h); float best_iou = 0; int best_class_id = -1; for(t = 0; t < l.max_boxes; ++t){ box truth = float_to_box(state.truth + t*5 + b*l.truths); int class_id = state.truth[t * 5 + b*l.truths + 4]; if (class_id >= l.classes) continue; // if label contains class_id more than number of classes in the cfg-file if(!truth.x) break; // continue; float iou = box_iou(pred, truth); if (iou > best_iou) { best_class_id = state.truth[t*5 + b*l.truths + 4]; best_iou = iou; } } avg_anyobj += l.output[index + 4]; l.delta[index + 4] = l.noobject_scale * ((0 - l.output[index + 4]) * logistic_gradient(l.output[index + 4])); if(l.classfix == -1) l.delta[index + 4] = l.noobject_scale * ((best_iou - l.output[index + 4]) * logistic_gradient(l.output[index + 4])); else{ if (best_iou > l.thresh) { l.delta[index + 4] = 0; if(l.classfix > 0){ delta_region_class(l.output, l.delta, index + 5, best_class_id, l.classes, l.softmax_tree, l.class_scale*(l.classfix == 2 ? l.output[index + 4] : 1), &avg_cat, l.focal_loss); ++class_count; } } } if(*(state.net.seen) < 12800){ box truth = {0}; truth.x = (i + .5)/l.w; truth.y = (j + .5)/l.h; truth.w = l.biases[2*n]; truth.h = l.biases[2*n+1]; if(DOABS){ truth.w = l.biases[2*n]/l.w; truth.h = l.biases[2*n+1]/l.h; } delta_region_box(truth, l.output, l.biases, n, index, i, j, l.w, l.h, l.delta, .01); } } } } for(t = 0; t < l.max_boxes; ++t){ box truth = float_to_box(state.truth + t*5 + b*l.truths); int class_id = state.truth[t * 5 + b*l.truths + 4]; if (class_id >= l.classes) { printf("\n Warning: in txt-labels class_id=%d >= classes=%d in cfg-file. In txt-labels class_id should be [from 0 to %d] \n", class_id, l.classes, l.classes-1); getchar(); continue; // if label contains class_id more than number of classes in the cfg-file } if(!truth.x) break; // continue; float best_iou = 0; int best_index = 0; int best_n = 0; i = (truth.x * l.w); j = (truth.y * l.h); //printf("%d %f %d %f\n", i, truth.x*l.w, j, truth.y*l.h); box truth_shift = truth; truth_shift.x = 0; truth_shift.y = 0; //printf("index %d %d\n",i, j); for(n = 0; n < l.n; ++n){ int index = size*(j*l.w*l.n + i*l.n + n) + b*l.outputs; box pred = get_region_box(l.output, l.biases, n, index, i, j, l.w, l.h); if(l.bias_match){ pred.w = l.biases[2*n]; pred.h = l.biases[2*n+1]; if(DOABS){ pred.w = l.biases[2*n]/l.w; pred.h = l.biases[2*n+1]/l.h; } } //printf("pred: (%f, %f) %f x %f\n", pred.x, pred.y, pred.w, pred.h); pred.x = 0; pred.y = 0; float iou = box_iou(pred, truth_shift); if (iou > best_iou){ best_index = index; best_iou = iou; best_n = n; } } //printf("%d %f (%f, %f) %f x %f\n", best_n, best_iou, truth.x, truth.y, truth.w, truth.h); float iou = delta_region_box(truth, l.output, l.biases, best_n, best_index, i, j, l.w, l.h, l.delta, l.coord_scale); if(iou > .5) recall += 1; avg_iou += iou; //l.delta[best_index + 4] = iou - l.output[best_index + 4]; avg_obj += l.output[best_index + 4]; l.delta[best_index + 4] = l.object_scale * (1 - l.output[best_index + 4]) * logistic_gradient(l.output[best_index + 4]); if (l.rescore) { l.delta[best_index + 4] = l.object_scale * (iou - l.output[best_index + 4]) * logistic_gradient(l.output[best_index + 4]); } if (l.map) class_id = l.map[class_id]; delta_region_class(l.output, l.delta, best_index + 5, class_id, l.classes, l.softmax_tree, l.class_scale, &avg_cat, l.focal_loss); ++count; ++class_count; } } //printf("\n"); #ifndef GPU flatten(l.delta, l.w*l.h, size*l.n, l.batch, 0); #endif *(l.cost) = pow(mag_array(l.delta, l.outputs * l.batch), 2); printf("Region Avg IOU: %f, Class: %f, Obj: %f, No Obj: %f, Avg Recall: %f, count: %d\n", avg_iou/count, avg_cat/class_count, avg_obj/count, avg_anyobj/(l.w*l.h*l.n*l.batch), recall/count, count); } void backward_region_layer(const region_layer l, network_state state) { axpy_cpu(l.batch*l.inputs, 1, l.delta, 1, state.delta, 1); } void get_region_boxes(layer l, int w, int h, float thresh, float **probs, box *boxes, int only_objectness, int *map) { int i; float *const predictions = l.output; #pragma omp parallel for for (i = 0; i < l.w*l.h; ++i){ int j, n; int row = i / l.w; int col = i % l.w; for(n = 0; n < l.n; ++n){ int index = i*l.n + n; int p_index = index * (l.classes + 5) + 4; float scale = predictions[p_index]; if(l.classfix == -1 && scale < .5) scale = 0; int box_index = index * (l.classes + 5); boxes[index] = get_region_box(predictions, l.biases, n, box_index, col, row, l.w, l.h); boxes[index].x *= w; boxes[index].y *= h; boxes[index].w *= w; boxes[index].h *= h; int class_index = index * (l.classes + 5) + 5; if(l.softmax_tree){ hierarchy_predictions(predictions + class_index, l.classes, l.softmax_tree, 0); int found = 0; if(map){ for(j = 0; j < 200; ++j){ float prob = scale*predictions[class_index+map[j]]; probs[index][j] = (prob > thresh) ? prob : 0; } } else { for(j = l.classes - 1; j >= 0; --j){ if(!found && predictions[class_index + j] > .5){ found = 1; } else { predictions[class_index + j] = 0; } float prob = predictions[class_index+j]; probs[index][j] = (scale > thresh) ? prob : 0; } } } else { for(j = 0; j < l.classes; ++j){ float prob = scale*predictions[class_index+j]; probs[index][j] = (prob > thresh) ? prob : 0; } } if(only_objectness){ probs[index][0] = scale; } } } } #ifdef GPU void forward_region_layer_gpu(const region_layer l, network_state state) { /* if(!state.train){ copy_ongpu(l.batch*l.inputs, state.input, 1, l.output_gpu, 1); return; } */ flatten_ongpu(state.input, l.h*l.w, l.n*(l.coords + l.classes + 1), l.batch, 1, l.output_gpu); if(l.softmax_tree){ int i; int count = 5; for (i = 0; i < l.softmax_tree->groups; ++i) { int group_size = l.softmax_tree->group_size[i]; softmax_gpu(l.output_gpu+count, group_size, l.classes + 5, l.w*l.h*l.n*l.batch, 1, l.output_gpu + count); count += group_size; } }else if (l.softmax){ softmax_gpu(l.output_gpu+5, l.classes, l.classes + 5, l.w*l.h*l.n*l.batch, 1, l.output_gpu + 5); } float* in_cpu = (float*)xcalloc(l.batch * l.inputs, sizeof(float)); float *truth_cpu = 0; if(state.truth){ int num_truth = l.batch*l.truths; truth_cpu = (float*)xcalloc(num_truth, sizeof(float)); cuda_pull_array(state.truth, truth_cpu, num_truth); } cuda_pull_array(l.output_gpu, in_cpu, l.batch*l.inputs); //cudaStreamSynchronize(get_cuda_stream()); network_state cpu_state = state; cpu_state.train = state.train; cpu_state.truth = truth_cpu; cpu_state.input = in_cpu; forward_region_layer(l, cpu_state); //cuda_push_array(l.output_gpu, l.output, l.batch*l.outputs); free(cpu_state.input); if(!state.train) return; cuda_push_array(l.delta_gpu, l.delta, l.batch*l.outputs); //cudaStreamSynchronize(get_cuda_stream()); if(cpu_state.truth) free(cpu_state.truth); } void backward_region_layer_gpu(region_layer l, network_state state) { flatten_ongpu(l.delta_gpu, l.h*l.w, l.n*(l.coords + l.classes + 1), l.batch, 0, state.delta); } #endif void correct_region_boxes(detection *dets, int n, int w, int h, int netw, int neth, int relative) { int i; int new_w = 0; int new_h = 0; if (((float)netw / w) < ((float)neth / h)) { new_w = netw; new_h = (h * netw) / w; } else { new_h = neth; new_w = (w * neth) / h; } for (i = 0; i < n; ++i) { box b = dets[i].bbox; b.x = (b.x - (netw - new_w) / 2. / netw) / ((float)new_w / netw); b.y = (b.y - (neth - new_h) / 2. / neth) / ((float)new_h / neth); b.w *= (float)netw / new_w; b.h *= (float)neth / new_h; if (!relative) { b.x *= w; b.w *= w; b.y *= h; b.h *= h; } dets[i].bbox = b; } } void get_region_detections(layer l, int w, int h, int netw, int neth, float thresh, int *map, float tree_thresh, int relative, detection *dets) { int i, j, n, z; float *predictions = l.output; if (l.batch == 2) { float *flip = l.output + l.outputs; for (j = 0; j < l.h; ++j) { for (i = 0; i < l.w / 2; ++i) { for (n = 0; n < l.n; ++n) { for (z = 0; z < l.classes + l.coords + 1; ++z) { int i1 = z*l.w*l.h*l.n + n*l.w*l.h + j*l.w + i; int i2 = z*l.w*l.h*l.n + n*l.w*l.h + j*l.w + (l.w - i - 1); float swap = flip[i1]; flip[i1] = flip[i2]; flip[i2] = swap; if (z == 0) { flip[i1] = -flip[i1]; flip[i2] = -flip[i2]; } } } } } for (i = 0; i < l.outputs; ++i) { l.output[i] = (l.output[i] + flip[i]) / 2.; } } for (i = 0; i < l.w*l.h; ++i) { int row = i / l.w; int col = i % l.w; for (n = 0; n < l.n; ++n) { int index = n*l.w*l.h + i; for (j = 0; j < l.classes; ++j) { dets[index].prob[j] = 0; } int obj_index = entry_index(l, 0, n*l.w*l.h + i, l.coords); int box_index = entry_index(l, 0, n*l.w*l.h + i, 0); int mask_index = entry_index(l, 0, n*l.w*l.h + i, 4); float scale = l.background ? 1 : predictions[obj_index]; dets[index].bbox = get_region_box(predictions, l.biases, n, box_index, col, row, l.w, l.h);// , l.w*l.h); dets[index].objectness = scale > thresh ? scale : 0; if (dets[index].mask) { for (j = 0; j < l.coords - 4; ++j) { dets[index].mask[j] = l.output[mask_index + j*l.w*l.h]; } } int class_index = entry_index(l, 0, n*l.w*l.h + i, l.coords + !l.background); if (l.softmax_tree) { hierarchy_predictions(predictions + class_index, l.classes, l.softmax_tree, 0);// , l.w*l.h); if (map) { for (j = 0; j < 200; ++j) { int class_index = entry_index(l, 0, n*l.w*l.h + i, l.coords + 1 + map[j]); float prob = scale*predictions[class_index]; dets[index].prob[j] = (prob > thresh) ? prob : 0; } } else { int j = hierarchy_top_prediction(predictions + class_index, l.softmax_tree, tree_thresh, l.w*l.h); dets[index].prob[j] = (scale > thresh) ? scale : 0; } } else { if (dets[index].objectness) { for (j = 0; j < l.classes; ++j) { int class_index = entry_index(l, 0, n*l.w*l.h + i, l.coords + 1 + j); float prob = scale*predictions[class_index]; dets[index].prob[j] = (prob > thresh) ? prob : 0; } } } } } correct_region_boxes(dets, l.w*l.h*l.n, w, h, netw, neth, relative); } void zero_objectness(layer l) { int i, n; for (i = 0; i < l.w*l.h; ++i) { for (n = 0; n < l.n; ++n) { int obj_index = entry_index(l, 0, n*l.w*l.h + i, l.coords); l.output[obj_index] = 0; } } }
omptl_algorithm.h
// Copyright (C) 2006 Fokko Beekhof // Email contact: Fokko.Beekhof@cui.unige.ch // The OMPTL library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef OMPTL_ALGORITHM_H #define OMPTL_ALGORITHM_H #ifndef OMPTL_ALGORITHM #warning <omptl_algorithm> not included. Do not include <omptl_algorithm.h>! #include <omptl_algorithm> #endif /* OMPTL_ALGORITHM */ #include <omptl_tools.h> #include <omptl_numeric> #include <iterator> namespace omptl { /* * Not (yet) paralellized due to data dependance. */ template <class ForwardIterator> ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, unsigned int P) { return ::std::adjacent_find(first, last); } /* * Not (yet) paralellized due to data dependance. */ template <class ForwardIterator, class BinaryPredicate> ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred, unsigned int P) { return ::std::adjacent_find(first, last, binary_pred); } template <class ForwardIterator, class T, class StrictWeakOrdering> bool binary_search(ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) return ::std::binary_search(first, last, value, comp); ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); bool results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::binary_search(partitions[t].first, partitions[t].second, value, comp); return ::std::count(static_cast<bool *>(results), results + P, false); } template <class IteratorIn, class IteratorOut, class IteratorInTag, class IteratorOutTag> IteratorOut _copy(IteratorIn first, IteratorIn last, IteratorOut result, unsigned int P, IteratorInTag, IteratorOutTag) { if (_linear_serial_is_faster(first, last, P)) return ::std::copy(first, last, result); ::std::pair<IteratorIn, IteratorIn> source_partitions[P]; ::omptl::_partition_range(first, last, source_partitions, P); IteratorOut dest_partitions[P]; ::omptl::_copy_partitions(source_partitions, result, dest_partitions,P); IteratorOut results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::copy(source_partitions[t].first, source_partitions[t].second, dest_partitions[t]); return results[P - 1]; } template <class InputIterator, class OutputIterator, class InputIteratorTag> OutputIterator _copy(InputIterator first, InputIterator last, OutputIterator result, unsigned int P, InputIteratorTag, ::std::output_iterator_tag) { return ::std::copy(first, last, result); } template <class InputIterator, class OutputIterator, class OutputIteratorTag> OutputIterator _copy(InputIterator first, InputIterator last, OutputIterator result, unsigned int P, ::std::input_iterator_tag, OutputIteratorTag) { return ::std::copy(first, last, result); } template <class InputIterator, class OutputIterator> OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result, unsigned int P) { return ::omptl::_copy(first, last, result, P, typename ::std::iterator_traits<InputIterator>::iterator_category(), typename ::std::iterator_traits<OutputIterator>::iterator_category()); } template <class BidirectionalIterator1, class BidirectionalIterator2> BidirectionalIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) return ::std::copy_backward(first, last, result); ::std::pair<BidirectionalIterator1, BidirectionalIterator1> source_partitions[P]; ::omptl::_partition_range(first, last, source_partitions, P); BidirectionalIterator2 dest_partitions[P]; ::omptl::_copy_partitions(source_partitions, result, dest_partitions, P); BidirectionalIterator2 results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::copy_backward(source_partitions[t].first, source_partitions[t].second, dest_partitions[t]); return results[P - 1]; } template <class Iterator, class EqualityComparable, class IteratorTag> typename ::std::iterator_traits<Iterator>::difference_type _count(Iterator first, Iterator last, const EqualityComparable& value, unsigned int P, ::std::input_iterator_tag) { return ::std::count(first, last, value); } template <class Iterator, class EqualityComparable, class IteratorTag> typename ::std::iterator_traits<Iterator>::difference_type _count(Iterator first, Iterator last, const EqualityComparable& value, unsigned int P, IteratorTag) { if (_linear_serial_is_faster(first, last, P)) return ::std::count(first, last, value); ::std::pair<Iterator, Iterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); typedef typename ::std::iterator_traits<Iterator>::difference_type Tdif; Tdif results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::count(partitions[t].first, partitions[t].second, value); return ::std::accumulate(static_cast<Tdif *>(results), results + P, 0); } template <class InputIterator, class EqualityComparable> typename ::std::iterator_traits<InputIterator>::difference_type count(InputIterator first, InputIterator last, const EqualityComparable& value, unsigned int P) { return ::omptl::_count(first, last, value, P, typename ::std::iterator_traits<InputIterator>::iterator_category()); } template <class InputIterator, class EqualityComparable, class Size> void count(InputIterator first, InputIterator last, const EqualityComparable& value, Size& n, unsigned int P) { n = ::omptl::count(first, last, value, P); } template <class InputIterator, class Predicate> typename ::std::iterator_traits<InputIterator>::difference_type _count_if(InputIterator first, InputIterator last, Predicate pred, unsigned int P, ::std::input_iterator_tag) { return ::std::count_if(first, last, pred); } template <class Iterator, class Predicate, class IteratorTag> typename ::std::iterator_traits<Iterator>::difference_type _count_if(Iterator first, Iterator last, Predicate pred, unsigned int P, IteratorTag) { if (_linear_serial_is_faster(first, last, P)) return ::std::count_if(first, last, pred); ::std::pair<Iterator, Iterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); typedef typename ::std::iterator_traits<Iterator>::difference_type Tdif; Tdif results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::count_if(partitions[t].first, partitions[t].second, pred); return ::omptl::accumulate<Tdif>(&results[0], results + P, Tdif(0)); } template <class InputIterator, class Predicate> typename ::std::iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last, Predicate pred, unsigned int P) { return ::omptl::_count_if(first, last, pred, typename ::std::iterator_traits<InputIterator>::iterator_category()); } template <class InputIterator, class Predicate, class Size> void count_if(InputIterator first, InputIterator last, Predicate pred, Size& n, unsigned int P) { n = ::omptl::count_if(first, last, pred, P); } template <class Iterator1, class Iterator2, class BinaryPredicate, class Iterator1Tag, class Iterator2Tag> bool _equal(Iterator1 first1, Iterator1 last1, Iterator2 first2, BinaryPredicate binary_pred, unsigned int P, Iterator1Tag, Iterator2Tag) { if (_linear_serial_is_faster(first1, last1, P)) return ::std::equal(first1, last1, first2, binary_pred); ::std::pair<Iterator1, Iterator1> source_partitions[P]; ::omptl::_partition_range(first1, last1, source_partitions, P); Iterator2 dest_partitions[P]; ::omptl::_copy_partitions(source_partitions, first2, dest_partitions, P); bool results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::equal(source_partitions[t].first, source_partitions[t].second, dest_partitions[t], binary_pred); return ::std::count(static_cast<bool *>(results), results + P, false); } template <class InputIterator1, class InputIterator2, class BinaryPredicate, class InputIterator1Tag> bool _equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred, unsigned int P, InputIterator1Tag, ::std::input_iterator_tag) { return ::std::equal(first1, last1, first2, binary_pred); } template <class InputIterator1, class InputIterator2, class BinaryPredicate, class InputIterator2Tag> bool _equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred, unsigned int P, ::std::input_iterator_tag, InputIterator2Tag) { return ::std::equal(first1, last1, first2, binary_pred); } template <class InputIterator1, class InputIterator2, class BinaryPredicate> bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred, unsigned int P) { return ::omptl::_equal(first1, last1, first2, binary_pred, typename ::std::iterator_traits<InputIterator1>::iterator_category(), typename ::std::iterator_traits<InputIterator2>::iterator_category()); } //TODO template <class ForwardIterator, class T, class StrictWeakOrdering> ::std::pair<ForwardIterator, ForwardIterator> equal_range(ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp, unsigned int P) { return ::std::equal_range(first, last, value, comp); } template <class ForwardIterator, class T> void fill(ForwardIterator first, ForwardIterator last, const T& value, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) ::std::fill(first, last, value); ::std::pair<ForwardIterator, ForwardIterator> source_partitions[P]; ::omptl::_partition_range(first, last, source_partitions, P); int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::fill(source_partitions[t].first, source_partitions[t].second, value); } template <class Iterator, class Size, class T, class IteratorTag> Iterator _fill_n(Iterator first, Size n, const T& value, unsigned int P, IteratorTag) { const Size range = (n / P) + ( (n % P) ? 1 : 0 ); Size ranges[P]; ::std::fill(&ranges[0], P - 1, range); ranges[P - 1] = n - (P - 1) * range; Iterator source_partitions[P]; source_partitions[0] = first; for (unsigned int i = 1; i < P; ++i) { source_partitions[i] = source_partitions[i - 1]; ::std::advance(source_partitions[i], range); } Iterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::fill_n(source_partitions[t], ranges[t], value); return results[P - 1]; } template <class OutputIterator, class Size, class T> OutputIterator _fill_n(OutputIterator first, Size n, const T& value, unsigned int P, ::std::output_iterator_tag) { return ::std::fill_n(first, n, value); } template <class OutputIterator, class Size, class T> OutputIterator fill_n(OutputIterator first, Size n, const T& value, unsigned int P) { return ::omptl::_fill_n(first, n, value, P, typename ::std::iterator_traits<OutputIterator>::iterator_category()); } template<class InputIterator, class EqualityComparable> InputIterator _find(InputIterator first, InputIterator last, const EqualityComparable& value, unsigned int P, ::std::input_iterator_tag) { return std::find(first, last, value); } template<class Iterator, class EqualityComparable, class IteratorTag> Iterator _find(Iterator first, Iterator last, const EqualityComparable& value, unsigned int P, IteratorTag) { if (_linear_serial_is_faster(first, last, P)) return ::std::find(first, last, value); ::std::pair<Iterator, Iterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); Iterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::find(partitions[t].first, partitions[t].second, value); Iterator *result = ::std::find_if(results, results + P, ::std::bind2nd(::std::not_equal_to<Iterator>(), last) ); if (result != results + P) return *result; return last; } template<class InputIterator, class EqualityComparable> InputIterator find(InputIterator first, InputIterator last, const EqualityComparable& value, unsigned int P) { return ::omptl::_find(first, last, value, P, ::std::iterator_traits<InputIterator>::iterator_category()); } template<class InputIterator, class Predicate> InputIterator _find_if( InputIterator first, InputIterator last, Predicate pred, unsigned int P, ::std::input_iterator_tag) { return ::std::find_if(first, last, pred); } template<class Iterator, class Predicate, class IteratorTag> Iterator _find_if( Iterator first, Iterator last, Predicate pred, unsigned int P, IteratorTag) { if (_linear_serial_is_faster(first, last, P)) return ::std::find_if(first, last, pred); ::std::pair<Iterator, Iterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); Iterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::find_if(partitions[t].first, partitions[t].second, pred); Iterator *result = ::std::find_if(results, results + P, ::std::bind2nd(::std::not_equal_to<Iterator>(), last) ); if (result != results + P) return *result; return last; } template<class InputIterator, class Predicate> InputIterator find_if(InputIterator first, InputIterator last, Predicate pred, unsigned int P) { return ::omptl::_find_if(first, last, pred, P, typename ::std::iterator_traits<InputIterator>::iterator_category()); } // TODO template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate comp, unsigned int P) { return ::std::find_end(first1, last1, first2, last2, comp); } template <class InputIterator, class ForwardIterator, class BinaryPredicate> InputIterator _find_first_of(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate comp, unsigned int P, ::std::input_iterator_tag) { return ::std::find_first_of(first1, last1, first2, last2, comp); } // find_first_of suffers from a loss of efficiency, and potentially a loss of // performance when executed in parallel! template <class Iterator, class ForwardIterator, class BinaryPredicate, class IteratorTag> Iterator _find_first_of(Iterator first1, Iterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate comp, unsigned int P, IteratorTag) { if (_linear_serial_is_faster(first1, last2, P)) return ::std::find_first_of(first1, last1, first2, last2, comp); ::std::pair<Iterator, Iterator> partitions[P]; ::omptl::_partition_range(first1, last2, partitions, P); Iterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::find_first_of(partitions[t].first, partitions[t].second, first2, last2, comp); Iterator *result = ::std::find_if(results, results + P, ::std::bind2nd(::std::not_equal_to<Iterator>(), last1) ); if (result != results + P) return *result; return last1; } template <class InputIterator, class ForwardIterator, class BinaryPredicate> InputIterator find_first_of(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate comp, unsigned int P) { return ::omptl::_find_first_of(first1, last1, first2, last2, comp, typename ::std::iterator_traits<InputIterator>::iterator_category() ); } template <class InputIterator, class UnaryFunction> UnaryFunction _for_each(InputIterator first, InputIterator last, UnaryFunction f, unsigned int P, ::std::input_iterator_tag) { return ::std::for_each(first, last, f); } template <class Iterator, class UnaryFunction, class IteratorTag> UnaryFunction _for_each(Iterator first, Iterator last, UnaryFunction f, unsigned int P, IteratorTag) { if (_linear_serial_is_faster(first, last, P)) return ::std::for_each(first, last, f); ::std::pair<Iterator, Iterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::for_each(partitions[t].first, partitions[t].second, f); return f; } template <class InputIterator, class UnaryFunction> UnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f, unsigned int P) { return ::omptl::_for_each(first, last, f, P, typename ::std::iterator_traits<InputIterator>::iterator_category() ); } template <class ForwardIterator, class Generator> void generate(ForwardIterator first, ForwardIterator last, Generator gen) { ::std::generate(first, last, gen); } template <class ForwardIterator, class Generator> void par_generate(ForwardIterator first, ForwardIterator last, Generator gen, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) { ::std::generate(first, last, gen); return; } ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::generate(partitions[t].first, partitions[t].second, gen); } template <class RandomAccessIterator, class StrictWeakOrdering> void push_heap(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp, unsigned int P) { return ::std::push_heap(first, last, comp); } template <class RandomAccessIterator, class StrictWeakOrdering> inline void pop_heap(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp, unsigned int P) { return ::std::pop_heap(first, last, comp); } template <class RandomAccessIterator, class StrictWeakOrdering> void make_heap(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp, unsigned int P) { return ::std::make_heap(first, last, comp); } template <class RandomAccessIterator, class StrictWeakOrdering> void sort_heap(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp, unsigned int P) { return ::std::sort_heap(first, last, comp); } template <class InputIterator1, class InputIterator2, class StrictWeakOrdering, class Iterator1Tag> bool _includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, StrictWeakOrdering comp, unsigned int P, Iterator1Tag, ::std::input_iterator_tag) { return ::std::includes(first1, last1, first2, last2, comp); } template <class InputIterator1, class InputIterator2, class StrictWeakOrdering, class Iterator2Tag> bool _includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, StrictWeakOrdering comp, unsigned int P, ::std::input_iterator_tag, Iterator2Tag) { return ::std::includes(first1, last1, first2, last2, comp); } template <class Iterator1, class Iterator2, class StrictWeakOrdering, class Iterator1Tag, class Iterator2Tag> bool _includes(Iterator1 first1, Iterator1 last1, Iterator2 first2, Iterator2 last2, StrictWeakOrdering comp, unsigned int P, Iterator1Tag, Iterator2Tag) { if (_linear_serial_is_faster(first2, last2, P)) return ::std::includes(first1, last1, first2, last2, comp); ::std::pair<Iterator2, Iterator2> partitions[P]; ::omptl::_partition_range(first2, last2, partitions, P); bool results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::includes(first1, last1, partitions[t].first, partitions[t].second, comp); return (::std::count(&results[0], results + P, true) == P); } template <class InputIterator1, class InputIterator2, class StrictWeakOrdering> bool includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, StrictWeakOrdering comp, unsigned int P) { return ::omptl::_includes(first1, last1, first2, last2, comp, typename ::std::iterator_traits<InputIterator1>::iterator_category(), typename ::std::iterator_traits<InputIterator2>::iterator_category()); } template <class InputIterator1, class InputIterator2, class BinaryPredicate> bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, BinaryPredicate comp, unsigned int P) { return ::std::lexicographical_compare(first1, last1, first2, last2, comp); } template <class ForwardIterator, class T, class StrictWeakOrdering> ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp, unsigned int P) { if (_logn_serial_is_faster(first, last, P)) return ::std::lower_bound(first, last, value, comp); ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); ForwardIterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::lower_bound(partitions[t].first, partitions[t].second, value, comp); ForwardIterator *result = ::std::find_if(results, results + P, ::std::bind2nd(::std::not_equal_to<ForwardIterator>(), last) ); if (result != results + P) return *result; return last; } // Not parallelized, dependencies between data. template <class InputIterator1, class InputIterator2, class OutputIterator, class StrictWeakOrdering> OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp, unsigned int P) { return ::std::merge(first1, last1, first2, last2, result, comp); } template <class ForwardIterator, class BinaryPredicate> ForwardIterator min_element(ForwardIterator first, ForwardIterator last, BinaryPredicate comp, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) return ::std::min_element(first, last, comp); ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); ForwardIterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::min_element(partitions[t].first, partitions[t].second, comp); // There should be a better way. Is there a way to compare // dereferenced iterators ? ForwardIterator result = results[0]; for (unsigned int i = 1; i < P; ++i) if (comp(results[i], result)) // i.e.: (results[i] < result) result = results[i]; return result; } template <class ForwardIterator, class BinaryPredicate> ForwardIterator max_element(ForwardIterator first, ForwardIterator last, BinaryPredicate comp, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) return ::std::max_element(first, last, comp); ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); ForwardIterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::max_element(partitions[t].first, partitions[t].second, comp); // There should be a better way. Is there a way to compare // dereferenced iterators ? ForwardIterator result = results[0]; for (unsigned int i = 1; i < P; ++i) if (comp(result, results[i])) // i.e.: (result < results[i]) result = results[i]; return result; } template <class InputIterator1, class InputIterator2, class BinaryPredicate, class Iterator1Tag> ::std::pair<InputIterator1, InputIterator2> _mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred, unsigned int P, Iterator1Tag, ::std::input_iterator_tag) { return ::std::mismatch(first1, last1, first2, binary_pred); } template <class InputIterator1, class InputIterator2, class BinaryPredicate, class Iterator2Tag> ::std::pair<InputIterator1, InputIterator2> _mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred, unsigned int P, ::std::input_iterator_tag, Iterator2Tag) { return ::std::mismatch(first1, last1, first2, binary_pred); } template <class Iterator1, class Iterator2, class BinaryPredicate, class Iterator1Tag, class Iterator2Tag> ::std::pair<Iterator1, Iterator2> _mismatch(Iterator1 first1, Iterator1 last1, Iterator2 first2, BinaryPredicate binary_pred, unsigned int P, Iterator1Tag, Iterator2Tag) { if (_linear_serial_is_faster(first1, last1, P)) return ::std::mismatch(first1, last1, first2, binary_pred); ::std::pair<Iterator1, Iterator1> source_partitions[P]; ::omptl::_partition_range(first1, last1, source_partitions, P); Iterator2 dest_partitions[P]; ::omptl::_copy_partitions(source_partitions, first2, dest_partitions, P); ::std::pair<Iterator1, Iterator2> results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::mismatch(source_partitions[t].first, source_partitions[t].second, dest_partitions[t], binary_pred); // This could have been done more elegantly with select1st for (unsigned int i = 0; i < P - 1; ++i) if (results[i].first != source_partitions[i].second) return results[i]; return results[P - 1]; } template <class InputIterator1, class InputIterator2, class BinaryPredicate> ::std::pair<InputIterator1, InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred, unsigned int P) { return ::omptl::_mismatch(first1, last1, first2, binary_pred, P, typename ::std::iterator_traits<InputIterator1>::iterator_category(), typename ::std::iterator_traits<InputIterator2>::iterator_category()); } // TODO How can this be parallelized ? template <class RandomAccessIterator, class StrictWeakOrdering> void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, StrictWeakOrdering comp, unsigned int P) { ::std::nth_element(first, nth, last, comp); } template <class RandomAccessIterator, class StrictWeakOrdering> void partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, StrictWeakOrdering comp, unsigned int P) { ::omptl::_pivot_range(first, last, *middle); ::omptl::sort(first, middle, P); } // Not parallelized due to dependencies. template <class InputIterator, class RandomAccessIterator> RandomAccessIterator partial_sort_copy(InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last, unsigned int P) { return ::std::partial_sort_copy(first, last, result_first, result_last); } // Not parallelized due to dependencies. template <class InputIterator, class RandomAccessIterator, class StrictWeakOrdering> RandomAccessIterator partial_sort_copy(InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last, StrictWeakOrdering comp, unsigned int P) { return ::std::partial_sort_copy(first, last, result_first, result_last, comp); } // Not (yet) parallelized, not straightforward due to possible dependencies // between subtasks. template <class ForwardIterator, class Predicate> ForwardIterator partition(ForwardIterator first, ForwardIterator last, Predicate pred, unsigned int P) { return ::std::partition(first, last, pred); } // Not (yet) parallelized, not straightforward due to possible dependencies // between subtasks. template <class ForwardIterator, class Predicate> ForwardIterator stable_partition(ForwardIterator first, ForwardIterator last, Predicate pred, unsigned int P) { return ::std::stable_partition(first, last, pred); } template <class BidirectionalIterator, class StrictWeakOrdering> bool next_permutation(BidirectionalIterator first, BidirectionalIterator last, StrictWeakOrdering comp, unsigned int P) { return ::std::next_permutation(first, last, comp); } template <class BidirectionalIterator, class StrictWeakOrdering> bool prev_permutation(BidirectionalIterator first, BidirectionalIterator last, StrictWeakOrdering comp, unsigned int P) { return ::std::prev_permutation(first, last, comp); } template <class RandomAccessIterator, class RandomNumberGenerator> void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, unsigned int P) { ::std::random_shuffle(first, last); } template <class RandomAccessIterator, class RandomNumberGenerator> void random_shuffle(RandomAccessIterator first, RandomAccessIterator last) { ::std::random_shuffle(first, last); } template <class RandomAccessIterator, class RandomNumberGenerator> void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& rgen, unsigned int P) { ::std::random_shuffle(first, last, rgen); } template <class RandomAccessIterator, class RandomNumberGenerator> void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& rgen) { ::std::random_shuffle(first, last, rgen); } // Not (yet) parallelized, not straightforward due to possible dependencies // between subtasks. template <class ForwardIterator, class T> ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value, unsigned int P) { return ::std::remove(first, last, value); } // Not (yet) parallelized, not straightforward due to possible dependencies // between subtasks. template <class ForwardIterator, class Predicate> ForwardIterator remove_if(ForwardIterator first, ForwardIterator last, Predicate pred, unsigned int P) { return ::std::remove_if(first, last, pred); } // Not parallelized due to possible complications with OutputIterators. // No par_remove_copy exists due to possible dependencies between subtasks. template <class InputIterator, class OutputIterator, class T> OutputIterator remove_copy(InputIterator first, InputIterator last, OutputIterator result, const T& value, unsigned int P) { return ::std::remove_copy(first, last, result, value); } // Not parallelized due to possible complications with OutputIterators. // No par_remove_copy_if exists due to possible dependencies between subtasks. template <class InputIterator, class OutputIterator, class Predicate> OutputIterator remove_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred, unsigned int P) { return ::std::remove_copy(first, last, result, pred); } template <class ForwardIterator, class T> void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) ::std::replace(first, last, old_value, new_value); ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::replace(partitions[t].first, partitions[t].second, old_value, new_value); } // TODO template <class InputIterator, class OutputIterator, class T> OutputIterator replace_copy(InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value, unsigned int P) { ::std::replace_copy(first, last, result, old_value, new_value); } // TODO template <class InputIterator, class OutputIterator, class Predicate, class T> OutputIterator replace_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T& new_value, unsigned int P) { ::std::replace_copy_if(first, last, result, pred, new_value); } template <class ForwardIterator, class Predicate, class T> void replace_if(ForwardIterator first, ForwardIterator last, Predicate pred, const T& new_value, unsigned int P) { if (_linear_serial_is_faster(first, last, P)) return ::std::replace_if(first, last, pred, new_value); ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::replace_if(partitions[t].first, partitions[t].second, pred, new_value); } // TODO template <class BidirectionalIterator> void reverse(BidirectionalIterator first, BidirectionalIterator last, unsigned int P = omp_get_max_threads()) { ::std::reverse(first, last); } // TODO template <class BidirectionalIterator, class OutputIterator> OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result, unsigned int P = omp_get_max_threads()) { return ::std::reverse_copy(first, last, result); } // TODO template <class ForwardIterator> ForwardIterator rotate( ForwardIterator first, ForwardIterator middle, ForwardIterator last, unsigned int P = omp_get_max_threads()) { return ::std::rotate(first, middle, last); } // TODO template <class ForwardIterator, class OutputIterator> OutputIterator rotate_copy(ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result, unsigned int P = omp_get_max_threads()) { return ::std::rotate(first, middle, last, result); } template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate binary_pred, unsigned int P) { if (_linear_serial_is_faster(first1, last1, P)) return ::std::search(first1, last1, first2, last2, binary_pred); ::std::pair<ForwardIterator1, ForwardIterator1> source_partitions[P]; ::omptl::_partition_range(first1, last1, source_partitions, P); ForwardIterator1 results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::search(source_partitions[t].first, source_partitions[t].second, first2, last2, binary_pred); ForwardIterator1 *result = ::std::find_if(results, results + P, ::std::bind2nd(::std::not_equal_to<ForwardIterator1>(), last1)); if (result != results + P) return *result; return last1; } // TODO template <class ForwardIterator, class Integer, class T, class BinaryPredicate> ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Integer count, const T& value, BinaryPredicate binary_pred, unsigned int P) { ::std::search_n(first, last, count, value, binary_pred); } template <class InputIterator1, class InputIterator2, class OutputIterator, class StrictWeakOrdering> OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp, unsigned int P) { return ::std::set_difference(first1, last1, first2, last2, result, comp); } template <class InputIterator1, class InputIterator2, class OutputIterator, class StrictWeakOrdering> OutputIterator set_intersection(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp, unsigned int P) { return ::std::set_intersection( first1, last1, first2, last2, result, comp); } template <class InputIterator1, class InputIterator2, class OutputIterator, class StrictWeakOrdering> OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp, unsigned int P) { return ::std::set_symmetric_difference( first1, last1, first2, last2, result, comp); } template <class InputIterator1, class InputIterator2, class OutputIterator, class StrictWeakOrdering> OutputIterator set_union(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp, unsigned int P) { return ::std::set_union(first1, last1, first2, last2, result, comp); } template<typename RandomAccessIterator> void sort(RandomAccessIterator first, RandomAccessIterator last, unsigned int P) { if (::omptl::_nlogn_serial_is_faster(first, last, P)) { ::std::sort(first, last); return; } // Generate pivots ::std::vector<typename RandomAccessIterator::value_type> pivots; _find_pivots(first, last, pivots, P); // Sort sufficiently to respect pivot order ::std::pair<RandomAccessIterator, RandomAccessIterator> partitions[P]; ::omptl::_partition_range_by_pivots(first, last, pivots, partitions, P); // Sort int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::sort(partitions[t].first, partitions[t].second); } template<typename RandomAccessIterator> void stable_sort(RandomAccessIterator first, RandomAccessIterator last, unsigned int P) { if (::omptl::_nlogn_serial_is_faster(first, last, P)) { ::std::stable_sort(first, last); return; } // Generate pivots ::std::vector<typename RandomAccessIterator::value_type> pivots; _find_pivots(first, last, pivots, P); // Sort sufficiently to respect pivot order ::std::pair<RandomAccessIterator, RandomAccessIterator> partitions[P]; ::omptl::_partition_range_stable_by_pivots(first, last, pivots, partitions, P); // Sort int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) ::std::stable_sort(partitions[t].first, partitions[t].second); } template <class ForwardIterator1, class ForwardIterator2> ForwardIterator2 swap_ranges(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, unsigned int P) { if (_linear_serial_is_faster(first1, last1, P)) return ::std::swap_ranges(first1, last1, first2); ::std::pair<ForwardIterator1, ForwardIterator1> source_partitions[P]; ::omptl::_partition_range(first1, last1, source_partitions, P); ForwardIterator2 dest_partitions[P]; ::omptl::_copy_partitions(source_partitions, first2, dest_partitions, P); ForwardIterator2 results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::swap_ranges(source_partitions[t].first, source_partitions[t].second, dest_partitions[t]); return results[P - 1]; } template <class InputIterator, class OutputIterator, class UnaryFunction, class IteratorInTag> OutputIterator _transform(InputIterator first, InputIterator last, OutputIterator result, UnaryFunction op, unsigned int P, IteratorInTag, ::std::output_iterator_tag) { return ::std::transform(first, last, result, op); } template <class InputIterator, class OutputIterator, class UnaryFunction, class IteratorOutTag> OutputIterator _transform(InputIterator first, InputIterator last, OutputIterator result, UnaryFunction op, unsigned int P, ::std::input_iterator_tag, IteratorOutTag) { return ::std::transform(first, last, result, op); } template <class IteratorIn, class IteratorOut, class UnaryFunction, class IteratorInTag, class IteratorOutTag> IteratorOut _transform(IteratorIn first, IteratorIn last, IteratorOut result, UnaryFunction op, unsigned int P, IteratorInTag, IteratorOutTag) { if (_linear_serial_is_faster(first, last, P)) return ::std::transform(first, last, result, op); ::std::pair<IteratorIn, IteratorIn> source_partitions[P]; ::omptl::_partition_range(first, last, source_partitions, P); IteratorOut dest_partitions[P]; ::omptl::_copy_partitions(source_partitions, result, dest_partitions, P); IteratorOut results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::transform(source_partitions[t].first, source_partitions[t].second, dest_partitions[t], op); return results[P - 1]; } template <class InputIterator, class OutputIterator, class UnaryFunction> OutputIterator transform(InputIterator first, InputIterator last, OutputIterator result, UnaryFunction op, unsigned int P) { return ::omptl::_transform(first, last, result, op, P, typename ::std::iterator_traits<InputIterator>::iterator_category(), typename ::std::iterator_traits<OutputIterator>::iterator_category()); } template <class InputIterator1, class InputIterator2, class OutputIterator, class BinaryFunction, class Iterator2Tag, class IteratorOutTag> OutputIterator _transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryFunction binary_op, unsigned int P, ::std::input_iterator_tag, Iterator2Tag, IteratorOutTag) { return ::std::transform(first1, last1, first2, result, binary_op); } template <class InputIterator1, class InputIterator2, class OutputIterator, class BinaryFunction, class Iterator1Tag, class IteratorOutTag> OutputIterator _transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryFunction binary_op, unsigned int P, Iterator1Tag, ::std::input_iterator_tag, IteratorOutTag) { return ::std::transform(first1, last1, first2, result, binary_op); } template <class InputIterator1, class InputIterator2, class OutputIterator, class BinaryFunction, class Iterator1Tag, class Iterator2Tag> OutputIterator _transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryFunction binary_op, unsigned int P, Iterator1Tag, Iterator2Tag, ::std::output_iterator_tag) { return ::std::transform(first1, last1, first2, result, binary_op); } template <class Iterator1, class Iterator2, class IteratorOut, class BinaryFunction, class Iterator1Tag, class Iterator2Tag, class IteratorOutTag> IteratorOut _transform(Iterator1 first1, Iterator1 last1, Iterator2 first2, IteratorOut result, BinaryFunction binary_op, unsigned int P, Iterator1Tag, Iterator2Tag, IteratorOutTag) { if (_linear_serial_is_faster(first1, last1, P)) return ::std::transform(first1, last1, first2, result, binary_op); ::std::pair<Iterator1, Iterator1> source_partitions1[P]; ::omptl::_partition_range(first1, last1, source_partitions1, P); Iterator2 source_partitions2[P]; ::omptl::_copy_partitions(source_partitions1, first2, source_partitions2 , P); IteratorOut dest_partitions[P]; ::omptl::_copy_partitions(source_partitions1, result, dest_partitions, P); IteratorOut results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::transform(source_partitions1[t].first, source_partitions1[t].second, source_partitions2[t], dest_partitions[t], binary_op); return results[P - 1]; } template <class InputIterator1, class InputIterator2, class OutputIterator, class BinaryFunction> OutputIterator transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryFunction binary_op, unsigned int P) { return ::omptl::_transform(first1, last1, first2, result, binary_op, P, typename ::std::iterator_traits<InputIterator1>::iterator_category(), typename ::std::iterator_traits<InputIterator2>::iterator_category(), typename ::std::iterator_traits<OutputIterator>::iterator_category()); } template <class ForwardIterator, class BinaryPredicate> ForwardIterator unique(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred = ::std::equal_to<typename ForwardIterator::value_type>(), unsigned int P = omp_get_max_threads()) { return ::std::unique_copy(first, last, binary_pred); } template <class InputIterator, class OutputIterator, class BinaryPredicate> OutputIterator unique_copy(InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate binary_pred = ::std::equal_to<typename InputIterator::value_type>(), unsigned int P = omp_get_max_threads()) { return ::std::unique_copy(first, last, result, binary_pred); } template <class ForwardIterator, class T, class StrictWeakOrdering> ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp, unsigned int P) { if (_logn_serial_is_faster(first, last, P)) return ::std::upper_bound(first, last, value, comp); ::std::pair<ForwardIterator, ForwardIterator> partitions[P]; ::omptl::_partition_range(first, last, partitions, P); ForwardIterator results[P]; int t; #pragma omp parallel for default(shared) private(t) for (t = 0; t < int(P); ++t) results[t] = ::std::upper_bound(partitions[t].first, partitions[t].second, value, comp); // There has to be a better way... for (unsigned int i = P - 1; i > 0; --i) if (results[i] != last) return results[i]; return results[0]; } } /* namespace omptl */ #endif /* OMPTL_ALGORITHM_H */
gen_fffc.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_utilities.h" #include "hypre_hopscotch_hash.h" #include "_hypre_parcsr_mv.h" #include "_hypre_lapack.h" #include "_hypre_blas.h" /* ----------------------------------------------------------------------------- * generate AFF or AFC * ----------------------------------------------------------------------------- */ HYPRE_Int hypre_ParCSRMatrixGenerateFFFC( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, HYPRE_BigInt *cpts_starts, hypre_ParCSRMatrix *S, hypre_ParCSRMatrix **A_FC_ptr, hypre_ParCSRMatrix **A_FF_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); /* diag part of S */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); /* off-diag part of S */ hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); hypre_ParCSRMatrix *A_FC; hypre_CSRMatrix *A_FC_diag, *A_FC_offd; HYPRE_Int *A_FC_diag_i, *A_FC_diag_j, *A_FC_offd_i, *A_FC_offd_j=NULL; HYPRE_Complex *A_FC_diag_data, *A_FC_offd_data=NULL; HYPRE_Int num_cols_offd_A_FC; HYPRE_BigInt *col_map_offd_A_FC = NULL; hypre_ParCSRMatrix *A_FF; hypre_CSRMatrix *A_FF_diag, *A_FF_offd; HYPRE_Int *A_FF_diag_i, *A_FF_diag_j, *A_FF_offd_i, *A_FF_offd_j; HYPRE_Complex *A_FF_diag_data, *A_FF_offd_data; HYPRE_Int num_cols_offd_A_FF; HYPRE_BigInt *col_map_offd_A_FF = NULL; HYPRE_Int *fine_to_coarse; HYPRE_Int *fine_to_fine; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *fine_to_fine_offd = NULL; HYPRE_Int i, j, jj; HYPRE_Int startc, index; HYPRE_Int cpt, fpt, row; HYPRE_Int *CF_marker_offd = NULL, *marker_offd=NULL; HYPRE_Int *int_buf_data = NULL; HYPRE_BigInt *big_convert; HYPRE_BigInt *big_convert_offd = NULL; HYPRE_BigInt *big_buf_data = NULL; HYPRE_BigInt total_global_fpts, total_global_cpts, *fpts_starts; HYPRE_Int my_id, num_procs, num_sends; HYPRE_Int d_count_FF, d_count_FC, o_count_FF, o_count_FC; HYPRE_Int n_Fpts; HYPRE_Int *cpt_array, *fpt_array; HYPRE_Int start, stop; HYPRE_Int num_threads; num_threads = hypre_NumThreads(); /* MPI size and rank*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); fine_to_fine = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); big_convert = hypre_CTAlloc(HYPRE_BigInt, n_fine, HYPRE_MEMORY_HOST); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); fpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,jj,start,stop,row,cpt,fpt,d_count_FC,d_count_FF,o_count_FC,o_count_FF) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); start = (n_fine/num_threads)*my_thread_num; if (my_thread_num == num_threads-1) { stop = n_fine; } else { stop = (n_fine/num_threads)*(my_thread_num+1); } for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num+1]++; } else { fpt_array[my_thread_num+1]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i=1; i < num_threads; i++) { cpt_array[i+1] += cpt_array[i]; fpt_array[i+1] += fpt_array[i]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cpt = cpt_array[my_thread_num]; fpt = fpt_array[my_thread_num]; for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { fine_to_coarse[i] = cpt++; fine_to_fine[i] = -1; } else { fine_to_fine[i] = fpt++; fine_to_coarse[i] = -1; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { HYPRE_BigInt big_Fpts; n_Fpts = fpt_array[num_threads]; big_Fpts = n_Fpts; fpts_starts = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_MPI_Scan(&big_Fpts, fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); fpts_starts[0] = fpts_starts[1] - big_Fpts; if (my_id == num_procs - 1) { total_global_fpts = fpts_starts[1]; total_global_cpts = cpts_starts[1]; } hypre_MPI_Bcast(&total_global_fpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { big_convert[i] = (HYPRE_BigInt)fine_to_coarse[i] + cpts_starts[0]; } else { big_convert[i] = (HYPRE_BigInt)fine_to_fine[i] + fpts_starts[0]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (num_cols_A_offd) { CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); big_convert_offd = hypre_CTAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_HOST); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); fine_to_fine_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); } index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); big_buf_data = hypre_CTAlloc(HYPRE_BigInt, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { int_buf_data[index] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; big_buf_data[index++] = big_convert[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = hypre_ParCSRCommHandleCreate( 21, comm_pkg, big_buf_data, big_convert_offd); hypre_ParCSRCommHandleDestroy(comm_handle); marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); for (i = 0; i < n_fine; i++) { if (CF_marker[i] < 0) { for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { marker_offd[S_offd_j[j]] = 1; } } } num_cols_offd_A_FC = 0; num_cols_offd_A_FF = 0; if (num_cols_A_offd) { for (i=0; i < num_cols_A_offd; i++) { if (CF_marker_offd[i] > 0 && marker_offd[i] > 0) { fine_to_coarse_offd[i] = num_cols_offd_A_FC++; fine_to_fine_offd[i] = -1; } else if (CF_marker_offd[i] < 0 && marker_offd[i] > 0) { fine_to_fine_offd[i] = num_cols_offd_A_FF++; fine_to_coarse_offd[i] = -1; } } col_map_offd_A_FF = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A_FF, HYPRE_MEMORY_HOST); col_map_offd_A_FC = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A_FC, HYPRE_MEMORY_HOST); cpt = 0; fpt = 0; for (i=0; i < num_cols_A_offd; i++) { if (CF_marker_offd[i] > 0 && marker_offd[i] > 0) { col_map_offd_A_FC[cpt++] = big_convert_offd[i]; } else if (CF_marker_offd[i] < 0 && marker_offd[i] > 0) { col_map_offd_A_FF[fpt++] = big_convert_offd[i]; } } } A_FF_diag_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); A_FC_diag_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); A_FF_offd_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); A_FC_offd_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif d_count_FC = 0; d_count_FF = 0; o_count_FC = 0; o_count_FF = 0; row = fpt_array[my_thread_num]; for (i=start; i < stop; i++) { if (CF_marker[i] < 0) { row++; d_count_FF++; /* account for diagonal element */ for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jj = S_diag_j[j]; if (CF_marker[jj] > 0) d_count_FC++; else d_count_FF++; } A_FF_diag_i[row] = d_count_FF; A_FC_diag_i[row] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jj = S_offd_j[j]; if (CF_marker_offd[jj] > 0) o_count_FC++; else o_count_FF++; } A_FF_offd_i[row] = o_count_FF; A_FC_offd_i[row] = o_count_FC; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { HYPRE_Int fpt2; for (i=1; i<num_threads+1; i++) { fpt = fpt_array[i]; fpt2 = fpt_array[i-1]; if (fpt == fpt2) { continue; } A_FC_diag_i[fpt] += A_FC_diag_i[fpt2]; A_FF_diag_i[fpt] += A_FF_diag_i[fpt2]; A_FC_offd_i[fpt] += A_FC_offd_i[fpt2]; A_FF_offd_i[fpt] += A_FF_offd_i[fpt2]; } row = fpt_array[num_threads]; d_count_FC = A_FC_diag_i[row]; d_count_FF = A_FF_diag_i[row]; o_count_FC = A_FC_offd_i[row]; o_count_FF = A_FF_offd_i[row]; A_FF_diag_j = hypre_CTAlloc(HYPRE_Int,d_count_FF, memory_location_P); A_FC_diag_j = hypre_CTAlloc(HYPRE_Int,d_count_FC, memory_location_P); A_FF_offd_j = hypre_CTAlloc(HYPRE_Int,o_count_FF, memory_location_P); A_FC_offd_j = hypre_CTAlloc(HYPRE_Int,o_count_FC, memory_location_P); A_FF_diag_data = hypre_CTAlloc(HYPRE_Real,d_count_FF, memory_location_P); A_FC_diag_data = hypre_CTAlloc(HYPRE_Real,d_count_FC, memory_location_P); A_FF_offd_data = hypre_CTAlloc(HYPRE_Real,o_count_FF, memory_location_P); A_FC_offd_data = hypre_CTAlloc(HYPRE_Real,o_count_FC, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif row = fpt_array[my_thread_num]; d_count_FC = A_FC_diag_i[row]; d_count_FF = A_FF_diag_i[row]; o_count_FC = A_FC_offd_i[row]; o_count_FF = A_FF_offd_i[row]; for (i=start; i < stop; i++) { if (CF_marker[i] < 0) { HYPRE_Int jS, jA; row++; jA = A_diag_i[i]; A_FF_diag_j[d_count_FF] = fine_to_fine[A_diag_j[jA]]; A_FF_diag_data[d_count_FF++] = A_diag_data[jA++]; for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jA = A_diag_i[i]+1; jS = S_diag_j[j]; while (A_diag_j[jA] != jS) jA++; if (CF_marker[S_diag_j[j]] > 0) { A_FC_diag_j[d_count_FC] = fine_to_coarse[A_diag_j[jA]]; A_FC_diag_data[d_count_FC++] = A_diag_data[jA++]; } else { A_FF_diag_j[d_count_FF] = fine_to_fine[A_diag_j[jA]]; A_FF_diag_data[d_count_FF++] = A_diag_data[jA++]; } } A_FF_diag_i[row] = d_count_FF; A_FC_diag_i[row] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jA = A_offd_i[i]; jS = S_offd_j[j]; while (jS != A_offd_j[jA]) jA++; if (CF_marker_offd[S_offd_j[j]] > 0) { A_FC_offd_j[o_count_FC] = fine_to_coarse_offd[A_offd_j[jA]]; A_FC_offd_data[o_count_FC++] = A_offd_data[jA++]; } else { A_FF_offd_j[o_count_FF] = fine_to_fine_offd[A_offd_j[jA]]; A_FF_offd_data[o_count_FF++] = A_offd_data[jA++]; } } A_FF_offd_i[row] = o_count_FF; A_FC_offd_i[row] = o_count_FC; } } } /*end parallel region */ A_FC = hypre_ParCSRMatrixCreate(comm, total_global_fpts, total_global_cpts, fpts_starts, cpts_starts, num_cols_offd_A_FC, A_FC_diag_i[n_Fpts], A_FC_offd_i[n_Fpts]); A_FF = hypre_ParCSRMatrixCreate(comm, total_global_fpts, total_global_fpts, fpts_starts, fpts_starts, num_cols_offd_A_FF, A_FF_diag_i[n_Fpts], A_FF_offd_i[n_Fpts]); A_FC_diag = hypre_ParCSRMatrixDiag(A_FC); hypre_CSRMatrixData(A_FC_diag) = A_FC_diag_data; hypre_CSRMatrixI(A_FC_diag) = A_FC_diag_i; hypre_CSRMatrixJ(A_FC_diag) = A_FC_diag_j; A_FC_offd = hypre_ParCSRMatrixOffd(A_FC); hypre_CSRMatrixData(A_FC_offd) = A_FC_offd_data; hypre_CSRMatrixI(A_FC_offd) = A_FC_offd_i; hypre_CSRMatrixJ(A_FC_offd) = A_FC_offd_j; hypre_ParCSRMatrixOwnsRowStarts(A_FC) = 1; hypre_ParCSRMatrixOwnsColStarts(A_FC) = 0; hypre_ParCSRMatrixColMapOffd(A_FC) = col_map_offd_A_FC; hypre_CSRMatrixMemoryLocation(A_FC_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(A_FC_offd) = memory_location_P; A_FF_diag = hypre_ParCSRMatrixDiag(A_FF); hypre_CSRMatrixData(A_FF_diag) = A_FF_diag_data; hypre_CSRMatrixI(A_FF_diag) = A_FF_diag_i; hypre_CSRMatrixJ(A_FF_diag) = A_FF_diag_j; A_FF_offd = hypre_ParCSRMatrixOffd(A_FF); hypre_CSRMatrixData(A_FF_offd) = A_FF_offd_data; hypre_CSRMatrixI(A_FF_offd) = A_FF_offd_i; hypre_CSRMatrixJ(A_FF_offd) = A_FF_offd_j; hypre_ParCSRMatrixOwnsRowStarts(A_FF) = 0; hypre_ParCSRMatrixOwnsColStarts(A_FF) = 0; hypre_ParCSRMatrixColMapOffd(A_FF) = col_map_offd_A_FF; hypre_CSRMatrixMemoryLocation(A_FF_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(A_FF_offd) = memory_location_P; hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(big_convert, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_fine_offd, HYPRE_MEMORY_HOST); hypre_TFree(big_convert_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(big_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(fpt_array, HYPRE_MEMORY_HOST); *A_FC_ptr = A_FC; *A_FF_ptr = A_FF; return hypre_error_flag; } /* ----------------------------------------------------------------------------- * generate AFF, AFC, for 2 stage extended interpolation * ----------------------------------------------------------------------------- */ HYPRE_Int hypre_ParCSRMatrixGenerateFFFC3( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, HYPRE_BigInt *cpts_starts, hypre_ParCSRMatrix *S, hypre_ParCSRMatrix **A_FC_ptr, hypre_ParCSRMatrix **A_FF_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); /* diag part of S */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); /* off-diag part of S */ hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); hypre_ParCSRMatrix *A_FC; hypre_CSRMatrix *A_FC_diag, *A_FC_offd; HYPRE_Int *A_FC_diag_i, *A_FC_diag_j, *A_FC_offd_i, *A_FC_offd_j=NULL; HYPRE_Complex *A_FC_diag_data, *A_FC_offd_data=NULL; HYPRE_Int num_cols_offd_A_FC; HYPRE_BigInt *col_map_offd_A_FC = NULL; hypre_ParCSRMatrix *A_FF; hypre_CSRMatrix *A_FF_diag, *A_FF_offd; HYPRE_Int *A_FF_diag_i, *A_FF_diag_j, *A_FF_offd_i, *A_FF_offd_j; HYPRE_Complex *A_FF_diag_data, *A_FF_offd_data; HYPRE_Int num_cols_offd_A_FF; HYPRE_BigInt *col_map_offd_A_FF = NULL; HYPRE_Int *fine_to_coarse; HYPRE_Int *fine_to_fine; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *fine_to_fine_offd = NULL; HYPRE_Int i, j, jj; HYPRE_Int startc, index; HYPRE_Int cpt, fpt, new_fpt, row, rowc; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *int_buf_data = NULL; HYPRE_BigInt *big_convert; HYPRE_BigInt *big_convert_offd = NULL; HYPRE_BigInt *big_buf_data = NULL; HYPRE_BigInt total_global_fpts, total_global_cpts, total_global_new_fpts; HYPRE_BigInt *fpts_starts, *new_fpts_starts; HYPRE_Int my_id, num_procs, num_sends; HYPRE_Int d_count_FF, d_count_FC, o_count_FF, o_count_FC; HYPRE_Int n_Fpts; HYPRE_Int n_new_Fpts; HYPRE_Int *cpt_array, *fpt_array, *new_fpt_array; HYPRE_Int start, stop; HYPRE_Int num_threads; num_threads = hypre_NumThreads(); /* MPI size and rank*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); fine_to_fine = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); big_convert = hypre_CTAlloc(HYPRE_BigInt, n_fine, HYPRE_MEMORY_HOST); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); fpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); new_fpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,jj,start,stop,row,rowc,cpt,new_fpt,fpt,d_count_FC,d_count_FF,o_count_FC,o_count_FF) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); start = (n_fine/num_threads)*my_thread_num; if (my_thread_num == num_threads-1) { stop = n_fine; } else { stop = (n_fine/num_threads)*(my_thread_num+1); } for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num+1]++; } else if (CF_marker[i] == -2) { new_fpt_array[my_thread_num+1]++; fpt_array[my_thread_num+1]++; } else { fpt_array[my_thread_num+1]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i=1; i < num_threads; i++) { cpt_array[i+1] += cpt_array[i]; fpt_array[i+1] += fpt_array[i]; new_fpt_array[i+1] += new_fpt_array[i]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cpt = cpt_array[my_thread_num]; fpt = fpt_array[my_thread_num]; for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { fine_to_coarse[i] = cpt++; fine_to_fine[i] = -1; } else { fine_to_fine[i] = fpt++; fine_to_coarse[i] = -1; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { HYPRE_BigInt big_Fpts, big_new_Fpts; n_Fpts = fpt_array[num_threads]; n_new_Fpts = new_fpt_array[num_threads]; big_Fpts = n_Fpts; big_new_Fpts = n_new_Fpts; fpts_starts = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); new_fpts_starts = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_MPI_Scan(&big_Fpts, fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); hypre_MPI_Scan(&big_new_Fpts, new_fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); fpts_starts[0] = fpts_starts[1] - big_Fpts; new_fpts_starts[0] = new_fpts_starts[1] - big_new_Fpts; if (my_id == num_procs - 1) { total_global_new_fpts = new_fpts_starts[1]; total_global_fpts = fpts_starts[1]; total_global_cpts = cpts_starts[1]; } hypre_MPI_Bcast(&total_global_new_fpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_global_fpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { big_convert[i] = (HYPRE_BigInt)fine_to_coarse[i] + cpts_starts[0]; } else { big_convert[i] = (HYPRE_BigInt)fine_to_fine[i] + fpts_starts[0]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (num_cols_A_offd) { CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); big_convert_offd = hypre_CTAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_HOST); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); fine_to_fine_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); } index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); big_buf_data = hypre_CTAlloc(HYPRE_BigInt, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { int_buf_data[index] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; big_buf_data[index++] = big_convert[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = hypre_ParCSRCommHandleCreate( 21, comm_pkg, big_buf_data, big_convert_offd); hypre_ParCSRCommHandleDestroy(comm_handle); num_cols_offd_A_FC = 0; num_cols_offd_A_FF = 0; if (num_cols_A_offd) { for (i=0; i < num_cols_A_offd; i++) { if (CF_marker_offd[i] > 0) { fine_to_coarse_offd[i] = num_cols_offd_A_FC++; fine_to_fine_offd[i] = -1; } else { fine_to_fine_offd[i] = num_cols_offd_A_FF++; fine_to_coarse_offd[i] = -1; } } col_map_offd_A_FF = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A_FF, HYPRE_MEMORY_HOST); col_map_offd_A_FC = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A_FC, HYPRE_MEMORY_HOST); cpt = 0; fpt = 0; for (i=0; i < num_cols_A_offd; i++) { if (CF_marker_offd[i] > 0) { col_map_offd_A_FC[cpt++] = big_convert_offd[i]; } else { col_map_offd_A_FF[fpt++] = big_convert_offd[i]; } } } A_FF_diag_i = hypre_CTAlloc(HYPRE_Int,n_new_Fpts+1, memory_location_P); A_FC_diag_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); A_FF_offd_i = hypre_CTAlloc(HYPRE_Int,n_new_Fpts+1, memory_location_P); A_FC_offd_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif d_count_FC = 0; d_count_FF = 0; o_count_FC = 0; o_count_FF = 0; row = new_fpt_array[my_thread_num]; rowc = fpt_array[my_thread_num]; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { row++; rowc++; d_count_FF++; /* account for diagonal element */ for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jj = S_diag_j[j]; if (CF_marker[jj] > 0) d_count_FC++; else d_count_FF++; } A_FF_diag_i[row] = d_count_FF; A_FC_diag_i[rowc] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jj = S_offd_j[j]; if (CF_marker_offd[jj] > 0) o_count_FC++; else o_count_FF++; } A_FF_offd_i[row] = o_count_FF; A_FC_offd_i[rowc] = o_count_FC; } else if (CF_marker[i] < 0) { rowc++; for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jj = S_diag_j[j]; if (CF_marker[jj] > 0) d_count_FC++; } A_FC_diag_i[rowc] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jj = S_offd_j[j]; if (CF_marker_offd[jj] > 0) o_count_FC++; } A_FC_offd_i[rowc] = o_count_FC; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { HYPRE_Int fpt2, new_fpt2; for (i=1; i<num_threads+1; i++) { fpt = fpt_array[i]; new_fpt = new_fpt_array[i]; fpt2 = fpt_array[i-1]; new_fpt2 = new_fpt_array[i-1]; if (new_fpt != new_fpt2) { A_FF_diag_i[new_fpt] += A_FF_diag_i[new_fpt2]; A_FF_offd_i[new_fpt] += A_FF_offd_i[new_fpt2]; } if (fpt != fpt2) { A_FC_diag_i[fpt] += A_FC_diag_i[fpt2]; A_FC_offd_i[fpt] += A_FC_offd_i[fpt2]; } } row = new_fpt_array[num_threads]; rowc = fpt_array[num_threads]; d_count_FC = A_FC_diag_i[rowc]; d_count_FF = A_FF_diag_i[row]; o_count_FC = A_FC_offd_i[rowc]; o_count_FF = A_FF_offd_i[row]; A_FF_diag_j = hypre_CTAlloc(HYPRE_Int,d_count_FF, memory_location_P); A_FC_diag_j = hypre_CTAlloc(HYPRE_Int,d_count_FC, memory_location_P); A_FF_offd_j = hypre_CTAlloc(HYPRE_Int,o_count_FF, memory_location_P); A_FC_offd_j = hypre_CTAlloc(HYPRE_Int,o_count_FC, memory_location_P); A_FF_diag_data = hypre_CTAlloc(HYPRE_Real,d_count_FF, memory_location_P); A_FC_diag_data = hypre_CTAlloc(HYPRE_Real,d_count_FC, memory_location_P); A_FF_offd_data = hypre_CTAlloc(HYPRE_Real,o_count_FF, memory_location_P); A_FC_offd_data = hypre_CTAlloc(HYPRE_Real,o_count_FC, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif row = new_fpt_array[my_thread_num]; rowc = fpt_array[my_thread_num]; d_count_FC = A_FC_diag_i[rowc]; d_count_FF = A_FF_diag_i[row]; o_count_FC = A_FC_offd_i[rowc]; o_count_FF = A_FF_offd_i[row]; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { HYPRE_Int jS, jA; row++; rowc++; jA = A_diag_i[i]; A_FF_diag_j[d_count_FF] = fine_to_fine[A_diag_j[jA]]; A_FF_diag_data[d_count_FF++] = A_diag_data[jA++]; for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jA = A_diag_i[i]+1; jS = S_diag_j[j]; while (A_diag_j[jA] != jS) jA++; if (CF_marker[S_diag_j[j]] > 0) { A_FC_diag_j[d_count_FC] = fine_to_coarse[A_diag_j[jA]]; A_FC_diag_data[d_count_FC++] = A_diag_data[jA++]; } else { A_FF_diag_j[d_count_FF] = fine_to_fine[A_diag_j[jA]]; A_FF_diag_data[d_count_FF++] = A_diag_data[jA++]; } } A_FF_diag_i[row] = d_count_FF; A_FC_diag_i[rowc] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jA = A_offd_i[i]; jS = S_offd_j[j]; while (jS != A_offd_j[jA]) jA++; if (CF_marker_offd[S_offd_j[j]] > 0) { A_FC_offd_j[o_count_FC] = fine_to_coarse_offd[A_offd_j[jA]]; A_FC_offd_data[o_count_FC++] = A_offd_data[jA++]; } else { A_FF_offd_j[o_count_FF] = fine_to_fine_offd[A_offd_j[jA]]; A_FF_offd_data[o_count_FF++] = A_offd_data[jA++]; } } A_FF_offd_i[row] = o_count_FF; A_FC_offd_i[rowc] = o_count_FC; } else if (CF_marker[i] < 0) { HYPRE_Int jS, jA; rowc++; for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jA = A_diag_i[i]+1; jS = S_diag_j[j]; while (A_diag_j[jA] != jS) jA++; if (CF_marker[S_diag_j[j]] > 0) { A_FC_diag_j[d_count_FC] = fine_to_coarse[A_diag_j[jA]]; A_FC_diag_data[d_count_FC++] = A_diag_data[jA++]; } } A_FC_diag_i[rowc] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jA = A_offd_i[i]; jS = S_offd_j[j]; while (jS != A_offd_j[jA]) jA++; if (CF_marker_offd[S_offd_j[j]] > 0) { A_FC_offd_j[o_count_FC] = fine_to_coarse_offd[A_offd_j[jA]]; A_FC_offd_data[o_count_FC++] = A_offd_data[jA++]; } } A_FC_offd_i[rowc] = o_count_FC; } } } /*end parallel region */ A_FC = hypre_ParCSRMatrixCreate(comm, total_global_fpts, total_global_cpts, fpts_starts, cpts_starts, num_cols_offd_A_FC, A_FC_diag_i[n_Fpts], A_FC_offd_i[n_Fpts]); A_FF = hypre_ParCSRMatrixCreate(comm, total_global_new_fpts, total_global_fpts, new_fpts_starts, fpts_starts, num_cols_offd_A_FF, A_FF_diag_i[n_new_Fpts], A_FF_offd_i[n_new_Fpts]); A_FC_diag = hypre_ParCSRMatrixDiag(A_FC); hypre_CSRMatrixData(A_FC_diag) = A_FC_diag_data; hypre_CSRMatrixI(A_FC_diag) = A_FC_diag_i; hypre_CSRMatrixJ(A_FC_diag) = A_FC_diag_j; A_FC_offd = hypre_ParCSRMatrixOffd(A_FC); hypre_CSRMatrixData(A_FC_offd) = A_FC_offd_data; hypre_CSRMatrixI(A_FC_offd) = A_FC_offd_i; hypre_CSRMatrixJ(A_FC_offd) = A_FC_offd_j; hypre_ParCSRMatrixOwnsRowStarts(A_FC) = 1; hypre_ParCSRMatrixOwnsColStarts(A_FC) = 0; hypre_ParCSRMatrixColMapOffd(A_FC) = col_map_offd_A_FC; hypre_CSRMatrixMemoryLocation(A_FC_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(A_FC_offd) = memory_location_P; A_FF_diag = hypre_ParCSRMatrixDiag(A_FF); hypre_CSRMatrixData(A_FF_diag) = A_FF_diag_data; hypre_CSRMatrixI(A_FF_diag) = A_FF_diag_i; hypre_CSRMatrixJ(A_FF_diag) = A_FF_diag_j; A_FF_offd = hypre_ParCSRMatrixOffd(A_FF); hypre_CSRMatrixData(A_FF_offd) = A_FF_offd_data; hypre_CSRMatrixI(A_FF_offd) = A_FF_offd_i; hypre_CSRMatrixJ(A_FF_offd) = A_FF_offd_j; hypre_ParCSRMatrixOwnsRowStarts(A_FF) = 1; hypre_ParCSRMatrixOwnsColStarts(A_FF) = 0; hypre_ParCSRMatrixColMapOffd(A_FF) = col_map_offd_A_FF; hypre_CSRMatrixMemoryLocation(A_FF_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(A_FF_offd) = memory_location_P; hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(big_convert, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_fine_offd, HYPRE_MEMORY_HOST); hypre_TFree(big_convert_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(big_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(fpt_array, HYPRE_MEMORY_HOST); hypre_TFree(new_fpt_array, HYPRE_MEMORY_HOST); *A_FC_ptr = A_FC; *A_FF_ptr = A_FF; return hypre_error_flag; } /* ----------------------------------------------------------------------------- * generate AFF, AFC, AFFC for 2 stage extended+i(e)interpolation * ----------------------------------------------------------------------------- */ HYPRE_Int hypre_ParCSRMatrixGenerateFFFCD3( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, HYPRE_BigInt *cpts_starts, hypre_ParCSRMatrix *S, hypre_ParCSRMatrix **A_FC_ptr, hypre_ParCSRMatrix **A_FF_ptr, HYPRE_Real **D_lambda_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); /* diag part of S */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); /* off-diag part of S */ hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Real *D_lambda; hypre_ParCSRMatrix *A_FC; hypre_CSRMatrix *A_FC_diag, *A_FC_offd; HYPRE_Int *A_FC_diag_i, *A_FC_diag_j, *A_FC_offd_i, *A_FC_offd_j=NULL; HYPRE_Complex *A_FC_diag_data, *A_FC_offd_data=NULL; HYPRE_Int num_cols_offd_A_FC; HYPRE_BigInt *col_map_offd_A_FC = NULL; hypre_ParCSRMatrix *A_FF; hypre_CSRMatrix *A_FF_diag, *A_FF_offd; HYPRE_Int *A_FF_diag_i, *A_FF_diag_j, *A_FF_offd_i, *A_FF_offd_j; HYPRE_Complex *A_FF_diag_data, *A_FF_offd_data; HYPRE_Int num_cols_offd_A_FF; HYPRE_BigInt *col_map_offd_A_FF = NULL; HYPRE_Int *fine_to_coarse; HYPRE_Int *fine_to_fine; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *fine_to_fine_offd = NULL; HYPRE_Int i, j, jj; HYPRE_Int startc, index; HYPRE_Int cpt, fpt, new_fpt, row, rowc; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *int_buf_data = NULL; HYPRE_BigInt *big_convert; HYPRE_BigInt *big_convert_offd = NULL; HYPRE_BigInt *big_buf_data = NULL; HYPRE_BigInt total_global_fpts, total_global_cpts, total_global_new_fpts; HYPRE_BigInt *fpts_starts, *new_fpts_starts; HYPRE_Int my_id, num_procs, num_sends; HYPRE_Int d_count_FF, d_count_FC, o_count_FF, o_count_FC; HYPRE_Int n_Fpts; HYPRE_Int n_new_Fpts; HYPRE_Int *cpt_array, *fpt_array, *new_fpt_array; HYPRE_Int start, stop; HYPRE_Int num_threads; num_threads = hypre_NumThreads(); /* MPI size and rank*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); fine_to_fine = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); big_convert = hypre_CTAlloc(HYPRE_BigInt, n_fine, HYPRE_MEMORY_HOST); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); fpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); new_fpt_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,jj,start,stop,row,rowc,cpt,new_fpt,fpt,d_count_FC,d_count_FF,o_count_FC,o_count_FF) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); start = (n_fine/num_threads)*my_thread_num; if (my_thread_num == num_threads-1) { stop = n_fine; } else { stop = (n_fine/num_threads)*(my_thread_num+1); } for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num+1]++; } else if (CF_marker[i] == -2) { new_fpt_array[my_thread_num+1]++; fpt_array[my_thread_num+1]++; } else { fpt_array[my_thread_num+1]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i=1; i < num_threads; i++) { cpt_array[i+1] += cpt_array[i]; fpt_array[i+1] += fpt_array[i]; new_fpt_array[i+1] += new_fpt_array[i]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cpt = cpt_array[my_thread_num]; fpt = fpt_array[my_thread_num]; for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { fine_to_coarse[i] = cpt++; fine_to_fine[i] = -1; } else { fine_to_fine[i] = fpt++; fine_to_coarse[i] = -1; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { HYPRE_BigInt big_Fpts, big_new_Fpts; n_Fpts = fpt_array[num_threads]; n_new_Fpts = new_fpt_array[num_threads]; big_Fpts = n_Fpts; big_new_Fpts = n_new_Fpts; fpts_starts = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); new_fpts_starts = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_MPI_Scan(&big_Fpts, fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); hypre_MPI_Scan(&big_new_Fpts, new_fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); fpts_starts[0] = fpts_starts[1] - big_Fpts; new_fpts_starts[0] = new_fpts_starts[1] - big_new_Fpts; if (my_id == num_procs - 1) { total_global_new_fpts = new_fpts_starts[1]; total_global_fpts = fpts_starts[1]; total_global_cpts = cpts_starts[1]; } hypre_MPI_Bcast(&total_global_new_fpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_global_fpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i=start; i < stop; i++) { if (CF_marker[i] > 0) { big_convert[i] = (HYPRE_BigInt)fine_to_coarse[i] + cpts_starts[0]; } else { big_convert[i] = (HYPRE_BigInt)fine_to_fine[i] + fpts_starts[0]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (num_cols_A_offd) { CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); big_convert_offd = hypre_CTAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_HOST); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); fine_to_fine_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); } index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); big_buf_data = hypre_CTAlloc(HYPRE_BigInt, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { int_buf_data[index] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; big_buf_data[index++] = big_convert[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = hypre_ParCSRCommHandleCreate( 21, comm_pkg, big_buf_data, big_convert_offd); hypre_ParCSRCommHandleDestroy(comm_handle); num_cols_offd_A_FC = 0; num_cols_offd_A_FF = 0; if (num_cols_A_offd) { for (i=0; i < num_cols_A_offd; i++) { if (CF_marker_offd[i] > 0) { fine_to_coarse_offd[i] = num_cols_offd_A_FC++; fine_to_fine_offd[i] = -1; } else { fine_to_fine_offd[i] = num_cols_offd_A_FF++; fine_to_coarse_offd[i] = -1; } } col_map_offd_A_FF = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A_FF, HYPRE_MEMORY_HOST); col_map_offd_A_FC = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A_FC, HYPRE_MEMORY_HOST); cpt = 0; fpt = 0; for (i=0; i < num_cols_A_offd; i++) { if (CF_marker_offd[i] > 0) { col_map_offd_A_FC[cpt++] = big_convert_offd[i]; } else { col_map_offd_A_FF[fpt++] = big_convert_offd[i]; } } } A_FF_diag_i = hypre_CTAlloc(HYPRE_Int,n_new_Fpts+1, memory_location_P); A_FC_diag_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); A_FF_offd_i = hypre_CTAlloc(HYPRE_Int,n_new_Fpts+1, memory_location_P); A_FC_offd_i = hypre_CTAlloc(HYPRE_Int,n_Fpts+1, memory_location_P); D_lambda = hypre_CTAlloc(HYPRE_Real, n_Fpts, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif d_count_FC = 0; d_count_FF = 0; o_count_FC = 0; o_count_FF = 0; row = new_fpt_array[my_thread_num]; rowc = fpt_array[my_thread_num]; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { row++; rowc++; d_count_FF++; /* account for diagonal element */ for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jj = S_diag_j[j]; if (CF_marker[jj] > 0) d_count_FC++; else d_count_FF++; } A_FF_diag_i[row] = d_count_FF; A_FC_diag_i[rowc] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jj = S_offd_j[j]; if (CF_marker_offd[jj] > 0) o_count_FC++; else o_count_FF++; } A_FF_offd_i[row] = o_count_FF; A_FC_offd_i[rowc] = o_count_FC; } else if (CF_marker[i] < 0) { rowc++; for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jj = S_diag_j[j]; if (CF_marker[jj] > 0) d_count_FC++; } A_FC_diag_i[rowc] = d_count_FC; for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jj = S_offd_j[j]; if (CF_marker_offd[jj] > 0) o_count_FC++; } A_FC_offd_i[rowc] = o_count_FC; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { HYPRE_Int fpt2, new_fpt2; for (i=1; i<num_threads+1; i++) { fpt = fpt_array[i]; new_fpt = new_fpt_array[i]; fpt2 = fpt_array[i-1]; new_fpt2 = new_fpt_array[i-1]; if (fpt != fpt2) { A_FC_diag_i[fpt] += A_FC_diag_i[fpt2]; A_FC_offd_i[fpt] += A_FC_offd_i[fpt2]; } if (new_fpt != new_fpt2) { A_FF_diag_i[new_fpt] += A_FF_diag_i[new_fpt2]; A_FF_offd_i[new_fpt] += A_FF_offd_i[new_fpt2]; } } row = new_fpt_array[num_threads]; rowc = fpt_array[num_threads]; d_count_FC = A_FC_diag_i[rowc]; d_count_FF = A_FF_diag_i[row]; o_count_FC = A_FC_offd_i[rowc]; o_count_FF = A_FF_offd_i[row]; A_FF_diag_j = hypre_CTAlloc(HYPRE_Int,d_count_FF, memory_location_P); A_FC_diag_j = hypre_CTAlloc(HYPRE_Int,d_count_FC, memory_location_P); A_FF_offd_j = hypre_CTAlloc(HYPRE_Int,o_count_FF, memory_location_P); A_FC_offd_j = hypre_CTAlloc(HYPRE_Int,o_count_FC, memory_location_P); A_FF_diag_data = hypre_CTAlloc(HYPRE_Real,d_count_FF, memory_location_P); A_FC_diag_data = hypre_CTAlloc(HYPRE_Real,d_count_FC, memory_location_P); A_FF_offd_data = hypre_CTAlloc(HYPRE_Real,o_count_FF, memory_location_P); A_FC_offd_data = hypre_CTAlloc(HYPRE_Real,o_count_FC, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif row = new_fpt_array[my_thread_num]; rowc = fpt_array[my_thread_num]; d_count_FC = A_FC_diag_i[rowc]; d_count_FF = A_FF_diag_i[row]; o_count_FC = A_FC_offd_i[rowc]; o_count_FF = A_FF_offd_i[row]; for (i=start; i < stop; i++) { if (CF_marker[i] == -2) { HYPRE_Int jS, jA; HYPRE_Real sum = 0; row++; jA = A_diag_i[i]; A_FF_diag_j[d_count_FF] = fine_to_fine[A_diag_j[jA]]; A_FF_diag_data[d_count_FF++] = A_diag_data[jA++]; for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jA = A_diag_i[i]+1; jS = S_diag_j[j]; while (A_diag_j[jA] != jS) jA++; if (CF_marker[S_diag_j[j]] > 0) { A_FC_diag_j[d_count_FC] = fine_to_coarse[A_diag_j[jA]]; A_FC_diag_data[d_count_FC++] = A_diag_data[jA++]; } else { sum += 1; D_lambda[rowc] += A_diag_data[jA]; A_FF_diag_j[d_count_FF] = fine_to_fine[A_diag_j[jA]]; A_FF_diag_data[d_count_FF++] = A_diag_data[jA++]; } } for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jA = A_offd_i[i]; jS = S_offd_j[j]; while (jS != A_offd_j[jA]) jA++; if (CF_marker_offd[S_offd_j[j]] > 0) { A_FC_offd_j[o_count_FC] = fine_to_coarse_offd[A_offd_j[jA]]; A_FC_offd_data[o_count_FC++] = A_offd_data[jA++]; } else { sum += 1; D_lambda[rowc] += A_offd_data[jA]; A_FF_offd_j[o_count_FF] = fine_to_fine_offd[A_offd_j[jA]]; A_FF_offd_data[o_count_FF++] = A_offd_data[jA++]; } } if (sum) D_lambda[rowc] = D_lambda[rowc]/sum; rowc++; A_FF_diag_i[row] = d_count_FF; A_FC_diag_i[rowc] = d_count_FC; A_FF_offd_i[row] = o_count_FF; A_FC_offd_i[rowc] = o_count_FC; } else if (CF_marker[i] < 0) { HYPRE_Int jS, jA; HYPRE_Real sum = 0; for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++) { jA = A_diag_i[i]+1; jS = S_diag_j[j]; while (A_diag_j[jA] != jS) jA++; if (CF_marker[S_diag_j[j]] > 0) { A_FC_diag_j[d_count_FC] = fine_to_coarse[A_diag_j[jA]]; A_FC_diag_data[d_count_FC++] = A_diag_data[jA++]; } else { sum += 1; D_lambda[rowc] += A_diag_data[jA]; } } for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++) { jA = A_offd_i[i]; jS = S_offd_j[j]; while (jS != A_offd_j[jA]) jA++; if (CF_marker_offd[S_offd_j[j]] > 0) { A_FC_offd_j[o_count_FC] = fine_to_coarse_offd[A_offd_j[jA]]; A_FC_offd_data[o_count_FC++] = A_offd_data[jA++]; } else { sum += 1; D_lambda[rowc] += A_offd_data[jA]; } } if (sum) D_lambda[rowc] = D_lambda[rowc]/sum; rowc++; A_FC_diag_i[rowc] = d_count_FC; A_FC_offd_i[rowc] = o_count_FC; } } } /*end parallel region */ A_FC = hypre_ParCSRMatrixCreate(comm, total_global_fpts, total_global_cpts, fpts_starts, cpts_starts, num_cols_offd_A_FC, A_FC_diag_i[n_Fpts], A_FC_offd_i[n_Fpts]); A_FF = hypre_ParCSRMatrixCreate(comm, total_global_new_fpts, total_global_fpts, new_fpts_starts, fpts_starts, num_cols_offd_A_FF, A_FF_diag_i[n_new_Fpts], A_FF_offd_i[n_new_Fpts]); A_FC_diag = hypre_ParCSRMatrixDiag(A_FC); hypre_CSRMatrixData(A_FC_diag) = A_FC_diag_data; hypre_CSRMatrixI(A_FC_diag) = A_FC_diag_i; hypre_CSRMatrixJ(A_FC_diag) = A_FC_diag_j; A_FC_offd = hypre_ParCSRMatrixOffd(A_FC); hypre_CSRMatrixData(A_FC_offd) = A_FC_offd_data; hypre_CSRMatrixI(A_FC_offd) = A_FC_offd_i; hypre_CSRMatrixJ(A_FC_offd) = A_FC_offd_j; hypre_ParCSRMatrixOwnsRowStarts(A_FC) = 1; hypre_ParCSRMatrixOwnsColStarts(A_FC) = 0; hypre_ParCSRMatrixColMapOffd(A_FC) = col_map_offd_A_FC; hypre_CSRMatrixMemoryLocation(A_FC_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(A_FC_offd) = memory_location_P; A_FF_diag = hypre_ParCSRMatrixDiag(A_FF); hypre_CSRMatrixData(A_FF_diag) = A_FF_diag_data; hypre_CSRMatrixI(A_FF_diag) = A_FF_diag_i; hypre_CSRMatrixJ(A_FF_diag) = A_FF_diag_j; A_FF_offd = hypre_ParCSRMatrixOffd(A_FF); hypre_CSRMatrixData(A_FF_offd) = A_FF_offd_data; hypre_CSRMatrixI(A_FF_offd) = A_FF_offd_i; hypre_CSRMatrixJ(A_FF_offd) = A_FF_offd_j; hypre_ParCSRMatrixOwnsRowStarts(A_FF) = 1; hypre_ParCSRMatrixOwnsColStarts(A_FF) = 0; hypre_ParCSRMatrixColMapOffd(A_FF) = col_map_offd_A_FF; hypre_CSRMatrixMemoryLocation(A_FF_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(A_FF_offd) = memory_location_P; hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(big_convert, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_fine_offd, HYPRE_MEMORY_HOST); hypre_TFree(big_convert_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(big_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(fpt_array, HYPRE_MEMORY_HOST); hypre_TFree(new_fpt_array, HYPRE_MEMORY_HOST); *A_FC_ptr = A_FC; *A_FF_ptr = A_FF; *D_lambda_ptr = D_lambda; return hypre_error_flag; }
ZQ_CNN_MTCNN_ncnn.h
#ifndef _ZQ_CNN_MTCNN_H_ #define _ZQ_CNN_MTCNN_H_ #pragma once #include "net.h" #include <algorithm> #include <omp.h> #ifndef __max #define __max(x,y) ((x>y)?(x):(y)) #endif #ifndef __min #define __min(x,y) ((x<y)?(x):(y)) #endif namespace ZQ { class ZQ_CNN_MTCNN_ncnn { public: class ZQ_CNN_BBox { public: float score; int row1; int col1; int row2; int col2; float area; bool exist; bool need_check_overlap_count; float ppoint[10]; float regreCoord[4]; ZQ_CNN_BBox() { memset(this, 0, sizeof(ZQ_CNN_BBox)); } ~ZQ_CNN_BBox() {} bool ReadFromBinary(FILE* in) { if (fread(this, sizeof(ZQ_CNN_BBox), 1, in) != 1) return false; return true; } bool WriteBinary(FILE* out) const { if (fwrite(this, sizeof(ZQ_CNN_BBox), 1, out) != 1) return false; return true; } }; class ZQ_CNN_BBox106 { public: float score; int row1; int col1; int row2; int col2; float area; bool exist; bool need_check_overlap_count; float ppoint[212]; float regreCoord[4]; ZQ_CNN_BBox106() { memset(this, 0, sizeof(ZQ_CNN_BBox106)); } ~ZQ_CNN_BBox106() {} bool ReadFromBinary(FILE* in) { if (fread(this, sizeof(ZQ_CNN_BBox106), 1, in) != 1) return false; return true; } bool WriteBinary(FILE* out) const { if (fwrite(this, sizeof(ZQ_CNN_BBox106), 1, out) != 1) return false; return true; } }; class ZQ_CNN_OrderScore { public: float score; int oriOrder; ZQ_CNN_OrderScore() { memset(this, 0, sizeof(ZQ_CNN_OrderScore)); } }; static bool _cmp_score(const ZQ_CNN_OrderScore& lsh, const ZQ_CNN_OrderScore& rsh) { return lsh.score < rsh.score; } static void _nms(std::vector<ZQ_CNN_BBox> &boundingBox, std::vector<ZQ_CNN_OrderScore> &bboxScore, const float overlap_threshold, const std::string& modelname = "Union", int overlap_count_thresh = 0) { if (boundingBox.empty() || overlap_threshold >= 1.0) { return; } std::vector<int> heros; std::vector<int> overlap_num; //sort the score sort(bboxScore.begin(), bboxScore.end(), _cmp_score); int order = 0; float IOU = 0; float maxX = 0; float maxY = 0; float minX = 0; float minY = 0; while (bboxScore.size() > 0) { order = bboxScore.back().oriOrder; bboxScore.pop_back(); if (order < 0)continue; heros.push_back(order); int cur_overlap = 0; boundingBox[order].exist = false;//delete it int box_num = boundingBox.size(); for (int num = 0; num < box_num; num++) { if (boundingBox[num].exist) { //the iou maxY = __max(boundingBox[num].row1, boundingBox[order].row1); maxX = __max(boundingBox[num].col1, boundingBox[order].col1); minY = __min(boundingBox[num].row2, boundingBox[order].row2); minX = __min(boundingBox[num].col2, boundingBox[order].col2); //maxX1 and maxY1 reuse maxX = __max(minX - maxX + 1, 0); maxY = __max(minY - maxY + 1, 0); //IOU reuse for the area of two bbox IOU = maxX * maxY; float area1 = boundingBox[num].area; float area2 = boundingBox[order].area; if (!modelname.compare("Union")) IOU = IOU / (area1 + area2 - IOU); else if (!modelname.compare("Min")) { IOU = IOU / __min(area1, area2); } if (IOU > overlap_threshold) { cur_overlap++; boundingBox[num].exist = false; for (std::vector<ZQ_CNN_OrderScore>::iterator it = bboxScore.begin(); it != bboxScore.end(); it++) { if ((*it).oriOrder == num) { (*it).oriOrder = -1; break; } } } } } overlap_num.push_back(cur_overlap); } for (int i = 0; i < heros.size(); i++) { if (!boundingBox[heros[i]].need_check_overlap_count || overlap_num[i] >= overlap_count_thresh) boundingBox[heros[i]].exist = true; } //clear exist= false; for (int i = boundingBox.size() - 1; i >= 0; i--) { if (!boundingBox[i].exist) { boundingBox.erase(boundingBox.begin() + i); } } } static void _refine_and_square_bbox(std::vector<ZQ_CNN_BBox> &vecBbox, const int width, const int height, bool square = true) { float bbw = 0, bbh = 0, bboxSize = 0; float h = 0, w = 0; float x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (std::vector<ZQ_CNN_BBox>::iterator it = vecBbox.begin(); it != vecBbox.end(); it++) { if ((*it).exist) { bbh = (*it).row2 - (*it).row1 + 1; bbw = (*it).col2 - (*it).col1 + 1; y1 = (*it).row1 + (*it).regreCoord[1] * bbh; x1 = (*it).col1 + (*it).regreCoord[0] * bbw; y2 = (*it).row2 + (*it).regreCoord[3] * bbh; x2 = (*it).col2 + (*it).regreCoord[2] * bbw; w = x2 - x1 + 1; h = y2 - y1 + 1; if (square) { bboxSize = (h > w) ? h : w; y1 = y1 + h*0.5 - bboxSize*0.5; x1 = x1 + w*0.5 - bboxSize*0.5; (*it).row2 = round(y1 + bboxSize - 1); (*it).col2 = round(x1 + bboxSize - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); } else { (*it).row2 = round(y1 + h - 1); (*it).col2 = round(x1 + w - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); } //boundary check /*if ((*it).row1 < 0)(*it).row1 = 0; if ((*it).col1 < 0)(*it).col1 = 0; if ((*it).row2 > height)(*it).row2 = height - 1; if ((*it).col2 > width)(*it).col2 = width - 1;*/ it->area = (it->row2 - it->row1)*(it->col2 - it->col1); } } } static void _square_bbox(std::vector<ZQ_CNN_BBox> &vecBbox, const int width, const int height) { float bbw = 0, bbh = 0, bboxSize = 0; float h = 0, w = 0; float x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (std::vector<ZQ_CNN_BBox>::iterator it = vecBbox.begin(); it != vecBbox.end(); it++) { if ((*it).exist) { y1 = (*it).row1; x1 = (*it).col1; h = (*it).row2 - (*it).row1 + 1; w = (*it).col2 - (*it).col1 + 1; bboxSize = (h > w) ? h : w; y1 = y1 + h*0.5 - bboxSize*0.5; x1 = x1 + w*0.5 - bboxSize*0.5; (*it).row2 = round(y1 + bboxSize - 1); (*it).col2 = round(x1 + bboxSize - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); //boundary check /*if ((*it).row1 < 0)(*it).row1 = 0; if ((*it).col1 < 0)(*it).col1 = 0; if ((*it).row2 > height)(*it).row2 = height - 1; if ((*it).col2 > width)(*it).col2 = width - 1;*/ it->area = (it->row2 - it->row1)*(it->col2 - it->col1); } } } public: ZQ_CNN_MTCNN_ncnn() { min_size = 60; thresh[0] = 0.6; thresh[1] = 0.7; thresh[2] = 0.7; nms_thresh[0] = 0.6; nms_thresh[1] = 0.7; nms_thresh[2] = 0.7; width = 0; height = 0; factor = 0.709; pnet_overlap_thresh_count = 4; pnet_size = 12; pnet_stride = 2; special_handle_very_big_face = false; force_run_pnet_multithread = false; show_debug_info = false; limit_r_num = 0; limit_o_num = 0; limit_l_num = 0; } ~ZQ_CNN_MTCNN_ncnn() { } private: std::vector<ncnn::Net> pnet, rnet, onet, lnet; std::vector<ncnn::UnlockedPoolAllocator> g_blob_pool_allocator; std::vector<ncnn::UnlockedPoolAllocator> g_workspace_pool_allocator; bool has_lnet; int thread_num; float thresh[3], nms_thresh[3]; int min_size; int width, height; float factor; int pnet_overlap_thresh_count; int pnet_size; int pnet_stride; int rnet_size; int onet_size; int lnet_size; bool special_handle_very_big_face; bool do_landmark; float early_accept_thresh; float nms_thresh_per_scale; bool force_run_pnet_multithread; std::vector<float> scales; std::vector<ncnn::Mat> pnet_images; ncnn::Mat input, rnet_image, onet_image; bool show_debug_info; int limit_r_num; int limit_o_num; int limit_l_num; public: void TurnOnShowDebugInfo() { show_debug_info = true; } void TurnOffShowDebugInfo() { show_debug_info = false; } void SetLimit(int limit_r = 0, int limit_o = 0, int limit_l = 0) { limit_r_num = limit_r; limit_o_num = limit_o; limit_l_num = limit_l; } private: static bool _load(ncnn::Net& net, const std::string& param, const std::string& model) { if (-1 == net.load_param(param.c_str())) return false; if (-1 == net.load_model(model.c_str())) return false; return true; } static bool _roi(const ncnn::Mat& input, ncnn::Mat& output, int off_x, int off_y, int width, int height) { if (off_x >= 0 && off_y >= 0 && width > 0 && height > 0 && off_x + width <= input.w && off_y + height <= input.h) { copy_cut_border(input, output, off_y, input.h - off_y - height, off_x, input.w - off_x - width); return true; } else return false; } public: bool Init(const std::string& pnet_param, const std::string& pnet_model, const std::string& rnet_param, const std::string& rnet_model, const std::string& onet_param, const std::string& onet_model, int thread_num = 1, bool has_lnet = false, const std::string& lnet_param = "", const std::string& lnet_model = "") { if (thread_num < 1) force_run_pnet_multithread = true; else force_run_pnet_multithread = false; thread_num = __max(1, thread_num); pnet.resize(thread_num); rnet.resize(thread_num); onet.resize(thread_num); this->has_lnet = has_lnet; if (has_lnet) { lnet.resize(thread_num); } g_blob_pool_allocator.resize(thread_num); g_workspace_pool_allocator.resize(thread_num); bool ret = true; for (int i = 0; i < thread_num; i++) { ret = _load(pnet[i], pnet_param, pnet_model) && _load(rnet[i], rnet_param, rnet_model) && _load(onet[i], onet_param, onet_model); if (has_lnet && ret) ret = _load(lnet[i], lnet_param, lnet_model); if (!ret) break; } if (!ret) { pnet.clear(); rnet.clear(); onet.clear(); if (has_lnet) lnet.clear(); this->thread_num = 0; } else this->thread_num = thread_num; for (int i = 0; i < thread_num; i++) { g_blob_pool_allocator[i].clear(); g_workspace_pool_allocator[i].clear(); } return ret; } void SetPara(int w, int h, int min_face_size = 60, float pthresh = 0.6, float rthresh = 0.7, float othresh = 0.7, float nms_pthresh = 0.6, float nms_rthresh = 0.7, float nms_othresh = 0.7, float scale_factor = 0.709, int pnet_overlap_thresh_count = 4, int pnet_size = 12, int pnet_stride = 2, bool special_handle_very_big_face = false, bool do_landmark = true, float early_accept_thresh = 1.00) { min_size = __max(pnet_size, min_face_size); thresh[0] = __max(0.1, pthresh); thresh[1] = __max(0.1, rthresh); thresh[2] = __max(0.1, othresh); nms_thresh[0] = __max(0.1, nms_pthresh); nms_thresh[1] = __max(0.1, nms_rthresh); nms_thresh[2] = __max(0.1, nms_othresh); scale_factor = __max(0.5, __min(0.97, scale_factor)); this->pnet_overlap_thresh_count = __max(0, pnet_overlap_thresh_count); this->pnet_size = pnet_size; this->pnet_stride = pnet_stride; this->special_handle_very_big_face = special_handle_very_big_face; this->do_landmark = do_landmark; this->early_accept_thresh = early_accept_thresh; if (pnet_size == 20 && pnet_stride == 4) nms_thresh_per_scale = 0.45; else nms_thresh_per_scale = 0.495; if (width != w || height != h || factor != scale_factor) { scales.clear(); pnet_images.clear(); width = w; height = h; float minside = __min(width, height); int MIN_DET_SIZE = pnet_size; float m = (float)MIN_DET_SIZE / min_size; minside *= m; while (minside > MIN_DET_SIZE) { scales.push_back(m); minside *= factor; m *= factor; } minside = __min(width, height); int count = scales.size(); for (int i = scales.size() - 1; i >= 0; i--) { if (ceil(scales[i] * minside) <= pnet_size) { count--; } } if (special_handle_very_big_face) { if (count > 2) count--; scales.resize(count); if (count > 0) { float last_size = ceil(scales[count - 1] * minside); for (int tmp_size = last_size - 1; tmp_size >= pnet_size + 1; tmp_size -= 2) { scales.push_back((float)tmp_size / minside); count++; } } scales.push_back((float)pnet_size / minside); count++; } else { scales.push_back((float)pnet_size / minside); count++; } pnet_images.resize(count); } } bool Find(const unsigned char* bgr_img, int _width, int _height, int _widthStep, std::vector<ZQ_CNN_BBox>& results) { double t1 = omp_get_wtime(); std::vector<ZQ_CNN_BBox> firstBbox, secondBbox, thirdBbox; if (!_Pnet_stage(bgr_img, _width, _height, _widthStep, firstBbox)) return false; //results = firstBbox; //return true; if (limit_r_num > 0) { _select(firstBbox, limit_r_num, _width, _height); } double t2 = omp_get_wtime(); if (!_Rnet_stage(firstBbox, secondBbox)) return false; //results = secondBbox; //return true; if (limit_o_num > 0) { _select(secondBbox, limit_o_num, _width, _height); } double t3 = omp_get_wtime(); if (!_Onet_stage(secondBbox, results)) return false; double t4 = omp_get_wtime(); if (show_debug_info) { printf("final found num: %d\n", (int)results.size()); printf("total cost: %.3f ms (P: %.3f ms, R: %.3f ms, O: %.3f ms)\n", 1000 * (t4 - t1), 1000 * (t2 - t1), 1000 * (t3 - t2), 1000 * (t4 - t3)); } return true; } private: void _compute_Pnet_single_thread(std::vector<std::vector<float> >& maps, std::vector<int>& mapH, std::vector<int>& mapW) { int scale_num = 0; for (int i = 0; i < scales.size(); i++) { int changedH = (int)ceil(height*scales[i]); int changedW = (int)ceil(width*scales[i]); if (changedH < pnet_size || changedW < pnet_size) continue; scale_num++; mapH.push_back((changedH - pnet_size) / pnet_stride + 1); mapW.push_back((changedW - pnet_size) / pnet_stride + 1); } maps.resize(scale_num); for (int i = 0; i < scale_num; i++) { maps[i].resize(mapH[i] * mapW[i]); } for (int i = 0; i < scale_num; i++) { int changedH = (int)ceil(height*scales[i]); int changedW = (int)ceil(width*scales[i]); float cur_scale_x = (float)width / changedW; float cur_scale_y = (float)height / changedH; double t10 = omp_get_wtime(); if (scales[i] != 1) { ncnn::resize_bilinear(input, pnet_images[i], changedW, changedH); } double t11 = omp_get_wtime(); ncnn::Extractor ex = pnet[0].create_extractor(); ex.set_light_mode(true); ex.set_blob_allocator(&g_blob_pool_allocator[0]); ex.set_workspace_allocator(&g_workspace_pool_allocator[0]); ex.set_num_threads(1); if (scales[i] == 1) ex.input("data", input); else ex.input("data", pnet_images[i]); ncnn::Mat score, location; ex.extract("prob1", score); ex.extract("conv4-2", location); double t12 = omp_get_wtime(); if (show_debug_info) printf("Pnet [%d]: resolution [%dx%d], resize:%.3f ms, cost:%.3f ms\n", i, changedW, changedH, 1000 * (t11 - t10), 1000 * (t12 - t11)); //score p float *p = score.channel(1); int scoreH = score.h; int scoreW = score.w; for (int row = 0; row < scoreH; row++) { for (int col = 0; col < scoreW; col++) { if (row < mapH[i] && col < mapW[i]) maps[i][row*mapW[i] + col] = *p; p++; } } } } void _compute_Pnet_multi_thread(std::vector<std::vector<float> >& maps, std::vector<int>& mapH, std::vector<int>& mapW) { if (thread_num <= 1) { for (int i = 0; i < scales.size(); i++) { int changedH = (int)ceil(height*scales[i]); int changedW = (int)ceil(width*scales[i]); if (changedH < pnet_size || changedW < pnet_size) continue; if (scales[i] != 1) { ncnn::resize_bilinear(input, pnet_images[i], changedW, changedH); } } } else { #pragma omp parallel for num_threads(thread_num) for (int i = 0; i < scales.size(); i++) { int changedH = (int)ceil(height*scales[i]); int changedW = (int)ceil(width*scales[i]); if (changedH < pnet_size || changedW < pnet_size) continue; if (scales[i] != 1) { ncnn::resize_bilinear(input, pnet_images[i], changedW, changedH); } } } int scale_num = 0; for (int i = 0; i < scales.size(); i++) { int changedH = (int)ceil(height*scales[i]); int changedW = (int)ceil(width*scales[i]); if (changedH < pnet_size || changedW < pnet_size) continue; scale_num++; mapH.push_back((changedH - pnet_size) / pnet_stride + 1); mapW.push_back((changedW - pnet_size) / pnet_stride + 1); } maps.resize(scale_num); for (int i = 0; i < scale_num; i++) { maps[i].resize(mapH[i] * mapW[i]); } std::vector<int> task_rect_off_x; std::vector<int> task_rect_off_y; std::vector<int> task_rect_width; std::vector<int> task_rect_height; std::vector<float> task_scale; std::vector<int> task_scale_id; int stride = pnet_stride; const int block_size = 64 * stride; int cellsize = pnet_size; int border_size = cellsize - stride; int overlap_border_size = cellsize / stride; int jump_size = block_size - border_size; for (int i = 0; i < scales.size(); i++) { int changeH = (int)ceil(height*scales[i]); int changeW = (int)ceil(width*scales[i]); if (changeH < pnet_size || changeW < pnet_size) continue; int block_H_num = 0; int block_W_num = 0; int start = 0; while (start < changeH) { block_H_num++; if (start + block_size >= changeH) break; start += jump_size; } start = 0; while (start < changeW) { block_W_num++; if (start + block_size >= changeW) break; start += jump_size; } for (int s = 0; s < block_H_num; s++) { for (int t = 0; t < block_W_num; t++) { int rect_off_x = t * jump_size; int rect_off_y = s * jump_size; int rect_width = __min(changeW, rect_off_x + block_size) - rect_off_x; int rect_height = __min(changeH, rect_off_y + block_size) - rect_off_y; if (rect_width >= cellsize && rect_height >= cellsize) { task_rect_off_x.push_back(rect_off_x); task_rect_off_y.push_back(rect_off_y); task_rect_width.push_back(rect_width); task_rect_height.push_back(rect_height); task_scale.push_back(scales[i]); task_scale_id.push_back(i); } } } } // int task_num = task_scale.size(); std::vector<ncnn::Mat> task_pnet_images(thread_num); if (thread_num <= 1) { for (int i = 0; i < task_num; i++) { int thread_id = omp_get_thread_num(); int scale_id = task_scale_id[i]; float cur_scale = task_scale[i]; int i_rect_off_x = task_rect_off_x[i]; int i_rect_off_y = task_rect_off_y[i]; int i_rect_width = task_rect_width[i]; int i_rect_height = task_rect_height[i]; if (scale_id == 0 && scales[0] == 1) { if (!_roi(input, task_pnet_images[thread_id], i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height)) continue; } else { if (!_roi(pnet_images[scale_id], task_pnet_images[thread_id], i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height)) continue; } ncnn::Extractor ex = pnet[thread_id].create_extractor(); ex.set_light_mode(true); ex.set_blob_allocator(&g_blob_pool_allocator[0]); ex.set_workspace_allocator(&g_workspace_pool_allocator[0]); ex.set_num_threads(1); ex.input("data", task_pnet_images[thread_id]); ncnn::Mat score, location; ex.extract("prob1", score); ex.extract("conv4-2", location); //score p float *p = score.channel(1); int scoreH = score.h; int scoreW = score.w; ZQ_CNN_BBox bbox; ZQ_CNN_OrderScore order; for (int row = 0; row < scoreH; row++) { for (int col = 0; col < scoreW; col++) { int real_row = row + i_rect_off_y / stride; int real_col = col + i_rect_off_x / stride; if (real_row < mapH[scale_id] && real_col < mapW[scale_id]) maps[scale_id][real_row*mapW[scale_id] + real_col] = *p; p++; } } } } else { #pragma omp parallel for num_threads(thread_num) for (int i = 0; i < task_num; i++) { int thread_id = omp_get_thread_num(); int scale_id = task_scale_id[i]; float cur_scale = task_scale[i]; int i_rect_off_x = task_rect_off_x[i]; int i_rect_off_y = task_rect_off_y[i]; int i_rect_width = task_rect_width[i]; int i_rect_height = task_rect_height[i]; if (scale_id == 0 && scales[0] == 1) { if (!_roi(input, task_pnet_images[thread_id], i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height)) continue; } else { if (!_roi(pnet_images[scale_id], task_pnet_images[thread_id], i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height)) continue; } ncnn::Extractor ex = pnet[thread_id].create_extractor(); ex.set_light_mode(true); ex.set_blob_allocator(&g_blob_pool_allocator[thread_id]); ex.set_workspace_allocator(&g_workspace_pool_allocator[thread_id]); ex.input("data", task_pnet_images[thread_id]); ncnn::Mat score, location; ex.extract("prob1", score); ex.extract("conv4-2", location); //score p float *p = score.channel(1); int scoreH = score.h; int scoreW = score.w; ZQ_CNN_BBox bbox; ZQ_CNN_OrderScore order; for (int row = 0; row < scoreH; row++) { for (int col = 0; col < scoreW; col++) { int real_row = row + i_rect_off_y / stride; int real_col = col + i_rect_off_x / stride; if (real_row < mapH[scale_id] && real_col < mapW[scale_id]) maps[scale_id][real_row*mapW[scale_id] + real_col] = *p; p++; } } } } } bool _Pnet_stage(const unsigned char* bgr_img, int _width, int _height, int _widthStep, std::vector<ZQ_CNN_BBox>& firstBbox) { if (thread_num <= 0) return false; double t1 = omp_get_wtime(); firstBbox.clear(); if (width != _width || height != _height) return false; input = ncnn::Mat::from_pixels(bgr_img, ncnn::Mat::PIXEL_BGR, _width, _height); float mean_vals[3] = { 127.5,127.5,127.5 }; float norm_vals[3] = { 1.0 / 128,1.0 / 128,1.0 / 128 }; input.substract_mean_normalize(mean_vals, norm_vals); double t2 = omp_get_wtime(); if (show_debug_info) printf("convert cost: %.3f ms\n", 1000 * (t2 - t1)); std::vector<std::vector<float> > maps; std::vector<int> mapH; std::vector<int> mapW; if (thread_num == 1 && !force_run_pnet_multithread) { _compute_Pnet_single_thread(maps, mapH, mapW); } else { _compute_Pnet_multi_thread(maps, mapH, mapW); } ZQ_CNN_OrderScore order; std::vector<std::vector<ZQ_CNN_BBox> > bounding_boxes(scales.size()); std::vector<std::vector<ZQ_CNN_OrderScore> > bounding_scores(scales.size()); const int block_size = 32; int stride = pnet_stride; int cellsize = pnet_size; int border_size = cellsize / stride; for (int i = 0; i < maps.size(); i++) { double t13 = omp_get_wtime(); int changedH = (int)ceil(height*scales[i]); int changedW = (int)ceil(width*scales[i]); if (changedH < pnet_size || changedW < pnet_size) continue; float cur_scale_x = (float)width / changedW; float cur_scale_y = (float)height / changedH; int count = 0; //score p int scoreH = mapH[i]; int scoreW = mapW[i]; const float *p = &maps[i][0]; if (scoreW <= block_size && scoreH < block_size) { ZQ_CNN_BBox bbox; ZQ_CNN_OrderScore order; for (int row = 0; row < scoreH; row++) { for (int col = 0; col < scoreW; col++) { if (*p > thresh[0]) { bbox.score = *p; order.score = *p; order.oriOrder = count; bbox.row1 = stride*row; bbox.col1 = stride*col; bbox.row2 = stride*row + cellsize; bbox.col2 = stride*col + cellsize; bbox.exist = true; bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1); bbox.need_check_overlap_count = (row >= border_size && row < scoreH - border_size) && (col >= border_size && col < scoreW - border_size); bounding_boxes[i].push_back(bbox); bounding_scores[i].push_back(order); count++; } p++; } } int before_count = bounding_boxes[i].size(); _nms(bounding_boxes[i], bounding_scores[i], nms_thresh_per_scale, "Union", pnet_overlap_thresh_count); int after_count = bounding_boxes[i].size(); for (int j = 0; j < after_count; j++) { ZQ_CNN_BBox& bbox = bounding_boxes[i][j]; bbox.row1 = round(bbox.row1 *cur_scale_y); bbox.col1 = round(bbox.col1 *cur_scale_x); bbox.row2 = round(bbox.row2 *cur_scale_y); bbox.col2 = round(bbox.col2 *cur_scale_x); bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1); } double t14 = omp_get_wtime(); if (show_debug_info) printf("nms cost: %.3f ms, (%d-->%d)\n", 1000 * (t14 - t13), before_count, after_count); } else { int before_count = 0, after_count = 0; int block_H_num = __max(1, scoreH / block_size); int block_W_num = __max(1, scoreW / block_size); int block_num = block_H_num*block_W_num; int width_per_block = scoreW / block_W_num; int height_per_block = scoreH / block_H_num; std::vector<std::vector<ZQ_CNN_BBox> > tmp_bounding_boxes(block_num); std::vector<std::vector<ZQ_CNN_OrderScore> > tmp_bounding_scores(block_num); std::vector<int> block_start_w(block_num), block_end_w(block_num); std::vector<int> block_start_h(block_num), block_end_h(block_num); for (int bh = 0; bh < block_H_num; bh++) { for (int bw = 0; bw < block_W_num; bw++) { int bb = bh * block_W_num + bw; block_start_w[bb] = (bw == 0) ? 0 : (bw*width_per_block - border_size); block_end_w[bb] = (bw == block_num - 1) ? scoreW : ((bw + 1)*width_per_block); block_start_h[bb] = (bh == 0) ? 0 : (bh*height_per_block - border_size); block_end_h[bb] = (bh == block_num - 1) ? scoreH : ((bh + 1)*height_per_block); } } int chunk_size = 1; if (thread_num <= 1) { for (int bb = 0; bb < block_num; bb++) { ZQ_CNN_BBox bbox; ZQ_CNN_OrderScore order; int count = 0; for (int row = block_start_h[bb]; row < block_end_h[bb]; row++) { p = &maps[i][0] + row*scoreW + block_start_w[bb]; for (int col = block_start_w[bb]; col < block_end_w[bb]; col++) { if (*p > thresh[0]) { bbox.score = *p; order.score = *p; order.oriOrder = count; bbox.row1 = stride*row; bbox.col1 = stride*col; bbox.row2 = stride*row + cellsize; bbox.col2 = stride*col + cellsize; bbox.exist = true; bbox.need_check_overlap_count = (row >= border_size && row < scoreH - border_size) && (col >= border_size && col < scoreW - border_size); bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1); tmp_bounding_boxes[bb].push_back(bbox); tmp_bounding_scores[bb].push_back(order); count++; } p++; } } int tmp_before_count = tmp_bounding_boxes[bb].size(); _nms(tmp_bounding_boxes[bb], tmp_bounding_scores[bb], nms_thresh_per_scale, "Union", pnet_overlap_thresh_count); int tmp_after_count = tmp_bounding_boxes[bb].size(); before_count += tmp_before_count; after_count += tmp_after_count; } } else { #pragma omp parallel for schedule(dynamic, chunk_size) num_threads(thread_num) for (int bb = 0; bb < block_num; bb++) { ZQ_CNN_BBox bbox; ZQ_CNN_OrderScore order; int count = 0; for (int row = block_start_h[bb]; row < block_end_h[bb]; row++) { const float* p = &maps[i][0] + row*scoreW + block_start_w[bb]; for (int col = block_start_w[bb]; col < block_end_w[bb]; col++) { if (*p > thresh[0]) { bbox.score = *p; order.score = *p; order.oriOrder = count; bbox.row1 = stride*row; bbox.col1 = stride*col; bbox.row2 = stride*row + cellsize; bbox.col2 = stride*col + cellsize; bbox.exist = true; bbox.need_check_overlap_count = (row >= border_size && row < scoreH - border_size) && (col >= border_size && col < scoreW - border_size); bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1); tmp_bounding_boxes[bb].push_back(bbox); tmp_bounding_scores[bb].push_back(order); count++; } p++; } } int tmp_before_count = tmp_bounding_boxes[bb].size(); _nms(tmp_bounding_boxes[bb], tmp_bounding_scores[bb], nms_thresh_per_scale, "Union", pnet_overlap_thresh_count); int tmp_after_count = tmp_bounding_boxes[bb].size(); before_count += tmp_before_count; after_count += tmp_after_count; } } count = 0; for (int bb = 0; bb < block_num; bb++) { std::vector<ZQ_CNN_BBox>::iterator it = tmp_bounding_boxes[bb].begin(); for (; it != tmp_bounding_boxes[bb].end(); it++) { if ((*it).exist) { bounding_boxes[i].push_back(*it); order.score = (*it).score; order.oriOrder = count; bounding_scores[i].push_back(order); count++; } } } //ZQ_CNN_BBoxUtils::_nms(bounding_boxes[i], bounding_scores[i], nms_thresh_per_scale, "Union", 0); after_count = bounding_boxes[i].size(); for (int j = 0; j < after_count; j++) { ZQ_CNN_BBox& bbox = bounding_boxes[i][j]; bbox.row1 = round(bbox.row1 *cur_scale_y); bbox.col1 = round(bbox.col1 *cur_scale_x); bbox.row2 = round(bbox.row2 *cur_scale_y); bbox.col2 = round(bbox.col2 *cur_scale_x); bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1); } double t14 = omp_get_wtime(); if (show_debug_info) printf("nms cost: %.3f ms, (%d-->%d)\n", 1000 * (t14 - t13), before_count, after_count); } } std::vector<ZQ_CNN_OrderScore> firstOrderScore; int count = 0; for (int i = 0; i < scales.size(); i++) { std::vector<ZQ_CNN_BBox>::iterator it = bounding_boxes[i].begin(); for (; it != bounding_boxes[i].end(); it++) { if ((*it).exist) { firstBbox.push_back(*it); order.score = (*it).score; order.oriOrder = count; firstOrderScore.push_back(order); count++; } } } //the first stage's nms if (count < 1) return false; double t15 = omp_get_wtime(); _nms(firstBbox, firstOrderScore, nms_thresh[0], "Union", 0); _refine_and_square_bbox(firstBbox, width, height, true); double t16 = omp_get_wtime(); if (show_debug_info) printf("nms cost: %.3f ms\n", 1000 * (t16 - t15)); if (show_debug_info) printf("first stage candidate count: %d\n", count); double t3 = omp_get_wtime(); if (show_debug_info) printf("stage 1: cost %.3f ms\n", 1000 * (t3 - t2)); return true; } bool _Rnet_stage(std::vector<ZQ_CNN_BBox>& firstBbox, std::vector<ZQ_CNN_BBox>& secondBbox) { double t3 = omp_get_wtime(); secondBbox.clear(); std::vector<ZQ_CNN_BBox>::iterator it = firstBbox.begin(); std::vector<ZQ_CNN_OrderScore> secondScore; std::vector<int> src_off_x, src_off_y, src_rect_w, src_rect_h; int r_count = 0; for (; it != firstBbox.end(); it++) { if ((*it).exist) { int off_x = it->col1; int off_y = it->row1; int rect_w = it->col2 - off_x; int rect_h = it->row2 - off_y; if (/*off_x < 0 || off_x + rect_w > width || off_y < 0 || off_y + rect_h > height ||*/ rect_w <= 0.5*min_size || rect_h <= 0.5*min_size) { (*it).exist = false; continue; } else { src_off_x.push_back(off_x); src_off_y.push_back(off_y); src_rect_w.push_back(rect_w); src_rect_h.push_back(rect_h); r_count++; secondBbox.push_back(*it); } } } secondBbox.resize(r_count); if (thread_num <= 1) { for (int pp = 0; pp < r_count; pp++) { ncnn::Mat task_rnet_images; ncnn::Mat tempIm; copy_cut_border(input, tempIm, src_off_y[pp], input.h - src_off_y[pp] - src_rect_h[pp], src_off_x[pp], input.w - src_off_x[pp] - src_rect_w[pp]); resize_bilinear(tempIm, task_rnet_images, 24, 24); ncnn::Extractor ex = rnet[0].create_extractor(); ex.set_light_mode(true); ex.set_blob_allocator(&g_blob_pool_allocator[0]); ex.set_workspace_allocator(&g_workspace_pool_allocator[0]); ex.set_num_threads(1); ex.input("data", task_rnet_images); ncnn::Mat score, bbox, keyPoint; ex.extract("prob1", score); ex.extract("conv5-2", bbox); if ((float)score[1] > thresh[1]) { for (int j = 0; j < 4; j++) secondBbox[pp].regreCoord[j] = (float)bbox[j]; secondBbox[pp].area = src_rect_w[pp] * src_rect_h[pp]; secondBbox[pp].score = (float)score[1]; } else { secondBbox[pp].exist = false; } } } else { #pragma omp parallel for num_threads(thread_num) schedule(dynamic,1) for (int pp = 0; pp < r_count; pp++) { int thread_id = omp_get_thread_num(); ncnn::Mat task_rnet_images; ncnn::Mat tempIm; copy_cut_border(input, tempIm, src_off_y[pp], input.h - src_off_y[pp] - src_rect_h[pp], src_off_x[pp], input.w - src_off_x[pp] - src_rect_w[pp]); resize_bilinear(tempIm, task_rnet_images, 24, 24); ncnn::Extractor ex = rnet[thread_id].create_extractor(); ex.set_light_mode(true); ex.set_blob_allocator(&g_blob_pool_allocator[thread_id]); ex.set_workspace_allocator(&g_workspace_pool_allocator[thread_id]); ex.set_num_threads(1); ex.input("data", task_rnet_images); ncnn::Mat score, bbox, keyPoint; ex.extract("prob1", score); ex.extract("conv5-2", bbox); if ((float)score[1] > thresh[1]) { for (int j = 0; j < 4; j++) secondBbox[pp].regreCoord[j] = (float)bbox[j]; secondBbox[pp].area = src_rect_w[pp] * src_rect_h[pp]; secondBbox[pp].score = (float)score[1]; } else { secondBbox[pp].exist = false; } } } for (int i = secondBbox.size() - 1; i >= 0; i--) { if (!secondBbox[i].exist) secondBbox.erase(secondBbox.begin() + i); } int count = secondBbox.size(); secondScore.resize(count); for (int i = 0; i < count; i++) { secondScore[i].score = secondBbox[i].score; secondScore[i].oriOrder = i; } //_nms(secondBbox, secondScore, nms_thresh[1], "Union"); _nms(secondBbox, secondScore, nms_thresh[1], "Min"); _refine_and_square_bbox(secondBbox, width, height, true); count = secondBbox.size(); double t4 = omp_get_wtime(); if (show_debug_info) printf("run Rnet [%d] times, candidate after nms: %d \n", r_count, count); if (show_debug_info) printf("stage 2: cost %.3f ms\n", 1000 * (t4 - t3)); return true; } bool _Onet_stage(std::vector<ZQ_CNN_BBox>& secondBbox, std::vector<ZQ_CNN_BBox>& thirdBbox) { double t3 = omp_get_wtime(); thirdBbox.clear(); std::vector<ZQ_CNN_BBox>::iterator it = secondBbox.begin(); std::vector<ZQ_CNN_OrderScore> thirdScore; std::vector<int> src_off_x, src_off_y, src_rect_w, src_rect_h; int o_count = 0; for (; it != secondBbox.end(); it++) { if ((*it).exist) { int off_x = it->col1; int off_y = it->row1; int rect_w = it->col2 - off_x; int rect_h = it->row2 - off_y; if (/*off_x < 0 || off_x + rect_w > width || off_y < 0 || off_y + rect_h > height ||*/ rect_w <= 0.5*min_size || rect_h <= 0.5*min_size) { (*it).exist = false; continue; } else { src_off_x.push_back(off_x); src_off_y.push_back(off_y); src_rect_w.push_back(rect_w); src_rect_h.push_back(rect_h); o_count++; thirdBbox.push_back(*it); } } } thirdBbox.resize(o_count); if (thread_num <= 1) { for (int pp = 0; pp < o_count; pp++) { ncnn::Mat task_onet_images; ncnn::Mat tempIm; copy_cut_border(input, tempIm, src_off_y[pp], input.h - src_off_y[pp] - src_rect_h[pp], src_off_x[pp], input.w - src_off_x[pp] - src_rect_w[pp]); resize_bilinear(tempIm, task_onet_images, 48, 48); ncnn::Extractor ex = onet[0].create_extractor(); ex.set_light_mode(true); ex.set_blob_allocator(&g_blob_pool_allocator[0]); ex.set_workspace_allocator(&g_workspace_pool_allocator[0]); ex.set_num_threads(1); ex.input("data", task_onet_images); ncnn::Mat score, bbox, keyPoint; ex.extract("prob1", score); ex.extract("conv6-2", bbox); if ((float)score[1] > thresh[2]) { for (int j = 0; j < 4; j++) thirdBbox[pp].regreCoord[j] = (float)bbox[j]; thirdBbox[pp].area = src_rect_w[pp] * src_rect_h[pp]; thirdBbox[pp].score = (float)score[1]; } else { thirdBbox[pp].exist = false; } } } else { #pragma omp parallel for num_threads(thread_num) schedule(dynamic,1) for (int pp = 0; pp < o_count; pp++) { int thread_id = omp_get_thread_num(); ncnn::Mat task_onet_images; ncnn::Mat tempIm; copy_cut_border(input, tempIm, src_off_y[pp], input.h - src_off_y[pp] - src_rect_h[pp], src_off_x[pp], input.w - src_off_x[pp] - src_rect_w[pp]); resize_bilinear(tempIm, task_onet_images, 48, 48); ncnn::Extractor ex = onet[thread_id].create_extractor(); ex.set_light_mode(true); ex.set_blob_allocator(&g_blob_pool_allocator[thread_id]); ex.set_workspace_allocator(&g_workspace_pool_allocator[thread_id]); ex.set_num_threads(1); ex.input("data", task_onet_images); ncnn::Mat score, bbox, keyPoint; ex.extract("prob1", score); ex.extract("conv6-2", bbox); if ((float)score[1] > thresh[2]) { for (int j = 0; j < 4; j++) thirdBbox[pp].regreCoord[j] = (float)bbox[j]; thirdBbox[pp].area = src_rect_w[pp] * src_rect_h[pp]; thirdBbox[pp].score = (float)score[1]; } else { thirdBbox[pp].exist = false; } } } for (int i = thirdBbox.size() - 1; i >= 0; i--) { if (!thirdBbox[i].exist) thirdBbox.erase(thirdBbox.begin() + i); } int count = thirdBbox.size(); thirdScore.resize(count); for (int i = 0; i < count; i++) { thirdScore[i].score = thirdScore[i].score; thirdScore[i].oriOrder = i; } _nms(thirdBbox, thirdScore, nms_thresh[2], "Min"); _refine_and_square_bbox(thirdBbox, width, height, true); count = thirdBbox.size(); double t4 = omp_get_wtime(); if (show_debug_info) printf("run Onet [%d] times, candidate after nms: %d \n", o_count, count); if (show_debug_info) printf("stage 3: cost %.3f ms\n", 1000 * (t4 - t3)); return true; } void _select(std::vector<ZQ_CNN_BBox>& bbox, int limit_num, int width, int height) { int in_num = bbox.size(); if (limit_num >= in_num) return; bbox.resize(limit_num); } }; } #endif
irbuilder_for_unsigned_down.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=45 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-LABEL: define {{.*}}@workshareloop_unsigned_down( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8 // CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4 // CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LASTITER:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LOWERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_UPPERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_STRIDE:.+]] = alloca i32, align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store i32 32000000, i32* %[[I]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0 // CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]]) // CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER]]: // CHECK-NEXT: store i32 0, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = sub i32 %[[DOTCOUNT]], 1 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: store i32 1, i32* %[[P_STRIDE]], align 4 // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 34, i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]], i32 1, i32 0) // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: %[[TMP6:.+]] = sub i32 %[[TMP5]], %[[TMP4]] // CHECK-NEXT: %[[TMP7:.+]] = add i32 %[[TMP6]], 1 // CHECK-NEXT: br label %[[OMP_LOOP_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_HEADER]]: // CHECK-NEXT: %[[OMP_LOOP_IV:.+]] = phi i32 [ 0, %[[OMP_LOOP_PREHEADER]] ], [ %[[OMP_LOOP_NEXT:.+]], %[[OMP_LOOP_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_LOOP_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_COND]]: // CHECK-NEXT: %[[OMP_LOOP_CMP:.+]] = icmp ult i32 %[[OMP_LOOP_IV]], %[[TMP7]] // CHECK-NEXT: br i1 %[[OMP_LOOP_CMP]], label %[[OMP_LOOP_BODY:.+]], label %[[OMP_LOOP_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: %[[TMP8:.+]] = add i32 %[[OMP_LOOP_IV]], %[[TMP4]] // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[TMP8]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[CONV:.+]] = uitofp i32 %[[TMP9]] to float // CHECK-NEXT: %[[TMP10:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP11:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = zext i32 %[[TMP11]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP10]], i64 %[[IDXPROM]] // CHECK-NEXT: store float %[[CONV]], float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_INC]]: // CHECK-NEXT: %[[OMP_LOOP_NEXT]] = add nuw i32 %[[OMP_LOOP_IV]], 1 // CHECK-NEXT: br label %[[OMP_LOOP_HEADER]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_EXIT]]: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]]) // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM2:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @2, i32 %[[OMP_GLOBAL_THREAD_NUM2]]) // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-NEXT: } extern "C" void workshareloop_unsigned_down(float *a) { #pragma omp for for (unsigned i = 32000000; i > 33; i -= 7) { a[i] = i; } } #endif // HEADER // // // // // // CHECK-LABEL: define {{.*}}@__captured_stmt( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8 // CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4 // CHECK-NEXT: store i32 33, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 -7, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp ugt i32 %[[TMP4]], %[[TMP5]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub i32 %[[TMP6]], %[[TMP7]] // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub nsw i32 0, %[[TMP8]] // CHECK-NEXT: %[[SUB2:.+]] = sub i32 %[[SUB1]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB2]] // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB3:.+]] = sub nsw i32 0, %[[TMP9]] // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[SUB3]] // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ] // CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define {{.*}}@__captured_stmt.1( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8 // CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: %[[MUL:.+]] = mul i32 -7, %[[TMP3]] // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]] // CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 45} // CHECK: ![[META2:[0-9]+]] =
mixed_tentusscher_myo_epi_2004_S1_2.c
// Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S1_2.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.6775309540028,0.00126031074107193,0.782379594133090,0.782216749001106,0.000172068343086772,0.486227463562957,0.00291750746806204,0.999998383839518,1.89860165324306e-08,1.86371442934849e-05,0.999771183306077,1.00730952275387,0.999997729764813,4.01181567168462e-05,0.661435383223664,9.89216406636310,139.601234209998}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.9645635317638,0.000234559273515713,0.000158508496150117,0.000387718953473422,0.271550011299244,0.171313643894679,0.148132634408518,3.52429749186627,0.0163232963007063,1.80625170161156,1099.99984094905,0.000508428591582056,0.426315288126368,0.0193610246251599,0.00342305438925442,2.79133840240607e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
convdw3x3s2_pack4_neon.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "option.h" #include "mat.h" namespace ncnn{ static void convdw3x3s2_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const int tailstep = (w - 2*outw + w) * 4; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g=0; g<group; g++) { Mat out = top_blob.channel(g); float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + g * 4) : vdupq_n_f32(0.f); const float* k0 = kernel.row(g); float* outptr0 = out; const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); float32x4_t _k00 = vld1q_f32(k0); float32x4_t _k01 = vld1q_f32(k0+4); float32x4_t _k02 = vld1q_f32(k0+8); float32x4_t _k10 = vld1q_f32(k0+12); float32x4_t _k11 = vld1q_f32(k0+16); float32x4_t _k12 = vld1q_f32(k0+20); float32x4_t _k20 = vld1q_f32(k0+24); float32x4_t _k21 = vld1q_f32(k0+28); float32x4_t _k22 = vld1q_f32(k0+32); int i = 0; for (; i < outh; i++) { int j = 0; for (; j+3 < outw; j+=4) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%1, #512] \n" "ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%1], #64 \n"// r00 r01 r02 r03 "mov v28.16b, %17.16b \n"// sum00 "mov v29.16b, %17.16b \n"// sum01 "mov v30.16b, %17.16b \n"// sum02 "mov v31.16b, %17.16b \n"// sum03 "prfm pldl1keep, [%1, #512] \n" "ld1 {v14.4s, v15.4s, v16.4s, v17.4s}, [%1], #64 \n"// r04 r05 r06 r07 "fmla v28.4s, %8.4s, v10.4s \n" "fmla v29.4s, %8.4s, v12.4s \n" "fmla v30.4s, %8.4s, v14.4s \n" "fmla v31.4s, %8.4s, v16.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n"// r08 "fmla v28.4s, %9.4s, v11.4s \n" "fmla v29.4s, %9.4s, v13.4s \n" "fmla v30.4s, %9.4s, v15.4s \n" "fmla v31.4s, %9.4s, v17.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"// r10 r11 r12 r13 "fmla v28.4s, %10.4s, v12.4s \n" "fmla v29.4s, %10.4s, v14.4s \n" "fmla v30.4s, %10.4s, v16.4s \n" "fmla v31.4s, %10.4s, v18.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"// r14 r15 r16 r17 "fmla v28.4s, %11.4s, v20.4s \n" "fmla v29.4s, %11.4s, v22.4s \n" "fmla v30.4s, %11.4s, v24.4s \n" "fmla v31.4s, %11.4s, v26.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n"// r18 "fmla v28.4s, %12.4s, v21.4s \n" "fmla v29.4s, %12.4s, v23.4s \n" "fmla v30.4s, %12.4s, v25.4s \n" "fmla v31.4s, %12.4s, v27.4s \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%3], #64 \n"// r20 r21 r22 r23 "fmla v28.4s, %13.4s, v22.4s \n" "fmla v29.4s, %13.4s, v24.4s \n" "fmla v30.4s, %13.4s, v26.4s \n" "fmla v31.4s, %13.4s, v19.4s \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v14.4s, v15.4s, v16.4s, v17.4s}, [%3], #64 \n"// r24 r25 r26 r27 "fmla v28.4s, %14.4s, v10.4s \n" "fmla v29.4s, %14.4s, v12.4s \n" "fmla v30.4s, %14.4s, v14.4s \n" "fmla v31.4s, %14.4s, v16.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v18.4s}, [%3] \n"// r28 "fmla v28.4s, %15.4s, v11.4s \n" "fmla v29.4s, %15.4s, v13.4s \n" "fmla v30.4s, %15.4s, v15.4s \n" "fmla v31.4s, %15.4s, v17.4s \n" "fmla v28.4s, %16.4s, v12.4s \n" "fmla v29.4s, %16.4s, v14.4s \n" "fmla v30.4s, %16.4s, v16.4s \n" "fmla v31.4s, %16.4s, v18.4s \n" "st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%0], #64 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22), // %16 "w"(_bias0) // %17 : "memory", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31" ); #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d28-d31}, [%1 :128]! \n"// r00 r01 "vmov q10, %q17 \n"// sum00 "vmla.f32 q10, %q8, q14 \n" "vmov q11, %q17 \n"// sum01 "vmla.f32 q10, %q9, q15 \n" "pld [%1, #256] \n" "vld1.f32 {d28-d31}, [%1 :128]! \n"// r02 r03 "vmla.f32 q11, %q8, q14 \n" "vmla.f32 q10, %q10, q14 \n" "vmov q12, %q17 \n"// sum02 "vmla.f32 q11, %q9, q15 \n" "pld [%1, #256] \n" "vld1.f32 {d28-d31}, [%1 :128]! \n"// r04 r05 "vmla.f32 q12, %q8, q14 \n" "vmla.f32 q11, %q10, q14 \n" "vmla.f32 q12, %q9, q15 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// r10 r11 "vmla.f32 q10, %q11, q14 \n" "vmov q13, %q17 \n"// sum03 "vmla.f32 q10, %q12, q15 \n" "pld [%1, #256] \n" "vld1.f32 {d28-d31}, [%1 :128]! \n"// r06 r07 "vmla.f32 q13, %q8, q14 \n" "vmla.f32 q12, %q10, q14 \n" "vmla.f32 q13, %q9, q15 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// r12 r13 "vmla.f32 q11, %q11, q14 \n" "vmla.f32 q10, %q13, q14 \n" "vmla.f32 q11, %q12, q15 \n" "vld1.f32 {d28-d29}, [%1 :128] \n"// r08 "vmla.f32 q13, %q10, q14 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// r14 r15 "vmla.f32 q12, %q11, q14 \n" "vmla.f32 q11, %q13, q14 \n" "vmla.f32 q12, %q12, q15 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// r20 r21 "vmla.f32 q10, %q14, q14 \n" "vmla.f32 q10, %q15, q15 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// r16 r17 "vmla.f32 q13, %q11, q14 \n" "vmla.f32 q12, %q13, q14 \n" "vmla.f32 q13, %q12, q15 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// r22 r23 "vmla.f32 q11, %q14, q14 \n" "vmla.f32 q10, %q16, q14 \n" "vmla.f32 q11, %q15, q15 \n" "vld1.f32 {d28-d29}, [%2 :128] \n"// r18 "vmla.f32 q13, %q13, q14 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// r24 r25 "vmla.f32 q12, %q14, q14 \n" "vmla.f32 q11, %q16, q14 \n" "vmla.f32 q12, %q15, q15 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// r26 r27 "vmla.f32 q13, %q14, q14 \n" "vmla.f32 q12, %q16, q14 \n" "vmla.f32 q13, %q15, q15 \n" "vld1.f32 {d28-d29}, [%3 :128] \n"// r28 "vmla.f32 q13, %q16, q14 \n" "vstm %0!, {d20-d27} \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22), // %16 "w"(_bias0) // %17 : "memory", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif } for (; j+1 < outw; j+=2) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%1, #512] \n" "ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%1], #64 \n"// r00 r01 r02 r03 "mov v20.16b, %17.16b \n"// sum00 "mov v21.16b, %17.16b \n"// sum01 "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "fmla v20.4s, %8.4s, v10.4s \n" "fmla v21.4s, %8.4s, v12.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v14.4s}, [%1] \n"// r04 "fmla v22.4s, %9.4s, v11.4s \n" "fmla v23.4s, %9.4s, v13.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%2], #64 \n"// r10 r11 r12 r13 "fmla v20.4s, %10.4s, v12.4s \n" "fmla v21.4s, %10.4s, v14.4s \n" "fmla v22.4s, %11.4s, v16.4s \n" "fmla v23.4s, %11.4s, v18.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v15.4s}, [%2] \n"// r14 "fmla v20.4s, %12.4s, v17.4s \n" "fmla v21.4s, %12.4s, v19.4s \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%3], #64 \n"// r20 r21 r22 r23 "fmla v22.4s, %13.4s, v18.4s \n" "fmla v23.4s, %13.4s, v15.4s \n" "fmla v20.4s, %14.4s, v10.4s \n" "fmla v21.4s, %14.4s, v12.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v14.4s}, [%3] \n"// r24 "fmla v22.4s, %15.4s, v11.4s \n" "fmla v23.4s, %15.4s, v13.4s \n" "fmla v20.4s, %16.4s, v12.4s \n" "fmla v21.4s, %16.4s, v14.4s \n" "fadd v20.4s, v20.4s, v22.4s \n" "fadd v21.4s, v21.4s, v23.4s \n" "st1 {v20.4s, v21.4s}, [%0], #32 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22), // %16 "w"(_bias0) // %17 : "memory", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// r00 r01 "vmov q10, %q17 \n"// sum00 "vmov q11, %q17 \n"// sum01 "vmla.f32 q10, %q8, q12 \n" "pld [%1, #256] \n" "vld1.f32 {d28-d31}, [%1 :128]! \n"// r02 r03 "vmla.f32 q10, %q9, q13 \n" "vmla.f32 q11, %q8, q14 \n" "vmla.f32 q10, %q10, q14 \n" "vld1.f32 {d24-d25}, [%1 :128] \n"// r04 "vmla.f32 q11, %q9, q15 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// r10 r11 "vmla.f32 q11, %q10, q12 \n" "vmla.f32 q10, %q11, q14 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// r12 r13 "vmla.f32 q10, %q12, q15 \n" "vmla.f32 q11, %q11, q12 \n" "vmla.f32 q10, %q13, q12 \n" "vld1.f32 {d28-d29}, [%2 :128] \n"// r14 "vmla.f32 q11, %q12, q13 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// r20 r21 "vmla.f32 q11, %q13, q14 \n" "vmla.f32 q10, %q14, q12 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// r22 r23 "vmla.f32 q10, %q15, q13 \n" "vmla.f32 q11, %q14, q14 \n" "vmla.f32 q10, %q16, q14 \n" "vld1.f32 {d24-d25}, [%3 :128] \n"// r24 "vmla.f32 q11, %q15, q15 \n" "vmla.f32 q11, %q16, q12 \n" "vst1.f32 {d20-d23}, [%0 :128]! \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22), // %16 "w"(_bias0) // %17 : "memory", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif } for (; j < outw; j++) { float32x4_t _sum0 = _bias0; float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r01 = vld1q_f32(r0+4); float32x4_t _r02 = vld1q_f32(r0+8); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r11 = vld1q_f32(r1+4); float32x4_t _r12 = vld1q_f32(r1+8); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r21 = vld1q_f32(r2+4); float32x4_t _r22 = vld1q_f32(r2+8); _sum0 = vmlaq_f32(_sum0, _k00, _r00); _sum0 = vmlaq_f32(_sum0, _k01, _r01); _sum0 = vmlaq_f32(_sum0, _k02, _r02); _sum0 = vmlaq_f32(_sum0, _k10, _r10); _sum0 = vmlaq_f32(_sum0, _k11, _r11); _sum0 = vmlaq_f32(_sum0, _k12, _r12); _sum0 = vmlaq_f32(_sum0, _k20, _r20); _sum0 = vmlaq_f32(_sum0, _k21, _r21); _sum0 = vmlaq_f32(_sum0, _k22, _r22); vst1q_f32(outptr0, _sum0); r0 += 2*4; r1 += 2*4; r2 += 2*4; outptr0 += 4; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } }
FullyDistSpVec.h
/****************************************************************/ /* Parallel Combinatorial BLAS Library (for Graph Computations) */ /* version 1.2 -------------------------------------------------*/ /* date: 10/06/2011 --------------------------------------------*/ /* authors: Aydin Buluc (abuluc@lbl.gov), Adam Lugowski --------*/ /****************************************************************/ /* Copyright (c) 2011, Aydin Buluc 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 _FULLY_DIST_SP_VEC_H_ #define _FULLY_DIST_SP_VEC_H_ #include <iostream> #include <vector> #include <utility> #ifdef NOTR1 #include <boost/tr1/memory.hpp> #include <boost/tr1/unordered_map.hpp> #else #include <tr1/memory> #include <tr1/unordered_map> #endif #include "CommGrid.h" #include "promote.h" #include "SpParMat.h" #include "FullyDist.h" #include "Exception.h" #include "OptBuf.h" using namespace std; using namespace std::tr1; template <class IT, class NT, class DER> class SpParMat; template <class IT> class DistEdgeList; template <class IU, class NU> class FullyDistVec; template <class IU, class NU> class SparseVectorLocalIterator; /** * A sparse vector of length n (with nnz <= n of them being nonzeros) is distributed to * "all the processors" in a way that "respects ordering" of the nonzero indices * Example: x = [5,1,6,2,9] for nnz(x)=5 and length(x)=12 * we use 4 processors P_00, P_01, P_10, P_11 * Then P_00 owns [1,2] (in the range [0,...,2]), P_01 ow`ns [5] (in the range [3,...,5]), and so on. * In the case of A(v,w) type sparse matrix indexing, this doesn't matter because n = nnz * After all, A(v,w) will have dimensions length(v) x length (w) * v and w will be of numerical type (NT) "int" and their indices (IT) will be consecutive integers * It is possibly that nonzero counts are distributed unevenly * Example: x=[1,2,3,4,5] and length(x) = 20, then P_00 would own all the nonzeros and the rest will hold empry vectors * Just like in SpParMat case, indices are local to processors (they belong to range [0,...,length-1] on each processor) * \warning Always create vectors with the right length, setting elements won't increase its length (similar to operator[] on std::vector) **/ template <class IT, class NT> class FullyDistSpVec: public FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type> { public: FullyDistSpVec ( ); FullyDistSpVec ( IT glen ); FullyDistSpVec ( shared_ptr<CommGrid> grid); FullyDistSpVec ( shared_ptr<CommGrid> grid, IT glen); FullyDistSpVec (const FullyDistVec<IT,NT> & rhs); // Conversion copy-constructor //! like operator=, but instead of making a deep copy it just steals the contents. //! Useful for places where the "victim" will be distroyed immediately after the call. void stealFrom(FullyDistSpVec<IT,NT> & victim); FullyDistSpVec<IT,NT> & operator=(const FullyDistSpVec< IT,NT > & rhs); FullyDistSpVec<IT,NT> & operator=(const FullyDistVec< IT,NT > & rhs); // convert from dense FullyDistSpVec<IT,NT> & operator+=(const FullyDistSpVec<IT,NT> & rhs); FullyDistSpVec<IT,NT> & operator-=(const FullyDistSpVec<IT,NT> & rhs); ifstream& ReadDistribute (ifstream& infile, int master); template <typename NNT> operator FullyDistSpVec< IT,NNT > () const //!< Type conversion operator { FullyDistSpVec<IT,NNT> CVT(commGrid); CVT.ind = vector<IT>(ind.begin(), ind.end()); CVT.num = vector<NNT>(num.begin(), num.end()); CVT.glen = glen; CVT.NOT_FOUND = NOT_FOUND; return CVT; } bool operator==(const FullyDistSpVec<IT,NT> & rhs) const { FullyDistVec<IT,NT> v = *this; FullyDistVec<IT,NT> w = rhs; return (v == w); } void PrintInfo(string vecname) const; void iota(IT globalsize, NT first); FullyDistVec<IT,NT> operator() (const FullyDistVec<IT,IT> & ri) const; //!< SpRef (expects ri to be 0-based) void SetElement (IT indx, NT numx); // element-wise assignment void DelElement (IT indx); // element-wise deletion NT operator[](IT indx) const; NT GetZero() const { return zero; } void SetZero(const NT& z) { zero = z; } // sort the vector itself // return the permutation vector (0-based) FullyDistSpVec<IT, IT> sort(); IT getlocnnz() const { return ind.size(); } IT getnnz() const { IT totnnz = 0; IT locnnz = ind.size(); (commGrid->GetWorld()).Allreduce( &locnnz, & totnnz, 1, MPIType<IT>(), MPI::SUM); return totnnz; } using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::LengthUntil; using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::MyLocLength; using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::MyRowLength; using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::TotalLength; using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::Owner; using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::RowLenUntil; void setNumToInd() { IT offset = LengthUntil(); IT spsize = ind.size(); #ifdef _OPENMP #pragma omp parallel for #endif for(IT i=0; i< spsize; ++i) num[i] = ind[i] + offset; } template <typename _Predicate> IT Count(_Predicate pred) const; //!< Return the number of elements for which pred is true template <typename _UnaryOperation> void Apply(_UnaryOperation __unary_op) { transform(num.begin(), num.end(), num.begin(), __unary_op); } template <typename _BinaryOperation> NT Reduce(_BinaryOperation __binary_op, NT init); template <typename _BinaryOperation, typename _UnaryOperation> NT Reduce(_BinaryOperation __binary_op, NT default_val, _UnaryOperation __unary_op); void DebugPrint(); shared_ptr<CommGrid> getCommGrid() { return commGrid; } NT NOT_FOUND; protected: using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::glen; using FullyDist<IT,NT,typename disable_if< is_boolean<NT>::value, NT >::type>::commGrid; private: vector< IT > ind; // ind.size() give the number of nonzeros vector< NT > num; NT zero; template <class IU, class NU> friend class FullyDistSpVec; template <class IU, class NU> friend class FullyDistVec; template <class IU, class NU, class UDER> friend class SpParMat; template <class IU, class NU> friend class SparseVectorLocalIterator; template <typename SR, typename IU, typename NUM, typename NUV, typename UDER> friend FullyDistSpVec<IU,typename promote_trait<NUM,NUV>::T_promote> SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,NUV> & x ); template <typename SR, typename IU, typename NUM, typename UDER> friend FullyDistSpVec<IU,typename promote_trait<NUM,IU>::T_promote> SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IU> & x, bool indexisvalue); template <typename SR, typename IU, typename NUM, typename UDER> friend FullyDistSpVec<IU,typename promote_trait<NUM,IU>::T_promote> SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IU> & x, bool indexisvalue, OptBuf<IU, typename promote_trait<NUM,IU>::T_promote > & optbuf); template <typename _BinaryOperation, typename IU, typename NUM, typename NUV, typename UDER> friend void ColWiseApply (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,NUV> & x, _BinaryOperation __binary_op); template <typename IU, typename NU1, typename NU2> friend FullyDistSpVec<IU,typename promote_trait<NU1,NU2>::T_promote> EWiseMult (const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , bool exclude, NU2 zero); template <typename IU, typename NU1, typename NU2, typename _BinaryOperation> friend FullyDistSpVec<IU,typename promote_trait<NU1,NU2>::T_promote> EWiseApply (const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , _BinaryOperation _binary_op, typename promote_trait<NU1,NU2>::T_promote zero); template <typename IU> friend void RandPerm(FullyDistSpVec<IU,IU> & V); // called on an existing object, randomly permutes it template <typename IU> friend void RenameVertices(DistEdgeList<IU> & DEL); }; #include "FullyDistSpVec.cpp" #endif
matvec_float_avx2.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #include <math.h> #define N_RUNS 20 #define N 10240 // read timer in second double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //Create a matrix and a vector and fill with random numbers void init(float *matrix, float *vector) { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) { matrix[i*N+j] = (float)rand()/(float)(RAND_MAX/10.0); } vector[i] = (float)rand()/(float)(RAND_MAX/10.0); } } void matvec_simd(float *matrix, float *vector, float *dest) { for (int i = 0; i<N; i++) { float tmp = 0; #pragma omp simd simdlen(8) reduction(+: tmp) for (int j = 0; j<N; j++) { tmp += matrix[i*N+j] * vector[j]; } dest[i] = tmp; } } // Debug functions void matvec_serial(float *matrix, float *vector, float *dest) { for (int i = 0; i<N; i++) { float tmp = 0; for (int j = 0; j<N; j++) { tmp += matrix[i*N+j] * vector[j]; } dest[i] = tmp; } } void print_matrix(float *matrix) { for (int i = 0; i<8; i++) { printf("["); for (int j = 0; j<8; j++) { printf("%.2f ", matrix[i*N+j]); } puts("]"); } puts(""); } void print_vector(float *vector) { printf("["); for (int i = 0; i<8; i++) { printf("%.2f ", vector[i]); } puts("]"); } float check(float *A, float *B){ float difference = 0; for(int i = 0;i<N; i++){ difference += fabsf(A[i]- B[i]); } return difference; } int main(int argc, char **argv) { //Set everything up float *dest_vector = malloc(sizeof(float*)*N); float *serial_vector = malloc(sizeof(float*)*N); float *matrix = malloc(sizeof(float*)*N*N); float *vector = malloc(sizeof(float)*N); srand(time(NULL)); init(matrix, vector); //warming up matvec_simd(matrix, vector, dest_vector); double t = 0; double start = read_timer(); for (int i = 0; i<N_RUNS; i++) matvec_simd(matrix, vector, dest_vector); t += (read_timer() - start); double t_serial = 0; double start_serial = read_timer(); for (int i = 0; i<N_RUNS; i++) matvec_serial(matrix, vector, serial_vector); t_serial += (read_timer() - start_serial); print_matrix(matrix); print_vector(vector); puts("=\n"); print_vector(dest_vector); puts("---------------------------------"); print_vector(serial_vector); double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t); double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial); printf("==================================================================\n"); printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------\n"); printf("Matrix-vector (SIMD):\t\t%4f\t%4f\n", t/N_RUNS, gflops); printf("Matrix-vector (Serial):\t\t%4f\t%4f\n", t_serial/N_RUNS, gflops_serial); printf("Correctness check: %f\n", check(dest_vector,serial_vector)); free(dest_vector); free(serial_vector); free(matrix); free(vector); return 0; }
38f9a6e_so12_advfsg_gcc.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include "omp.h" #include <stdio.h> #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; double section1; double section2; }; void bf0(float *restrict r118_vec, float *restrict r119_vec, float *restrict r74_vec, float *restrict r75_vec, float *restrict r76_vec, float *restrict r77_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw); void bf1(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r118_vec, float *restrict r119_vec, float *restrict r73_vec, float *restrict r74_vec, float *restrict r75_vec, float *restrict r76_vec, float *restrict r77_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int t1, const int t2, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw); int ForwardTTI(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, struct dataobj *restrict delta_vec, const float dt, struct dataobj *restrict epsilon_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict phi_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict theta_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, const int x_size, const int y_size, const int z_size, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine) { int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data; float(*restrict delta)[delta_vec->size[1]][delta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[delta_vec->size[1]][delta_vec->size[2]])delta_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict phi)[phi_vec->size[1]][phi_vec->size[2]] __attribute__((aligned(64))) = (float(*)[phi_vec->size[1]][phi_vec->size[2]])phi_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict theta)[theta_vec->size[1]][theta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[theta_vec->size[1]][theta_vec->size[2]])theta_vec->data; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; float (*r73)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void**)&r73, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float (*r74)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void**)&r74, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float (*r75)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void**)&r75, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float (*r76)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void**)&r76, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float (*r77)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void**)&r77, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float (*r118)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void**)&r118, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float (*r119)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void**)&r119, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(static,1) for (int x = x_m - 3; x <= x_M + 3; x += 1) { for (int y = y_m - 3; y <= y_M + 3; y += 1) { #pragma omp simd aligned(delta,phi,theta:32) for (int z = z_m - 3; z <= z_M + 3; z += 1) { r73[x + 3][y + 3][z + 3] = sqrt(2*delta[x + 12][y + 12][z + 12] + 1); r74[x + 3][y + 3][z + 3] = cos(theta[x + 12][y + 12][z + 12]); r75[x + 3][y + 3][z + 3] = sin(phi[x + 12][y + 12][z + 12]); r76[x + 3][y + 3][z + 3] = sin(theta[x + 12][y + 12][z + 12]); r77[x + 3][y + 3][z + 3] = cos(phi[x + 12][y + 12][z + 12]); } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; int xb_size = block_sizes[0]; int sf = 6; int t_blk_size = 2 * sf * (time_M - time_m); printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size, yb_size, x0_blk0_size, y0_blk0_size); for (int t_blk = time_m; t_blk <= 1 + sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m - 3 ; xb <= (x_M + 3 + sf * (time_M - time_m)); xb += xb_size) { //printf(" Change of outer xblock %d \n", xb); for (int yb = y_m - 3 ; yb <= (y_M + 3 + sf * (time_M - time_m)); yb += yb_size) { //printf(" Timestep tw: %d, Updating x: %d y: %d \n", xb, yb); for (int time = t_blk, t0 = (time) % (3), t1 = (time + 2) % (3), t2 = (time + 1) % (3); time <= 2 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1))) % (3), t1 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3)) { int tw = ((time / sf) % (time_M - time_m + 1)); struct timeval start_section1, end_section1; gettimeofday(&start_section1, NULL); /* Begin section1 */ bf0((float *)r118, (float *)r119, (float *)r74, (float *)r75, (float *)r76, (float *)r77, u_vec, v_vec, x_size, y_size, z_size, time, t0, x0_blk0_size, x_M + 3, x_m - 3, y0_blk0_size, y_M + 3, y_m - 3, z_M, z_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf("\n BF0 - 1 IS OVER"); /*==============================================*/ bf1(damp_vec, dt, epsilon_vec, (float *)r118, (float *)r119, (float *)r73, (float *)r74, (float *)r75, (float *)r76, (float *)r77, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x_size, y_size, z_size, time, t0, t1, t2, x0_blk0_size, x_M, x_m, y0_blk0_size, y_M, y_m , z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf("\n BF1 - 1 IS OVER"); /* End section1 */ gettimeofday(&end_section1, NULL); timers->section1 += (double)(end_section1.tv_sec - start_section1.tv_sec) + (double)(end_section1.tv_usec - start_section1.tv_usec) / 1000000; } } } } free(r77); free(r76); free(r75); free(r74); free(r73); free(r118); free(r119); return 0; } void bf0(float *restrict r118_vec, float *restrict r119_vec, float *restrict r74_vec, float *restrict r75_vec, float *restrict r76_vec, float *restrict r77_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw) { float (*restrict r118)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r118_vec; float (*restrict r119)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r119_vec; float (*restrict r74)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r74_vec; float (*restrict r75)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r75_vec; float (*restrict r76)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r76_vec; float (*restrict r77)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r77_vec; float (*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]]) u_vec->data; float (*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]]) v_vec->data; #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { //printf(" Change of inner x0_blk0 %d \n", x0_blk0); for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { //printf(" bf0 Timestep tw: %d, Updating x: %d \n", tw, x - time + 1); for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { #pragma omp simd aligned(u, v : 32) for (int z = z_m - 3; z <= z_M + 3; z += 1) { //printf(" bf0 Updating x: %d y: %d z: %d \n", x - time + 2, y - time + 2, z + 2); r118[x - time + 3][y - time + 3][z + 3] = -(1.66666669e-3F*(-u[t0][x - time + 9][y - time + 12][z + 12] + u[t0][x - time + 15][y - time + 12][z + 12]) + 1.50000002e-2F*(u[t0][x - time + 10][y - time + 12][z + 12] - u[t0][x - time + 14][y - time + 12][z + 12]) + 7.50000011e-2F*(-u[t0][x - time + 11][y - time + 12][z + 12] + u[t0][x - time + 13][y - time + 12][z + 12]))*r76[x - time + 3][y - time + 3][z + 3]*r77[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F*(-u[t0][x - time + 12][y - time + 9][z + 12] + u[t0][x - time + 12][y - time + 15][z + 12]) + 1.50000002e-2F*(u[t0][x - time + 12][y - time + 10][z + 12] - u[t0][x - time + 12][y - time + 14][z + 12]) + 7.50000011e-2F*(-u[t0][x - time + 12][y - time + 11][z + 12] + u[t0][x - time + 12][y - time + 13][z + 12]))*r75[x - time + 3][y - time + 3][z + 3]*r76[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F*(-u[t0][x - time + 12][y - time + 12][z + 9] + u[t0][x - time + 12][y - time + 12][z + 15]) + 1.50000002e-2F*(u[t0][x - time + 12][y - time + 12][z + 10] - u[t0][x - time + 12][y - time + 12][z + 14]) + 7.50000011e-2F*(-u[t0][x - time + 12][y - time + 12][z + 11] + u[t0][x - time + 12][y - time + 12][z + 13]))*r74[x - time + 3][y - time + 3][z + 3]; r119[x - time + 3][y - time + 3][z + 3] = -(1.66666669e-3F*(-v[t0][x - time + 9][y - time + 12][z + 12] + v[t0][x - time + 15][y - time + 12][z + 12]) + 1.50000002e-2F*(v[t0][x - time + 10][y - time + 12][z + 12] - v[t0][x - time + 14][y - time + 12][z + 12]) + 7.50000011e-2F*(-v[t0][x - time + 11][y - time + 12][z + 12] + v[t0][x - time + 13][y - time + 12][z + 12]))*r76[x - time + 3][y - time + 3][z + 3]*r77[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F*(-v[t0][x - time + 12][y - time + 9][z + 12] + v[t0][x - time + 12][y - time + 15][z + 12]) + 1.50000002e-2F*(v[t0][x - time + 12][y - time + 10][z + 12] - v[t0][x - time + 12][y - time + 14][z + 12]) + 7.50000011e-2F*(-v[t0][x - time + 12][y - time + 11][z + 12] + v[t0][x - time + 12][y - time + 13][z + 12]))*r75[x - time + 3][y - time + 3][z + 3]*r76[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F*(-v[t0][x - time + 12][y - time + 12][z + 9] + v[t0][x - time + 12][y - time + 12][z + 15]) + 1.50000002e-2F*(v[t0][x - time + 12][y - time + 12][z + 10] - v[t0][x - time + 12][y - time + 12][z + 14]) + 7.50000011e-2F*(-v[t0][x - time + 12][y - time + 12][z + 11] + v[t0][x - time + 12][y - time + 12][z + 13]))*r74[x - time + 3][y - time + 3][z + 3]; //printf("bf0 Timestep tw: %d, Updating x: %d y: %d value: %f \n", tw, x - time + 2, y - time + 2, v[t0][x - time + 9][y - time + 8][z + 8]); } } } } } } } void bf1(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r118_vec, float *restrict r119_vec, float *restrict r73_vec, float *restrict r74_vec, float *restrict r75_vec, float *restrict r76_vec, float *restrict r77_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int t1, const int t2, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw) { float (*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[damp_vec->size[1]][damp_vec->size[2]]) damp_vec->data; float (*restrict epsilon)[epsilon_vec->size[1]][epsilon_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[epsilon_vec->size[1]][epsilon_vec->size[2]]) epsilon_vec->data; float (*restrict r118)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r118_vec; float (*restrict r119)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r119_vec; float (*restrict r73)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r73_vec; float (*restrict r74)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r74_vec; float (*restrict r75)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r75_vec; float (*restrict r76)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r76_vec; float (*restrict r77)[y_size + 3 + 3][z_size + 3 + 3] __attribute__ ((aligned (64))) = (float (*)[y_size + 3 + 3][z_size + 3 + 3]) r77_vec; float (*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]]) u_vec->data; float (*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]]) v_vec->data; float (*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[vp_vec->size[1]][vp_vec->size[2]]) vp_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; //printf("In bf1 \n"); #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(dynamic, 1) for (int x1_blk0 = max((x_m + time), xb - 0); x1_blk0 <= +min((x_M + time), (xb - 0 + xb_size)); x1_blk0 += x1_blk0_size) { //printf(" Change of inner x1_blk0 %d \n", x1_blk0); for (int y1_blk0 = max((y_m + time), yb - 0); y1_blk0 <= +min((y_M + time), (yb - 0 + yb_size)); y1_blk0 += y1_blk0_size) { for (int x = x1_blk0; x <= min(min((x_M + time), (xb - 0 + xb_size - 1)), (x1_blk0 + x1_blk0_size - 1)); x++) { //printf(" bf1 Timestep tw: %d, Updating x: %d \n", tw, x - time + 4); for (int y = y1_blk0; y <= min(min((y_M + time), (yb - 0 + yb_size - 1)), (y1_blk0 + y1_blk0_size - 1)); y++) { //printf(" bf1 Timestep tw: %d, Updating x: %d y: %d \n", tw, x - time + 4, y - time + 4); #pragma omp simd aligned(damp, epsilon, u, v, vp : 32) for (int z = z_m; z <= z_M; z += 1) { //printf(" bf1 Updating x: %d y: %d z: %d \n", x - time + 4, y - time + 4, z + 4); //printf(" bf1 Updating x: %d y: %d z: %d \n", x - time + 4, y - time + 4, z + 4); float r130 = 1.0/dt; float r129 = 1.0/(dt*dt); float r128 = 1.50000002e-2F*(-r119[x - time + 1][y - time + 3][z + 3]*r76[x - time + 1][y - time + 3][z + 3]*r77[x - time + 1][y - time + 3][z + 3] - r119[x - time + 3][y - time + 1][z + 3]*r75[x - time + 3][y - time + 1][z + 3]*r76[x - time + 3][y - time + 1][z + 3] - r119[x - time + 3][y - time + 3][z + 1]*r74[x - time + 3][y - time + 3][z + 1] + r119[x - time + 3][y - time + 3][z + 5]*r74[x - time + 3][y - time + 3][z + 5] + r119[x - time + 3][y - time + 5][z + 3]*r75[x - time + 3][y - time + 5][z + 3]*r76[x - time + 3][y - time + 5][z + 3] + r119[x - time + 5][y - time + 3][z + 3]*r76[x - time + 5][y - time + 3][z + 3]*r77[x - time + 5][y - time + 3][z + 3]); float r127 = 1.66666669e-3F*(r119[x - time][y - time + 3][z + 3]*r76[x - time][y - time + 3][z + 3]*r77[x - time][y - time + 3][z + 3] + r119[x - time + 3][y - time][z + 3]*r75[x - time + 3][y - time][z + 3]*r76[x - time + 3][y - time][z + 3] + r119[x - time + 3][y - time + 3][z]*r74[x - time + 3][y - time + 3][z] - r119[x - time + 3][y - time + 3][z + 6]*r74[x - time + 3][y - time + 3][z + 6] - r119[x - time + 3][y - time + 6][z + 3]*r75[x - time + 3][y - time + 6][z + 3]*r76[x - time + 3][y - time + 6][z + 3] - r119[x - time + 6][y - time + 3][z + 3]*r76[x - time + 6][y - time + 3][z + 3]*r77[x - time + 6][y - time + 3][z + 3]); float r126 = 7.50000011e-2F*(r119[x - time + 2][y - time + 3][z + 3]*r76[x - time + 2][y - time + 3][z + 3]*r77[x - time + 2][y - time + 3][z + 3] + r119[x - time + 3][y - time + 2][z + 3]*r75[x - time + 3][y - time + 2][z + 3]*r76[x - time + 3][y - time + 2][z + 3] + r119[x - time + 3][y - time + 3][z + 2]*r74[x - time + 3][y - time + 3][z + 2] - r119[x - time + 3][y - time + 3][z + 4]*r74[x - time + 3][y - time + 3][z + 4] - r119[x - time + 3][y - time + 4][z + 3]*r75[x - time + 3][y - time + 4][z + 3]*r76[x - time + 3][y - time + 4][z + 3] - r119[x - time + 4][y - time + 3][z + 3]*r76[x - time + 4][y - time + 3][z + 3]*r77[x - time + 4][y - time + 3][z + 3]); float r125 = pow(vp[x - time + 12][y - time + 12][z + 12], -2); float r124 = 1.0/(r125*r129 + r130*damp[x - time + 1][y - time + 1][z + 1]); float r123 = 1.66666669e-3F*(-r118[x - time][y - time + 3][z + 3]*r76[x - time][y - time + 3][z + 3]*r77[x - time][y - time + 3][z + 3] - r118[x - time + 3][y - time][z + 3]*r75[x - time + 3][y - time][z + 3]*r76[x - time + 3][y - time][z + 3] - r118[x - time + 3][y - time + 3][z]*r74[x - time + 3][y - time + 3][z] + r118[x - time + 3][y - time + 3][z + 6]*r74[x - time + 3][y - time + 3][z + 6] + r118[x - time + 3][y - time + 6][z + 3]*r75[x - time + 3][y - time + 6][z + 3]*r76[x - time + 3][y - time + 6][z + 3] + r118[x - time + 6][y - time + 3][z + 3]*r76[x - time + 6][y - time + 3][z + 3]*r77[x - time + 6][y - time + 3][z + 3]) + 1.50000002e-2F*(r118[x - time + 1][y - time + 3][z + 3]*r76[x - time + 1][y - time + 3][z + 3]*r77[x - time + 1][y - time + 3][z + 3] + r118[x - time + 3][y - time + 1][z + 3]*r75[x - time + 3][y - time + 1][z + 3]*r76[x - time + 3][y - time + 1][z + 3] + r118[x - time + 3][y - time + 3][z + 1]*r74[x - time + 3][y - time + 3][z + 1] - r118[x - time + 3][y - time + 3][z + 5]*r74[x - time + 3][y - time + 3][z + 5] - r118[x - time + 3][y - time + 5][z + 3]*r75[x - time + 3][y - time + 5][z + 3]*r76[x - time + 3][y - time + 5][z + 3] - r118[x - time + 5][y - time + 3][z + 3]*r76[x - time + 5][y - time + 3][z + 3]*r77[x - time + 5][y - time + 3][z + 3]) + 7.50000011e-2F*(-r118[x - time + 2][y - time + 3][z + 3]*r76[x - time + 2][y - time + 3][z + 3]*r77[x - time + 2][y - time + 3][z + 3] - r118[x - time + 3][y - time + 2][z + 3]*r75[x - time + 3][y - time + 2][z + 3]*r76[x - time + 3][y - time + 2][z + 3] - r118[x - time + 3][y - time + 3][z + 2]*r74[x - time + 3][y - time + 3][z + 2] + r118[x - time + 3][y - time + 3][z + 4]*r74[x - time + 3][y - time + 3][z + 4] + r118[x - time + 3][y - time + 4][z + 3]*r75[x - time + 3][y - time + 4][z + 3]*r76[x - time + 3][y - time + 4][z + 3] + r118[x - time + 4][y - time + 3][z + 3]*r76[x - time + 4][y - time + 3][z + 3]*r77[x - time + 4][y - time + 3][z + 3]) - 6.01250588e-7F*(u[t0][x - time + 6][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 6][z + 12] + u[t0][x - time + 12][y - time + 12][z + 6] + u[t0][x - time + 12][y - time + 12][z + 18] + u[t0][x - time + 12][y - time + 18][z + 12] + u[t0][x - time + 18][y - time + 12][z + 12]) + 1.03896102e-5F*(u[t0][x - time + 7][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 7][z + 12] + u[t0][x - time + 12][y - time + 12][z + 7] + u[t0][x - time + 12][y - time + 12][z + 17] + u[t0][x - time + 12][y - time + 17][z + 12] + u[t0][x - time + 17][y - time + 12][z + 12]) - 8.92857123e-5F*(u[t0][x - time + 8][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 8][z + 12] + u[t0][x - time + 12][y - time + 12][z + 8] + u[t0][x - time + 12][y - time + 12][z + 16] + u[t0][x - time + 12][y - time + 16][z + 12] + u[t0][x - time + 16][y - time + 12][z + 12]) + 5.29100517e-4F*(u[t0][x - time + 9][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 9][z + 12] + u[t0][x - time + 12][y - time + 12][z + 9] + u[t0][x - time + 12][y - time + 12][z + 15] + u[t0][x - time + 12][y - time + 15][z + 12] + u[t0][x - time + 15][y - time + 12][z + 12]) - 2.67857137e-3F*(u[t0][x - time + 10][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 10][z + 12] + u[t0][x - time + 12][y - time + 12][z + 10] + u[t0][x - time + 12][y - time + 12][z + 14] + u[t0][x - time + 12][y - time + 14][z + 12] + u[t0][x - time + 14][y - time + 12][z + 12]) + 1.71428568e-2F*(u[t0][x - time + 11][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 11][z + 12] + u[t0][x - time + 12][y - time + 12][z + 11] + u[t0][x - time + 12][y - time + 12][z + 13] + u[t0][x - time + 12][y - time + 13][z + 12] + u[t0][x - time + 13][y - time + 12][z + 12]) - 8.94833313e-2F*u[t0][x - time + 12][y - time + 12][z + 12]; float r116 = r129*(-2.0F*u[t0][x - time + 12][y - time + 12][z + 12] + u[t1][x - time + 12][y - time + 12][z + 12]); float r117 = r129*(-2.0F*v[t0][x - time + 12][y - time + 12][z + 12] + v[t1][x - time + 12][y - time + 12][z + 12]); u[t2][x - time + 12][y - time + 12][z + 12] = r124*((-r116)*r125 + r123*(2*epsilon[x - time + 12][y - time + 12][z + 12] + 1) + r130*(damp[x - time + 1][y - time + 1][z + 1]*u[t0][x - time + 12][y - time + 12][z + 12]) + (r126 + r127 + r128)*r73[x - time + 3][y - time + 3][z + 3]); v[t2][x - time + 12][y - time + 12][z + 12] = r124*((-r117)*r125 + r123*r73[x - time + 3][y - time + 3][z + 3] + r126 + r127 + r128 + r130*(damp[x - time + 1][y - time + 1][z + 1]*v[t0][x - time + 12][y - time + 12][z + 12])); } //int sp_zi_M = nnz_sp_source_mask[x - time][y - time] - 1; for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1) { int zind = sp_source_mask[x - time][y - time][sp_zi]; float r0 = save_src_u[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; //#pragma omp atomic update u[t2][x - time + 12][y - time + 12][zind + 12] += r0; float r1 = save_src_v[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; //#pragma omp atomic update v[t2][x - time + 12][y - time + 12][zind + 12] += r1; printf("Source injection at time %d , at : x: %d, y: %d, %d, %f, %f \n", tw, x - time + 12, y - time + 12, zind + 8, r0, r1); } } } } } } }
test_openmp.c
#include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <pthread.h> #define data_type double struct option opt_options[] = { {"threads", required_argument, NULL, 'n'}, {"help", no_argument, NULL, 'h'}, {NULL, no_argument, NULL, 0} }; const char* opt_string = "n:h"; void usage(char* process_name) { printf("\ usage: %s option [arguments] \n \ --help -h print this help infomation. \n \ --threads -n [thread number] set the thread number. \n \ \n", process_name); exit(0); } data_type* matrix; data_type* vec; data_type* res; int thread_count = -1, opt_index; int row, col; void func() { #pragma omp parallel for for (int i = 0; i < row; ++i) { data_type t = 0.0; for (int j = 0; j < col; ++j) { t += matrix[i * col + j] * vec[j]; } res[i] = t; } } int main(int argc, char** argv) { freopen("out.txt", "r", stdin); int opt = getopt_long(argc, argv, opt_string, opt_options, &opt_index); if (opt == -1) { usage(argv[0]); } while (~opt) { switch(opt) { case 'n': thread_count = atoi(optarg); break; case 'h': default: usage(argv[0]); } opt = getopt_long(argc, argv, opt_string, opt_options, &opt_index); } if (thread_count == -1) { fprintf(stderr, "please give the run threads.\n"); return -1; } scanf("%d %d", &row, &col); matrix = malloc(row * col * sizeof(data_type)); vec = malloc(col * sizeof(data_type)); res = malloc(row * sizeof(data_type)); printf("input the matrix:\n"); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { scanf("%lf", matrix + i * col + j); } } printf("input the vector x:\n"); for (int i = 0; i < col; ++i) { scanf("%lf", vec + i); } for (int _t = 0; _t < 100000; ++_t) { func(); } printf("%f ", res[233]); printf("\n"); free(matrix); free(vec); free(res); return 0; }
GB_binop__bor_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_01__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_03__bor_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bor_uint8) // A*D function (colscale): GB (_AxD__bor_uint8) // D*A function (rowscale): GB (_DxB__bor_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__bor_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__bor_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bor_uint8) // C=scalar+B GB (_bind1st__bor_uint8) // C=scalar+B' GB (_bind1st_tran__bor_uint8) // C=A+scalar GB (_bind2nd__bor_uint8) // C=A'+scalar GB (_bind2nd_tran__bor_uint8) // C type: uint8_t // A type: uint8_t // B,b type: uint8_t // BinaryOp: cij = (aij) | (bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x) | (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BOR || GxB_NO_UINT8 || GxB_NO_BOR_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bor_uint8) ( 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__bor_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bor_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__bor_uint8) ( 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 uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__bor_uint8) ( 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 uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bor_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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__bor_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__bor_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bor_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__bor_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bor_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = (x) | (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bor_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) | (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) | (aij) ; \ } GrB_Info GB (_bind1st_tran__bor_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) | (y) ; \ } GrB_Info GB (_bind2nd_tran__bor_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bug51781.c
// Use the generic state machine. On some architectures, other threads in the // main thread's warp must avoid barrier instructions. // // RUN: %libomptarget-compile-run-and-check-generic // SPMDize. There is no main thread, so there's no issue. // // RUN: %libomptarget-compile-generic -O1 -Rpass=openmp-opt > %t.spmd 2>&1 // RUN: %fcheck-nvptx64-nvidia-cuda -check-prefix=SPMD -input-file=%t.spmd // RUN: %fcheck-amdgcn-amd-amdhsa -check-prefix=SPMD -input-file=%t.spmd // RUN: %libomptarget-run-generic 2>&1 | %fcheck-generic // // SPMD: Transformed generic-mode kernel to SPMD-mode. // Use the custom state machine, which must avoid the same barrier problem as // the generic state machine. // // RUN: %libomptarget-compile-generic -O1 -Rpass=openmp-opt \ // RUN: -mllvm -openmp-opt-disable-spmdization > %t.custom 2>&1 // RUN: %fcheck-nvptx64-nvidia-cuda -check-prefix=CUSTOM -input-file=%t.custom // RUN: %fcheck-amdgcn-amd-amdhsa -check-prefix=CUSTOM -input-file=%t.custom // RUN: %libomptarget-run-generic 2>&1 | %fcheck-generic // // Repeat with reduction clause, which has managed to break the custom state // machine in the past. // // RUN: %libomptarget-compile-generic -O1 -Rpass=openmp-opt -DADD_REDUCTION \ // RUN: -mllvm -openmp-opt-disable-spmdization > %t.custom 2>&1 // RUN: %fcheck-nvptx64-nvidia-cuda -check-prefix=CUSTOM -input-file=%t.custom // RUN: %fcheck-amdgcn-amd-amdhsa -check-prefix=CUSTOM -input-file=%t.custom // RUN: %libomptarget-run-generic 2>&1 | %fcheck-generic // // CUSTOM: Rewriting generic-mode kernel with a customized state machine. // Hangs // UNSUPPORTED: amdgcn-amd-amdhsa // UNSUPPORTED: amdgcn-amd-amdhsa-newDriver #if ADD_REDUCTION # define REDUCTION(...) reduction(__VA_ARGS__) #else # define REDUCTION(...) #endif #include <stdio.h> int main() { int x = 0, y = 1; #pragma omp target teams num_teams(1) map(tofrom:x, y) REDUCTION(+:x) { x += 5; #pragma omp parallel y = 6; } // CHECK: 5, 6 printf("%d, %d\n", x, y); return 0; }
LAGraph_dense_relabel.c
//------------------------------------------------------------------------------ // LAGraph_dense_relabel: dense relabeling of ids to matrix indices //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // // See additional acknowledgments in the LICENSE file, // or contact permission@sei.cmu.edu for the full terms. //------------------------------------------------------------------------------ // FIXME: this is not yet included in the test coverage suite // LAGraph_dense_relabel: relabel sparse IDs to dense row/column indices // Contributed by Marton Elekes and Gabor Szarnyas, // Budapest University of Technology and Economics // (with accented characters: M\'{a}rton Elekes and G\'{a}bor Sz\'{a}rnyas. // Converts array of sparse IDs (ids) to row/column indices between 0...(nids-1). // The order of IDs is kept, therefore ids can be used for index -> ID // conversion: ids[index]=id. // // Gives back two binary matrices for conversion between ID- and index-based // vertices. // id2index vector can be used to look up for indices of chosen IDs. // id_dimension gives back the height of Id2index matrix and id2index vector. // (Same as width of Index2id_handle matrix.) // id_dimension is the size that can store the largest ID in the array. // Currently it is the largest valid dimension in GraphBLAS // (GrB_INDEX_MAX+1) // // Find usage example in /Test/DenseRelabel/dense_relabel_test.c #define LAGraph_FREE_ALL \ { \ LAGraph_Free ((void **)&indices) ; \ LAGraph_Free ((void **)&true_values) ; \ } #include <string.h> // for memset #include <LAGraph.h> #include <LAGraphX.h> #include <LG_internal.h> // from src/utility // These should be freed by the calling code // GrB_free (Id2index_handle) ; \ // GrB_free (Index2id_handle) ; \ // GrB_free (id2index_handle) ; \ //------------------------------------------------------------------------------ GrB_Info LAGraph_dense_relabel // relabel sparse IDs to dense row/column indices ( GrB_Matrix *Id2index_handle, // output matrix: A(id, index)=1 (unfilled if NULL) GrB_Matrix *Index2id_handle, // output matrix: B(index, id)=1 (unfilled if NULL) GrB_Vector *id2index_handle, // output vector: v(id)=index (unfilled if NULL) const GrB_Index *ids, // array of unique identifiers (<= GrB_INDEX_MAX) GrB_Index nids, // number of identifiers GrB_Index *id_dimension // number of rows in Id2index matrix, id2index vector (unfilled if NULL) ) { GrB_Info info; // needed for LAGRAPH_OK GrB_Index *indices = NULL; bool *true_values = NULL; // from LAGraph_1_to_n.c int nthreads; LAGRAPH_OK (LAGraph_GetNumThreads(&nthreads, NULL)) ; nthreads = LAGraph_MIN ((int64_t) (nids / 4096), nthreads); nthreads = LAGraph_MAX (nthreads, 1); //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- if (!Id2index_handle && !Index2id_handle && !id2index_handle) { LAGRAPH_ERROR ("All output mapping arguments are NULL", GrB_NULL_POINTER); } if (!ids) { LAGRAPH_ERROR ("ids is NULL", GrB_NULL_POINTER); } // the largest valid dimension in GraphBLAS GrB_Index id_max_dimension = GrB_INDEX_MAX+1; if (id_dimension) *id_dimension = id_max_dimension; // set indices 0..(nids-1) indices = LAGraph_Malloc(nids, sizeof(*indices)); if (!indices) { LAGRAPH_ERROR ("Out of Memory", GrB_OUT_OF_MEMORY); } #pragma omp parallel for num_threads(nthreads) schedule(static) for (size_t i = 0; i < nids; ++i) { indices[i] = i; } // build vector id2index(original_id) = index if (id2index_handle) { LAGRAPH_OK (GrB_Vector_new(id2index_handle, GrB_UINT64, id_max_dimension)); LAGRAPH_OK (GrB_Vector_build(*id2index_handle, ids, indices, nids, GrB_SECOND_UINT64)); } if (Id2index_handle || Index2id_handle) { // initialize true values of the matrix true_values = LAGraph_Malloc(nids, sizeof(*true_values)); if (!true_values) { LAGRAPH_ERROR ("Out of Memory", GrB_OUT_OF_MEMORY); } memset(true_values, true, nids * sizeof(*true_values)); // build matrix Index2id(index, original_id) = 1 if (Index2id_handle) { LAGRAPH_OK (GrB_Matrix_new(Index2id_handle, GrB_BOOL, nids, id_max_dimension)); LAGRAPH_OK (GrB_Matrix_build(*Index2id_handle, indices, ids, true_values, nids, GrB_SECOND_UINT64)); } // build matrix Id2index(original_id, index) = 1 if (Id2index_handle) { LAGRAPH_OK (GrB_Matrix_new(Id2index_handle, GrB_BOOL, id_max_dimension, nids)); LAGRAPH_OK (GrB_Matrix_build(*Id2index_handle, ids, indices, true_values, nids, GrB_SECOND_UINT64)); } } LAGraph_FREE_ALL; return GrB_SUCCESS; }
GB_unaryop__identity_bool_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_bool_int64 // op(A') function: GB_tran__identity_bool_int64 // C type: bool // A type: int64_t // cast: bool cij = (bool) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ bool z = (bool) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_bool_int64 ( bool *restrict Cx, const int64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_bool_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
IOLayersRules.h
// Copyright 2016-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #ifndef INPUTLAYER_H #define INPUTLAYER_H #include "Metadata.h" // Rulebook Format // rules[0][0] == mode // rules[0][1] == maxActive per spatial location (==1 for modes 0,1,2) // rules[0][2] == nInputRows // rules[0][3] == nOutputRows // rules[1] nOutputRows x (1+maxActive) // mode 0==guaranteed unique 1==overwrite, 2=keep, 3=sum, 4=mean template <Int dimension> void inputLayerRules(SparseGrids<dimension> &SGs, RuleBook &rules, long *coords, Int nInputRows, Int nInputColumns, Int batchSize, Int mode, Int &nActive) { EASY_FUNCTION(profiler::colors::Blue300); assert(nActive == 0); assert(rules.size() == 0); assert(SGs.size() == 0); SGs.resize(batchSize); // Set a minimum batch size if necessary Point<dimension> p; if (mode == 0) { nActive = nInputRows; rules.resize(1); rules[0].push_back(mode); rules[0].push_back(1); rules[0].push_back(nInputRows); rules[0].push_back(nInputRows); if (nInputColumns == dimension) { SGs.resize(1); auto &sg = SGs[0]; for (Int i = 0; i < nInputRows; ++i) { for (Int j = 0; j < dimension; j++) p[j] = coords[j]; coords += dimension; sg.mp[p] = i; } } else { // nInputColumns == dimension + 1 Int idx; for (Int i = 0; i < nInputRows; ++i) { for (Int j = 0; j < dimension; j++) p[j] = coords[j]; idx = coords[dimension]; coords += dimension + 1; if (idx + 1 >= (Int)SGs.size()) SGs.resize(idx + 1); SGs[idx].mp[p] = i; } } return; } // Compile list of how input rows correspond to output rows std::vector<std::vector<Int>> outputRows; if (nInputColumns == dimension) { SGs.resize(1); auto &sg = SGs[0]; for (Int i = 0; i < nInputRows; ++i) { for (Int j = 0; j < dimension; j++) p[j] = coords[j]; coords += dimension; auto iter = sg.mp.find(p); if (iter == sg.mp.end()) { sg.mp[p] = nActive++; outputRows.resize(nActive); } outputRows[sg.mp[p]].push_back(i); } } else { // nInputColumns == dimension + 1 Int idx; for (Int i = 0; i < nInputRows; ++i) { for (Int j = 0; j < dimension; j++) p[j] = coords[j]; idx = coords[dimension]; coords += dimension + 1; if (idx + 1 >= (Int)SGs.size()) SGs.resize(idx + 1); auto &sg = SGs[idx]; auto iter = sg.mp.find(p); if (iter == sg.mp.end()) { sg.mp[p] = nActive++; outputRows.resize(nActive); } outputRows[sg.mp[p]].push_back(i); } } rules.resize(2); rules[0].push_back(mode); rules[0].push_back(1); // replace with maxActive if mode==3 or 4 rules[0].push_back(nInputRows); rules[0].push_back(outputRows.size()); auto &rule = rules[1]; if (mode == 1) { for (Int i = 0; i < nActive; ++i) { rule.push_back(1); rule.push_back(outputRows[i].front()); } } if (mode == 2) { for (Int i = 0; i < nActive; ++i) { rule.push_back(1); rule.push_back(outputRows[i].back()); } } if (mode == 3 or mode == 4) { Int maxActive = 0; for (auto &row : outputRows) maxActive = std::max(maxActive, (Int)row.size()); rules[0][1] = maxActive; for (auto &row : outputRows) { rule.push_back(row.size()); for (auto &r : row) rule.push_back(r); rule.resize((rule.size() + maxActive) / (maxActive + 1) * (maxActive + 1)); } } } #ifdef GPU_GRID // TODO template <Int dimension> void inputLayerRulesSimple(GPU_SparseGrids<dimension> &SGs, RuleBook &rules, long *coords, Int nInputRows, Int nInputColumns, Int batchSize, Int mode, Int &nActive) { EASY_FUNCTION(profiler::colors::Blue300); assert(mode == 3 || mode == 4); assert(nActive == 0); assert(rules.size() == 0); assert(SGs.size() == 0); // Compile list of how input rows correspond to output rows // nInputColumns == dimension + 1 Points<dimension> points; points.resize(nInputRows); SGs.resize(batchSize); std::vector<uint32_t> point_cloud_start(batchSize+1); uint32_t *d_keys = NULL; uint32_t *d_index = NULL; uint32_t *d_points = NULL; // Allocate memory for keys gpuErrchk(cudaMalloc((void**)&d_keys, sizeof(uint32_t) * nInputRows)); gpuErrchk(cudaMalloc((void**)&d_index, sizeof(uint32_t) * nInputRows)); gpuErrchk(cudaMalloc((void**)&d_points, sizeof(uint32_t) * dimension * nInputRows)); HashInputPointClouds<dimension>(coords, (uint32_t * )point_cloud_start.data(), d_points, d_keys, d_index, nInputRows, batchSize); Int numOutputRules = 0; int max_repeat_num = 0; for(Int i = 0; i < batchSize; i++) { auto &SG = SGs[i]; if(i != 0) { SG.ctr = SGs[i-1].ctr + SGs[i-1].pHash->size; } int maxRepeat; SGs[i].pHash->InsertAndCompactPointCloud(d_keys + point_cloud_start[i],d_index + point_cloud_start[i], d_points, point_cloud_start[i+1] - point_cloud_start[i], nInputRows,maxRepeat); if(maxRepeat > max_repeat_num) max_repeat_num = maxRepeat; numOutputRules += SGs[i].pHash->size; } gpuErrchk(cudaFree(d_keys)); gpuErrchk(cudaFree(d_index)); gpuErrchk(cudaFree(d_points)); std::vector<Int> currentRule(numOutputRules * (max_repeat_num + 1)); Int * rule_index = (Int * )currentRule.data(); for(Int i = 0; i < batchSize; i++) { auto &SG = SGs[i]; SG.pHash->generateInputRules(rule_index, max_repeat_num); rule_index += SG.pHash->size * (max_repeat_num+1); } nActive = numOutputRules; rules.clear(); rules.resize(2); rules[0].push_back(mode); rules[0].push_back(1); // replace with maxActive if mode==3 or 4 rules[0].push_back(nInputRows); rules[0].push_back(numOutputRules); rules[1] = currentRule; rules[0][1] = max_repeat_num; } // TODO template <Int dimension> void inputLayerRules(GPU_SparseGrids<dimension> &SGs, RuleBook &rules, long *coords, Int nInputRows, Int nInputColumns, Int batchSize, Int mode, Int &nActive) { EASY_FUNCTION(profiler::colors::Blue300); EASY_BLOCK("coord to point"); assert(mode == 3 || mode == 4); assert(nActive == 0); assert(rules.size() == 0); assert(SGs.size() == 0); Point<dimension> p; // Compile list of how input rows correspond to output rows // nInputColumns == dimension + 1 Points<dimension> points; points.resize(nInputRows); std::vector<Int> pc_start; // size = batchsize + 1 int cnt = -1; long *coords_ptr = coords; for (Int i = 0; i < nInputRows; ++i) { for (Int j = 0; j < dimension; j++) p[j] = coords_ptr[j]; points[i] = p; if(cnt < coords_ptr[dimension]) { cnt ++; pc_start.push_back(i); } coords_ptr += (dimension+1); } pc_start.push_back(nInputRows); batchSize = pc_start.size() - 1; SGs.resize(batchSize); // Set a minimum batch size if necessary std::vector<std::vector<Int>> outputRows; EASY_END_BLOCK; EASY_BLOCK("Point to gpu hash"); for(Int i = 0; i < batchSize; i++) { auto &SG = SGs[i]; Points<dimension> points_sample(points.begin() + pc_start[i], points.begin() + pc_start[i+1]); Ints idx; if(i != 0) { SG.ctr = SGs[i-1].ctr + SGs[i-1].pHash->size; } // for(Int k = 0; k < (Int)points_sample.size(); k++) { // // std::cout << points_sample[k] << std::endl; // printf("%d, %d, %d\n", points_sample[k][0], points_sample[k][1], points_sample[k][2]); // } SG.pHash->insert_points(points_sample); SG.pHash->retrieve_points(points_sample, idx); outputRows.resize(SG.ctr + SGs[i].pHash->size); for(Int j = 0; j < (Int)idx.size(); j++) { outputRows[SG.ctr + idx[j]].push_back(pc_start[i] + j); } } EASY_END_BLOCK; EASY_BLOCK("max,mean"); nActive = outputRows.size(); rules.resize(2); rules[0].push_back(mode); rules[0].push_back(1); // replace with maxActive if mode==3 or 4 rules[0].push_back(nInputRows); rules[0].push_back(outputRows.size()); auto &rule = rules[1]; if (mode == 3 or mode == 4) { Int maxActive = 0; for (auto &row : outputRows) maxActive = std::max(maxActive, (Int)row.size()); rules[0][1] = maxActive; for (auto &row : outputRows) { rule.push_back(row.size()); for (auto &r : row) rule.push_back(r); rule.resize((rule.size() + maxActive) / (maxActive + 1) * (maxActive + 1)); } } EASY_END_BLOCK; } #endif // Rulebook Format // rules[0][0] == mode // rules[0][1] == maxActive per spatial location (==1 for modes 0,1,2) // rules[0][2] == batchSize // rules[0][3] == length // rules[0][4] == nOutputRows // rules[1] nOutputRows x (1+maxActive) // bl is a batchSize x length x dimension long array of coordinates // mode 0==guaranteed unique and all present; 1==overwrite, 2=keep, 3=sum, // 4=mean template <Int dimension> void blRules(SparseGrids<dimension> &SGs, RuleBook &rules, long *coords, Int batchSize, Int length, Int mode, Int &nActive) { assert(nActive == 0); assert(rules.size() == 0); assert(SGs.size() == 0); SGs.resize(batchSize); Int I; if (mode == 0) { nActive = batchSize * length; rules.resize(1); rules[0].push_back(mode); rules[0].push_back(1); rules[0].push_back(batchSize); rules[0].push_back(length); rules[0].push_back(nActive); #pragma omp parallel for private(I) for (I = 0; I < batchSize; I++) { auto &sg = SGs[I]; sg.ctr = I * length; auto c = coords + I * length * dimension; Point<dimension> p; for (Int l = 0; l < length; ++l) { for (Int j = 0; j < dimension; ++j) p[j] = c[j]; c += dimension; sg.mp[p] = l; } } return; } // Compile list of how input rows correspond to output rows std::vector<std::vector<std::vector<Int>>> outputRows(batchSize); std::vector<Int> nActives(batchSize); #pragma omp parallel for private(I) for (I = 0; I < batchSize; I++) { auto &sg = SGs[I]; auto &ors = outputRows[I]; auto &nAct = nActives[I]; auto c = coords + I * length * dimension; Int i = I * length; Point<dimension> p; for (Int l = 0; l < length; ++l, ++i) { for (Int j = 0; j < dimension; ++j) p[j] = *c++; if (p[0] >= 0) { auto iter = sg.mp.find(p); if (iter == sg.mp.end()) { sg.mp[p] = nAct++; ors.resize(nAct); } ors[sg.mp[p]].push_back(i); } } } for (I = 0; I < batchSize; I++) { SGs[I].ctr = nActive; nActive += nActives[I]; } Int maxActive = 1; if (mode >= 3) for (auto &ors : outputRows) for (auto &row : ors) maxActive = std::max(maxActive, (Int)row.size()); rules.resize(2); rules[0].push_back(mode); rules[0].push_back(maxActive); rules[0].push_back(batchSize); rules[0].push_back(length); rules[0].push_back(nActive); auto &rule = rules[1]; if (mode == 1) { rule.resize(2 * nActive); #pragma omp parallel for private(I) for (I = 0; I < batchSize; I++) { auto &ors = outputRows[I]; auto rr = &rule[SGs[I].ctr * 2]; for (auto &row : ors) { rr[0] = row.size(); rr[1] = row.back(); rr += 2; } } } if (mode == 2) { rule.resize(2 * nActive); #pragma omp parallel for private(I) for (I = 0; I < batchSize; I++) { auto &ors = outputRows[I]; auto rr = &rule[SGs[I].ctr * 2]; for (auto &row : ors) { rr[0] = row.size(); rr[1] = row.front(); rr += 2; } } } if (mode == 3 or mode == 4) { rule.resize((maxActive + 1) * nActive); #pragma omp parallel for private(I) for (I = 0; I < batchSize; I++) { auto &ors = outputRows[I]; auto rr = &rule[SGs[I].ctr * (maxActive + 1)]; for (auto &row : ors) { rr[0] = row.size(); for (Int i = 0; i < (Int)row.size(); ++i) rr[i + 1] = row[i]; rr += 1 + maxActive; } } } } #endif /* INPUTLAYER_H */
GB_unaryop__one_uint32_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__one_uint32_uint32 // op(A') function: GB_tran__one_uint32_uint32 // C type: uint32_t // A type: uint32_t // cast: ; // unaryop: cij = 1 #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1 ; // casting #define GB_CASTING(z, 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_ONE || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__one_uint32_uint32 ( uint32_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__one_uint32_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
reader.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef READER_H_ #define READER_H_ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <type_traits> #include "pvector.h" #include "misc.h" /* GAP Benchmark Suite Class: Reader Author: Scott Beamer Given filename, returns an edgelist or the entire graph (if serialized) - Intended to be called from Builder - Determines file format from the filename's suffix - If the input graph is serialized (.sg or .wsg), reads the graph directly into the returned graph instance - Otherwise, reads the file and returns an edgelist */ ///* template <typename VertexID_, typename DestID_ = VertexID_> inline DestID_** GenIndex(const pvector<SGOffset> &offsets, DestID_* neighs) { VertexID_ length = offsets.size(); DestID_** index = new DestID_*[length]; #pragma omp parallel for for (VertexID_ n=0; n < length; n++) index[n] = neighs + offsets[n]; return index; } //*/ template <typename VertexID_, typename DestID_ = VertexID_, typename WeightT_ = VertexID_, bool invert = true> class Reader { typedef EdgePair<VertexID_, DestID_> Edge; typedef pvector<Edge> EdgeList; std::string filename_; public: explicit Reader(std::string filename) : filename_(filename) {} std::string GetSuffix() { std::size_t suff_pos = filename_.rfind('.'); if (suff_pos == std::string::npos) { std::cout << "Could't find suffix of " << filename_ << std::endl; std::exit(-1); } return filename_.substr(suff_pos); } EdgeList ReadInEL(std::ifstream &in) { EdgeList el; VertexID_ u, v; while (in >> u >> v) { el.push_back(Edge(u, v)); } return el; } EdgeList ReadInWEL(std::ifstream &in) { EdgeList el; VertexID_ u; VertexWeight<VertexID_, WeightT_> v; while (in >> u >> v) { el.push_back(Edge(u, v)); } return el; } // Note: converts vertex numbering from 1..N to 0..N-1 EdgeList ReadInGR(std::ifstream &in) { EdgeList el; char c; VertexID_ u; VertexWeight<VertexID_, WeightT_> v; while (!in.eof()) { c = in.peek(); if (c == 'a') { in >> c >> u >> v; el.push_back(Edge(u - 1, VertexWeight<VertexID_, WeightT_>(v.v-1, v.w))); } else { in.ignore(200, '\n'); } } return el; } // Note: converts vertex numbering from 1..N to 0..N-1 EdgeList ReadInMetis(std::ifstream &in, bool &needs_weights) { EdgeList el; VertexID_ num_vertices, num_edges; char c; std::string line; bool read_weights = false; while (true) { c = in.peek(); if (c == '%') { in.ignore(200, '\n'); } else { std::getline(in, line, '\n'); std::istringstream header_stream(line); header_stream >> num_vertices >> num_edges; header_stream >> std::ws; if (!header_stream.eof()) { int32_t fmt; header_stream >> fmt; if (fmt == 1) { read_weights = true; } else if ((fmt != 0) && (fmt != 100)) { std::cout << "Do not support METIS fmt type: " << fmt << std::endl; std::exit(-20); } } break; } } VertexID_ u = 0; while (u < num_vertices) { c = in.peek(); if (c == '%') { in.ignore(200, '\n'); } else { std::getline(in, line); if (line != "") { std::istringstream edge_stream(line); if (read_weights) { VertexWeight<VertexID_, WeightT_> v; while (edge_stream >> v >> std::ws) { v.v -= 1; el.push_back(Edge(u, v)); } } else { VertexID_ v; while (edge_stream >> v >> std::ws) { el.push_back(Edge(u, v - 1)); } } } u++; } } needs_weights = !read_weights; return el; } // Note: converts vertex numbering from 1..N to 0..N-1 // Note: weights casted to type WeightT_ EdgeList ReadInMTX(std::ifstream &in, bool &needs_weights) { EdgeList el; std::string start, object, format, field, symmetry, line; in >> start >> object >> format >> field >> symmetry >> std::ws; if (start != "%%MatrixMarket") { std::cout << ".mtx file did not start with %%MatrixMarket" << std::endl; std::exit(-21); } if ((object != "matrix") || (format != "coordinate")) { std::cout << "only allow matrix coordinate format for .mtx" << std::endl; std::exit(-22); } if (field == "complex") { std::cout << "do not support complex weights for .mtx" << std::endl; std::exit(-23); } bool read_weights; if (field == "pattern") { read_weights = false; } else if ((field == "real") || (field == "double") || (field == "integer")) { read_weights = true; } else { std::cout << "unrecognized field type for .mtx" << std::endl; std::exit(-24); } bool undirected; if (symmetry == "symmetric") { undirected = true; } else if ((symmetry == "general") || (symmetry == "skew-symmetric")) { undirected = false; } else { std::cout << "unsupported symmetry type for .mtx" << std::endl; std::exit(-25); } while (true) { char c = in.peek(); if (c == '%') { in.ignore(200, '\n'); } else { break; } } int64_t m, n, nonzeros; in >> m >> n >> nonzeros >> std::ws; if (m != n) { std::cout << m << " " << n << " " << nonzeros << std::endl; std::cout << "matrix must be square for .mtx" << std::endl; std::exit(-26); } while (std::getline(in, line)) { std::istringstream edge_stream(line); VertexID_ u; edge_stream >> u; if (read_weights) { VertexWeight<VertexID_, WeightT_> v; edge_stream >> v; v.v -= 1; el.push_back(Edge(u - 1, v)); if (undirected) el.push_back(Edge(v, u - 1)); } else { VertexID_ v; edge_stream >> v; el.push_back(Edge(u - 1, v - 1)); if (undirected) el.push_back(Edge(v - 1, u - 1)); } } needs_weights = !read_weights; return el; } EdgeList ReadFile(bool &needs_weights) { Timer t; t.Start(); EdgeList el; std::string suffix = GetSuffix(); std::ifstream file(filename_); if (!file.is_open()) { std::cout << "Couldn't open file " << filename_ << std::endl; std::exit(-2); } if (suffix == ".el") { el = ReadInEL(file); } else if (suffix == ".wel") { needs_weights = false; el = ReadInWEL(file); } else if (suffix == ".gr") { needs_weights = false; el = ReadInGR(file); } else if (suffix == ".graph") { el = ReadInMetis(file, needs_weights); } else if (suffix == ".mtx") { el = ReadInMTX(file, needs_weights); } else { std::cout << "Unrecognized suffix: " << suffix << std::endl; std::exit(-3); } file.close(); t.Stop(); PrintTime("Read Time", t.Seconds()); return el; } //CSRGraph<VertexID_, DestID_, invert>& ReadSerializedGraph() { void ReadSerializedGraph(CSRGraph<VertexID_, DestID_, invert>& g) { bool weighted = GetSuffix() == ".wsg"; if (!std::is_same<VertexID_, SGID>::value) { std::cout << "serialized graphs only allowed for 32bit" << std::endl; std::exit(-5); } if (!weighted && !std::is_same<VertexID_, DestID_>::value) { std::cout << ".sg not allowed for weighted graphs" << std::endl; std::exit(-5); } if (weighted && std::is_same<VertexID_, DestID_>::value) { std::cout << ".wsg only allowed for weighted graphs" << std::endl; std::exit(-5); } if (weighted && !std::is_same<WeightT_, SGID>::value) { std::cout << ".wsg only allowed for int32_t weights" << std::endl; std::exit(-5); } std::ifstream file(filename_); if (!file.is_open()) { std::cout << "Couldn't open file " << filename_ << std::endl; std::exit(-6); } Timer t; t.Start(); bool directed; SGOffset num_vertices, num_edges; DestID_ **index = nullptr, **inv_index = nullptr; DestID_ *neighs = nullptr, *inv_neighs = nullptr; file.read(reinterpret_cast<char*>(&directed), sizeof(bool)); file.read(reinterpret_cast<char*>(&num_edges), sizeof(SGOffset)); file.read(reinterpret_cast<char*>(&num_vertices), sizeof(SGOffset)); pvector<SGOffset> offsets(num_vertices+1); neighs = new DestID_[num_edges]; std::streamsize num_index_bytes = (num_vertices+1) * sizeof(SGOffset); std::streamsize num_neigh_bytes = num_edges * sizeof(DestID_); file.read(reinterpret_cast<char*>(offsets.data()), num_index_bytes); file.read(reinterpret_cast<char*>(neighs), num_neigh_bytes); index = GenIndex<VertexID_, DestID_>(offsets, neighs); //index = CSRGraph<VertexID_, DestID_>::GenIndex(offsets, neighs); if (directed && invert) { inv_neighs = new DestID_[num_edges]; file.read(reinterpret_cast<char*>(offsets.data()), num_index_bytes); file.read(reinterpret_cast<char*>(inv_neighs), num_neigh_bytes); inv_index = GenIndex<VertexID_, DestID_>(offsets, inv_neighs); //inv_index = CSRGraph<VertexID_, DestID_>::GenIndex(offsets, inv_neighs); } file.close(); t.Stop(); PrintTime("Read Time", t.Seconds()); if (directed) g.Setup(num_vertices, NULL, index, neighs, NULL, inv_index, inv_neighs); //return CSRGraph<VertexID_, DestID_, invert>(num_vertices, index, neighs, inv_index, inv_neighs); else g.Setup(num_vertices, NULL, index, neighs); //return CSRGraph<VertexID_, DestID_, invert>(num_vertices, index, neighs); } }; #endif // READER_H_
text_parser.h
/*! * Copyright (c) 2015 by Contributors * \file text_parser.h * \brief iterator parser to parse text format * \author Tianqi Chen */ #ifndef DMLC_DATA_TEXT_PARSER_H_ #define DMLC_DATA_TEXT_PARSER_H_ #include "dmlc/data.h" #include "dmlc/omp.h" #include <vector> #include <cstring> #include <algorithm> #include "./row_block.h" #include "./parser.h" namespace dmlc { namespace data { /*! * \brief Text parser that parses the input lines * and returns rows in input data */ template <typename IndexType> class TextParserBase : public ParserImpl<IndexType> { public: explicit TextParserBase(InputSplit *source, int nthread) : bytes_read_(0), source_(source) { int maxthread; #pragma omp parallel { maxthread = std::max(omp_get_num_procs() / 2 - 4, 1); } nthread_ = std::min(maxthread, nthread); } virtual ~TextParserBase() { delete source_; } virtual void BeforeFirst(void) { source_->BeforeFirst(); } virtual size_t BytesRead(void) const { return bytes_read_; } virtual bool ParseNext(std::vector<RowBlockContainer<IndexType> > *data) { return FillData(data); } protected: /*! * \brief parse data into out * \param begin beginning of buffer * \param end end of buffer */ virtual void ParseBlock(char *begin, char *end, RowBlockContainer<IndexType> *out) = 0; /*! * \brief read in next several blocks of data * \param data vector of data to be returned * \return true if the data is loaded, false if reach end */ inline bool FillData(std::vector<RowBlockContainer<IndexType> > *data); /*! * \brief start from bptr, go backward and find first endof line * \param bptr end position to go backward * \param begin the beginning position of buffer * \return position of first endof line going backward */ inline char* BackFindEndLine(char *bptr, char *begin) { for (; bptr != begin; --bptr) { if (*bptr == '\n' || *bptr == '\r') return bptr; } return begin; } private: // nthread int nthread_; // number of bytes readed size_t bytes_read_; // source split that provides the data InputSplit *source_; }; // implementation template <typename IndexType> inline bool TextParserBase<IndexType>:: FillData(std::vector<RowBlockContainer<IndexType> > *data) { InputSplit::Blob chunk; if (!source_->NextChunk(&chunk)) return false; int nthread; #pragma omp parallel num_threads(nthread_) { nthread = omp_get_num_threads(); } // reserve space for data data->resize(nthread); bytes_read_ += chunk.size; CHECK_NE(chunk.size, 0); char *head = reinterpret_cast<char*>(chunk.dptr); #pragma omp parallel num_threads(nthread_) { // threadid int tid = omp_get_thread_num(); size_t nstep = (chunk.size + nthread - 1) / nthread; size_t sbegin = std::min(tid * nstep, chunk.size); size_t send = std::min((tid + 1) * nstep, chunk.size); char *pbegin = BackFindEndLine(head + sbegin, head); char *pend; if (tid + 1 == nthread) { pend = head + send; } else { pend = BackFindEndLine(head + send, head); } ParseBlock(pbegin, pend, &(*data)[tid]); } this->data_ptr_ = 0; return true; } } // namespace data } // namespace dmlc #endif // DMLC_DATA_TEXT_PARSER_H_
test.c
#include <stdio.h> #include <omp.h> #include "../utilities/check.h" #include "../utilities/utilities.h" #define TRIALS (1) #define N (992) #define INIT() INIT_LOOP(N, {C[i] = 1; D[i] = i; E[i] = -i;}) #define ZERO(X) ZERO_ARRAY(N, X) int main(void) { check_offloading(); double A[N], B[N], C[N], D[N], E[N]; int fail = 0; INIT(); // ************************** // Series 1: no dist_schedule // ************************** // // Test: #iterations == #teams // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // **************************** // Series 2: with dist_schedule // **************************** // // Test: #iterations == #teams, dist_schedule(1) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,1) num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations == #teams, dist_schedule(#iterations) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,512) num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations == #teams, dist_schedule(#iterations/10), variable chunk size // ZERO(A); int ten = 10; int chunkSize = 512/ten; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,chunkSize) num_teams(512) for (int i = 0 ; i < 512 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 512 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams, dist_schedule(1) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,1) num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams, dist_schedule(#iterations) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,500) num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations > #teams, dist_schedule(#iterations/10), variable chunk size // ZERO(A); ten = 10; chunkSize = 500/ten; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,chunkSize) num_teams(256) for (int i = 0 ; i < 500 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 500 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams, dist_schedule(1) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,1) num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams, dist_schedule(#iterations) // ZERO(A); for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,123) num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: #iterations < #teams, dist_schedule(#iterations) // ZERO(A); ten = 10; chunkSize = 123/ten; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute dist_schedule(static,chunkSize) num_teams(256) for (int i = 0 ; i < 123 ; i++) { A[i] += C[i]; // += 1 per position } } for (int i = 0 ; i < 123 ; i++) if (A[i] != TRIALS) { printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // **************************** // Series 3: with ds attributes // **************************** // // Test: private // ZERO(A); ZERO(B); double p = 2.0, q = 4.0; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute private(p,q) num_teams(256) for(int i = 0 ; i < N ; i++) { p = 2; q = 3; A[i] += p; B[i] += q; } } for(int i = 0 ; i < N ; i++) { if (A[i] != TRIALS*2) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) TRIALS*2, A[i]); fail = 1; } if (B[i] != TRIALS*3) { printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) TRIALS*3, B[i]); fail = 1; } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: firstprivate // ZERO(A); ZERO(B); p = 2.0, q = 4.0; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute firstprivate(p,q) num_teams(64) for(int i = 0 ; i < 128 ; i++) { // 2 iterations for each team p += 3.0; // p and q are firstprivate to the team, and as such incremented twice (2 iterations per team) q += 7.0; A[i] += p; B[i] += q; } } for(int i = 0 ; i < 128 ; i++) { if (i % 2 == 0) { if (A[i] != (2.0+3.0)*TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]); fail = 1; } if (B[i] != (4.0+7.0)*TRIALS) { printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0)*TRIALS, B[i]); fail = 1; } } else { if (A[i] != (2.0+3.0*2)*TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0*2)*TRIALS, A[i]); fail = 1; } if (B[i] != (4.0+7.0*2)*TRIALS) { printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0*2)*TRIALS, B[i]); fail = 1; } } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: lastprivate // // requires array because scalar would be treated as implicit firstprivate by target int lastpriv[2] = {-1,-1}; #pragma omp target teams distribute lastprivate(lastpriv) num_teams(10) for(int i = 0 ; i < omp_get_num_teams() ; i++) { lastpriv[0] = omp_get_team_num(); } if(lastpriv[0] != 9) { printf("lastpriv value is %d and should have been %d\n", lastpriv[0], 9); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // *************************** // Series 4: with parallel for // *************************** // // Test: simple blocking loop // ZERO(A); ZERO(B); int nte = 32; int tl = 64; int blockSize = tl; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(nte) thread_limit(tl) for(int j = 0 ; j < 256 ; j += blockSize) { #pragma omp parallel for for(int i = j ; i < j+blockSize; i++) { A[i] += B[i] + C[i]; } } } for(int i = 0 ; i < 256 ; i++) { if (A[i] != TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]); fail = 1; } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: blocking loop where upper bound is not a multiple of tl*nte // ZERO(A); ZERO(B); nte = 32; tl = 64; blockSize = tl; for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute num_teams(nte) thread_limit(tl) for(int j = 0 ; j < 510 ; j += blockSize) { int ub = (j+blockSize < 510) ? (j+blockSize) : 512; #pragma omp parallel for for(int i = j ; i < ub; i++) { A[i] += B[i] + C[i]; } } } for(int i = 0 ; i < 256 ; i++) { if (A[i] != TRIALS) { printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]); fail = 1; } } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // ************************** // Series 5: collapse // ************************** // // Test: 2 loops // double * S = malloc(N*N*sizeof(double)); double * T = malloc(N*N*sizeof(double)); double * U = malloc(N*N*sizeof(double)); for (int i = 0 ; i < N ; i++) for (int j = 0 ; j < N ; j++) { S[i*N+j] = 0.0; T[i*N+j] = 1.0; U[i*N+j] = 2.0; } for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute collapse(2) map(tofrom:S[:N*N]), map(to:T[:N*N],U[:N*N]) num_teams(512) for (int i = 0 ; i < N ; i++) for (int j = 0 ; j < N ; j++) S[i*N+j] += T[i*N+j] + U[i*N+j]; // += 3 at each t } for (int i = 0 ; i < N ; i++) for (int j = 0 ; j < N ; j++) if (S[i*N+j] != TRIALS*3.0) { printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, S[i*N+j]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); // // Test: 3 loops // int M = N/8; double * V = malloc(M*M*M*sizeof(double)); double * Z = malloc(M*M*M*sizeof(double)); for (int i = 0 ; i < M ; i++) for (int j = 0 ; j < M ; j++) for (int k = 0 ; k < M ; k++) { V[i*M*M+j*M+k] = 2.0; Z[i*M*M+j*M+k] = 3.0; } for (int t = 0 ; t < TRIALS ; t++) { #pragma omp target teams distribute collapse(3) map(tofrom:V[:M*M*M]), map(to:Z[:M*M*M]) num_teams(512) for (int i = 0 ; i < M ; i++) for (int j = 0 ; j < M ; j++) for (int k = 0 ; k < M ; k++) V[i*M*M+j*M+k] += Z[i*M*M+j*M+k]; // += 3 at each t } for (int i = 0 ; i < M ; i++) for (int j = 0 ; j < M ; j++) for (int k = 0 ; k < M ; k++) if (V[i*M*M+j*M+k] != 2.0+TRIALS*3.0) { printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, V[i*M*M+j*M+k]); fail = 1; } if(fail) printf("Failed\n"); else printf("Succeeded\n"); return 0; }
cc_cpufn.c
#include <stdlib.h> #include <string.h> #include <math.h> #include "cc_assert.h" #include "util_log.h" #include "cc_cpufn.h" #define UNSUPPORTED_DTYPE_LOG(dt) \ utlog_format(UTLOG_ERR, \ "cc_cpufn: unsupported dtype [%x]@%s: %d\n",\ dt, __FILE__, __LINE__); #define CC_CPU_RELU_CASE_TEMP(_dt) \ for (i = 0; i < elems; ++i) { \ *(((_dt*)inp) + i) = \ *(((_dt*)inp) + i) > 0 ? \ *(((_dt*)inp) + i) : 0; \ } void cc_cpu_activation_relu(void *inp, cc_int32 elems, cc_dtype dt) { cc_int32 i; switch (dt) { case CC_UINT8: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_uint8); break; case CC_UINT16: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_uint16); break; case CC_UINT32: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_uint32); break; case CC_UINT64: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_uint64); break; case CC_INT8: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_int8); break; case CC_INT16: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_int16); break; case CC_INT32: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_int32); break; case CC_INT64: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_int64); break; case CC_FLOAT32: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_float32); break; case CC_FLOAT64: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU_CASE_TEMP(cc_float64); break; default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define CC_CPU_RELU6_CASE_TEMP(_dt) \ for (i = 0; i < elems; ++i) { \ *(((_dt*)inp) + i) = \ *(((_dt*)inp) + i) > 0 ? \ *(((_dt*)inp) + i) : 0; \ *(((_dt*)inp) + i) = \ *(((_dt*)inp) + i) > 6 ? \ 6 : *(((_dt*)inp) + i); \ } void cc_cpu_activation_relu6(void *inp, cc_int32 elems, cc_dtype dt) { cc_int32 i; switch (dt) { case CC_UINT8: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_uint8); break; case CC_UINT16: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_uint16); break; case CC_UINT32: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_uint32); break; case CC_UINT64: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_uint64); break; case CC_INT8: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_int8); break; case CC_INT16: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_int16); break; case CC_INT32: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_int32); break; case CC_INT64: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_int64); break; case CC_FLOAT32: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_float32); break; case CC_FLOAT64: #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif CC_CPU_RELU6_CASE_TEMP(cc_float64); break; default: UNSUPPORTED_DTYPE_LOG(dt); break; } } static void cc_cpu_activation_softmax_float32( cc_float32 *inp, cc_int32 elems) { cc_int32 i; cc_float32 v, s = 0; for (i = 0; i < elems; ++i) { #ifdef CONFIG_STD_C89 v = (cc_float32)exp(inp[i]); inp[i] = v; s += v; #else v = expf(inp[i]); inp[i] = v; s += v; #endif } for (i = 0; i < elems; ++i) { inp[i] = inp[i] / s; } } static void cc_cpu_activation_softmax_float64( cc_float64 *inp, cc_int32 elems) { cc_int32 i; cc_float64 v, s = 0; for (i = 0; i < elems; ++i) { v = exp(inp[i]); inp[i] = v; s += v; } for (i = 0; i < elems; ++i) { inp[i] = inp[i] / s; } } void cc_cpu_activation_softmax(void *inp, cc_int32 elems, cc_dtype dt) { switch (dt) { case CC_FLOAT32: cc_cpu_activation_softmax_float32( (cc_float32*)inp, elems); break; case CC_FLOAT64: cc_cpu_activation_softmax_float64( (cc_float64*)inp, elems); break; default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define CC_CPU_MAX_POO2D_IMPLEMENTATION(dt) \ static void cc_cpu_max_pool2d_ ## dt (const cc_ ## dt *in, \ cc_ ## dt *out, cc_int32 x, cc_int32 y, cc_int32 sx, \ cc_int32 sy, cc_int32 kw) \ { \ cc_int32 i, j, u, v; \ cc_ ## dt max; \ for (i = 0; i <= y - kw; i += sy) { \ for (j = 0; j <= x - kw; j += sx) { \ max = *(in + i * x + j); \ for (u = 0; u < kw; ++u) { \ for (v = 0; v < kw; ++v) { \ max = max < *(in + (i + u) * x + (j + v)) ? \ *(in + (i + u) * x + (j + v)) : max; \ } \ } \ *out++ = max; \ } \ } \ } CC_CPU_MAX_POO2D_IMPLEMENTATION (uint8) CC_CPU_MAX_POO2D_IMPLEMENTATION (uint16) CC_CPU_MAX_POO2D_IMPLEMENTATION (uint32) CC_CPU_MAX_POO2D_IMPLEMENTATION (uint64) CC_CPU_MAX_POO2D_IMPLEMENTATION (int8) CC_CPU_MAX_POO2D_IMPLEMENTATION (int16) CC_CPU_MAX_POO2D_IMPLEMENTATION (int32) CC_CPU_MAX_POO2D_IMPLEMENTATION (int64) CC_CPU_MAX_POO2D_IMPLEMENTATION (float32) CC_CPU_MAX_POO2D_IMPLEMENTATION (float64) #define CC_CPU_MAX_POOL2D_CASE(DT, dtype) \ case DT: \ cc_cpu_max_pool2d_ ## dtype((const cc_ ## dtype*)inp, \ (cc_ ## dtype*)oup, x, y, sx, sy, kw); \ break; void cc_cpu_max_pool2d(const void *inp, void *oup, cc_int32 x, cc_int32 y, cc_int32 sx, cc_int32 sy, cc_int32 kw, cc_dtype dt) { switch (dt) { CC_CPU_MAX_POOL2D_CASE(CC_UINT8, uint8) CC_CPU_MAX_POOL2D_CASE(CC_UINT16, uint16) CC_CPU_MAX_POOL2D_CASE(CC_UINT32, uint32) CC_CPU_MAX_POOL2D_CASE(CC_UINT64, uint64) CC_CPU_MAX_POOL2D_CASE(CC_INT8, int8) CC_CPU_MAX_POOL2D_CASE(CC_INT16, int16) CC_CPU_MAX_POOL2D_CASE(CC_INT32, int32) CC_CPU_MAX_POOL2D_CASE(CC_INT64, int64) CC_CPU_MAX_POOL2D_CASE(CC_FLOAT32, float32) CC_CPU_MAX_POOL2D_CASE(CC_FLOAT64, float64) default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define CC_CPU_AVG_POO2D_IMPLEMENTATION(dt) \ static void cc_cpu_avg_pool2d_ ## dt (const cc_ ## dt *in, \ cc_ ## dt *out, cc_int32 ix, cc_int32 iy, cc_int32 sx, \ cc_int32 sy, cc_int32 kw) \ { \ cc_int32 i, j, u, v, n = kw * kw; \ cc_ ## dt avg; \ for (i = 0; i <= iy - kw; i += sy) { \ for (j = 0; j <= ix - kw; j += sx) { \ avg = 0; \ for (u = 0; u < kw; ++u) { \ for (v = 0; v < kw; ++v) { \ avg += *(in + (i + u) * ix + (j + v)); \ } \ } \ *out++ = avg / n; \ } \ } \ } CC_CPU_AVG_POO2D_IMPLEMENTATION (uint8) CC_CPU_AVG_POO2D_IMPLEMENTATION (uint16) CC_CPU_AVG_POO2D_IMPLEMENTATION (uint32) CC_CPU_AVG_POO2D_IMPLEMENTATION (uint64) CC_CPU_AVG_POO2D_IMPLEMENTATION (int8) CC_CPU_AVG_POO2D_IMPLEMENTATION (int16) CC_CPU_AVG_POO2D_IMPLEMENTATION (int32) CC_CPU_AVG_POO2D_IMPLEMENTATION (int64) CC_CPU_AVG_POO2D_IMPLEMENTATION (float32) CC_CPU_AVG_POO2D_IMPLEMENTATION (float64) #define CC_CPU_AVG_POOL2D_CASE(DT, dtype) \ case DT: \ cc_cpu_avg_pool2d_ ## dtype((const cc_ ## dtype*)inp, \ (cc_ ## dtype*)oup, x, y, sx, sy, kw); \ break; void cc_cpu_avg_pool2d(const void *inp, void *oup, cc_int32 x, cc_int32 y, cc_int32 sx, cc_int32 sy, cc_int32 kw, cc_dtype dt) { switch (dt) { CC_CPU_AVG_POOL2D_CASE(CC_UINT8, uint8) CC_CPU_AVG_POOL2D_CASE(CC_UINT16, uint16) CC_CPU_AVG_POOL2D_CASE(CC_UINT32, uint32) CC_CPU_AVG_POOL2D_CASE(CC_UINT64, uint64) CC_CPU_AVG_POOL2D_CASE(CC_INT8, int8) CC_CPU_AVG_POOL2D_CASE(CC_INT16, int16) CC_CPU_AVG_POOL2D_CASE(CC_INT32, int32) CC_CPU_AVG_POOL2D_CASE(CC_INT64, int64) CC_CPU_AVG_POOL2D_CASE(CC_FLOAT32, float32) CC_CPU_AVG_POOL2D_CASE(CC_FLOAT64, float64) default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define CC_CPU_CONV2D_IMPLEMENTATION(dt) \ static void cc_cpu_conv2d_ ## dt (const cc_ ## dt *in, \ cc_ ## dt *out, cc_int32 x, cc_int32 y, cc_int32 sx, \ cc_int32 sy, const cc_ ## dt *k, cc_int32 kw) { \ cc_int32 i, j, u, v; \ cc_ ## dt acc; \ for (i = 0; i <= y - kw; i += sy) { \ for (j = 0; j <= x - kw; j += sx) { \ acc = 0; \ for (u = 0; u < kw; ++u) { \ for (v = 0; v < kw; ++v) { \ acc += *(in + (i + u) * x + (j + v)) * \ *(k + u * kw + v); \ } \ } \ *out++ = acc; \ } \ } \ } CC_CPU_CONV2D_IMPLEMENTATION (uint8) CC_CPU_CONV2D_IMPLEMENTATION (uint16) CC_CPU_CONV2D_IMPLEMENTATION (uint32) CC_CPU_CONV2D_IMPLEMENTATION (uint64) CC_CPU_CONV2D_IMPLEMENTATION (int8) CC_CPU_CONV2D_IMPLEMENTATION (int16) CC_CPU_CONV2D_IMPLEMENTATION (int32) CC_CPU_CONV2D_IMPLEMENTATION (int64) CC_CPU_CONV2D_IMPLEMENTATION (float32) CC_CPU_CONV2D_IMPLEMENTATION (float64) #define CC_CPU_CONV2D_CASE(DT, dtype) \ case DT: \ cc_cpu_conv2d_ ## dtype((const cc_ ## dtype*)inp, \ (cc_ ## dtype*)oup, x, y, sx, sy, (cc_ ## dtype*)filter, fw); \ break; void cc_cpu_conv2d(const void *inp, void *oup, cc_int32 x, cc_int32 y, cc_int32 sx, cc_int32 sy, const void *filter, cc_int32 fw, cc_dtype dt) { switch (dt) { CC_CPU_CONV2D_CASE(CC_UINT8, uint8) CC_CPU_CONV2D_CASE(CC_UINT16, uint16) CC_CPU_CONV2D_CASE(CC_UINT32, uint32) CC_CPU_CONV2D_CASE(CC_UINT64, uint64) CC_CPU_CONV2D_CASE(CC_INT8, int8) CC_CPU_CONV2D_CASE(CC_INT16, int16) CC_CPU_CONV2D_CASE(CC_INT32, int32) CC_CPU_CONV2D_CASE(CC_INT64, int64) CC_CPU_CONV2D_CASE(CC_FLOAT32, float32) CC_CPU_CONV2D_CASE(CC_FLOAT64, float64) default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #ifndef CC_BN_OFFSET_CFG #define CC_BN_OFFSET_CFG enum { CC_BN_OFFSET_GAMMA = 0, CC_BN_OFFSET_BETA, CC_BN_OFFSET_MEAN, CC_BN_OFFSET_VAR, CC_BN_OFFSET_EPSILON, CC_BN_PARAMETERS }; #endif #define CC_CPU_BATCH_NORM_IMPLEMENTATION(dt) \ void cc_cpu_batch_norm_ ## dt(cc_ ## dt *inp, \ cc_int32 len, cc_ ## dt *bnpara) \ { \ cc_ ## dt gamma = *(bnpara + CC_BN_OFFSET_GAMMA), \ beta = *(bnpara + CC_BN_OFFSET_BETA), \ mean = *(bnpara + CC_BN_OFFSET_MEAN), \ var = *(bnpara + CC_BN_OFFSET_VAR), \ epsilon = *(bnpara + CC_BN_OFFSET_EPSILON); \ cc_ ## dt frac = (cc_ ## dt)sqrt((double)var + epsilon); \ cc_int32 i; \ for (i = 0; i < len; ++i) { \ *(inp + i) = (gamma * \ (*(inp + i) - mean) / frac) \ + beta; \ } \ return; \ } CC_CPU_BATCH_NORM_IMPLEMENTATION (uint8) CC_CPU_BATCH_NORM_IMPLEMENTATION (uint16) CC_CPU_BATCH_NORM_IMPLEMENTATION (uint32) CC_CPU_BATCH_NORM_IMPLEMENTATION (uint64) CC_CPU_BATCH_NORM_IMPLEMENTATION (int8) CC_CPU_BATCH_NORM_IMPLEMENTATION (int16) CC_CPU_BATCH_NORM_IMPLEMENTATION (int32) CC_CPU_BATCH_NORM_IMPLEMENTATION (int64) CC_CPU_BATCH_NORM_IMPLEMENTATION (float32) CC_CPU_BATCH_NORM_IMPLEMENTATION (float64) #define CC_CPU_BATCH_NORM_CASE(DT, dtype) \ case DT: \ cc_cpu_batch_norm_ ## dtype( \ (cc_ ## dtype*)inp, len, (cc_ ## dtype*)bnpara); \ break; void cc_cpu_batch_norm(void *inp, cc_int32 len, const void *bnpara, cc_dtype dt) { switch (dt) { CC_CPU_BATCH_NORM_CASE(CC_UINT8, uint8) CC_CPU_BATCH_NORM_CASE(CC_UINT16, uint16) CC_CPU_BATCH_NORM_CASE(CC_UINT32, uint32) CC_CPU_BATCH_NORM_CASE(CC_UINT64, uint64) CC_CPU_BATCH_NORM_CASE(CC_INT8, int8) CC_CPU_BATCH_NORM_CASE(CC_INT16, int16) CC_CPU_BATCH_NORM_CASE(CC_INT32, int32) CC_CPU_BATCH_NORM_CASE(CC_INT64, int64) CC_CPU_BATCH_NORM_CASE(CC_FLOAT32, float32) CC_CPU_BATCH_NORM_CASE(CC_FLOAT64, float64) default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_SC_OPS(op, oup, arr, elem, arrlen, dtype) \ for (i = 0; i < arrlen; ++i) { \ *((dtype*)oup + i) = *((dtype*)arr + i) op *(dtype*)elem; \ } #define ARRAY_ELEM_SET(arr, elem, arrlen, dtype) \ for (i = 0; i < arrlen; ++i) { \ *((dtype*)arr + i) = *(dtype*)elem; \ } #define ARRAY_ELEM_CLIP(arr, min, max, arrlen, dtype) \ for (i = 0; i < arrlen; ++i) { \ if (min) { \ *((dtype*)arr + i) = \ *((dtype*)arr + i) < *(dtype*)min ? \ *(dtype*)min : *((dtype*)arr + i); \ } \ if (max) { \ *((dtype*)arr + i) = \ *((dtype*)arr + i) > *(dtype*)max ? \ *(dtype*)max : *((dtype*)arr + i); \ } \ } #define ARRAY_EW_OPS(op, oup, a, b, arrlen, dtype) \ for (i = 0; i < arrlen; ++i) { \ *((dtype*)oup + i) = *((dtype*)a + i) op \ *((dtype*)b + i); \ } #define ARRAY_SUM(arr, arrlen, dtype, sum) \ *(dtype*)sum = 0; \ for (i = 0; i < arrlen; ++i) { \ *(dtype*)sum += *((dtype*)arr + i); \ } #define ARRAY_CAST_CASE(_DT, _srcdt, _dstdt) \ case _DT: \ for (i = 0; i < arrlen; ++i) \ *((_dstdt*)dst + i) = (_dstdt)*((_srcdt*)src + i); \ break; #define CC_CPU_ARRAY_CAST_IMPLEMENTATION(dtype) \ void cc_cpu_array_cast_ ## dtype( \ void *dst, const void *src, int arrlen, int dt) \ { \ cc_int32 i; \ switch (dt) { \ ARRAY_CAST_CASE(CC_UINT8, cc_uint8, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_UINT16, cc_uint16, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_UINT32, cc_uint32, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_UINT64, cc_uint64, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_INT8, cc_int8, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_INT16, cc_int16, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_INT32, cc_int32, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_INT64, cc_int64, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_FLOAT32, cc_float32, cc_ ## dtype); \ ARRAY_CAST_CASE(CC_FLOAT64, cc_float64, cc_ ## dtype); \ default: \ UNSUPPORTED_DTYPE_LOG(dt); \ break; \ } \ } #define ARRAY_SET_CASE(_DT, _dt) \ case _DT: \ ARRAY_ELEM_SET(arr, x, arrlen, _dt) \ break; void cc_cpu_array_set(void *arr, int arrlen, const void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_SET_CASE(CC_UINT8, cc_uint8); ARRAY_SET_CASE(CC_UINT16, cc_uint16); ARRAY_SET_CASE(CC_UINT32, cc_uint32); ARRAY_SET_CASE(CC_UINT64, cc_uint64); ARRAY_SET_CASE(CC_INT8, cc_int8); ARRAY_SET_CASE(CC_INT16, cc_int16); ARRAY_SET_CASE(CC_INT32, cc_int32); ARRAY_SET_CASE(CC_INT64, cc_int64); ARRAY_SET_CASE(CC_FLOAT32, cc_float32); ARRAY_SET_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_CLIP_CASE(_DT, _dt) \ case _DT: \ ARRAY_ELEM_CLIP(arr, min, max, arrlen, _dt); \ break; void cc_cpu_array_clip_by_value( void *arr, int arrlen, const void *min, const void *max, int dt) { cc_int32 i; switch (dt) { ARRAY_CLIP_CASE(CC_UINT8, cc_uint8); ARRAY_CLIP_CASE(CC_UINT16, cc_uint16); ARRAY_CLIP_CASE(CC_UINT32, cc_uint32); ARRAY_CLIP_CASE(CC_UINT64, cc_uint64); ARRAY_CLIP_CASE(CC_INT8, cc_int8); ARRAY_CLIP_CASE(CC_INT16, cc_int16); ARRAY_CLIP_CASE(CC_INT32, cc_int32); ARRAY_CLIP_CASE(CC_INT64, cc_int64); ARRAY_CLIP_CASE(CC_FLOAT32, cc_float32); ARRAY_CLIP_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } CC_CPU_ARRAY_CAST_IMPLEMENTATION (uint8) CC_CPU_ARRAY_CAST_IMPLEMENTATION (uint16) CC_CPU_ARRAY_CAST_IMPLEMENTATION (uint32) CC_CPU_ARRAY_CAST_IMPLEMENTATION (uint64) CC_CPU_ARRAY_CAST_IMPLEMENTATION (int8) CC_CPU_ARRAY_CAST_IMPLEMENTATION (int16) CC_CPU_ARRAY_CAST_IMPLEMENTATION (int32) CC_CPU_ARRAY_CAST_IMPLEMENTATION (int64) CC_CPU_ARRAY_CAST_IMPLEMENTATION (float32) CC_CPU_ARRAY_CAST_IMPLEMENTATION (float64) #define ARRAY_ADD_BY_CASE(_DT, _dt) \ case _DT: \ ARRAY_SC_OPS(+, oup, a, x, arrlen, _dt); \ break; void cc_cpu_array_add_by(void *oup, int arrlen, const void *a, const void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_ADD_BY_CASE(CC_UINT8, cc_uint8); ARRAY_ADD_BY_CASE(CC_UINT16, cc_uint16); ARRAY_ADD_BY_CASE(CC_UINT32, cc_uint32); ARRAY_ADD_BY_CASE(CC_UINT64, cc_uint64); ARRAY_ADD_BY_CASE(CC_INT8, cc_int8); ARRAY_ADD_BY_CASE(CC_INT16, cc_int16); ARRAY_ADD_BY_CASE(CC_INT32, cc_int32); ARRAY_ADD_BY_CASE(CC_INT64, cc_int64); ARRAY_ADD_BY_CASE(CC_FLOAT32, cc_float32); ARRAY_ADD_BY_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_SUB_BY_CASE(_DT, _dt) \ case _DT: \ ARRAY_SC_OPS(-, oup, a, x, arrlen, _dt); \ break; void cc_cpu_array_sub_by(void *oup, int arrlen, const void *a, const void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_SUB_BY_CASE(CC_UINT8, cc_uint8); ARRAY_SUB_BY_CASE(CC_UINT16, cc_uint16); ARRAY_SUB_BY_CASE(CC_UINT32, cc_uint32); ARRAY_SUB_BY_CASE(CC_UINT64, cc_uint64); ARRAY_SUB_BY_CASE(CC_INT8, cc_int8); ARRAY_SUB_BY_CASE(CC_INT16, cc_int16); ARRAY_SUB_BY_CASE(CC_INT32, cc_int32); ARRAY_SUB_BY_CASE(CC_INT64, cc_int64); ARRAY_SUB_BY_CASE(CC_FLOAT32, cc_float32); ARRAY_SUB_BY_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_MUL_BY_CASE(_DT, _dt) \ case _DT: \ ARRAY_SC_OPS(*, oup, a, x, arrlen, _dt); \ break; void cc_cpu_array_mul_by(void *oup, int arrlen, const void *a, const void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_MUL_BY_CASE(CC_UINT8, cc_uint8); ARRAY_MUL_BY_CASE(CC_UINT16, cc_uint16); ARRAY_MUL_BY_CASE(CC_UINT32, cc_uint32); ARRAY_MUL_BY_CASE(CC_UINT64, cc_uint64); ARRAY_MUL_BY_CASE(CC_INT8, cc_int8); ARRAY_MUL_BY_CASE(CC_INT16, cc_int16); ARRAY_MUL_BY_CASE(CC_INT32, cc_int32); ARRAY_MUL_BY_CASE(CC_INT64, cc_int64); ARRAY_MUL_BY_CASE(CC_FLOAT32, cc_float32); ARRAY_MUL_BY_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_DIV_BY_CASE(_DT, _dt) \ case _DT: \ ARRAY_SC_OPS(/, oup, a, x, arrlen, _dt); \ break; void cc_cpu_array_div_by(void *oup, int arrlen, const void *a, const void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_DIV_BY_CASE(CC_UINT8, cc_uint8); ARRAY_DIV_BY_CASE(CC_UINT16, cc_uint16); ARRAY_DIV_BY_CASE(CC_UINT32, cc_uint32); ARRAY_DIV_BY_CASE(CC_UINT64, cc_uint64); ARRAY_DIV_BY_CASE(CC_INT8, cc_int8); ARRAY_DIV_BY_CASE(CC_INT16, cc_int16); ARRAY_DIV_BY_CASE(CC_INT32, cc_int32); ARRAY_DIV_BY_CASE(CC_INT64, cc_int64); ARRAY_DIV_BY_CASE(CC_FLOAT32, cc_float32); ARRAY_DIV_BY_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_ADD_EW_CASE(_DT, _dt) \ case _DT: \ ARRAY_EW_OPS(+, oup, a, b, arrlen, _dt); \ break; void cc_cpu_array_add_ew(void *oup, int arrlen, const void *a, const void *b, int dt) { cc_int32 i; switch (dt) { ARRAY_ADD_EW_CASE(CC_UINT8, cc_uint8); ARRAY_ADD_EW_CASE(CC_UINT16, cc_uint16); ARRAY_ADD_EW_CASE(CC_UINT32, cc_uint32); ARRAY_ADD_EW_CASE(CC_UINT64, cc_uint64); ARRAY_ADD_EW_CASE(CC_INT8, cc_int8); ARRAY_ADD_EW_CASE(CC_INT16, cc_int16); ARRAY_ADD_EW_CASE(CC_INT32, cc_int32); ARRAY_ADD_EW_CASE(CC_INT64, cc_int64); ARRAY_ADD_EW_CASE(CC_FLOAT32, cc_float32); ARRAY_ADD_EW_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_SUB_EW_CASE(_DT, _dt) \ case _DT: \ ARRAY_EW_OPS(-, oup, a, b, arrlen, _dt); \ break; void cc_cpu_array_sub_ew(void *oup, int arrlen, const void *a, const void *b, int dt) { cc_int32 i; switch (dt) { ARRAY_SUB_EW_CASE(CC_UINT8, cc_uint8); ARRAY_SUB_EW_CASE(CC_UINT16, cc_uint16); ARRAY_SUB_EW_CASE(CC_UINT32, cc_uint32); ARRAY_SUB_EW_CASE(CC_UINT64, cc_uint64); ARRAY_SUB_EW_CASE(CC_INT8, cc_int8); ARRAY_SUB_EW_CASE(CC_INT16, cc_int16); ARRAY_SUB_EW_CASE(CC_INT32, cc_int32); ARRAY_SUB_EW_CASE(CC_INT64, cc_int64); ARRAY_SUB_EW_CASE(CC_FLOAT32, cc_float32); ARRAY_SUB_EW_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_MUL_EW_CASE(_DT, _dt) \ case _DT: \ ARRAY_EW_OPS(*, oup, a, b, arrlen, _dt); \ break; void cc_cpu_array_mul_ew(void *oup, int arrlen, const void *a, const void *b, int dt) { cc_int32 i; switch (dt) { ARRAY_MUL_EW_CASE(CC_UINT8, cc_uint8); ARRAY_MUL_EW_CASE(CC_UINT16, cc_uint16); ARRAY_MUL_EW_CASE(CC_UINT32, cc_uint32); ARRAY_MUL_EW_CASE(CC_UINT64, cc_uint64); ARRAY_MUL_EW_CASE(CC_INT8, cc_int8); ARRAY_MUL_EW_CASE(CC_INT16, cc_int16); ARRAY_MUL_EW_CASE(CC_INT32, cc_int32); ARRAY_MUL_EW_CASE(CC_INT64, cc_int64); ARRAY_MUL_EW_CASE(CC_FLOAT32, cc_float32); ARRAY_MUL_EW_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_DIV_EW_CASE(_DT, _dt) \ case _DT: \ ARRAY_EW_OPS(/, oup, a, b, arrlen, _dt); \ break; void cc_cpu_array_div_ew(void *oup, int arrlen, const void *a, const void *b, int dt) { cc_int32 i; switch (dt) { ARRAY_DIV_EW_CASE(CC_UINT8, cc_uint8); ARRAY_DIV_EW_CASE(CC_UINT16, cc_uint16); ARRAY_DIV_EW_CASE(CC_UINT32, cc_uint32); ARRAY_DIV_EW_CASE(CC_UINT64, cc_uint64); ARRAY_DIV_EW_CASE(CC_INT8, cc_int8); ARRAY_DIV_EW_CASE(CC_INT16, cc_int16); ARRAY_DIV_EW_CASE(CC_INT32, cc_int32); ARRAY_DIV_EW_CASE(CC_INT64, cc_int64); ARRAY_DIV_EW_CASE(CC_FLOAT32, cc_float32); ARRAY_DIV_EW_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_DOTPROD_CASE(_DT, _dt) \ case _DT: \ *((_dt*)x) = 0; \ for (i = 0; i < arrlen; ++i) \ *((_dt*)x) += *(((_dt*)a) + i) * *(((_dt*)b) + i); \ break; void cc_cpu_array_dot_prod( const void *a, const void *b, int arrlen, void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_DOTPROD_CASE(CC_UINT8, cc_uint8); ARRAY_DOTPROD_CASE(CC_UINT16, cc_uint16); ARRAY_DOTPROD_CASE(CC_UINT32, cc_uint32); ARRAY_DOTPROD_CASE(CC_UINT64, cc_uint64); ARRAY_DOTPROD_CASE(CC_INT8, cc_int8); ARRAY_DOTPROD_CASE(CC_INT16, cc_int16); ARRAY_DOTPROD_CASE(CC_INT32, cc_int32); ARRAY_DOTPROD_CASE(CC_INT64, cc_int64); ARRAY_DOTPROD_CASE(CC_FLOAT32, cc_float32); ARRAY_DOTPROD_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_SUM_CASE(_DT, _dt) \ case _DT: \ ARRAY_SUM(arr, arrlen, _dt, x); \ break; void cc_cpu_array_sum(const void *arr, int arrlen, void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_SUM_CASE(CC_UINT8, cc_uint8); ARRAY_SUM_CASE(CC_UINT16, cc_uint16); ARRAY_SUM_CASE(CC_UINT32, cc_uint32); ARRAY_SUM_CASE(CC_UINT64, cc_uint64); ARRAY_SUM_CASE(CC_INT8, cc_int8); ARRAY_SUM_CASE(CC_INT16, cc_int16); ARRAY_SUM_CASE(CC_INT32, cc_int32); ARRAY_SUM_CASE(CC_INT64, cc_int64); ARRAY_SUM_CASE(CC_FLOAT32, cc_float32); ARRAY_SUM_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } } #define ARRAY_MEAN_CASE(_DT, _dt) \ case _DT: \ ARRAY_SUM(arr, arrlen, _dt, x); \ *(_dt*)x /= arrlen; \ break; void cc_cpu_array_mean(const void *arr, int arrlen, void *x, int dt) { cc_int32 i; switch (dt) { ARRAY_MEAN_CASE(CC_UINT8, cc_uint8); ARRAY_MEAN_CASE(CC_UINT16, cc_uint16); ARRAY_MEAN_CASE(CC_UINT32, cc_uint32); ARRAY_MEAN_CASE(CC_UINT64, cc_uint64); ARRAY_MEAN_CASE(CC_INT8, cc_int8); ARRAY_MEAN_CASE(CC_INT16, cc_int16); ARRAY_MEAN_CASE(CC_INT32, cc_int32); ARRAY_MEAN_CASE(CC_INT64, cc_int64); ARRAY_MEAN_CASE(CC_FLOAT32, cc_float32); ARRAY_MEAN_CASE(CC_FLOAT64, cc_float64); default: UNSUPPORTED_DTYPE_LOG(dt); break; } }
main.c
#include "omp.h" #include <stdio.h> #include <stdlib.h> #include "pca_.h" #include "wavelet_.h" #include "libSVM_predict.h" #include "libSVM_load_model.h" #include "hwPerf.h" #include "utils.h" #include "init.h" // #include "dat.h" #define HWPERF 1 #define DUMP_COUNTERS 1 //TO SELECT THE NUMBER OF CORES FOR THE MULTI-CORE EXECUTION JUST CHANGE THE DEFINED VARIABLE "CORE" IN init.h //TO EXECUTE THE MULTI-CORE APPLICATION COMPILE AND RUN WITH: make clean all run pulpFpu=1 pulpDiv=1 //FOR THE 8 CORES ONLY: make clean all run pulpFpu=1 pulpDiv=1 nbPe=8 //TO EXECUTE THE APPLICATION IN SEQUENTIAL COMPILE AND RUN WITH: make clean all run pulpFpu=1 pulpDiv=1 -f Makefile.seq void PCA_mrrr(int samples, int variables, float *input, int components, float *output); float datiOutput[channels][window]; PULP_L1_DATA extern float datiInput2[channels][window]; PULP_L1_DATA int max_nr_attr = 64; PULP_L1_DATA int nr_attr = 37; PULP_L1_DATA extern struct svm_node *x; PULP_L1_DATA extern struct svm_model *model; PULP_L1_DATA float *dec_values; PULP_L1_DATA float target_label, predict_label; PULP_L1_DATA int components; PULP_L1_DATA int i; PULP_L1_DATA int lev=0; PULP_L1_DATA int j=0; PULP_L1_DATA float energy_matrix[4][channels]; PULP_L1_DATA float *ptr_energy_vector; PULP_L1_DATA float energy_vector[4]; PULP_L1_DATA float dwt[window]; int main() { #ifdef SEQ if(get_core_id()) return 0; #endif #if HWPERF hw_perf_t perf; hw_perf_init(&perf); while (hw_perf_step(&perf)) { //hw_perf_start(&perf); #endif svm_node x1[37]; //PCA: call the funcion for Principal Component Analysis. components is the number of Principal Component we consider. hw_perf_start(&perf); #if 0 components=PCA(window, channels, datiOutput); #else components = 9; PCA_mrrr(window, channels, (float *)datiInput2, components, (float *)datiOutput); #endif hw_perf_stop(&perf); hw_perf_commit(&perf); ptr_energy_vector=energy_vector; //DWT: call the function gsl_wavelet_transform for all the PC. The result is in the vector dwt. //Energy: call the funcion calcolo_energia. We compute the energy of dwt. The result goes in energy_matrix. #pragma omp parallel private(dwt, i, energy_vector) shared(energy_matrix) num_threads(CORE)//shared(energy_matrix) { #pragma omp for for (j=0; j<components; j++){ int indx=0; for(indx=0; indx<window; indx++){ dwt[indx]=datiOutput[j][indx]; //printf("%d:iter %d, dwt[%d]=%d\n", omp_get_thread_num(), j, indx, (int)dwt[indx]); } gsl_wavelet_transform (dwt, 1, window); calcolo_energia(dwt, energy_vector); for(i=0;i<4;i++){ energy_matrix[i][j]=energy_vector[i]; //printf("%d\t\t", (int)energy_vector[i]); x1[((j)*4)+i].index=((j)*4)+i+1; x1[((j)*4)+i].value=energy_vector[i]/100000.0f; //printf("\nX:%d\n", (int)x1[((j-1)*4)+i].value); } } #pragma omp barrier }//omp x1[36].index=-1; x1[36].value=0.0f; printf("\nENERGY MATRIX\n\n"); for(j=0;j<4;j++){ for(i=0;i<components;i++){ printf("%d\t", (int)energy_matrix[j][i]); }printf("\n"); } //SVM: call the funcion svm_load_model , svm_init_data and svm_predict_values to perform the classification. svm_load_model(); dec_values = (float*) malloc(sizeof(float)*model->nr_class*(model->nr_class-1)/2); svm_predict_values( x1, dec_values); #if HWPERF // hw_perf_stop(&perf); // hw_perf_commit(&perf); } printf("HW performance counters results\n"); for (i=0; i<hw_perf_nb_events(&perf); i++) { printf("p: %s %d\n", hw_perf_get_name(&perf, i), hw_perf_get_value(&perf, i)); } #endif return 0; }
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; }
LinkedCells.h
/** * @file LinkedCells.h * * @author tchipevn * @date 17.02.2018 */ #pragma once #include "autopas/containers/CellBlock3D.h" #include "autopas/containers/CompatibleTraversals.h" #include "autopas/containers/ParticleContainer.h" #include "autopas/containers/linkedCells/traversals/LinkedCellTraversalInterface.h" #include "autopas/iterators/ParticleIterator.h" #include "autopas/iterators/RegionParticleIterator.h" #include "autopas/options/DataLayoutOption.h" #include "autopas/utils/ArrayMath.h" #include "autopas/utils/ParticleCellHelpers.h" #include "autopas/utils/StringUtils.h" #include "autopas/utils/WrapOpenMP.h" #include "autopas/utils/inBox.h" namespace autopas { /** * LinkedCells class. * This class uses a list of neighboring cells to store the particles. * These cells dimensions are at least as large as the given cutoff radius, * therefore short-range interactions only need to be calculated between * particles in neighboring cells. * @tparam Particle type of the particles that need to be stored * @tparam ParticleCell type of the ParticleCells that are used to store the particles * @tparam SoAArraysType type of the SoA, needed for verlet lists */ template <class Particle, class ParticleCell, class SoAArraysType = typename Particle::SoAArraysType> class LinkedCells : public ParticleContainer<Particle, ParticleCell, SoAArraysType> { public: /** * Constructor of the LinkedCells class * @param boxMin * @param boxMax * @param cutoff * @param skin * @param cellSizeFactor cell size factor relative to cutoff * By default all applicable traversals are allowed. */ LinkedCells(const std::array<double, 3> boxMin, const std::array<double, 3> boxMax, const double cutoff, const double skin, const double cellSizeFactor = 1.0) : ParticleContainer<Particle, ParticleCell, SoAArraysType>(boxMin, boxMax, cutoff, skin), _cellBlock(this->_cells, boxMin, boxMax, cutoff + skin, cellSizeFactor) {} ContainerOption getContainerType() override { return ContainerOption::linkedCells; } void addParticle(Particle &p) override { bool inBox = autopas::utils::inBox(p.getR(), this->getBoxMin(), this->getBoxMax()); if (inBox) { ParticleCell &cell = _cellBlock.getContainingCell(p.getR()); cell.addParticle(p); } else { utils::ExceptionHandler::exception( "LinkedCells: Trying to add a particle that is not inside the bounding box.\n" + p.toString()); } } void addHaloParticle(Particle &haloParticle) override { Particle pCopy = haloParticle; pCopy.setOwned(false); ParticleCell &cell = _cellBlock.getContainingCell(pCopy.getR()); cell.addParticle(pCopy); } bool updateHaloParticle(Particle &haloParticle) override { Particle pCopy = haloParticle; pCopy.setOwned(false); auto cells = _cellBlock.getNearbyHaloCells(pCopy.getR(), this->getSkin()); for (auto cellptr : cells) { bool updated = internal::checkParticleInCellAndUpdateByID(*cellptr, pCopy); if (updated) { return true; } } AutoPasLog(trace, "UpdateHaloParticle was not able to update particle at " "[{}, {}, {}]", pCopy.getR()[0], pCopy.getR()[1], pCopy.getR()[2]); return false; } void deleteHaloParticles() override { _cellBlock.clearHaloCells(); } void rebuildNeighborLists(TraversalInterface *traversal) override { // nothing to do. } void iteratePairwise(TraversalInterface *traversal) override { AutoPasLog(debug, "Using traversal {}.", utils::StringUtils::to_string(traversal->getTraversalType())); // Check if traversal is allowed for this container and give it the data it needs. auto *traversalInterface = dynamic_cast<LinkedCellTraversalInterface<ParticleCell> *>(traversal); auto *cellPairTraversal = dynamic_cast<CellPairTraversal<ParticleCell> *>(traversal); if (traversalInterface && cellPairTraversal) { cellPairTraversal->setCellsToTraverse(this->_cells); } else { autopas::utils::ExceptionHandler::exception( "Trying to use a traversal of wrong type in LinkedCells::iteratePairwise. TraversalID: {}", traversal->getTraversalType()); } traversal->initTraversal(); traversal->traverseParticlePairs(); traversal->endTraversal(); } AUTOPAS_WARN_UNUSED_RESULT std::vector<Particle> updateContainer() override { this->deleteHaloParticles(); std::vector<Particle> invalidParticles; #ifdef AUTOPAS_OPENMP #pragma omp parallel #endif // AUTOPAS_OPENMP { // private for each thread! std::vector<Particle> myInvalidParticles, myInvalidNotOwnedParticles; #ifdef AUTOPAS_OPENMP #pragma omp for #endif // AUTOPAS_OPENMP for (size_t cellId = 0; cellId < this->getCells().size(); ++cellId) { // if empty if (not this->getCells()[cellId].isNotEmpty()) continue; std::array<double, 3> cellLowerCorner = {}, cellUpperCorner = {}; this->getCellBlock().getCellBoundingBox(cellId, cellLowerCorner, cellUpperCorner); for (auto &&pIter = this->getCells()[cellId].begin(); pIter.isValid(); ++pIter) { // if not in cell if (utils::notInBox(pIter->getR(), cellLowerCorner, cellUpperCorner)) { myInvalidParticles.push_back(*pIter); pIter.deleteCurrentParticle(); } } } // implicit barrier here // the barrier is needed because iterators are not threadsafe w.r.t. addParticle() // this loop is executed for every thread and thus parallel. Don't use #pragma omp for here! for (auto &&p : myInvalidParticles) { // if not in halo if (utils::inBox(p.getR(), this->getBoxMin(), this->getBoxMax())) { addParticle(p); } else { myInvalidNotOwnedParticles.push_back(p); } } #ifdef AUTOPAS_OPENMP #pragma omp critical #endif { // merge private vectors to global one. invalidParticles.insert(invalidParticles.end(), myInvalidNotOwnedParticles.begin(), myInvalidNotOwnedParticles.end()); } } return invalidParticles; } bool isContainerUpdateNeeded() override { std::atomic<bool> outlierFound(false); #ifdef AUTOPAS_OPENMP // @todo: find a sensible value for magic number // numThreads should be at least 1 and maximal max_threads int numThreads = std::max(1, std::min(omp_get_max_threads(), (int)(this->_cells.size() / 500))); AutoPasLog(trace, "Using {} threads", numThreads); #pragma omp parallel for shared(outlierFound) num_threads(numThreads) #endif for (size_t cellIndex1d = 0; cellIndex1d < this->_cells.size(); ++cellIndex1d) { std::array<double, 3> boxmin{0., 0., 0.}; std::array<double, 3> boxmax{0., 0., 0.}; _cellBlock.getCellBoundingBox(cellIndex1d, boxmin, boxmax); for (auto iter = this->_cells[cellIndex1d].begin(); iter.isValid(); ++iter) { if (not utils::inBox(iter->getR(), boxmin, boxmax)) { outlierFound = true; // we need an update break; } } // abort loop (for all threads) by moving loop index to end if (outlierFound) cellIndex1d = this->_cells.size(); } return outlierFound; } TraversalSelectorInfo getTraversalSelectorInfo() override { return TraversalSelectorInfo(this->getCellBlock().getCellsPerDimensionWithHalo(), this->getInteractionLength(), this->getCellBlock().getCellLength()); } ParticleIteratorWrapper<Particle> begin(IteratorBehavior behavior = IteratorBehavior::haloAndOwned) override { return ParticleIteratorWrapper<Particle>( new internal::ParticleIterator<Particle, ParticleCell>(&this->_cells, 0, &_cellBlock, behavior)); } ParticleIteratorWrapper<Particle> getRegionIterator( const std::array<double, 3> &lowerCorner, const std::array<double, 3> &higherCorner, IteratorBehavior behavior = IteratorBehavior::haloAndOwned) override { // We increase the search region by skin, as particles can move over cell borders. auto startIndex3D = this->_cellBlock.get3DIndexOfPosition(ArrayMath::subScalar(lowerCorner, this->getSkin())); auto stopIndex3D = this->_cellBlock.get3DIndexOfPosition(ArrayMath::addScalar(higherCorner, this->getSkin())); size_t numCellsOfInterest = (stopIndex3D[0] - startIndex3D[0] + 1) * (stopIndex3D[1] - startIndex3D[1] + 1) * (stopIndex3D[2] - startIndex3D[2] + 1); std::vector<size_t> cellsOfInterest(numCellsOfInterest); int i = 0; for (size_t z = startIndex3D[2]; z <= stopIndex3D[2]; ++z) { for (size_t y = startIndex3D[1]; y <= stopIndex3D[1]; ++y) { for (size_t x = startIndex3D[0]; x <= stopIndex3D[0]; ++x) { cellsOfInterest[i++] = utils::ThreeDimensionalMapping::threeToOneD({x, y, z}, this->_cellBlock.getCellsPerDimensionWithHalo()); } } } return ParticleIteratorWrapper<Particle>(new internal::RegionParticleIterator<Particle, ParticleCell>( &this->_cells, lowerCorner, higherCorner, cellsOfInterest, &_cellBlock, behavior)); } /** * Get the cell block, not supposed to be used except by verlet lists * @return the cell block */ internal::CellBlock3D<ParticleCell> &getCellBlock() { return _cellBlock; } /** * returns reference to the data of LinkedCells * @return the data */ std::vector<ParticleCell> &getCells() { return this->_cells; } protected: /** * object to manage the block of cells. */ internal::CellBlock3D<ParticleCell> _cellBlock; // ThreeDimensionalCellHandler }; } // namespace autopas
thermodynamics.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 conversions and calculations of thermodynamic quantities of a moist atmosphere are collected. indices as usual: d: dry v: water vapour h: humid */ #include <stdio.h> #include <stdlib.h> #include <atmostracers.h> #include "../game_types.h" #include "../game_constants.h" #include "../spatial_operators/spatial_operators.h" #include "thermodynamics.h" int temperature_diagnostics(State *state, Grid *grid, Diagnostics *diagnostics) { /* This function diagnoses the temperature of the gas phase. */ #pragma omp parallel for for (int i = 0; i < NO_OF_SCALARS; ++i) { diagnostics -> temperature_gas[i] = (grid -> theta_bg[i] + state -> theta_pert[i])*(grid -> exner_bg[i] + state -> exner_pert[i]); } return 0; } double spec_heat_cap_diagnostics_v(State *state, int grid_point_index, Config *config) { double rho_g = 0; int no_of_relevant_constituents = 0; if (config -> assume_lte == 0) { no_of_relevant_constituents = NO_OF_GASEOUS_CONSTITUENTS; rho_g = density_gas(state, grid_point_index); } if (config -> assume_lte == 1) { no_of_relevant_constituents = 1; rho_g = state -> rho[NO_OF_CONDENSED_CONSTITUENTS*NO_OF_SCALARS + grid_point_index]; } double result = 0; for (int i = 0; i < no_of_relevant_constituents; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]/rho_g*spec_heat_capacities_v_gas(i); } return result; } double spec_heat_cap_diagnostics_p(State *state, int grid_point_index, Config *config) { double rho_g = 0; int no_of_relevant_constituents = 0; if (config -> assume_lte == 0) { no_of_relevant_constituents = NO_OF_GASEOUS_CONSTITUENTS; rho_g = density_gas(state, grid_point_index); } if (config -> assume_lte == 1) { no_of_relevant_constituents = 1; rho_g = state -> rho[NO_OF_CONDENSED_CONSTITUENTS*NO_OF_SCALARS + grid_point_index]; } double result = 0; for (int i = 0; i < no_of_relevant_constituents; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]/rho_g*spec_heat_capacities_p_gas(i); } return result; } double gas_constant_diagnostics(State *state, int grid_point_index, Config *config) { double rho_g = 0; int no_of_relevant_constituents = 0; if (config -> assume_lte == 0) { no_of_relevant_constituents = NO_OF_GASEOUS_CONSTITUENTS; rho_g = density_gas(state, grid_point_index); } if (config -> assume_lte == 1) { no_of_relevant_constituents = 1; rho_g = state -> rho[NO_OF_CONDENSED_CONSTITUENTS*NO_OF_SCALARS + grid_point_index]; } double result = 0; for (int i = 0; i < no_of_relevant_constituents; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]/rho_g*specific_gas_constants(i); } return result; } double density_total(State *state, int grid_point_index) { double result = 0; for (int i = 0; i < NO_OF_CONSTITUENTS; ++i) { result += state -> rho[i*NO_OF_SCALARS + grid_point_index]; } return result; } double density_gas(State *state, int grid_point_index) { double result = 0; for (int i = 0; i < NO_OF_GASEOUS_CONSTITUENTS; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]; } return result; } double calc_micro_density(double density_macro, double condensates_density_sum) { /* In a moist atmosphere one needs to distinguish between the densities with respect to the whole volume and the densities with respect to exclusively the gas phase. */ double result = density_macro/(1 - condensates_density_sum/RHO_WATER); if (result < 0) { printf("Error: microscopic density is negative.\n"); printf("Aborting.\n"); exit(1); } if (isnan(result)) { printf("Error: microscopic density is nan.\n"); printf("Aborting.\n"); exit(1); } return result; } double calc_condensates_density_sum(int scalar_gridpoint_index, Mass_densities mass_densities) { /* This is only needed for calculating the "micro densities". */ double result = 0; for (int i = 0; i < NO_OF_CONDENSED_CONSTITUENTS; ++i) { result += mass_densities[i*NO_OF_SCALARS + scalar_gridpoint_index]; } if (result < 0) { printf("Error: condensates_density_sum is negative.\n"); printf("Aborting.\n"); exit(1); } if (result >= RHO_WATER) { printf("Error: condensates_density_sum >= RHO_WATER.\n"); printf("Aborting.\n"); exit(1); } return result; } double calc_diffusion_coeff(double temperature, double density) { /* This function calculates the molecular diffusion coefficient according to the kinetic gas theory. */ // these things are hardly ever modified double particle_radius = 130e-12; double particle_mass = mean_particle_masses_gas(0); // actual calculation double thermal_velocity = sqrt(8*K_B*temperature/(M_PI*particle_mass)); double particle_density = density/particle_mass; double cross_section = 4*M_PI*pow(particle_radius, 2); double mean_free_path = 1/(sqrt(2)*particle_density*cross_section); double result = 1.0/3*thermal_velocity*mean_free_path; return result; } double mean_particle_masses_gas(int gas_constituent_id) { // binding to atmostracers return mean_particle_masses_gas_lookup(gas_constituent_id); } double spec_heat_capacities_v_gas(int gas_constituent_id) { // binding to atmostracers return spec_heat_capacities_v_gas_lookup(gas_constituent_id); } double spec_heat_capacities_p_gas(int gas_constituent_id) { // binding to atmostracers return spec_heat_capacities_p_gas_lookup(gas_constituent_id); } double specific_gas_constants(int gas_constituent_id) { // binding to atmostracers return specific_gas_constants_lookup(gas_constituent_id); }
GxB_Matrix_Option_get.c
//------------------------------------------------------------------------------ // GxB_Matrix_Option_get: get an option in a matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #include "GB.h" GrB_Info GxB_Matrix_Option_get // gets the current option of a matrix ( GrB_Matrix A, // matrix to query GxB_Option_Field field, // option to query ... // return value of the matrix option ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE1 ("GxB_Matrix_Option_get (A, field, &value)") ; GB_RETURN_IF_NULL_OR_FAULTY (A) ; ASSERT_MATRIX_OK (A, "A to get option", GB0) ; //-------------------------------------------------------------------------- // get the option //-------------------------------------------------------------------------- va_list ap ; switch (field) { case GxB_HYPER_SWITCH : { va_start (ap, field) ; double *hyper_switch = va_arg (ap, double *) ; va_end (ap) ; GB_RETURN_IF_NULL (hyper_switch) ; (*hyper_switch) = (double) A->hyper_switch ; } break ; case GxB_BITMAP_SWITCH : { va_start (ap, field) ; double *bitmap_switch = va_arg (ap, double *) ; va_end (ap) ; GB_RETURN_IF_NULL (bitmap_switch) ; (*bitmap_switch) = (double) A->bitmap_switch ; } break ; case GxB_SPARSITY_CONTROL : { va_start (ap, field) ; int *sparsity_control = va_arg (ap, int *) ; va_end (ap) ; GB_RETURN_IF_NULL (sparsity_control) ; (*sparsity_control) = A->sparsity_control ; } break ; case GxB_SPARSITY_STATUS : { va_start (ap, field) ; int *sparsity = va_arg (ap, int *) ; va_end (ap) ; GB_RETURN_IF_NULL (sparsity) ; (*sparsity) = GB_sparsity (A) ; } break ; case GxB_FORMAT : { va_start (ap, field) ; GxB_Format_Value *format = va_arg (ap, GxB_Format_Value *) ; va_end (ap) ; GB_RETURN_IF_NULL (format) ; (*format) = (A->is_csc) ? GxB_BY_COL : GxB_BY_ROW ; } break ; case GxB_IS_HYPER : // historical; use GxB_SPARSITY_STATUS instead { va_start (ap, field) ; bool *A_is_hyper = va_arg (ap, bool *) ; va_end (ap) ; GB_RETURN_IF_NULL (A_is_hyper) ; (*A_is_hyper) = (GB_sparsity (A) == GxB_HYPERSPARSE) ; } break ; default : return (GrB_INVALID_VALUE) ; } #pragma omp flush return (GrB_SUCCESS) ; }
RecordTable.h
/* * Souffle - A Datalog Compiler * Copyright (c) 2020, The Souffle Developers. All rights reserved. * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file RecordTable.h * * Data container to store Records of the Datalog program. * ***********************************************************************/ #pragma once #include "CompiledTuple.h" #include "ParallelUtils.h" #include "RamTypes.h" #include <cassert> #include <iostream> #include <limits> #include <map> #include <unordered_map> #include <vector> namespace souffle { /** * A bidirectional mapping between tuples and reference indices. */ class RecordMap { /** The arity of the stored tuples */ const size_t arity; /** The mapping from tuples to references/indices */ std::map<std::vector<RamDomain>, RamDomain> recordToIndex; /** The mapping from indices to tuples */ std::vector<std::vector<RamDomain>> indexToRecord; public: explicit RecordMap(size_t arity) : arity(arity), indexToRecord(1) {} // note: index 0 element left free /** * Pack the given vector -- create a new reference in necessary. */ RamDomain pack(const std::vector<RamDomain>& vector) { RamDomain index; #pragma omp critical(record_pack) { auto pos = recordToIndex.find(vector); if (pos != recordToIndex.end()) { index = pos->second; } else { #pragma omp critical(record_unpack) { indexToRecord.push_back(vector); index = indexToRecord.size() - 1; recordToIndex[vector] = index; // assert that new index is smaller than the range assert(index != std::numeric_limits<RamDomain>::max()); } } } return index; } /** * Packs the given tuple -- and may create a new reference if necessary. */ RamDomain pack(const RamDomain* tuple) { std::vector<RamDomain> tmp(arity); for (size_t i = 0; i < arity; i++) { tmp[i] = tuple[i]; } return pack(tmp); } /** * Obtains a pointer to the tuple addressed by the given index. */ RamDomain* unpack(RamDomain index) { RamDomain* res; #pragma omp critical(record_unpack) res = &(indexToRecord[index][0]); return res; } const RamDomain* unpack(RamDomain index) const { const RamDomain* res; #pragma omp critical(record_unpack) res = &(indexToRecord[index][0]); return res; } }; class RecordTable { public: RecordTable() = default; virtual ~RecordTable() = default; /** * A function packing a tuple of the given arity into a reference. */ RamDomain pack(RamDomain* tuple, size_t arity) { return getForArity(arity).pack(tuple); } /** * A function packing a vector into a reference. */ RamDomain pack(const std::vector<RamDomain>& vector) { return getForArity(vector.size()).pack(vector); } /** * A function packing a tuple of the given arity into a reference. */ template <typename Domain, std::size_t Arity> RamDomain pack(ram::Tuple<Domain, Arity> tuple) { return getForArity(Arity).pack(static_cast<RamDomain*>(tuple.data)); } /** * A function obtaining a pointer to the tuple addressed by the given reference. */ RamDomain* unpack(RamDomain ref, size_t arity) { auto iter = maps.find(arity); assert(iter != maps.end() && "Attempting to unpack non-existing record"); return (iter->second).unpack(ref); } /** * A function obtaining a pointer to the tuple addressed by the given reference. */ const RamDomain* unpack(RamDomain ref, size_t arity) const { auto iter = maps.find(arity); assert(iter != maps.end() && "Attempting to unpack non-existing record"); return (iter->second).unpack(ref); } /** * A function obtaining a pointer to the tuple addressed by the given reference. */ template <typename Domain, std::size_t Arity> ram::Tuple<Domain, Arity> unpackTuple(RamDomain ref) { ram::Tuple<RamDomain, Arity> tuple; RamDomain* data = getForArity(Arity).unpack(ref); for (size_t i = 0; i < Arity; ++i) { tuple.data[i] = data[i]; } return tuple; } /** * Determines whether the given reference is the nil reference encoding * the absence of any nested record. */ bool isNil(RamDomain ref) const { return ref == getNil(); } RamDomain getNil() const { return 0; } private: std::unordered_map<size_t, RecordMap> maps; RecordMap& getForArity(size_t arity) { std::unordered_map<size_t, RecordMap>::iterator mapsIterator; #pragma omp critical(RecordTableGetForArity) { // This will create a new map if it doesn't exist yet. mapsIterator = maps.emplace(arity, arity).first; } return mapsIterator->second; } }; } // namespace souffle
nlcpy_clip.c
/* # # * The source code in this file is developed independently by NEC Corporation. # # # NLCPy License # # # Copyright (c) 2020-2021 NEC Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither NEC Corporation nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "nlcpy.h" inline void clip_compare_bool(int32_t a, int32_t amin, int32_t amax, int32_t *pout) { if (amax <= amin) { *pout = amax; } else if (a < amin) { *pout = amin; } else if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_i32(int32_t a, int32_t amin, int32_t amax, int32_t *pout) { if (amax <= amin) { *pout = amax; } else if (a < amin) { *pout = amin; } else if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_i64(int64_t a, int64_t amin, int64_t amax, int64_t *pout) { if (amax <= amin) { *pout = amax; } else if (a < amin) { *pout = amin; } else if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_u32(uint32_t a, uint32_t amin, uint32_t amax, uint32_t *pout) { if (amax <= amin) { *pout = amax; } else if (a < amin) { *pout = amin; } else if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_u64(uint64_t a, uint64_t amin, uint64_t amax, uint64_t *pout) { if (amax <= amin) { *pout = amax; } else if (a < amin) { *pout = amin; } else if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_f32(float a, float amin, float amax, float *pout) { if (amax <= amin) { *pout = amax; } else if (a < amin) { *pout = amin; } else if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_f64(double a, double amin, double amax, double *pout) { if (amax <= amin) { *pout = amax; } else if (a < amin) { *pout = amin; } else if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_bool(int32_t a, int32_t amax, int32_t *pout) { if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_i32(int32_t a, int32_t amax, int32_t *pout) { if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_i64(int64_t a, int64_t amax, int64_t *pout) { if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_u32(uint32_t a, uint32_t amax, uint32_t *pout) { if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_u64(uint64_t a, uint64_t amax, uint64_t *pout) { if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_f32(float a, float amax, float *pout) { if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_f64(double a, double amax, double *pout) { if (a > amax) { *pout = amax; } else { *pout = a; } } inline void clip_compare_minimum_bool(int32_t a, int32_t amin, int32_t *pout) { if (a < amin) { *pout = amin; } else { *pout = a; } } inline void clip_compare_minimum_i32(int32_t a, int32_t amin, int32_t *pout) { if (a < amin) { *pout = amin; } else { *pout = a; } } inline void clip_compare_minimum_i64(int64_t a, int64_t amin, int64_t *pout) { if (a < amin) { *pout = amin; } else { *pout = a; } } inline void clip_compare_minimum_u32(uint32_t a, uint32_t amin, uint32_t *pout) { if (a < amin) { *pout = amin; } else { *pout = a; } } inline void clip_compare_minimum_u64(uint64_t a, uint64_t amin, uint64_t *pout) { if (a < amin) { *pout = amin; } else { *pout = a; } } inline void clip_compare_minimum_f32(float a, float amin, float *pout) { if (a < amin) { *pout = amin; } else { *pout = a; } } inline void clip_compare_minimum_f64(double a, double amin, double *pout) { if (a < amin) { *pout = amin; } else { *pout = a; } } inline void clip_compare_c64(float _Complex a, float _Complex amin, float _Complex amax, float _Complex *pout) { if (crealf(amax) <= crealf(amin)) { *pout = amax; } else if (crealf(a) < crealf(amin) || crealf(a) == crealf(amin) && cimagf(a) < cimagf(amin)) { *pout = amin; } else if (crealf(a) > crealf(amax) || crealf(a) == crealf(amax) && cimagf(a) > cimagf(amax)) { *pout = amax; } else { *pout = a; } } inline void clip_compare_c128(double _Complex a, double _Complex amin, double _Complex amax, double _Complex *pout) { if (creal(amax) <= creal(amin)) { *pout = amax; } else if (creal(a) < creal(amin) || creal(a) == creal(amin) && cimag(a) < cimag(amin)) { *pout = amin; } else if (creal(a) > creal(amax) || creal(a) == creal(amax) && cimag(a) > cimag(amax)) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_c64(float _Complex a, float _Complex amax, float _Complex *pout) { if (crealf(a) > crealf(amax) || crealf(a) == crealf(amax) && cimagf(a) > cimagf(amax)) { *pout = amax; } else { *pout = a; } } inline void clip_compare_maximum_c128(double _Complex a, double _Complex amax, double _Complex *pout) { if (creal(a) > creal(amax) || creal(a) == creal(amax) && cimag(a) > cimag(amax)) { *pout = amax; } else { *pout = a; } } inline void clip_compare_minimum_c64(float _Complex a, float _Complex amin, float _Complex *pout) { if (crealf(a) < crealf(amin) || crealf(a) == crealf(amin) && cimagf(a) < cimagf(amin)) { *pout = amin; } else { *pout = a; } } inline void clip_compare_minimum_c128(double _Complex a, double _Complex amin, double _Complex *pout) { if (creal(a) < creal(amin) || creal(a) == creal(amin) && cimag(a) < cimag(amin)) { *pout = amin; } else { *pout = a; } } uint64_t clip_bool(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { int32_t *pa = (int32_t *)nlcpy__get_ptr(a); int32_t *pout = (int32_t *)nlcpy__get_ptr(out); int32_t *pmin = (int32_t *)nlcpy__get_ptr(amin); int32_t *pmax = (int32_t *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_bool(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_bool(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_bool(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_bool(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_bool(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_bool(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_bool(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_bool(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_bool(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_bool(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_bool(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_bool(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_i32(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { int32_t *pa = (int32_t *)nlcpy__get_ptr(a); int32_t *pout = (int32_t *)nlcpy__get_ptr(out); int32_t *pmin = (int32_t *)nlcpy__get_ptr(amin); int32_t *pmax = (int32_t *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_i32(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_i32(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_i32(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_i32(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_i32(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_i32(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_i32(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_i32(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_i32(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_i32(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_i32(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_i32(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_i64(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { int64_t *pa = (int64_t *)nlcpy__get_ptr(a); int64_t *pout = (int64_t *)nlcpy__get_ptr(out); int64_t *pmin = (int64_t *)nlcpy__get_ptr(amin); int64_t *pmax = (int64_t *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_i64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_i64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_i64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_i64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_i64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_i64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_i64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_i64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_i64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_i64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_i64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_i64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_u32(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { uint32_t *pa = (uint32_t *)nlcpy__get_ptr(a); uint32_t *pout = (uint32_t *)nlcpy__get_ptr(out); uint32_t *pmin = (uint32_t *)nlcpy__get_ptr(amin); uint32_t *pmax = (uint32_t *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_u32(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_u32(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_u32(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_u32(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_u32(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_u32(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_u32(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_u32(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_u32(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_u32(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_u32(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_u32(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_u64(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { uint64_t *pa = (uint64_t *)nlcpy__get_ptr(a); uint64_t *pout = (uint64_t *)nlcpy__get_ptr(out); uint64_t *pmin = (uint64_t *)nlcpy__get_ptr(amin); uint64_t *pmax = (uint64_t *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_u64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_u64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_u64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_u64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_u64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_u64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_u64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_u64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_u64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_u64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_u64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_u64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_f32(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { float *pa = (float *)nlcpy__get_ptr(a); float *pout = (float *)nlcpy__get_ptr(out); float *pmin = (float *)nlcpy__get_ptr(amin); float *pmax = (float *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_f32(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_f32(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_f32(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_f32(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_f32(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_f32(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_f32(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_f32(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_f32(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_f32(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_f32(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_f32(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_f64(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { double *pa = (double *)nlcpy__get_ptr(a); double *pout = (double *)nlcpy__get_ptr(out); double *pmin = (double *)nlcpy__get_ptr(amin); double *pmax = (double *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_f64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_f64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_f64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_f64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_f64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_f64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_f64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_f64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_f64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_f64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_f64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_f64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_c64(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { float _Complex *pa = (float _Complex *)nlcpy__get_ptr(a); float _Complex *pout = (float _Complex *)nlcpy__get_ptr(out); float _Complex *pmin = (float _Complex *)nlcpy__get_ptr(amin); float _Complex *pmax = (float _Complex *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_c64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_c64(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_c64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_c64(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_c64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_c64(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_c64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_c64(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_c64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_c64(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_c64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_c64(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t clip_c128(ve_array *a, ve_array *out, ve_array *amin, ve_array *amax, ve_array *where, int32_t no_out, int32_t *psw) { double _Complex *pa = (double _Complex *)nlcpy__get_ptr(a); double _Complex *pout = (double _Complex *)nlcpy__get_ptr(out); double _Complex *pmin = (double _Complex *)nlcpy__get_ptr(amin); double _Complex *pmax = (double _Complex *)nlcpy__get_ptr(amax); Bint *pw = (Bint *)nlcpy__get_ptr(where); if (!pa || !pout || !pmin || !pmax || !pw) return NLCPY_ERROR_MEMORY; if (a->ndim < 2) { #ifdef _OPENMP #pragma omp single #endif /* _OPENMP */ { if (amin->size > 0 && amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_c128(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_c128(pa[i*ia0], pmin[i*imin0], pmax[i*imax0], pout+i*iout0); } } } else if (amin->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imin0 = amin->strides[0] / amin->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_minimum_c128(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_minimum_c128(pa[i*ia0], pmin[i*imin0], pout+i*iout0); } } } else if (amax->size > 0) { uint64_t ia0 = a->strides[0] / a->itemsize; uint64_t iout0 = out->strides[0] / out->itemsize; uint64_t imax0 = amax->strides[0] / amax->itemsize; if (where->size) { uint64_t iw0 = where->strides[0] / where->itemsize; for (int64_t i = 0; i < a->shape[0]; i++) { if (pw[i*iw0]) { clip_compare_maximum_c128(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } else if (no_out){ pout[i*iout0] = pa[i*ia0]; } } } else { for (int64_t i = 0; i < a->size; i++) { clip_compare_maximum_c128(pa[i*ia0], pmax[i*imax0], pout+i*iout0); } } } } } else if (a->ndim <= NLCPY_MAXNDIM) { #ifdef _OPENMP const int nt = omp_get_num_threads(); const int it = omp_get_thread_num(); #else const int nt = 1; const int it = 0; #endif /* _OPENMP */ int64_t i, j; int64_t *idx = (int64_t *)alloca(sizeof(int64_t) * a->ndim); nlcpy__rearrange_axis(a, idx); int64_t n_inner = a->ndim - 1; int64_t n_outer = 0; int64_t n_inner2 = idx[a->ndim - 1]; int64_t n_outer2 = idx[0]; int64_t ia = 0; int64_t iout = 0; int64_t iw = 0; int64_t ia0 = a->strides[n_inner2] / a->itemsize; int64_t iout0 = out->strides[n_inner2] / out->itemsize; int64_t *cnt_a = (int64_t*)alloca(sizeof(int64_t) * a->ndim); nlcpy__reset_coords(cnt_a, a->ndim); const int64_t lenm = a->shape[n_outer2]; const int64_t cntm_s = lenm * it / nt; const int64_t cntm_e = lenm * (it + 1) / nt; if (amin->size > 0 && amax->size > 0) { int64_t imin = 0; int64_t imax = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_c128(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_c128(pa[ia+i*ia0], pmin[imin+i*imin0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amin->size > 0) { int64_t imin = 0; int64_t imin0 = amin->strides[n_inner2] / amin->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_minimum_c128(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imin = cntm * amin->strides[n_outer2] / amin->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_minimum_c128(pa[ia+i*ia0], pmin[imin+i*imin0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imin += amin->strides[jj] / amin->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imin -= (amin->strides[jj] / amin->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } else if (amax->size > 0) { int64_t imax = 0; int64_t imax0 = amax->strides[n_inner2] / amax->itemsize; if (where->size) { int64_t iw0 = where->strides[n_inner2] / where->itemsize; for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; iw = cntm * where->strides[n_outer2] / where->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { if (pw[iw+i*iw0]) { clip_compare_maximum_c128(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } else if (no_out){ pout[iout+i*iout0] = pa[ia+i*ia0]; } } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; iw += where->strides[jj] / where->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); iw -= (where->strides[jj] / where->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } else { for (int64_t cntm = cntm_s; cntm < cntm_e; cntm++) { ia = cntm * a->strides[n_outer2] / a->itemsize; iout = cntm * out->strides[n_outer2] / out->itemsize; imax = cntm * amax->strides[n_outer2] / amax->itemsize; do { for (i = 0; i < a->shape[n_inner2]; i++) { clip_compare_maximum_c128(pa[ia+i*ia0], pmax[imax+i*imax0], pout+iout+i*iout0); } for (j = n_inner - 1; j > 0; j--) { uint64_t jj = idx[j]; if (++cnt_a[jj] < a->shape[jj]) { ia += a->strides[jj] / a->itemsize; iout += out->strides[jj] / out->itemsize; imax += amax->strides[jj] / amax->itemsize; break; } ia -= (a->strides[jj] / a->itemsize) * (a->shape[jj] - 1); iout -= (out->strides[jj] / out->itemsize) * (a->shape[jj] - 1); imax -= (amax->strides[jj] / amax->itemsize) * (a->shape[jj] - 1); cnt_a[jj] = 0; } } while(j > 0); } } } } else { return (uint64_t)NLCPY_ERROR_NDIM; } retrieve_fpe_flags(psw); return (uint64_t)NLCPY_ERROR_OK; } uint64_t nlcpy_clip(ve_arguments *args, int32_t *psw) { ve_array *a = &(args->clip.a); ve_array *out = &(args->clip.out); ve_array *work = &(args->clip.work); ve_array *amin = &(args->clip.amin); ve_array *amax = &(args->clip.amax); ve_array *where = &(args->clip.where); int32_t no_out = (out->ve_adr == work->ve_adr); uint64_t err = NLCPY_ERROR_OK; if (out->dtype == work->dtype) { switch (out->dtype) { case ve_i32: err = clip_i32 (a, out, amin, amax, where, no_out, psw); break; case ve_i64: err = clip_i64 (a, out, amin, amax, where, no_out, psw); break; case ve_u32: err = clip_u32 (a, out, amin, amax, where, no_out, psw); break; case ve_u64: err = clip_u64 (a, out, amin, amax, where, no_out, psw); break; case ve_f32: err = clip_f32 (a, out, amin, amax, where, no_out, psw); break; case ve_f64: err = clip_f64 (a, out, amin, amax, where, no_out, psw); break; case ve_c64: err = clip_c64 (a, out, amin, amax, where, no_out, psw); break; case ve_c128: err = clip_c128 (a, out, amin, amax, where, no_out, psw); break; case ve_bool: err = clip_bool (a, out, amin, amax, where, no_out, psw); break; default: return (uint64_t)NLCPY_ERROR_DTYPE; } } else { switch (work->dtype) { case ve_i32: err |= clip_i32 (a, work, amin, amax, where, no_out, psw); break; case ve_i64: err |= clip_i64 (a, work, amin, amax, where, no_out, psw); break; case ve_u32: err |= clip_u32 (a, work, amin, amax, where, no_out, psw); break; case ve_u64: err |= clip_u64 (a, work, amin, amax, where, no_out, psw); break; case ve_f32: err |= clip_f32 (a, work, amin, amax, where, no_out, psw); break; case ve_f64: err |= clip_f64 (a, work, amin, amax, where, no_out, psw); break; case ve_c64: err |= clip_c64 (a, work, amin, amax, where, no_out, psw); break; case ve_c128: err |= clip_c128 (a, work, amin, amax, where, no_out, psw); break; case ve_bool: err |= clip_bool (a, work, amin, amax, where, no_out, psw); break; default: return (uint64_t)NLCPY_ERROR_DTYPE; } #ifdef _OPENMP #pragma omp barrier #endif /* _OPENMP */ int32_t pswc; switch (out->dtype) { case ve_i32: err |= nlcpy_cast_i32 (work, out, 0, where, &pswc); break; case ve_i64: err |= nlcpy_cast_i64 (work, out, 0, where, &pswc); break; case ve_u32: err |= nlcpy_cast_u32 (work, out, 0, where, &pswc); break; case ve_u64: err |= nlcpy_cast_u64 (work, out, 0, where, &pswc); break; case ve_f32: err |= nlcpy_cast_f32 (work, out, 0, where, &pswc); break; case ve_f64: err |= nlcpy_cast_f64 (work, out, 0, where, &pswc); break; case ve_c64: err |= nlcpy_cast_c64 (work, out, 0, where, &pswc); break; case ve_c128: err |= nlcpy_cast_c128 (work, out, 0, where, &pswc); break; case ve_bool: err |= nlcpy_cast_bool (work, out, 0, where, &pswc); break; default: return (uint64_t)NLCPY_ERROR_DTYPE; } *psw |= pswc; } return (uint64_t)err; }
H2ERI-HF-J.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include <omp.h> #include "TinyDFT.h" #include "H2ERI.h" void TinyDFT_copy_shells_to_H2ERI(TinyDFT_p TinyDFT, H2ERI_p h2eri) { h2eri->natom = TinyDFT->natom; h2eri->nshell = TinyDFT->nshell; h2eri->shells = (shell_t *) malloc(sizeof(shell_t) * h2eri->nshell); assert(h2eri->shells != NULL); simint_initialize_shells(h2eri->nshell, h2eri->shells); shell_t *src_shells = (shell_t*) TinyDFT->simint->shells; shell_t *dst_shells = h2eri->shells; for (int i = 0; i < h2eri->nshell; i++) { simint_allocate_shell(src_shells[i].nprim, &dst_shells[i]); simint_copy_shell(&src_shells[i], &dst_shells[i]); } } void H2ERI_HFSCF(TinyDFT_p TinyDFT, H2ERI_p h2eri, const int max_iter) { // Start SCF iterations printf("HFSCF iteration started...\n"); printf("Nuclear repulsion energy = %.10lf\n", TinyDFT->E_nuc_rep); TinyDFT->iter = 0; TinyDFT->max_iter = max_iter; double E_prev, E_curr, E_delta = 19241112.0; int mat_size = TinyDFT->mat_size; double *D_mat = TinyDFT->D_mat; double *J_mat = TinyDFT->J_mat; double *K_mat = TinyDFT->K_mat; double *F_mat = TinyDFT->F_mat; double *X_mat = TinyDFT->X_mat; double *S_mat = TinyDFT->S_mat; double *Hcore_mat = TinyDFT->Hcore_mat; double *Cocc_mat = TinyDFT->Cocc_mat; double *E_nuc_rep = &TinyDFT->E_nuc_rep; double *E_one_elec = &TinyDFT->E_one_elec; double *E_two_elec = &TinyDFT->E_two_elec; double *E_HF_exchange = &TinyDFT->E_HF_exchange; while ((TinyDFT->iter < TinyDFT->max_iter) && (fabs(E_delta) >= TinyDFT->E_tol)) { printf("--------------- Iteration %d ---------------\n", TinyDFT->iter); double st0, et0, st1, et1, st2; st0 = get_wtime_sec(); // Build the Fock matrix st1 = get_wtime_sec(); TinyDFT_build_JKmat(TinyDFT, D_mat, NULL, K_mat); st2 = get_wtime_sec(); H2ERI_build_Coulomb(h2eri, D_mat, J_mat); #pragma omp parallel for simd for (int i = 0; i < mat_size; i++) F_mat[i] = Hcore_mat[i] + 2 * J_mat[i] - K_mat[i]; et1 = get_wtime_sec(); printf("* Build Fock matrix : %.3lf (s), H2ERI J mat used %.3lf (s)\n", et1 - st1, et1 - st2); // Calculate new system energy st1 = get_wtime_sec(); TinyDFT_calc_HF_energy( mat_size, D_mat, Hcore_mat, J_mat, K_mat, E_one_elec, E_two_elec, E_HF_exchange ); E_curr = (*E_nuc_rep) + (*E_one_elec) + (*E_two_elec) + (*E_HF_exchange); et1 = get_wtime_sec(); printf("* Calculate energy : %.3lf (s)\n", et1 - st1); E_delta = E_curr - E_prev; E_prev = E_curr; // CDIIS acceleration (Pulay mixing) st1 = get_wtime_sec(); TinyDFT_CDIIS(TinyDFT, X_mat, S_mat, D_mat, F_mat); et1 = get_wtime_sec(); printf("* CDIIS procedure : %.3lf (s)\n", et1 - st1); // Diagonalize and build the density matrix st1 = get_wtime_sec(); TinyDFT_build_Dmat_eig(TinyDFT, F_mat, X_mat, D_mat, Cocc_mat); et1 = get_wtime_sec(); printf("* Build density matrix : %.3lf (s)\n", et1 - st1); et0 = get_wtime_sec(); printf("* Iteration runtime = %.3lf (s)\n", et0 - st0); printf("* Energy = %.10lf", E_curr); if (TinyDFT->iter > 0) { printf(", delta = %e\n", E_delta); } else { printf("\n"); E_delta = 19241112.0; // Prevent the SCF exit after 1st iteration when no SAD initial guess } TinyDFT->iter++; fflush(stdout); } printf("--------------- SCF iterations finished ---------------\n"); } int main(int argc, char **argv) { if (argc < 5) { printf("Usage: %s <basis> <xyz> <niter> <QR_tol>\n", argv[0]); return 255; } printf("INFO: use H2ERI J (relerr %.2e), HF exchange K\n", atof(argv[4])); // Initialize TinyDFT TinyDFT_p TinyDFT; TinyDFT_init(&TinyDFT, argv[1], argv[2]); // Initialize H2P-ERI double st = get_wtime_sec(); H2ERI_p h2eri; H2ERI_init(&h2eri, 1e-10, 1e-10, atof(argv[4])); TinyDFT_copy_shells_to_H2ERI(TinyDFT, h2eri); H2ERI_process_shells(h2eri); H2ERI_partition(h2eri); H2ERI_build_H2(h2eri, 0); double et = get_wtime_sec(); printf("H2ERI build H2 for J matrix done, used %.3lf (s)\n", et - st); // Compute constant matrices and get initial guess for D TinyDFT_build_Hcore_S_X_mat(TinyDFT, TinyDFT->Hcore_mat, TinyDFT->S_mat, TinyDFT->X_mat); TinyDFT_build_Dmat_SAD(TinyDFT, TinyDFT->D_mat); // Do HFSCF calculation H2ERI_HFSCF(TinyDFT, h2eri, atoi(argv[3])); // Print H2P-ERI statistic info H2ERI_print_statistic(h2eri); // Free TinyDFT and H2P-ERI TinyDFT_destroy(&TinyDFT); H2ERI_destroy(h2eri); return 0; }
shear.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS H H EEEEE AAA RRRR % % SS H H E A A R R % % SSS HHHHH EEE AAAAA RRRR % % SS H H E A A R R % % SSSSS H H EEEEE A A R R % % % % % % MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The XShearImage() and YShearImage() methods are based on the paper "A Fast % Algorithm for General Raster Rotation" by Alan W. Paeth, Graphics % Interface '86 (Vancouver). ShearRotateImage() is adapted from a similar % method based on the Paeth paper written by Michael Halle of the Spatial % Imaging Group, MIT Media Lab. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache-private.h" #include "MagickCore/channel.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/list.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/shear.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C r o p T o F i t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropToFitImage() crops the sheared image as determined by the bounding box % as defined by width and height and shearing angles. % % The format of the CropToFitImage method is: % % MagickBooleanType CropToFitImage(Image **image, % const double x_shear,const double x_shear, % const double width,const double height, % const MagickBooleanType rotate,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear, width, height: Defines a region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CropToFitImage(Image **image, const double x_shear,const double y_shear, const double width,const double height, const MagickBooleanType rotate,ExceptionInfo *exception) { Image *crop_image; PointInfo extent[4], min, max; RectangleInfo geometry, page; ssize_t i; /* Calculate the rotated image size. */ extent[0].x=(double) (-width/2.0); extent[0].y=(double) (-height/2.0); extent[1].x=(double) width/2.0; extent[1].y=(double) (-height/2.0); extent[2].x=(double) (-width/2.0); extent[2].y=(double) height/2.0; extent[3].x=(double) width/2.0; extent[3].y=(double) height/2.0; for (i=0; i < 4; i++) { extent[i].x+=x_shear*extent[i].y; extent[i].y+=y_shear*extent[i].x; if (rotate != MagickFalse) extent[i].x+=x_shear*extent[i].y; extent[i].x+=(double) (*image)->columns/2.0; extent[i].y+=(double) (*image)->rows/2.0; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } geometry.x=CastDoubleToLong(ceil(min.x-0.5)); geometry.y=CastDoubleToLong(ceil(min.y-0.5)); geometry.width=(size_t) CastDoubleToLong(floor(max.x-min.x+0.5)); geometry.height=(size_t) CastDoubleToLong(floor(max.y-min.y+0.5)); page=(*image)->page; (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page); crop_image=CropImage(*image,&geometry,exception); if (crop_image == (Image *) NULL) return(MagickFalse); crop_image->page=page; *image=DestroyImage(*image); *image=crop_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s k e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeskewImage() removes skew from the image. Skew is an artifact that % occurs in scanned images because of the camera being misaligned, % imperfections in the scanning or surface, or simply because the paper was % not placed completely flat when scanned. % % The result will be auto-croped if the artifact "deskew:auto-crop" is % defined, while the amount the image is to be deskewed, in degrees is also % saved as the artifact "deskew:angle". % % The format of the DeskewImage method is: % % Image *DeskewImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: separate background from foreground. % % o exception: return any errors or warnings in this structure. % */ static void RadonProjection(const Image *image,MatrixInfo *source_matrixs, MatrixInfo *destination_matrixs,const ssize_t sign,size_t *projection) { MatrixInfo *swap; MatrixInfo *p, *q; ssize_t x; size_t step; p=source_matrixs; q=destination_matrixs; for (step=1; step < GetMatrixColumns(p); step*=2) { for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step) { ssize_t i; ssize_t y; unsigned short element, neighbor; for (i=0; i < (ssize_t) step; i++) { for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse) continue; } for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } for ( ; y < (ssize_t) GetMatrixRows(p); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } } } swap=p; p=q; q=swap; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,GetMatrixColumns(p),1) #else magick_unreferenced(image); #endif for (x=0; x < (ssize_t) GetMatrixColumns(p); x++) { ssize_t y; size_t sum; sum=0; for (y=0; y < (ssize_t) (GetMatrixRows(p)-1); y++) { ssize_t delta; unsigned short element, neighbor; if (GetMatrixElement(p,x,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x,y+1,&neighbor) == MagickFalse) continue; delta=(ssize_t) element-(ssize_t) neighbor; sum+=delta*delta; } projection[GetMatrixColumns(p)+sign*x-1]=sum; } } static MagickBooleanType RadonTransform(const Image *image, const double threshold,size_t *projection,ExceptionInfo *exception) { CacheView *image_view; MatrixInfo *destination_matrixs, *source_matrixs; MagickBooleanType status; size_t count, width; ssize_t j, y; unsigned char c; unsigned short bits[256]; for (width=1; width < ((image->columns+7)/8); width<<=1) ; source_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); destination_matrixs=AcquireMatrixInfo(width,image->rows, sizeof(unsigned short),exception); if ((source_matrixs == (MatrixInfo *) NULL) || (destination_matrixs == (MatrixInfo *) NULL)) { if (destination_matrixs != (MatrixInfo *) NULL) destination_matrixs=DestroyMatrixInfo(destination_matrixs); if (source_matrixs != (MatrixInfo *) NULL) source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } if (NullMatrix(source_matrixs) == MagickFalse) { destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } for (j=0; j < 256; j++) { c=(unsigned char) j; for (count=0; c != 0; c>>=1) count+=c & 0x01; bits[j]=(unsigned short) count; } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=(ssize_t) (image->columns+7)/8; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,-1,projection); (void) NullMatrix(source_matrixs); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,1,projection); image_view=DestroyCacheView(image_view); destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickTrue); } static void GetImageBackgroundColor(Image *image,const ssize_t offset, ExceptionInfo *exception) { CacheView *image_view; PixelInfo background; double count; ssize_t y; /* Compute average background color. */ if (offset <= 0) return; GetPixelInfo(image,&background); count=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; if ((y >= offset) && (y < ((ssize_t) image->rows-offset))) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) continue; for (x=0; x < (ssize_t) image->columns; x++) { if ((x >= offset) && (x < ((ssize_t) image->columns-offset))) continue; background.red+=QuantumScale*GetPixelRed(image,p); background.green+=QuantumScale*GetPixelGreen(image,p); background.blue+=QuantumScale*GetPixelBlue(image,p); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) background.alpha+=QuantumScale*GetPixelAlpha(image,p); count++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); image->background_color.red=(double) ClampToQuantum(QuantumRange* background.red/count); image->background_color.green=(double) ClampToQuantum(QuantumRange* background.green/count); image->background_color.blue=(double) ClampToQuantum(QuantumRange* background.blue/count); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->background_color.alpha=(double) ClampToQuantum(QuantumRange* background.alpha/count); } MagickExport Image *DeskewImage(const Image *image,const double threshold, ExceptionInfo *exception) { AffineMatrix affine_matrix; const char *artifact; double degrees; Image *clone_image, *crop_image, *deskew_image, *median_image; MagickBooleanType status; RectangleInfo geometry; ssize_t i; size_t max_projection, *projection, width; ssize_t skew; /* Compute deskew angle. */ for (width=1; width < ((image->columns+7)/8); width<<=1) ; projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1), sizeof(*projection)); if (projection == (size_t *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); status=RadonTransform(image,threshold,projection,exception); if (status == MagickFalse) { projection=(size_t *) RelinquishMagickMemory(projection); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } max_projection=0; skew=0; for (i=0; i < (ssize_t) (2*width-1); i++) { if (projection[i] > max_projection) { skew=i-(ssize_t) width+1; max_projection=projection[i]; } } projection=(size_t *) RelinquishMagickMemory(projection); degrees=RadiansToDegrees(-atan((double) skew/width/8)); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Deskew angle: %g",degrees); /* Deskew image. */ clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); { char angle[MagickPathExtent]; (void) FormatLocaleString(angle,MagickPathExtent,"%.20g",degrees); (void) SetImageArtifact(clone_image,"deskew:angle",angle); } (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod, exception); affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0)))); affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.tx=0.0; affine_matrix.ty=0.0; artifact=GetImageArtifact(image,"deskew:auto-crop"); if (IsStringTrue(artifact) == MagickFalse) { deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); return(deskew_image); } /* Auto-crop image. */ GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact), exception); deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); if (deskew_image == (Image *) NULL) return((Image *) NULL); median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception); if (median_image == (Image *) NULL) { deskew_image=DestroyImage(deskew_image); return((Image *) NULL); } geometry=GetImageBoundingBox(median_image,exception); median_image=DestroyImage(median_image); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule()," Deskew geometry: " "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); crop_image=CropImage(deskew_image,&geometry,exception); deskew_image=DestroyImage(deskew_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e g r a l R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IntegralRotateImage() rotates the image an integral of 90 degrees. It % allocates the memory necessary for the new Image structure and returns a % pointer to the rotated image. % % The format of the IntegralRotateImage method is: % % Image *IntegralRotateImage(const Image *image,size_t rotations, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o rotations: Specifies the number of 90 degree rotations. % */ MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations, ExceptionInfo *exception) { #define RotateImageTag "Rotate/Image" CacheView *image_view, *rotate_view; Image *rotate_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; /* Initialize rotated image attributes. */ assert(image != (Image *) NULL); page=image->page; rotations%=4; switch (rotations) { case 0: default: { rotate_image=CloneImage(image,0,0,MagickTrue,exception); break; } case 2: { rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); break; } case 1: case 3: { rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); break; } } if (rotate_image == (Image *) NULL) return((Image *) NULL); if (rotations == 0) return(rotate_image); /* Integral rotate the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); rotate_view=AcquireAuthenticCacheView(rotate_image,exception); switch (rotations) { case 1: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 90 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,rotate_image,image->rows/tile_height,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t y; size_t height, width; width=tile_width; if ((tile_width+tile_x) > image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_height+tile_y) > image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { const Quantum *magick_restrict tile_pixels; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t) (rotate_image->columns-(tile_y+height)),y+tile_x,height,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait rotate_traits = GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } case 2: { ssize_t y; /* Rotate 180 degrees. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,rotate_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(rotate_view,0,(ssize_t) (image->rows-y- 1),image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(rotate_image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; q-=GetPixelChannels(rotate_image); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait rotate_traits = GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,p[i],q); } p+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } case 3: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 270 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,rotate_image,image->rows/tile_height,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t y; size_t height, width; width=tile_width; if ((tile_width+tile_x) > image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_height+tile_y) > image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { const Quantum *magick_restrict tile_pixels; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+ rotate_image->rows-(tile_x+width)),height,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((width-1)-y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait rotate_traits = GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } default: break; } rotate_view=DestroyCacheView(rotate_view); image_view=DestroyCacheView(image_view); rotate_image->type=image->type; rotate_image->page=page; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + X S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % XShearImage() shears the image in the X direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a vertical % Y-axis. X shears will widen an image creating 'empty' triangles on the left % and right sides of the source image. % % The format of the XShearImage method is: % % MagickBooleanType XShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the X % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType XShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define XShearImageTag "XShear/Image" typedef enum { LEFT, RIGHT } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t y; /* X shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; background=image->background_color; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,height,1) #endif for (y=0; y < (ssize_t) height; y++) { PixelInfo pixel, source, destination; double area, displacement; Quantum *magick_restrict p, *magick_restrict q; ssize_t i; ShearDirection direction; ssize_t step; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=x_offset*GetPixelChannels(image); displacement=degrees*(double) (y-height/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=RIGHT; else { displacement*=(-1.0); direction=LEFT; } step=CastDoubleToLong(floor((double) displacement)); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case LEFT: { /* Transfer pixels left-to-right. */ if (step > x_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { if ((x_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case RIGHT: { /* Transfer pixels right-to-left. */ p+=width*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (x_offset+width+step-i) > image->columns) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,XShearImageTag,progress,height); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Y S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % YShearImage shears the image in the Y direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a % horizontal X-axis. Y shears will increase the height of an image creating % 'empty' triangles on the top and bottom of the source image. % % The format of the YShearImage method is: % % MagickBooleanType YShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the Y % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType YShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define YShearImageTag "YShear/Image" typedef enum { UP, DOWN } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t x; /* Y Shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; background=image->background_color; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,width,1) #endif for (x=0; x < (ssize_t) width; x++) { double area, displacement; PixelInfo pixel, source, destination; Quantum *magick_restrict p, *magick_restrict q; ssize_t i; ShearDirection direction; ssize_t step; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=y_offset*GetPixelChannels(image); displacement=degrees*(double) (x-width/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=DOWN; else { displacement*=(-1.0); direction=UP; } step=CastDoubleToLong(floor((double) displacement)); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case UP: { /* Transfer pixels top-to-bottom. */ if (step > y_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { if ((y_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case DOWN: { /* Transfer pixels bottom-to-top. */ p+=height*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (y_offset+height+step-i) > image->rows) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,YShearImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearImage() creates a new image that is a shear_image copy of an existing % one. Shearing slides one edge of an image along the X or Y axis, creating % a parallelogram. An X direction shear slides an edge along the X axis, % while a Y direction shear slides an edge along the Y axis. The amount of % the shear is controlled by a shear angle. For X direction shears, x_shear % is measured relative to the Y axis, and similarly, for Y direction shears % y_shear is measured relative to the X axis. Empty triangles left over from % shearing the image are filled with the background color defined by member % 'background_color' of the image.. ShearImage() allocates the memory % necessary for the new Image structure and returns a pointer to the new image. % % ShearImage() is based on the paper "A Fast Algorithm for General Raster % Rotatation" by Alan W. Paeth. % % The format of the ShearImage method is: % % Image *ShearImage(const Image *image,const double x_shear, % const double y_shear,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear: Specifies the number of degrees to shear the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearImage(const Image *image,const double x_shear, const double y_shear,ExceptionInfo *exception) { Image *integral_image, *shear_image; MagickBooleanType status; PointInfo shear; RectangleInfo border_info, bounds; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); /* Initialize shear angle. */ integral_image=CloneImage(image,0,0,MagickTrue,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0)))); shear.y=tan(DegreesToRadians(fmod(y_shear,360.0))); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute image size. */ bounds.width=image->columns+CastDoubleToLong(floor(fabs(shear.x)* image->rows+0.5)); bounds.x=CastDoubleToLong(ceil((double) image->columns+((fabs(shear.x)* image->rows)-image->columns)/2.0-0.5)); bounds.y=CastDoubleToLong(ceil((double) image->rows+((fabs(shear.y)* bounds.width)-image->rows)/2.0-0.5)); /* Surround image with border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; shear_image=BorderImage(integral_image,&border_info,image->compose,exception); integral_image=DestroyImage(integral_image); if (shear_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Shear the image. */ if (shear_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception); status=XShearImage(shear_image,shear.x,image->columns,image->rows,bounds.x, (ssize_t) (shear_image->rows-image->rows)/2,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=YShearImage(shear_image,shear.y,bounds.width,image->rows,(ssize_t) (shear_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType) image->columns,(MagickRealType) image->rows,MagickFalse,exception); shear_image->alpha_trait=image->alpha_trait; shear_image->compose=image->compose; shear_image->page.width=0; shear_image->page.height=0; if (status == MagickFalse) shear_image=DestroyImage(shear_image); return(shear_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearRotateImage() creates a new image that is a rotated copy of an existing % one. Positive angles rotate counter-clockwise (right-hand rule), while % negative angles rotate clockwise. Rotated images are usually larger than % the originals and have 'empty' triangular corners. X axis. Empty % triangles left over from shearing the image are filled with the background % color defined by member 'background_color' of the image. ShearRotateImage % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % ShearRotateImage() is based on the paper "A Fast Algorithm for General % Raster Rotatation" by Alan W. Paeth. ShearRotateImage is adapted from a % similar method based on the Paeth paper written by Michael Halle of the % Spatial Imaging Group, MIT Media Lab. % % The format of the ShearRotateImage method is: % % Image *ShearRotateImage(const Image *image,const double degrees, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: Specifies the number of degrees to rotate the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearRotateImage(const Image *image,const double degrees, ExceptionInfo *exception) { Image *integral_image, *rotate_image; MagickBooleanType status; MagickRealType angle; PointInfo shear; RectangleInfo border_info, bounds; size_t height, rotations, shear_width, width; /* Adjust rotation angle. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); angle=fmod(degrees,360.0); if (angle < -45.0) angle+=360.0; for (rotations=0; angle > 45.0; rotations++) angle-=90.0; rotations%=4; /* Calculate shear equations. */ integral_image=IntegralRotateImage(image,rotations,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan((double) DegreesToRadians(angle)/2.0)); shear.y=sin((double) DegreesToRadians(angle)); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute maximum bounds for 3 shear operations. */ width=integral_image->columns; height=integral_image->rows; bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5); bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5); shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+ bounds.width+0.5); bounds.x=CastDoubleToLong(floor((double) ((shear_width > bounds.width) ? width : bounds.width-shear_width+2)/2.0+0.5)); bounds.y=CastDoubleToLong(floor(((double) bounds.height-height+2)/2.0+0.5)); /* Surround image with a border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; rotate_image=BorderImage(integral_image,&border_info,image->compose, exception); integral_image=DestroyImage(integral_image); if (rotate_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Rotate the image. */ status=XShearImage(rotate_image,shear.x,width,height,bounds.x,(ssize_t) (rotate_image->rows-height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=YShearImage(rotate_image,shear.y,bounds.width,height,(ssize_t) (rotate_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=XShearImage(rotate_image,shear.x,bounds.width,bounds.height,(ssize_t) (rotate_image->columns-bounds.width)/2,(ssize_t) (rotate_image->rows- bounds.height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width, (MagickRealType) height,MagickTrue,exception); rotate_image->alpha_trait=image->alpha_trait; rotate_image->compose=image->compose; rotate_image->page.width=0; rotate_image->page.height=0; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); }
collapse.c
/* Based on OMP 3.0 A.10 Example A.10.1 */ void foo() { int j,k; int jlast, klast; #pragma omp parallel for private(j,k), collapse(2), lastprivate (jlast, klast) for (k=1;k<=100;k++) for (j=1;j<=100;j++) { jlast = j; klast = k; } }
residualbased_block_builder_and_solver_with_lagrange_multiplier.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Vicente Mataix // // #if !defined(KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER_WITH_LAGRANGE_MULTIPLIER ) #define KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER_WITH_LAGRANGE_MULTIPLIER /* System includes */ /* External includes */ /* Project includes */ #include "solving_strategies/builder_and_solvers/residualbased_block_builder_and_solver.h" #include "utilities/atomic_utilities.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier * @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 * Additionally the constraints are solver considering Lagrange multiplier (or double Lagrange multiplier) * @note Based on https://www.code-aster.org/V2/doc/default/en/man_r/r3/r3.03.01.pdf * @tparam TSparseSpace The sparse system considered * @tparam TDenseSpace The dense system considered * @tparam TLinearSolver The linear solver considered * @author Vicente Mataix Ferrandiz */ template<class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier : public ResidualBasedBlockBuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver > { public: ///@name Type Definitions ///@{ /// Definition of the flags KRATOS_DEFINE_LOCAL_FLAG( DOUBLE_LAGRANGE_MULTIPLIER ); KRATOS_DEFINE_LOCAL_FLAG( TRANSFORMATION_MATRIX_COMPUTED ); // Constraint enum enum class CONSTRAINT_FACTOR {CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR = 0, CONSIDER_MEAN_DIAGONAL_CONSTRAINT_FACTOR = 1, CONSIDER_PRESCRIBED_CONSTRAINT_FACTOR = 2}; enum class AUXILIAR_CONSTRAINT_FACTOR {CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR = 0, CONSIDER_MEAN_DIAGONAL_CONSTRAINT_FACTOR = 1, CONSIDER_PRESCRIBED_CONSTRAINT_FACTOR = 2}; /// Definition of the pointer KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier); /// Definition of the base class typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseBuilderAndSolverType; typedef ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; /// The definition of the current class typedef ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier<TSparseSpace, TDenseSpace, TLinearSolver> ClassType; // The size_t types typedef std::size_t SizeType; typedef std::size_t IndexType; /// Definition of the classes from the base class 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 typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; /// Additional definitions typedef PointerVectorSet<Element, IndexedObject> ElementsContainerType; typedef Element::EquationIdVectorType EquationIdVectorType; typedef Element::DofsVectorType DofsVectorType; /// DoF types definition typedef Node<3> NodeType; typedef typename NodeType::DofType DofType; typedef typename DofType::Pointer DofPointerType; ///@} ///@name Life Cycle ///@{ /** * @brief Default constructor */ explicit ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier() : BaseType() { } /** * @brief Default constructor. (with parameters) */ explicit ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier( typename TLinearSolver::Pointer pNewLinearSystemSolver, Parameters ThisParameters ) : BaseType(pNewLinearSystemSolver) { // Validate and assign defaults ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters()); this->AssignSettings(ThisParameters); } /** * @brief Default constructor. */ explicit ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier(typename TLinearSolver::Pointer pNewLinearSystemSolver) : BaseType(pNewLinearSystemSolver) { // Setting flags BaseType::mScalingDiagonal = BaseType::SCALING_DIAGONAL::NO_SCALING; BaseType::mOptions.Set(BaseType::SILENT_WARNINGS, false); mConstraintFactorConsidered = CONSTRAINT_FACTOR::CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR; mAuxiliarConstraintFactorConsidered = AUXILIAR_CONSTRAINT_FACTOR::CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR; BaseType::mOptions.Set(DOUBLE_LAGRANGE_MULTIPLIER, true); BaseType::mOptions.Set(TRANSFORMATION_MATRIX_COMPUTED, false); } /** Destructor. */ ~ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier() override { } /** * @brief Create method * @param pNewLinearSystemSolver The linear solver for the system of equations * @param ThisParameters The configuration parameters */ typename BaseBuilderAndSolverType::Pointer Create( typename TLinearSolver::Pointer pNewLinearSystemSolver, Parameters ThisParameters ) const override { return Kratos::make_shared<ClassType>(pNewLinearSystemSolver,ThisParameters); } /** * @brief Function to perform the build of the RHS. The vector could be sized as the total number * of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rb The RHS vector */ void Build( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rb ) override { KRATOS_TRY // Resize again the system to the original size if (rA.size1() != BaseType::mEquationSystemSize || rA.size2() != BaseType::mEquationSystemSize) { rA.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); BaseType::ConstructMatrixStructure(pScheme, rA, rModelPart); } // Base build BaseType::Build(pScheme, rModelPart, rA, rb); KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void SystemSolve( TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY // Compute the norm const double norm_b = (TSparseSpace::Size(rb) != 0) ? TSparseSpace::TwoNorm(rb) : 0.0; if (norm_b < std::numeric_limits<double>::epsilon()) { // Do solve BaseType::mpLinearSystemSolver->Solve(rA, rDx, rb); } else { TSparseSpace::SetToZero(rDx); } // Prints informations about the current time KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier", 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 rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector * @param rModelPart The model part of the problem to solve */ void SystemSolveWithPhysics( TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb, ModelPart& rModelPart ) override { BaseType::InternalSystemSolveWithPhysics(rA, rDx, rb, rModelPart); } /** * @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 rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY // Resize to the proper size const SizeType total_system_size = (BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER)) ? BaseType::mEquationSystemSize + 2 * BaseType::mSlaveIds.size() : BaseType::mEquationSystemSize + BaseType::mSlaveIds.size(); if (rDx.size() != total_system_size) { rDx.resize(total_system_size, false); TSparseSpace::SetToZero(rDx); } // Base build and solve BaseType::BuildAndSolve(pScheme, rModelPart, rA, rDx, rb); // Update the Lagrange multiplier solution #pragma omp parallel for for (int i = 0; i < static_cast<int>(BaseType::mSlaveIds.size()); ++i) { mLagrangeMultiplierVector[i] += rDx[BaseType::mEquationSystemSize + i]; } KRATOS_CATCH("") } /** * @brief Corresponds to the previews, but the System's matrix is considered already built and only the RHS is built again * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void BuildRHSAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY // Resize to the proper size const SizeType total_system_size = (BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER)) ? BaseType::mEquationSystemSize + 2 * BaseType::mSlaveIds.size() : BaseType::mEquationSystemSize + BaseType::mSlaveIds.size(); if (rDx.size() != total_system_size) { rDx.resize(total_system_size, false); TSparseSpace::SetToZero(rDx); } // Base build and solve BaseType::BuildRHSAndSolve(pScheme, rModelPart, rA, rDx, rb); // Update the Lagrange multiplier solution #pragma omp parallel for for (int i = 0; i < static_cast<int>(BaseType::mSlaveIds.size()); ++i) { mLagrangeMultiplierVector[i] += rDx[BaseType::mEquationSystemSize + i]; } KRATOS_CATCH("") } /** * @brief Function to perform the build of the RHS. * @details The vector could be sized as the total number of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rb The RHS vector */ void BuildRHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rb ) override { KRATOS_TRY // Resize again the system to the original size if (rb.size() != BaseType::mEquationSystemSize) { rb.resize(BaseType::mEquationSystemSize, false); } // Build the base RHS BaseType::BuildRHS(pScheme, rModelPart, rb); KRATOS_CATCH("") } /** * @brief This method computes the reactions of the system * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void CalculateReactions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { TSparseSpace::SetToZero(rb); // Refresh RHS to have the correct reactions BaseType::BuildRHSNoDirichlet(pScheme, rModelPart, rb); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); // First iterator const auto it_dof_begin = BaseType::mDofSet.begin(); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for for (int k = 0; k<ndofs; k++) { auto it_dof = it_dof_begin + k; if (it_dof->IsFixed()) { it_dof->GetSolutionStepReactionValue() = -rb[it_dof->EquationId()]; } } // NOTE: The constraints reactions are already computed when solving the dofs const int number_slave_dofs = BaseType::mSlaveIds.size(); #pragma omp parallel for for (int k = 0; k<number_slave_dofs; k++) { const IndexType equation_id = BaseType::mSlaveIds[k]; auto it_dof = it_dof_begin + equation_id; it_dof->GetSolutionStepReactionValue() = mLagrangeMultiplierVector[mCorrespondanceDofsSlave[equation_id]]; } } /** * @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 rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { const std::size_t system_size = rA.size1(); Vector scaling_factors (system_size); const auto it_dof_iterator_begin = BaseType::mDofSet.begin(); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); // NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for firstprivate(ndofs) for (int k = 0; k<ndofs; ++k) { auto it_dof_iterator = it_dof_iterator_begin + k; if (it_dof_iterator->IsFixed()) { scaling_factors[k] = 0.0; } else { scaling_factors[k] = 1.0; } } // Filling with ones the LM dofs #pragma omp parallel for firstprivate(ndofs) for (int k = ndofs; k<static_cast<int>(system_size); ++k) { scaling_factors[k] = 1.0; } double* Avalues = rA.value_data().begin(); std::size_t* Arow_indices = rA.index1_data().begin(); std::size_t* Acol_indices = rA.index2_data().begin(); // The diagonal considered BaseType::mScaleFactor = this->GetScaleNorm(rModelPart, rA); // Detect if there is a line of all zeros and set the diagonal to a 1 if this happens #pragma omp parallel firstprivate(system_size) { std::size_t col_begin = 0, col_end = 0; bool empty = true; #pragma omp for for (int k = 0; k < static_cast<int>(system_size); ++k) { col_begin = Arow_indices[k]; col_end = Arow_indices[k + 1]; empty = true; for (std::size_t j = col_begin; j < col_end; ++j) { if(Avalues[j] != 0.0) { empty = false; break; } } if(empty) { rA(k, k) = BaseType::mScaleFactor; rb[k] = 0.0; } } } #pragma omp parallel for firstprivate(system_size) for (int k = 0; k < static_cast<int>(system_size); ++k) { std::size_t col_begin = Arow_indices[k]; std::size_t col_end = Arow_indices[k+1]; const double k_factor = scaling_factors[k]; if (k_factor == 0.0) { // Zero out the whole row, except the diagonal for (std::size_t j = col_begin; j < col_end; ++j) if (static_cast<int>(Acol_indices[j]) != k ) Avalues[j] = 0.0; // Zero out the RHS rb[k] = 0.0; } else { // Zero out the column which is associated with the zero'ed row for (std::size_t j = col_begin; j < col_end; ++j) if(scaling_factors[ Acol_indices[j] ] == 0 ) Avalues[j] = 0.0; } } } /** * @brief Applies the constraints with master-slave relation matrix (RHS only) * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rb The RHS vector */ void ApplyRHSConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rb ) override { KRATOS_TRY if (rModelPart.MasterSlaveConstraints().size() != 0) { // First we check if CONSTRAINT_SCALE_FACTOR is defined if (mConstraintFactorConsidered != CONSTRAINT_FACTOR::CONSIDER_PRESCRIBED_CONSTRAINT_FACTOR) { TSystemMatrixType A(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize); BaseType::ConstructMatrixStructure(pScheme, A, rModelPart); this->BuildLHS(pScheme, rModelPart, A); const double constraint_scale_factor = mConstraintFactorConsidered == CONSTRAINT_FACTOR::CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR ? this->GetDiagonalNorm(A) : this->GetDiagonalNorm(A); mConstraintFactor = constraint_scale_factor; } // Check T has been computed if (TSparseSpace::Size1(BaseType::mT) != BaseType::mSlaveIds.size() || TSparseSpace::Size2(BaseType::mT) != BaseType::mEquationSystemSize) { BaseType::mT.resize(BaseType::mSlaveIds.size(), BaseType::mEquationSystemSize, false); ConstructMasterSlaveConstraintsStructure(rModelPart); } // If not previously computed we compute if (BaseType::mOptions.IsNot(TRANSFORMATION_MATRIX_COMPUTED)) { BuildMasterSlaveConstraints(rModelPart); } // Extend with the LM constribution const SizeType number_of_slave_dofs = TSparseSpace::Size1(BaseType::mT); // Definition of the total size of the system const SizeType total_size_of_system = BaseType::mEquationSystemSize + (BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER) ? 2 * number_of_slave_dofs : number_of_slave_dofs); TSystemVectorType b_modified(total_size_of_system); // Copy the RHS #pragma omp parallel for for (int i = 0; i < static_cast<int>(BaseType::mEquationSystemSize); ++i) { b_modified[i] = rb[i]; } // Fill with zeros #pragma omp parallel for for (int i = static_cast<int>(BaseType::mEquationSystemSize); i < static_cast<int>(total_size_of_system); ++i) { b_modified[i] = 0.0; } rb.resize(total_size_of_system, false); // Compute LM contributions TSystemVectorType b_lm(total_size_of_system); ComputeRHSLMContributions(b_lm, mConstraintFactor); // Fill auxiliar vector TSparseSpace::UnaliasedAdd(b_modified, 1.0, b_lm); // Finally reassign TSparseSpace::Copy(b_modified, rb); } KRATOS_CATCH("") } /** * @brief Applies the constraints with master-slave relation matrix * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rb The RHS vector */ void ApplyConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rb ) override { KRATOS_TRY if (rModelPart.MasterSlaveConstraints().size() != 0) { // Getting process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // First build the relation matrix BuildMasterSlaveConstraints(rModelPart); // Copy the LHS to avoid memory errors TSystemMatrixType copy_of_A; copy_of_A.swap(rA); TSystemMatrixType copy_of_T(BaseType::mT); TSystemMatrixType transpose_of_T(TSparseSpace::Size2(BaseType::mT), TSparseSpace::Size1(BaseType::mT)); SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(transpose_of_T, BaseType::mT); // Some common values const SizeType number_of_slave_dofs = TSparseSpace::Size1(BaseType::mT); // Definition of the total size of the system const SizeType total_size_of_system = BaseType::mEquationSystemSize + (BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER) ? 2 * number_of_slave_dofs : number_of_slave_dofs); TSystemVectorType b_modified(total_size_of_system); // Copy the RHS #pragma omp parallel for for (int i = 0; i < static_cast<int>(BaseType::mEquationSystemSize); ++i) { b_modified[i] = rb[i]; } // Fill with zeros #pragma omp parallel for for (int i = static_cast<int>(BaseType::mEquationSystemSize); i < static_cast<int>(total_size_of_system); ++i) { b_modified[i] = 0.0; } rb.resize(total_size_of_system, false); // Definition of the number of blocks const SizeType number_of_blocks = BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER) ? 3 : 2; // Create blocks DenseMatrix<TSystemMatrixType*> matrices_p_blocks(number_of_blocks, number_of_blocks); DenseMatrix<double> contribution_coefficients(number_of_blocks, number_of_blocks); DenseMatrix<bool> transpose_blocks(number_of_blocks, number_of_blocks); // Definition of the auxiliar values const bool has_constraint_scale_factor = mConstraintFactorConsidered == CONSTRAINT_FACTOR::CONSIDER_PRESCRIBED_CONSTRAINT_FACTOR ? true : false; KRATOS_ERROR_IF(has_constraint_scale_factor && !r_current_process_info.Has(CONSTRAINT_SCALE_FACTOR)) << "Constraint scale factor not defined at process info" << std::endl; const double constraint_scale_factor = has_constraint_scale_factor ? r_current_process_info.GetValue(CONSTRAINT_SCALE_FACTOR) : mConstraintFactorConsidered == CONSTRAINT_FACTOR::CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR ? this->GetDiagonalNorm(copy_of_A) : this->GetAveragevalueDiagonal(copy_of_A); mConstraintFactor = constraint_scale_factor; /* Fill common blocks */ // Fill blocks matrices_p_blocks(0,0) = &copy_of_A; matrices_p_blocks(0,1) = &transpose_of_T; matrices_p_blocks(1,0) = &copy_of_T; // Fill coefficients contribution_coefficients(0, 0) = 1.0; contribution_coefficients(0, 1) = mConstraintFactor; contribution_coefficients(1, 0) = mConstraintFactor; // Fill transpose positions for (IndexType i = 0; i < number_of_blocks; ++i) { for (IndexType j = 0; j < number_of_blocks; ++j) { transpose_blocks(i, j) = false; } } // Assemble the blocks if (BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER)) { // Definition of the build scale factor auxiliar value const bool has_auxiliar_constraint_scale_factor = mAuxiliarConstraintFactorConsidered == AUXILIAR_CONSTRAINT_FACTOR::CONSIDER_PRESCRIBED_CONSTRAINT_FACTOR ? true : false; KRATOS_ERROR_IF(has_auxiliar_constraint_scale_factor && !r_current_process_info.Has(AUXILIAR_CONSTRAINT_SCALE_FACTOR)) << "Auxiliar constraint scale factor not defined at process info" << std::endl; const double auxiliar_constraint_scale_factor = has_auxiliar_constraint_scale_factor ? r_current_process_info.GetValue(AUXILIAR_CONSTRAINT_SCALE_FACTOR) : mAuxiliarConstraintFactorConsidered == AUXILIAR_CONSTRAINT_FACTOR::CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR ? this->GetDiagonalNorm(copy_of_A) : this->GetAveragevalueDiagonal(copy_of_A); mAuxiliarConstraintFactor = auxiliar_constraint_scale_factor; // Create auxiliar identity matrix TSystemMatrixType identity_matrix(number_of_slave_dofs, number_of_slave_dofs); for (IndexType i = 0; i < number_of_slave_dofs; ++i) { identity_matrix.push_back(i, i, 1.0); } KRATOS_ERROR_IF_NOT(identity_matrix.nnz() == number_of_slave_dofs) << "Inconsistent number of non-zero values in the identity matrix: " << number_of_slave_dofs << " vs " << identity_matrix.nnz() << std::endl; // Fill blocks matrices_p_blocks(0,2) = &transpose_of_T; matrices_p_blocks(2,0) = &copy_of_T; matrices_p_blocks(1,1) = &identity_matrix; matrices_p_blocks(1,2) = &identity_matrix; matrices_p_blocks(2,1) = &identity_matrix; matrices_p_blocks(2,2) = &identity_matrix; // Fill coefficients contribution_coefficients(0, 2) = mConstraintFactor; contribution_coefficients(2, 0) = mConstraintFactor; contribution_coefficients(1, 1) = -mAuxiliarConstraintFactor; contribution_coefficients(1, 2) = mAuxiliarConstraintFactor; contribution_coefficients(2, 1) = mAuxiliarConstraintFactor; contribution_coefficients(2, 2) = -mAuxiliarConstraintFactor; // Assemble the matrix (NOTE: Like the identity matrix is created inside the condition must be used meanwhile is alive, so inside the condition) SparseMatrixMultiplicationUtility::AssembleSparseMatrixByBlocks(rA, matrices_p_blocks, contribution_coefficients, transpose_blocks); } else { // Create auxiliar zero matrix TSystemMatrixType zero_matrix(number_of_slave_dofs, number_of_slave_dofs); // Fill blocks matrices_p_blocks(1,1) = &zero_matrix; // Fill coefficients contribution_coefficients(1, 1) = 0.0; // Assemble the matrix (NOTE: Like the zero matrix is created inside the condition must be used meanwhile is alive, so inside the condition) SparseMatrixMultiplicationUtility::AssembleSparseMatrixByBlocks(rA, matrices_p_blocks, contribution_coefficients, transpose_blocks); } // Compute LM contributions TSystemVectorType b_lm(total_size_of_system); ComputeRHSLMContributions(b_lm, constraint_scale_factor); // Fill auxiliar vector TSparseSpace::UnaliasedAdd(b_modified, 1.0, b_lm); // Finally reassign TSparseSpace::Copy(b_modified, rb); } KRATOS_CATCH("") } /** * @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 { BaseType::Clear(); // Clear member variables mCorrespondanceDofsSlave.clear(); mLagrangeMultiplierVector.resize(0,false); // Reset flag BaseType::mOptions.Set(TRANSFORMATION_MATRIX_COMPUTED, false); } /** * @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 BaseType::Check(rModelPart); KRATOS_CATCH(""); } /** * @brief This method provides the defaults parameters to avoid conflicts between the different constructors * @return The default parameters */ Parameters GetDefaultParameters() const override { Parameters default_parameters = Parameters(R"( { "name" : "ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier", "consider_lagrange_multiplier_constraint_resolution" : "double", "constraint_scale_factor" : "use_mean_diagonal", "auxiliar_constraint_scale_factor" : "use_mean_diagonal" })"); // Getting base class default parameters const Parameters base_default_parameters = BaseType::GetDefaultParameters(); default_parameters.RecursivelyAddMissingParameters(base_default_parameters); return default_parameters; } /** * @brief Returns the name of the class as used in the settings (snake_case format) * @return The name of the class */ static std::string Name() { return "block_builder_and_solver_with_lagrange_multiplier"; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier"; } /// 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 ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ std::unordered_map<IndexType, IndexType> mCorrespondanceDofsSlave; /// A map of the correspondance between the slave dofs TSystemVectorType mLagrangeMultiplierVector; /// This is vector containing the Lagrange multiplier solution double mConstraintFactor = 0.0; /// The constraint scale factor double mAuxiliarConstraintFactor = 0.0; /// The auxiliar constraint scale factor CONSTRAINT_FACTOR mConstraintFactorConsidered; /// The value considered for the constraint factor AUXILIAR_CONSTRAINT_FACTOR mAuxiliarConstraintFactorConsidered; /// The value considered for the auxiliar constraint factor ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief This method constructs the master slaeve constraint structure * @param rModelPart The problem model part */ void ConstructMasterSlaveConstraintsStructure(ModelPart& rModelPart) override { KRATOS_TRY if (rModelPart.MasterSlaveConstraints().size() > 0) { Timer::Start("ConstraintsRelationMatrixStructure"); const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Vector containing the localization in the system of the different terms DofsVectorType slave_dof_list, master_dof_list; // Constraint initial iterator const auto it_const_begin = rModelPart.MasterSlaveConstraints().begin(); const std::size_t size_indices = BaseType::mDofSet.size(); std::vector<std::unordered_set<IndexType>> indices(size_indices); std::vector<LockObject> lock_array(size_indices); #pragma omp parallel firstprivate(slave_dof_list, master_dof_list) { Element::EquationIdVectorType slave_ids(3); Element::EquationIdVectorType master_ids(3); std::unordered_map<IndexType, std::unordered_set<IndexType>> temp_indices; #pragma omp for schedule(guided, 512) nowait for (int i_const = 0; i_const < static_cast<int>(rModelPart.MasterSlaveConstraints().size()); ++i_const) { auto it_const = it_const_begin + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if( it_const->IsDefined(ACTIVE) ) { constraint_is_active = it_const->Is(ACTIVE); } if(constraint_is_active) { it_const->EquationIdVector(slave_ids, master_ids, r_current_process_info); // Slave DoFs for (auto &id_i : slave_ids) { temp_indices[id_i].insert(id_i); temp_indices[id_i].insert(master_ids.begin(), master_ids.end()); } } } // Merging all the temporal indexes for (int i = 0; i < static_cast<int>(temp_indices.size()); ++i) { lock_array[i].lock(); indices[i].insert(temp_indices[i].begin(), temp_indices[i].end()); lock_array[i].unlock(); } } IndexType counter = 0; mCorrespondanceDofsSlave.clear(); BaseType::mSlaveIds.clear(); BaseType::mMasterIds.clear(); for (int i = 0; i < static_cast<int>(size_indices); ++i) { if (indices[i].size() == 0) { // Master dof! BaseType::mMasterIds.push_back(i); } else { // Slave dof BaseType::mSlaveIds.push_back(i); mCorrespondanceDofsSlave.insert(std::pair<IndexType, IndexType>(i, counter)); ++counter; } } // The slave size const std::size_t slave_size = BaseType::mSlaveIds.size(); // Count the row sizes std::size_t nnz = 0; #pragma omp parallel for reduction(+:nnz) for (int i = 0; i < static_cast<int>(slave_size); ++i) { nnz += indices[BaseType::mSlaveIds[i]].size(); } BaseType::mT = TSystemMatrixType(slave_size, size_indices, nnz); BaseType::mConstantVector.resize(slave_size, false); mLagrangeMultiplierVector.resize(slave_size, false); TSparseSpace::SetToZero(mLagrangeMultiplierVector); double *Tvalues = BaseType::mT.value_data().begin(); IndexType *Trow_indices = BaseType::mT.index1_data().begin(); IndexType *Tcol_indices = BaseType::mT.index2_data().begin(); // Filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Trow_indices[0] = 0; for (int i = 0; i < static_cast<int>(slave_size); ++i) { Trow_indices[i + 1] = Trow_indices[i] + indices[BaseType::mSlaveIds[i]].size(); } #pragma omp parallel for for (int i = 0; i < static_cast<int>(slave_size); ++i) { const IndexType row_begin = Trow_indices[i]; const IndexType row_end = Trow_indices[i + 1]; IndexType k = row_begin; const IndexType i_slave = BaseType::mSlaveIds[i]; for (auto it = indices[i_slave].begin(); it != indices[i_slave].end(); ++it) { Tcol_indices[k] = *it; Tvalues[k] = 0.0; ++k; } indices[i_slave].clear(); //deallocating the memory std::sort(&Tcol_indices[row_begin], &Tcol_indices[row_end]); } BaseType::mT.set_filled(slave_size + 1, nnz); // Reset flag BaseType::mOptions.Set(TRANSFORMATION_MATRIX_COMPUTED, false); Timer::Stop("ConstraintsRelationMatrixStructure"); } KRATOS_CATCH("") } /** * @brief This method builds the master slave relation matrix and vector * @param rModelPart The problem model part */ void BuildMasterSlaveConstraints(ModelPart& rModelPart) override { KRATOS_TRY TSparseSpace::SetToZero(BaseType::mT); TSparseSpace::SetToZero(BaseType::mConstantVector); // The current process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Vector containing the localization in the system of the different terms DofsVectorType slave_dof_list, master_dof_list; // Contributions to the system Matrix transformation_matrix = LocalSystemMatrixType(0, 0); Vector constant_vector = LocalSystemVectorType(0); // Vector containing the localization in the system of the different terms Element::EquationIdVectorType slave_equation_ids, master_equation_ids; const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size()); #pragma omp parallel firstprivate(transformation_matrix, constant_vector, slave_equation_ids, master_equation_ids) { #pragma omp for schedule(guided, 512) for (int i_const = 0; i_const < number_of_constraints; ++i_const) { auto it_const = rModelPart.MasterSlaveConstraints().begin() + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if (it_const->IsDefined(ACTIVE)) constraint_is_active = it_const->Is(ACTIVE); if (constraint_is_active) { it_const->CalculateLocalSystem(transformation_matrix, constant_vector, r_current_process_info); it_const->EquationIdVector(slave_equation_ids, master_equation_ids, r_current_process_info); for (IndexType i = 0; i < slave_equation_ids.size(); ++i) { const IndexType i_global = mCorrespondanceDofsSlave[slave_equation_ids[i]]; // Assemble matrix row BaseType::AssembleRowContribution(BaseType::mT, - transformation_matrix, i_global, i, master_equation_ids); // Assemble constant vector const double constant_value = constant_vector[i]; double& r_value = BaseType::mConstantVector[i_global]; AtomicAdd(r_value, constant_value); } } } } // Setting the slave dofs into the T system for (auto eq_id : BaseType::mSlaveIds) { BaseType::mT(mCorrespondanceDofsSlave[eq_id], eq_id) = 1.0; } // Set flag BaseType::mOptions.Set(TRANSFORMATION_MATRIX_COMPUTED, true); KRATOS_CATCH("") } /** * @brief This method validate and assign default parameters * @param rParameters Parameters to be validated * @param DefaultParameters The default parameters * @return Returns validated Parameters */ Parameters ValidateAndAssignParameters( Parameters ThisParameters, const Parameters DefaultParameters ) const override { ThisParameters.RecursivelyValidateAndAssignDefaults(DefaultParameters); return ThisParameters; } /** * @brief This method assigns settings to member variables * @param ThisParameters Parameters that are assigned to the member variables */ void AssignSettings(const Parameters ThisParameters) override { BaseType::AssignSettings(ThisParameters); // Auxiliar set for constraints std::set<std::string> available_options_for_constraints_scale = {"use_mean_diagonal","use_diagonal_norm","defined_in_process_info"}; // Definition of the constraint scale factor const std::string& r_constraint_scale_factor = ThisParameters["constraint_scale_factor"].GetString(); // Check the values if (available_options_for_constraints_scale.find(r_constraint_scale_factor) == available_options_for_constraints_scale.end()) { std::stringstream msg; msg << "Currently prescribed constraint scale factor : " << r_constraint_scale_factor << "\n"; msg << "Admissible values for the constraint scale factor are : use_mean_diagonal, use_diagonal_norm, or defined_in_process_info" << "\n"; KRATOS_ERROR << msg.str() << std::endl; } // This case will consider the mean value in the diagonal as a scaling value if (r_constraint_scale_factor == "use_mean_diagonal") { mConstraintFactorConsidered = CONSTRAINT_FACTOR::CONSIDER_MEAN_DIAGONAL_CONSTRAINT_FACTOR; } else if (r_constraint_scale_factor == "use_diagonal_norm") { // On this case the norm of the diagonal will be considered mConstraintFactorConsidered = CONSTRAINT_FACTOR::CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR; } else { // Otherwise we will assume we impose a numerical value mConstraintFactorConsidered = CONSTRAINT_FACTOR::CONSIDER_PRESCRIBED_CONSTRAINT_FACTOR; } // Definition of the auxiliar constraint scale factor const std::string& r_auxiliar_constraint_scale_factor = ThisParameters["auxiliar_constraint_scale_factor"].GetString(); // Check the values if (available_options_for_constraints_scale.find(r_auxiliar_constraint_scale_factor) == available_options_for_constraints_scale.end()) { std::stringstream msg; msg << "Currently prescribed constraint scale factor : " << r_auxiliar_constraint_scale_factor << "\n"; msg << "Admissible values for the constraint scale factor are : use_mean_diagonal, use_diagonal_norm, or defined_in_process_info" << "\n"; KRATOS_ERROR << msg.str() << std::endl; } // This case will consider the mean value in the diagonal as a scaling value if (r_auxiliar_constraint_scale_factor == "use_mean_diagonal") { mAuxiliarConstraintFactorConsidered = AUXILIAR_CONSTRAINT_FACTOR::CONSIDER_MEAN_DIAGONAL_CONSTRAINT_FACTOR; } else if (r_auxiliar_constraint_scale_factor == "use_diagonal_norm") { // On this case the norm of the diagonal will be considered mAuxiliarConstraintFactorConsidered = AUXILIAR_CONSTRAINT_FACTOR::CONSIDER_NORM_DIAGONAL_CONSTRAINT_FACTOR; } else { // Otherwise we will assume we impose a numerical value mAuxiliarConstraintFactorConsidered = AUXILIAR_CONSTRAINT_FACTOR::CONSIDER_PRESCRIBED_CONSTRAINT_FACTOR; } // Type of LM if (ThisParameters["consider_lagrange_multiplier_constraint_resolution"].GetString() == "double") { BaseType::mOptions.Set(DOUBLE_LAGRANGE_MULTIPLIER, true); } else { BaseType::mOptions.Set(DOUBLE_LAGRANGE_MULTIPLIER, false); } // Initialize flag BaseType::mOptions.Set(TRANSFORMATION_MATRIX_COMPUTED, false); } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ /** * @brief Applies the constraints LM contribution to the RHS * @param rbLM The RHS vector * @param ScaleFactor The scale factor considered */ void ComputeRHSLMContributions( TSystemVectorType& rbLM, const double ScaleFactor = 1.0 ) { KRATOS_TRY const auto it_dof_begin = BaseType::mDofSet.begin(); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); // Our auxiliar vector const SizeType number_of_slave_dofs = TSparseSpace::Size1(BaseType::mT); const SizeType total_size_of_system = BaseType::mEquationSystemSize + (BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER) ? 2 * number_of_slave_dofs : number_of_slave_dofs); if (TSparseSpace::Size(rbLM) != total_size_of_system) rbLM.resize(total_size_of_system, false); TSystemVectorType aux_lm_rhs_contribution(number_of_slave_dofs); TSystemVectorType aux_whole_dof_vector(ndofs); // NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for for (int i = 0; i < ndofs; ++i) { auto it_dof = it_dof_begin + i; aux_whole_dof_vector[i] = it_dof->GetSolutionStepValue(); } // Compute auxiliar contribution TSystemVectorType aux_slave_dof_vector(number_of_slave_dofs); TSparseSpace::Mult(BaseType::mT, aux_whole_dof_vector, aux_slave_dof_vector); // Finally compute the RHS LM contribution noalias(aux_lm_rhs_contribution) = ScaleFactor * (BaseType::mConstantVector - aux_slave_dof_vector); if (BaseType::mOptions.Is(DOUBLE_LAGRANGE_MULTIPLIER)) { #pragma omp parallel for for (int i = 0; i < static_cast<int>(number_of_slave_dofs); ++i) { rbLM[ndofs + i] = aux_lm_rhs_contribution[i]; rbLM[ndofs + number_of_slave_dofs + i] = aux_lm_rhs_contribution[i]; } } else { #pragma omp parallel for for (int i = 0; i < static_cast<int>(number_of_slave_dofs); ++i) { rbLM[ndofs + i] = aux_lm_rhs_contribution[i]; } } // We compute the transposed matrix of the global relation matrix TSystemMatrixType T_transpose_matrix(ndofs, number_of_slave_dofs); SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, BaseType::mT, -ScaleFactor); TSparseSpace::Mult(T_transpose_matrix, mLagrangeMultiplierVector, aux_whole_dof_vector); #pragma omp parallel for for (int i = 0; i < ndofs; ++i) { rbLM[i] = aux_whole_dof_vector[i]; } KRATOS_CATCH("") } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier */ ///@} ///@name Type Definitions ///@{ // Here one should use the KRATOS_CREATE_LOCAL_FLAG, but it does not play nice with template parameters template<class TSparseSpace, class TDenseSpace, class TLinearSolver> const Kratos::Flags ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier<TSparseSpace, TDenseSpace, TLinearSolver>::DOUBLE_LAGRANGE_MULTIPLIER(Kratos::Flags::Create(1)); template<class TSparseSpace, class TDenseSpace, class TLinearSolver> const Kratos::Flags ResidualBasedBlockBuilderAndSolverWithLagrangeMultiplier<TSparseSpace, TDenseSpace, TLinearSolver>::TRANSFORMATION_MATRIX_COMPUTED(Kratos::Flags::Create(2)); ///@} } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
3d7pt.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 7 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) /* 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])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (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); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][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] = 32; tile_size[1] = 32; tile_size[2] = 16; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // 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); } } } #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 >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,16);t1++) { lbp=max(ceild(t1,2),ceild(32*t1-Nt+3,32)); ubp=min(floord(Nt+Nz-4,32),floord(16*t1+Nz+13,32)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(32*t2-Nz-12,16)),t1);t3<=min(min(min(floord(Nt+Ny-4,16),floord(16*t1+Ny+29,16)),floord(32*t2+Ny+28,16)),floord(32*t1-32*t2+Nz+Ny+27,16));t3++) { for (t4=max(max(max(0,ceild(t1-7,8)),ceild(32*t2-Nz-124,128)),ceild(16*t3-Ny-124,128));t4<=min(min(min(min(floord(Nt+Nx-4,128),floord(16*t1+Nx+29,128)),floord(32*t2+Nx+28,128)),floord(16*t3+Nx+12,128)),floord(32*t1-32*t2+Nz+Nx+27,128));t4++) { for (t5=max(max(max(max(max(0,16*t1),32*t1-32*t2+1),32*t2-Nz+2),16*t3-Ny+2),128*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,16*t1+31),32*t2+30),16*t3+14),128*t4+126),32*t1-32*t2+Nz+29);t5++) { for (t6=max(max(32*t2,t5+1),-32*t1+32*t2+2*t5-31);t6<=min(min(32*t2+31,-32*t1+32*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) { lbv=max(128*t4,t5+1); ubv=min(128*t4+127,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* 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(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* 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]); */ return 0; }
GB_binop__eq_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__eq_int16) // A.*B function (eWiseMult): GB (_AemultB_08__eq_int16) // A.*B function (eWiseMult): GB (_AemultB_02__eq_int16) // A.*B function (eWiseMult): GB (_AemultB_04__eq_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_int16) // A*D function (colscale): GB (_AxD__eq_int16) // D*A function (rowscale): GB (_DxB__eq_int16) // C+=B function (dense accum): GB (_Cdense_accumB__eq_int16) // C+=b function (dense accum): GB (_Cdense_accumb__eq_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_int16) // C=scalar+B GB (_bind1st__eq_int16) // C=scalar+B' GB (_bind1st_tran__eq_int16) // C=A+scalar GB (_bind2nd__eq_int16) // C=A'+scalar GB (_bind2nd_tran__eq_int16) // C type: bool // A type: int16_t // A pattern? 0 // B type: int16_t // B pattern? 0 // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x == y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EQ || GxB_NO_INT16 || GxB_NO_EQ_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__eq_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__eq_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__eq_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__eq_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__eq_int16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__eq_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int16_t alpha_scalar ; int16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int16_t *) alpha_scalar_in)) ; beta_scalar = (*((int16_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__eq_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__eq_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__eq_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__eq_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__eq_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__eq_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__eq_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__eq_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
semantics.c
/* Perform the semantic phase of parsing, i.e., the process of building tree structure, checking semantic consistency, and building RTL. These routines are used both during actual parsing and during the instantiation of template functions. Copyright (C) 1998-2015 Free Software Foundation, Inc. Written by Mark Mitchell (mmitchell@usa.net) based on code found formerly in parse.y and pt.c. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "wide-int.h" #include "inchash.h" #include "tree.h" #include "stmt.h" #include "varasm.h" #include "stor-layout.h" #include "stringpool.h" #include "cp-tree.h" #include "c-family/c-common.h" #include "c-family/c-objc.h" #include "tree-inline.h" #include "intl.h" #include "toplev.h" #include "flags.h" #include "timevar.h" #include "diagnostic.h" #include "hash-map.h" #include "is-a.h" #include "plugin-api.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "ipa-ref.h" #include "cgraph.h" #include "tree-iterator.h" #include "target.h" #include "hash-table.h" #include "gimplify.h" #include "bitmap.h" #include "omp-low.h" #include "builtins.h" #include "convert.h" #include "gomp-constants.h" /* There routines provide a modular interface to perform many parsing operations. They may therefore be used during actual parsing, or during template instantiation, which may be regarded as a degenerate form of parsing. */ static tree maybe_convert_cond (tree); static tree finalize_nrv_r (tree *, int *, void *); static tree capture_decltype (tree); /* Deferred Access Checking Overview --------------------------------- Most C++ expressions and declarations require access checking to be performed during parsing. However, in several cases, this has to be treated differently. For member declarations, access checking has to be deferred until more information about the declaration is known. For example: class A { typedef int X; public: X f(); }; A::X A::f(); A::X g(); When we are parsing the function return type `A::X', we don't really know if this is allowed until we parse the function name. Furthermore, some contexts require that access checking is never performed at all. These include class heads, and template instantiations. Typical use of access checking functions is described here: 1. When we enter a context that requires certain access checking mode, the function `push_deferring_access_checks' is called with DEFERRING argument specifying the desired mode. Access checking may be performed immediately (dk_no_deferred), deferred (dk_deferred), or not performed (dk_no_check). 2. When a declaration such as a type, or a variable, is encountered, the function `perform_or_defer_access_check' is called. It maintains a vector of all deferred checks. 3. The global `current_class_type' or `current_function_decl' is then setup by the parser. `enforce_access' relies on these information to check access. 4. Upon exiting the context mentioned in step 1, `perform_deferred_access_checks' is called to check all declaration stored in the vector. `pop_deferring_access_checks' is then called to restore the previous access checking mode. In case of parsing error, we simply call `pop_deferring_access_checks' without `perform_deferred_access_checks'. */ typedef struct GTY(()) deferred_access { /* A vector representing name-lookups for which we have deferred checking access controls. We cannot check the accessibility of names used in a decl-specifier-seq until we know what is being declared because code like: class A { class B {}; B* f(); } A::B* A::f() { return 0; } is valid, even though `A::B' is not generally accessible. */ vec<deferred_access_check, va_gc> * GTY(()) deferred_access_checks; /* The current mode of access checks. */ enum deferring_kind deferring_access_checks_kind; } deferred_access; /* Data for deferred access checking. */ static GTY(()) vec<deferred_access, va_gc> *deferred_access_stack; static GTY(()) unsigned deferred_access_no_check; /* Save the current deferred access states and start deferred access checking iff DEFER_P is true. */ void push_deferring_access_checks (deferring_kind deferring) { /* For context like template instantiation, access checking disabling applies to all nested context. */ if (deferred_access_no_check || deferring == dk_no_check) deferred_access_no_check++; else { deferred_access e = {NULL, deferring}; vec_safe_push (deferred_access_stack, e); } } /* Save the current deferred access states and start deferred access checking, continuing the set of deferred checks in CHECKS. */ void reopen_deferring_access_checks (vec<deferred_access_check, va_gc> * checks) { push_deferring_access_checks (dk_deferred); if (!deferred_access_no_check) deferred_access_stack->last().deferred_access_checks = checks; } /* Resume deferring access checks again after we stopped doing this previously. */ void resume_deferring_access_checks (void) { if (!deferred_access_no_check) deferred_access_stack->last().deferring_access_checks_kind = dk_deferred; } /* Stop deferring access checks. */ void stop_deferring_access_checks (void) { if (!deferred_access_no_check) deferred_access_stack->last().deferring_access_checks_kind = dk_no_deferred; } /* Discard the current deferred access checks and restore the previous states. */ void pop_deferring_access_checks (void) { if (deferred_access_no_check) deferred_access_no_check--; else deferred_access_stack->pop (); } /* Returns a TREE_LIST representing the deferred checks. The TREE_PURPOSE of each node is the type through which the access occurred; the TREE_VALUE is the declaration named. */ vec<deferred_access_check, va_gc> * get_deferred_access_checks (void) { if (deferred_access_no_check) return NULL; else return (deferred_access_stack->last().deferred_access_checks); } /* Take current deferred checks and combine with the previous states if we also defer checks previously. Otherwise perform checks now. */ void pop_to_parent_deferring_access_checks (void) { if (deferred_access_no_check) deferred_access_no_check--; else { vec<deferred_access_check, va_gc> *checks; deferred_access *ptr; checks = (deferred_access_stack->last ().deferred_access_checks); deferred_access_stack->pop (); ptr = &deferred_access_stack->last (); if (ptr->deferring_access_checks_kind == dk_no_deferred) { /* Check access. */ perform_access_checks (checks, tf_warning_or_error); } else { /* Merge with parent. */ int i, j; deferred_access_check *chk, *probe; FOR_EACH_VEC_SAFE_ELT (checks, i, chk) { FOR_EACH_VEC_SAFE_ELT (ptr->deferred_access_checks, j, probe) { if (probe->binfo == chk->binfo && probe->decl == chk->decl && probe->diag_decl == chk->diag_decl) goto found; } /* Insert into parent's checks. */ vec_safe_push (ptr->deferred_access_checks, *chk); found:; } } } } /* Perform the access checks in CHECKS. The TREE_PURPOSE of each node is the BINFO indicating the qualifying scope used to access the DECL node stored in the TREE_VALUE of the node. If CHECKS is empty or we aren't in SFINAE context or all the checks succeed return TRUE, otherwise FALSE. */ bool perform_access_checks (vec<deferred_access_check, va_gc> *checks, tsubst_flags_t complain) { int i; deferred_access_check *chk; location_t loc = input_location; bool ok = true; if (!checks) return true; FOR_EACH_VEC_SAFE_ELT (checks, i, chk) { input_location = chk->loc; ok &= enforce_access (chk->binfo, chk->decl, chk->diag_decl, complain); } input_location = loc; return (complain & tf_error) ? true : ok; } /* Perform the deferred access checks. After performing the checks, we still have to keep the list `deferred_access_stack->deferred_access_checks' since we may want to check access for them again later in a different context. For example: class A { typedef int X; static X a; }; A::X A::a, x; // No error for `A::a', error for `x' We have to perform deferred access of `A::X', first with `A::a', next with `x'. Return value like perform_access_checks above. */ bool perform_deferred_access_checks (tsubst_flags_t complain) { return perform_access_checks (get_deferred_access_checks (), complain); } /* Defer checking the accessibility of DECL, when looked up in BINFO. DIAG_DECL is the declaration to use to print diagnostics. Return value like perform_access_checks above. */ bool perform_or_defer_access_check (tree binfo, tree decl, tree diag_decl, tsubst_flags_t complain) { int i; deferred_access *ptr; deferred_access_check *chk; /* Exit if we are in a context that no access checking is performed. */ if (deferred_access_no_check) return true; gcc_assert (TREE_CODE (binfo) == TREE_BINFO); ptr = &deferred_access_stack->last (); /* If we are not supposed to defer access checks, just check now. */ if (ptr->deferring_access_checks_kind == dk_no_deferred) { bool ok = enforce_access (binfo, decl, diag_decl, complain); return (complain & tf_error) ? true : ok; } /* See if we are already going to perform this check. */ FOR_EACH_VEC_SAFE_ELT (ptr->deferred_access_checks, i, chk) { if (chk->decl == decl && chk->binfo == binfo && chk->diag_decl == diag_decl) { return true; } } /* If not, record the check. */ deferred_access_check new_access = {binfo, decl, diag_decl, input_location}; vec_safe_push (ptr->deferred_access_checks, new_access); return true; } /* Returns nonzero if the current statement is a full expression, i.e. temporaries created during that statement should be destroyed at the end of the statement. */ int stmts_are_full_exprs_p (void) { return current_stmt_tree ()->stmts_are_full_exprs_p; } /* T is a statement. Add it to the statement-tree. This is the C++ version. The C/ObjC frontends have a slightly different version of this function. */ tree add_stmt (tree t) { enum tree_code code = TREE_CODE (t); if (EXPR_P (t) && code != LABEL_EXPR) { if (!EXPR_HAS_LOCATION (t)) SET_EXPR_LOCATION (t, input_location); /* When we expand a statement-tree, we must know whether or not the statements are full-expressions. We record that fact here. */ STMT_IS_FULL_EXPR_P (t) = stmts_are_full_exprs_p (); } if (code == LABEL_EXPR || code == CASE_LABEL_EXPR) STATEMENT_LIST_HAS_LABEL (cur_stmt_list) = 1; /* Add T to the statement-tree. Non-side-effect statements need to be recorded during statement expressions. */ gcc_checking_assert (!stmt_list_stack->is_empty ()); append_to_statement_list_force (t, &cur_stmt_list); return t; } /* Returns the stmt_tree to which statements are currently being added. */ stmt_tree current_stmt_tree (void) { return (cfun ? &cfun->language->base.x_stmt_tree : &scope_chain->x_stmt_tree); } /* If statements are full expressions, wrap STMT in a CLEANUP_POINT_EXPR. */ static tree maybe_cleanup_point_expr (tree expr) { if (!processing_template_decl && stmts_are_full_exprs_p ()) expr = fold_build_cleanup_point_expr (TREE_TYPE (expr), expr); return expr; } /* Like maybe_cleanup_point_expr except have the type of the new expression be void so we don't need to create a temporary variable to hold the inner expression. The reason why we do this is because the original type might be an aggregate and we cannot create a temporary variable for that type. */ tree maybe_cleanup_point_expr_void (tree expr) { if (!processing_template_decl && stmts_are_full_exprs_p ()) expr = fold_build_cleanup_point_expr (void_type_node, expr); return expr; } /* Create a declaration statement for the declaration given by the DECL. */ void add_decl_expr (tree decl) { tree r = build_stmt (input_location, DECL_EXPR, decl); if (DECL_INITIAL (decl) || (DECL_SIZE (decl) && TREE_SIDE_EFFECTS (DECL_SIZE (decl)))) r = maybe_cleanup_point_expr_void (r); add_stmt (r); } /* Finish a scope. */ tree do_poplevel (tree stmt_list) { tree block = NULL; if (stmts_are_full_exprs_p ()) block = poplevel (kept_level_p (), 1, 0); stmt_list = pop_stmt_list (stmt_list); if (!processing_template_decl) { stmt_list = c_build_bind_expr (input_location, block, stmt_list); /* ??? See c_end_compound_stmt re statement expressions. */ } return stmt_list; } /* Begin a new scope. */ static tree do_pushlevel (scope_kind sk) { tree ret = push_stmt_list (); if (stmts_are_full_exprs_p ()) begin_scope (sk, NULL); return ret; } /* Queue a cleanup. CLEANUP is an expression/statement to be executed when the current scope is exited. EH_ONLY is true when this is not meant to apply to normal control flow transfer. */ void push_cleanup (tree decl, tree cleanup, bool eh_only) { tree stmt = build_stmt (input_location, CLEANUP_STMT, NULL, cleanup, decl); CLEANUP_EH_ONLY (stmt) = eh_only; add_stmt (stmt); CLEANUP_BODY (stmt) = push_stmt_list (); } /* Simple infinite loop tracking for -Wreturn-type. We keep a stack of all the current loops, represented by 'NULL_TREE' if we've seen a possible exit, and 'error_mark_node' if not. This is currently used only to suppress the warning about a function with no return statements, and therefore we don't bother noting returns as possible exits. We also don't bother with gotos. */ static void begin_maybe_infinite_loop (tree cond) { /* Only track this while parsing a function, not during instantiation. */ if (!cfun || (DECL_TEMPLATE_INSTANTIATION (current_function_decl) && !processing_template_decl)) return; bool maybe_infinite = true; if (cond) { cond = fold_non_dependent_expr (cond); maybe_infinite = integer_nonzerop (cond); } vec_safe_push (cp_function_chain->infinite_loops, maybe_infinite ? error_mark_node : NULL_TREE); } /* A break is a possible exit for the current loop. */ void break_maybe_infinite_loop (void) { if (!cfun) return; cp_function_chain->infinite_loops->last() = NULL_TREE; } /* If we reach the end of the loop without seeing a possible exit, we have an infinite loop. */ static void end_maybe_infinite_loop (tree cond) { if (!cfun || (DECL_TEMPLATE_INSTANTIATION (current_function_decl) && !processing_template_decl)) return; tree current = cp_function_chain->infinite_loops->pop(); if (current != NULL_TREE) { cond = fold_non_dependent_expr (cond); if (integer_nonzerop (cond)) current_function_infinite_loop = 1; } } /* Begin a conditional that might contain a declaration. When generating normal code, we want the declaration to appear before the statement containing the conditional. When generating template code, we want the conditional to be rendered as the raw DECL_EXPR. */ static void begin_cond (tree *cond_p) { if (processing_template_decl) *cond_p = push_stmt_list (); } /* Finish such a conditional. */ static void finish_cond (tree *cond_p, tree expr) { if (processing_template_decl) { tree cond = pop_stmt_list (*cond_p); if (expr == NULL_TREE) /* Empty condition in 'for'. */ gcc_assert (empty_expr_stmt_p (cond)); else if (check_for_bare_parameter_packs (expr)) expr = error_mark_node; else if (!empty_expr_stmt_p (cond)) expr = build2 (COMPOUND_EXPR, TREE_TYPE (expr), cond, expr); } *cond_p = expr; } /* If *COND_P specifies a conditional with a declaration, transform the loop such that while (A x = 42) { } for (; A x = 42;) { } becomes while (true) { A x = 42; if (!x) break; } for (;;) { A x = 42; if (!x) break; } The statement list for BODY will be empty if the conditional did not declare anything. */ static void simplify_loop_decl_cond (tree *cond_p, tree body) { tree cond, if_stmt; if (!TREE_SIDE_EFFECTS (body)) return; cond = *cond_p; *cond_p = boolean_true_node; if_stmt = begin_if_stmt (); cond = cp_build_unary_op (TRUTH_NOT_EXPR, cond, 0, tf_warning_or_error); finish_if_stmt_cond (cond, if_stmt); finish_break_stmt (); finish_then_clause (if_stmt); finish_if_stmt (if_stmt); } /* Finish a goto-statement. */ tree finish_goto_stmt (tree destination) { if (identifier_p (destination)) destination = lookup_label (destination); /* We warn about unused labels with -Wunused. That means we have to mark the used labels as used. */ if (TREE_CODE (destination) == LABEL_DECL) TREE_USED (destination) = 1; else { if (check_no_cilk (destination, "Cilk array notation cannot be used as a computed goto expression", "%<_Cilk_spawn%> statement cannot be used as a computed goto expression")) destination = error_mark_node; destination = mark_rvalue_use (destination); if (!processing_template_decl) { destination = cp_convert (ptr_type_node, destination, tf_warning_or_error); if (error_operand_p (destination)) return NULL_TREE; destination = fold_build_cleanup_point_expr (TREE_TYPE (destination), destination); } } check_goto (destination); return add_stmt (build_stmt (input_location, GOTO_EXPR, destination)); } /* COND is the condition-expression for an if, while, etc., statement. Convert it to a boolean value, if appropriate. In addition, verify sequence points if -Wsequence-point is enabled. */ static tree maybe_convert_cond (tree cond) { /* Empty conditions remain empty. */ if (!cond) return NULL_TREE; /* Wait until we instantiate templates before doing conversion. */ if (processing_template_decl) return cond; if (warn_sequence_point) verify_sequence_points (cond); /* Do the conversion. */ cond = convert_from_reference (cond); if (TREE_CODE (cond) == MODIFY_EXPR && !TREE_NO_WARNING (cond) && warn_parentheses) { warning (OPT_Wparentheses, "suggest parentheses around assignment used as truth value"); TREE_NO_WARNING (cond) = 1; } return condition_conversion (cond); } /* Finish an expression-statement, whose EXPRESSION is as indicated. */ tree finish_expr_stmt (tree expr) { tree r = NULL_TREE; if (expr != NULL_TREE) { if (!processing_template_decl) { if (warn_sequence_point) verify_sequence_points (expr); expr = convert_to_void (expr, ICV_STATEMENT, tf_warning_or_error); } else if (!type_dependent_expression_p (expr)) convert_to_void (build_non_dependent_expr (expr), ICV_STATEMENT, tf_warning_or_error); if (check_for_bare_parameter_packs (expr)) expr = error_mark_node; /* Simplification of inner statement expressions, compound exprs, etc can result in us already having an EXPR_STMT. */ if (TREE_CODE (expr) != CLEANUP_POINT_EXPR) { if (TREE_CODE (expr) != EXPR_STMT) expr = build_stmt (input_location, EXPR_STMT, expr); expr = maybe_cleanup_point_expr_void (expr); } r = add_stmt (expr); } return r; } /* Begin an if-statement. Returns a newly created IF_STMT if appropriate. */ tree begin_if_stmt (void) { tree r, scope; scope = do_pushlevel (sk_cond); r = build_stmt (input_location, IF_STMT, NULL_TREE, NULL_TREE, NULL_TREE, scope); begin_cond (&IF_COND (r)); return r; } /* Process the COND of an if-statement, which may be given by IF_STMT. */ void finish_if_stmt_cond (tree cond, tree if_stmt) { finish_cond (&IF_COND (if_stmt), maybe_convert_cond (cond)); add_stmt (if_stmt); THEN_CLAUSE (if_stmt) = push_stmt_list (); } /* Finish the then-clause of an if-statement, which may be given by IF_STMT. */ tree finish_then_clause (tree if_stmt) { THEN_CLAUSE (if_stmt) = pop_stmt_list (THEN_CLAUSE (if_stmt)); return if_stmt; } /* Begin the else-clause of an if-statement. */ void begin_else_clause (tree if_stmt) { ELSE_CLAUSE (if_stmt) = push_stmt_list (); } /* Finish the else-clause of an if-statement, which may be given by IF_STMT. */ void finish_else_clause (tree if_stmt) { ELSE_CLAUSE (if_stmt) = pop_stmt_list (ELSE_CLAUSE (if_stmt)); } /* Finish an if-statement. */ void finish_if_stmt (tree if_stmt) { tree scope = IF_SCOPE (if_stmt); IF_SCOPE (if_stmt) = NULL; add_stmt (do_poplevel (scope)); } /* Begin a while-statement. Returns a newly created WHILE_STMT if appropriate. */ tree begin_while_stmt (void) { tree r; r = build_stmt (input_location, WHILE_STMT, NULL_TREE, NULL_TREE); add_stmt (r); WHILE_BODY (r) = do_pushlevel (sk_block); begin_cond (&WHILE_COND (r)); return r; } /* Process the COND of a while-statement, which may be given by WHILE_STMT. */ void finish_while_stmt_cond (tree cond, tree while_stmt, bool ivdep) { if (check_no_cilk (cond, "Cilk array notation cannot be used as a condition for while statement", "%<_Cilk_spawn%> statement cannot be used as a condition for while statement")) cond = error_mark_node; cond = maybe_convert_cond (cond); finish_cond (&WHILE_COND (while_stmt), cond); begin_maybe_infinite_loop (cond); if (ivdep && cond != error_mark_node) WHILE_COND (while_stmt) = build2 (ANNOTATE_EXPR, TREE_TYPE (WHILE_COND (while_stmt)), WHILE_COND (while_stmt), build_int_cst (integer_type_node, annot_expr_ivdep_kind)); simplify_loop_decl_cond (&WHILE_COND (while_stmt), WHILE_BODY (while_stmt)); } /* Finish a while-statement, which may be given by WHILE_STMT. */ void finish_while_stmt (tree while_stmt) { end_maybe_infinite_loop (boolean_true_node); WHILE_BODY (while_stmt) = do_poplevel (WHILE_BODY (while_stmt)); } /* Begin a do-statement. Returns a newly created DO_STMT if appropriate. */ tree begin_do_stmt (void) { tree r = build_stmt (input_location, DO_STMT, NULL_TREE, NULL_TREE); begin_maybe_infinite_loop (boolean_true_node); add_stmt (r); DO_BODY (r) = push_stmt_list (); return r; } /* Finish the body of a do-statement, which may be given by DO_STMT. */ void finish_do_body (tree do_stmt) { tree body = DO_BODY (do_stmt) = pop_stmt_list (DO_BODY (do_stmt)); if (TREE_CODE (body) == STATEMENT_LIST && STATEMENT_LIST_TAIL (body)) body = STATEMENT_LIST_TAIL (body)->stmt; if (IS_EMPTY_STMT (body)) warning (OPT_Wempty_body, "suggest explicit braces around empty body in %<do%> statement"); } /* Finish a do-statement, which may be given by DO_STMT, and whose COND is as indicated. */ void finish_do_stmt (tree cond, tree do_stmt, bool ivdep) { if (check_no_cilk (cond, "Cilk array notation cannot be used as a condition for a do-while statement", "%<_Cilk_spawn%> statement cannot be used as a condition for a do-while statement")) cond = error_mark_node; cond = maybe_convert_cond (cond); end_maybe_infinite_loop (cond); if (ivdep && cond != error_mark_node) cond = build2 (ANNOTATE_EXPR, TREE_TYPE (cond), cond, build_int_cst (integer_type_node, annot_expr_ivdep_kind)); DO_COND (do_stmt) = cond; } /* Finish a return-statement. The EXPRESSION returned, if any, is as indicated. */ tree finish_return_stmt (tree expr) { tree r; bool no_warning; expr = check_return_expr (expr, &no_warning); if (error_operand_p (expr) || (flag_openmp && !check_omp_return ())) { /* Suppress -Wreturn-type for this function. */ if (warn_return_type) TREE_NO_WARNING (current_function_decl) = true; return error_mark_node; } if (!processing_template_decl) { if (warn_sequence_point) verify_sequence_points (expr); if (DECL_DESTRUCTOR_P (current_function_decl) || (DECL_CONSTRUCTOR_P (current_function_decl) && targetm.cxx.cdtor_returns_this ())) { /* Similarly, all destructors must run destructors for base-classes before returning. So, all returns in a destructor get sent to the DTOR_LABEL; finish_function emits code to return a value there. */ return finish_goto_stmt (cdtor_label); } } r = build_stmt (input_location, RETURN_EXPR, expr); TREE_NO_WARNING (r) |= no_warning; r = maybe_cleanup_point_expr_void (r); r = add_stmt (r); return r; } /* Begin the scope of a for-statement or a range-for-statement. Both the returned trees are to be used in a call to begin_for_stmt or begin_range_for_stmt. */ tree begin_for_scope (tree *init) { tree scope = NULL_TREE; if (flag_new_for_scope > 0) scope = do_pushlevel (sk_for); if (processing_template_decl) *init = push_stmt_list (); else *init = NULL_TREE; return scope; } /* Begin a for-statement. Returns a new FOR_STMT. SCOPE and INIT should be the return of begin_for_scope, or both NULL_TREE */ tree begin_for_stmt (tree scope, tree init) { tree r; r = build_stmt (input_location, FOR_STMT, NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE); if (scope == NULL_TREE) { gcc_assert (!init || !(flag_new_for_scope > 0)); if (!init) scope = begin_for_scope (&init); } FOR_INIT_STMT (r) = init; FOR_SCOPE (r) = scope; return r; } /* Finish the for-init-statement of a for-statement, which may be given by FOR_STMT. */ void finish_for_init_stmt (tree for_stmt) { if (processing_template_decl) FOR_INIT_STMT (for_stmt) = pop_stmt_list (FOR_INIT_STMT (for_stmt)); add_stmt (for_stmt); FOR_BODY (for_stmt) = do_pushlevel (sk_block); begin_cond (&FOR_COND (for_stmt)); } /* Finish the COND of a for-statement, which may be given by FOR_STMT. */ void finish_for_cond (tree cond, tree for_stmt, bool ivdep) { if (check_no_cilk (cond, "Cilk array notation cannot be used in a condition for a for-loop", "%<_Cilk_spawn%> statement cannot be used in a condition for a for-loop")) cond = error_mark_node; cond = maybe_convert_cond (cond); finish_cond (&FOR_COND (for_stmt), cond); begin_maybe_infinite_loop (cond); if (ivdep && cond != error_mark_node) FOR_COND (for_stmt) = build2 (ANNOTATE_EXPR, TREE_TYPE (FOR_COND (for_stmt)), FOR_COND (for_stmt), build_int_cst (integer_type_node, annot_expr_ivdep_kind)); simplify_loop_decl_cond (&FOR_COND (for_stmt), FOR_BODY (for_stmt)); } /* Finish the increment-EXPRESSION in a for-statement, which may be given by FOR_STMT. */ void finish_for_expr (tree expr, tree for_stmt) { if (!expr) return; /* If EXPR is an overloaded function, issue an error; there is no context available to use to perform overload resolution. */ if (type_unknown_p (expr)) { cxx_incomplete_type_error (expr, TREE_TYPE (expr)); expr = error_mark_node; } if (!processing_template_decl) { if (warn_sequence_point) verify_sequence_points (expr); expr = convert_to_void (expr, ICV_THIRD_IN_FOR, tf_warning_or_error); } else if (!type_dependent_expression_p (expr)) convert_to_void (build_non_dependent_expr (expr), ICV_THIRD_IN_FOR, tf_warning_or_error); expr = maybe_cleanup_point_expr_void (expr); if (check_for_bare_parameter_packs (expr)) expr = error_mark_node; FOR_EXPR (for_stmt) = expr; } /* Finish the body of a for-statement, which may be given by FOR_STMT. The increment-EXPR for the loop must be provided. It can also finish RANGE_FOR_STMT. */ void finish_for_stmt (tree for_stmt) { end_maybe_infinite_loop (boolean_true_node); if (TREE_CODE (for_stmt) == RANGE_FOR_STMT) RANGE_FOR_BODY (for_stmt) = do_poplevel (RANGE_FOR_BODY (for_stmt)); else FOR_BODY (for_stmt) = do_poplevel (FOR_BODY (for_stmt)); /* Pop the scope for the body of the loop. */ if (flag_new_for_scope > 0) { tree scope; tree *scope_ptr = (TREE_CODE (for_stmt) == RANGE_FOR_STMT ? &RANGE_FOR_SCOPE (for_stmt) : &FOR_SCOPE (for_stmt)); scope = *scope_ptr; *scope_ptr = NULL; add_stmt (do_poplevel (scope)); } } /* Begin a range-for-statement. Returns a new RANGE_FOR_STMT. SCOPE and INIT should be the return of begin_for_scope, or both NULL_TREE . To finish it call finish_for_stmt(). */ tree begin_range_for_stmt (tree scope, tree init) { tree r; begin_maybe_infinite_loop (boolean_false_node); r = build_stmt (input_location, RANGE_FOR_STMT, NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE); if (scope == NULL_TREE) { gcc_assert (!init || !(flag_new_for_scope > 0)); if (!init) scope = begin_for_scope (&init); } /* RANGE_FOR_STMTs do not use nor save the init tree, so we pop it now. */ if (init) pop_stmt_list (init); RANGE_FOR_SCOPE (r) = scope; return r; } /* Finish the head of a range-based for statement, which may be given by RANGE_FOR_STMT. DECL must be the declaration and EXPR must be the loop expression. */ void finish_range_for_decl (tree range_for_stmt, tree decl, tree expr) { RANGE_FOR_DECL (range_for_stmt) = decl; RANGE_FOR_EXPR (range_for_stmt) = expr; add_stmt (range_for_stmt); RANGE_FOR_BODY (range_for_stmt) = do_pushlevel (sk_block); } /* Finish a break-statement. */ tree finish_break_stmt (void) { /* In switch statements break is sometimes stylistically used after a return statement. This can lead to spurious warnings about control reaching the end of a non-void function when it is inlined. Note that we are calling block_may_fallthru with language specific tree nodes; this works because block_may_fallthru returns true when given something it does not understand. */ if (!block_may_fallthru (cur_stmt_list)) return void_node; return add_stmt (build_stmt (input_location, BREAK_STMT)); } /* Finish a continue-statement. */ tree finish_continue_stmt (void) { return add_stmt (build_stmt (input_location, CONTINUE_STMT)); } /* Begin a switch-statement. Returns a new SWITCH_STMT if appropriate. */ tree begin_switch_stmt (void) { tree r, scope; scope = do_pushlevel (sk_cond); r = build_stmt (input_location, SWITCH_STMT, NULL_TREE, NULL_TREE, NULL_TREE, scope); begin_cond (&SWITCH_STMT_COND (r)); return r; } /* Finish the cond of a switch-statement. */ void finish_switch_cond (tree cond, tree switch_stmt) { tree orig_type = NULL; if (check_no_cilk (cond, "Cilk array notation cannot be used as a condition for switch statement", "%<_Cilk_spawn%> statement cannot be used as a condition for switch statement")) cond = error_mark_node; if (!processing_template_decl) { /* Convert the condition to an integer or enumeration type. */ cond = build_expr_type_conversion (WANT_INT | WANT_ENUM, cond, true); if (cond == NULL_TREE) { error ("switch quantity not an integer"); cond = error_mark_node; } /* We want unlowered type here to handle enum bit-fields. */ orig_type = unlowered_expr_type (cond); if (TREE_CODE (orig_type) != ENUMERAL_TYPE) orig_type = TREE_TYPE (cond); if (cond != error_mark_node) { /* Warn if the condition has boolean value. */ if (TREE_CODE (orig_type) == BOOLEAN_TYPE) warning_at (input_location, OPT_Wswitch_bool, "switch condition has type bool"); /* [stmt.switch] Integral promotions are performed. */ cond = perform_integral_promotions (cond); cond = maybe_cleanup_point_expr (cond); } } if (check_for_bare_parameter_packs (cond)) cond = error_mark_node; else if (!processing_template_decl && warn_sequence_point) verify_sequence_points (cond); finish_cond (&SWITCH_STMT_COND (switch_stmt), cond); SWITCH_STMT_TYPE (switch_stmt) = orig_type; add_stmt (switch_stmt); push_switch (switch_stmt); SWITCH_STMT_BODY (switch_stmt) = push_stmt_list (); } /* Finish the body of a switch-statement, which may be given by SWITCH_STMT. The COND to switch on is indicated. */ void finish_switch_stmt (tree switch_stmt) { tree scope; SWITCH_STMT_BODY (switch_stmt) = pop_stmt_list (SWITCH_STMT_BODY (switch_stmt)); pop_switch (); scope = SWITCH_STMT_SCOPE (switch_stmt); SWITCH_STMT_SCOPE (switch_stmt) = NULL; add_stmt (do_poplevel (scope)); } /* Begin a try-block. Returns a newly-created TRY_BLOCK if appropriate. */ tree begin_try_block (void) { tree r = build_stmt (input_location, TRY_BLOCK, NULL_TREE, NULL_TREE); add_stmt (r); TRY_STMTS (r) = push_stmt_list (); return r; } /* Likewise, for a function-try-block. The block returned in *COMPOUND_STMT is an artificial outer scope, containing the function-try-block. */ tree begin_function_try_block (tree *compound_stmt) { tree r; /* This outer scope does not exist in the C++ standard, but we need a place to put __FUNCTION__ and similar variables. */ *compound_stmt = begin_compound_stmt (0); r = begin_try_block (); FN_TRY_BLOCK_P (r) = 1; return r; } /* Finish a try-block, which may be given by TRY_BLOCK. */ void finish_try_block (tree try_block) { TRY_STMTS (try_block) = pop_stmt_list (TRY_STMTS (try_block)); TRY_HANDLERS (try_block) = push_stmt_list (); } /* Finish the body of a cleanup try-block, which may be given by TRY_BLOCK. */ void finish_cleanup_try_block (tree try_block) { TRY_STMTS (try_block) = pop_stmt_list (TRY_STMTS (try_block)); } /* Finish an implicitly generated try-block, with a cleanup is given by CLEANUP. */ void finish_cleanup (tree cleanup, tree try_block) { TRY_HANDLERS (try_block) = cleanup; CLEANUP_P (try_block) = 1; } /* Likewise, for a function-try-block. */ void finish_function_try_block (tree try_block) { finish_try_block (try_block); /* FIXME : something queer about CTOR_INITIALIZER somehow following the try block, but moving it inside. */ in_function_try_handler = 1; } /* Finish a handler-sequence for a try-block, which may be given by TRY_BLOCK. */ void finish_handler_sequence (tree try_block) { TRY_HANDLERS (try_block) = pop_stmt_list (TRY_HANDLERS (try_block)); check_handlers (TRY_HANDLERS (try_block)); } /* Finish the handler-seq for a function-try-block, given by TRY_BLOCK. COMPOUND_STMT is the outer block created by begin_function_try_block. */ void finish_function_handler_sequence (tree try_block, tree compound_stmt) { in_function_try_handler = 0; finish_handler_sequence (try_block); finish_compound_stmt (compound_stmt); } /* Begin a handler. Returns a HANDLER if appropriate. */ tree begin_handler (void) { tree r; r = build_stmt (input_location, HANDLER, NULL_TREE, NULL_TREE); add_stmt (r); /* Create a binding level for the eh_info and the exception object cleanup. */ HANDLER_BODY (r) = do_pushlevel (sk_catch); return r; } /* Finish the handler-parameters for a handler, which may be given by HANDLER. DECL is the declaration for the catch parameter, or NULL if this is a `catch (...)' clause. */ void finish_handler_parms (tree decl, tree handler) { tree type = NULL_TREE; if (processing_template_decl) { if (decl) { decl = pushdecl (decl); decl = push_template_decl (decl); HANDLER_PARMS (handler) = decl; type = TREE_TYPE (decl); } } else type = expand_start_catch_block (decl); HANDLER_TYPE (handler) = type; } /* Finish a handler, which may be given by HANDLER. The BLOCKs are the return value from the matching call to finish_handler_parms. */ void finish_handler (tree handler) { if (!processing_template_decl) expand_end_catch_block (); HANDLER_BODY (handler) = do_poplevel (HANDLER_BODY (handler)); } /* Begin a compound statement. FLAGS contains some bits that control the behavior and context. If BCS_NO_SCOPE is set, the compound statement does not define a scope. If BCS_FN_BODY is set, this is the outermost block of a function. If BCS_TRY_BLOCK is set, this is the block created on behalf of a TRY statement. Returns a token to be passed to finish_compound_stmt. */ tree begin_compound_stmt (unsigned int flags) { tree r; if (flags & BCS_NO_SCOPE) { r = push_stmt_list (); STATEMENT_LIST_NO_SCOPE (r) = 1; /* Normally, we try hard to keep the BLOCK for a statement-expression. But, if it's a statement-expression with a scopeless block, there's nothing to keep, and we don't want to accidentally keep a block *inside* the scopeless block. */ keep_next_level (false); } else r = do_pushlevel (flags & BCS_TRY_BLOCK ? sk_try : sk_block); /* When processing a template, we need to remember where the braces were, so that we can set up identical scopes when instantiating the template later. BIND_EXPR is a handy candidate for this. Note that do_poplevel won't create a BIND_EXPR itself here (and thus result in nested BIND_EXPRs), since we don't build BLOCK nodes when processing templates. */ if (processing_template_decl) { r = build3 (BIND_EXPR, NULL, NULL, r, NULL); BIND_EXPR_TRY_BLOCK (r) = (flags & BCS_TRY_BLOCK) != 0; BIND_EXPR_BODY_BLOCK (r) = (flags & BCS_FN_BODY) != 0; TREE_SIDE_EFFECTS (r) = 1; } return r; } /* Finish a compound-statement, which is given by STMT. */ void finish_compound_stmt (tree stmt) { if (TREE_CODE (stmt) == BIND_EXPR) { tree body = do_poplevel (BIND_EXPR_BODY (stmt)); /* If the STATEMENT_LIST is empty and this BIND_EXPR isn't special, discard the BIND_EXPR so it can be merged with the containing STATEMENT_LIST. */ if (TREE_CODE (body) == STATEMENT_LIST && STATEMENT_LIST_HEAD (body) == NULL && !BIND_EXPR_BODY_BLOCK (stmt) && !BIND_EXPR_TRY_BLOCK (stmt)) stmt = body; else BIND_EXPR_BODY (stmt) = body; } else if (STATEMENT_LIST_NO_SCOPE (stmt)) stmt = pop_stmt_list (stmt); else { /* Destroy any ObjC "super" receivers that may have been created. */ objc_clear_super_receiver (); stmt = do_poplevel (stmt); } /* ??? See c_end_compound_stmt wrt statement expressions. */ add_stmt (stmt); } /* Finish an asm-statement, whose components are a STRING, some OUTPUT_OPERANDS, some INPUT_OPERANDS, some CLOBBERS and some LABELS. Also note whether the asm-statement should be considered volatile. */ tree finish_asm_stmt (int volatile_p, tree string, tree output_operands, tree input_operands, tree clobbers, tree labels) { tree r; tree t; int ninputs = list_length (input_operands); int noutputs = list_length (output_operands); if (!processing_template_decl) { const char *constraint; const char **oconstraints; bool allows_mem, allows_reg, is_inout; tree operand; int i; oconstraints = XALLOCAVEC (const char *, noutputs); string = resolve_asm_operand_names (string, output_operands, input_operands, labels); for (i = 0, t = output_operands; t; t = TREE_CHAIN (t), ++i) { operand = TREE_VALUE (t); /* ??? Really, this should not be here. Users should be using a proper lvalue, dammit. But there's a long history of using casts in the output operands. In cases like longlong.h, this becomes a primitive form of typechecking -- if the cast can be removed, then the output operand had a type of the proper width; otherwise we'll get an error. Gross, but ... */ STRIP_NOPS (operand); operand = mark_lvalue_use (operand); if (!lvalue_or_else (operand, lv_asm, tf_warning_or_error)) operand = error_mark_node; if (operand != error_mark_node && (TREE_READONLY (operand) || CP_TYPE_CONST_P (TREE_TYPE (operand)) /* Functions are not modifiable, even though they are lvalues. */ || TREE_CODE (TREE_TYPE (operand)) == FUNCTION_TYPE || TREE_CODE (TREE_TYPE (operand)) == METHOD_TYPE /* If it's an aggregate and any field is const, then it is effectively const. */ || (CLASS_TYPE_P (TREE_TYPE (operand)) && C_TYPE_FIELDS_READONLY (TREE_TYPE (operand))))) cxx_readonly_error (operand, lv_asm); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t))); oconstraints[i] = constraint; if (parse_output_constraint (&constraint, i, ninputs, noutputs, &allows_mem, &allows_reg, &is_inout)) { /* If the operand is going to end up in memory, mark it addressable. */ if (!allows_reg && !cxx_mark_addressable (operand)) operand = error_mark_node; } else operand = error_mark_node; TREE_VALUE (t) = operand; } for (i = 0, t = input_operands; t; ++i, t = TREE_CHAIN (t)) { constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t))); bool constraint_parsed = parse_input_constraint (&constraint, i, ninputs, noutputs, 0, oconstraints, &allows_mem, &allows_reg); /* If the operand is going to end up in memory, don't call decay_conversion. */ if (constraint_parsed && !allows_reg && allows_mem) operand = mark_lvalue_use (TREE_VALUE (t)); else operand = decay_conversion (TREE_VALUE (t), tf_warning_or_error); /* If the type of the operand hasn't been determined (e.g., because it involves an overloaded function), then issue an error message. There's no context available to resolve the overloading. */ if (TREE_TYPE (operand) == unknown_type_node) { error ("type of asm operand %qE could not be determined", TREE_VALUE (t)); operand = error_mark_node; } if (constraint_parsed) { /* If the operand is going to end up in memory, mark it addressable. */ if (!allows_reg && allows_mem) { /* Strip the nops as we allow this case. FIXME, this really should be rejected or made deprecated. */ STRIP_NOPS (operand); if (!cxx_mark_addressable (operand)) operand = error_mark_node; } else if (!allows_reg && !allows_mem) { /* If constraint allows neither register nor memory, try harder to get a constant. */ tree constop = maybe_constant_value (operand); if (TREE_CONSTANT (constop)) operand = constop; } } else operand = error_mark_node; TREE_VALUE (t) = operand; } } r = build_stmt (input_location, ASM_EXPR, string, output_operands, input_operands, clobbers, labels); ASM_VOLATILE_P (r) = volatile_p || noutputs == 0; r = maybe_cleanup_point_expr_void (r); return add_stmt (r); } /* Finish a label with the indicated NAME. Returns the new label. */ tree finish_label_stmt (tree name) { tree decl = define_label (input_location, name); if (decl == error_mark_node) return error_mark_node; add_stmt (build_stmt (input_location, LABEL_EXPR, decl)); return decl; } /* Finish a series of declarations for local labels. G++ allows users to declare "local" labels, i.e., labels with scope. This extension is useful when writing code involving statement-expressions. */ void finish_label_decl (tree name) { if (!at_function_scope_p ()) { error ("__label__ declarations are only allowed in function scopes"); return; } add_decl_expr (declare_local_label (name)); } /* When DECL goes out of scope, make sure that CLEANUP is executed. */ void finish_decl_cleanup (tree decl, tree cleanup) { push_cleanup (decl, cleanup, false); } /* If the current scope exits with an exception, run CLEANUP. */ void finish_eh_cleanup (tree cleanup) { push_cleanup (NULL, cleanup, true); } /* The MEM_INITS is a list of mem-initializers, in reverse of the order they were written by the user. Each node is as for emit_mem_initializers. */ void finish_mem_initializers (tree mem_inits) { /* Reorder the MEM_INITS so that they are in the order they appeared in the source program. */ mem_inits = nreverse (mem_inits); if (processing_template_decl) { tree mem; for (mem = mem_inits; mem; mem = TREE_CHAIN (mem)) { /* If the TREE_PURPOSE is a TYPE_PACK_EXPANSION, skip the check for bare parameter packs in the TREE_VALUE, because any parameter packs in the TREE_VALUE have already been bound as part of the TREE_PURPOSE. See make_pack_expansion for more information. */ if (TREE_CODE (TREE_PURPOSE (mem)) != TYPE_PACK_EXPANSION && check_for_bare_parameter_packs (TREE_VALUE (mem))) TREE_VALUE (mem) = error_mark_node; } add_stmt (build_min_nt_loc (UNKNOWN_LOCATION, CTOR_INITIALIZER, mem_inits)); } else emit_mem_initializers (mem_inits); } /* Obfuscate EXPR if it looks like an id-expression or member access so that the call to finish_decltype in do_auto_deduction will give the right result. */ tree force_paren_expr (tree expr) { /* This is only needed for decltype(auto) in C++14. */ if (cxx_dialect < cxx14) return expr; /* If we're in unevaluated context, we can't be deducing a return/initializer type, so we don't need to mess with this. */ if (cp_unevaluated_operand) return expr; if (!DECL_P (expr) && TREE_CODE (expr) != COMPONENT_REF && TREE_CODE (expr) != SCOPE_REF) return expr; if (TREE_CODE (expr) == COMPONENT_REF) REF_PARENTHESIZED_P (expr) = true; else if (type_dependent_expression_p (expr)) expr = build1 (PAREN_EXPR, TREE_TYPE (expr), expr); else { cp_lvalue_kind kind = lvalue_kind (expr); if ((kind & ~clk_class) != clk_none) { tree type = unlowered_expr_type (expr); bool rval = !!(kind & clk_rvalueref); type = cp_build_reference_type (type, rval); /* This inhibits warnings in, eg, cxx_mark_addressable (c++/60955). */ warning_sentinel s (extra_warnings); expr = build_static_cast (type, expr, tf_error); if (expr != error_mark_node) REF_PARENTHESIZED_P (expr) = true; } } return expr; } /* Finish a parenthesized expression EXPR. */ tree finish_parenthesized_expr (tree expr) { if (EXPR_P (expr)) /* This inhibits warnings in c_common_truthvalue_conversion. */ TREE_NO_WARNING (expr) = 1; if (TREE_CODE (expr) == OFFSET_REF || TREE_CODE (expr) == SCOPE_REF) /* [expr.unary.op]/3 The qualified id of a pointer-to-member must not be enclosed in parentheses. */ PTRMEM_OK_P (expr) = 0; if (TREE_CODE (expr) == STRING_CST) PAREN_STRING_LITERAL_P (expr) = 1; expr = force_paren_expr (expr); return expr; } /* Finish a reference to a non-static data member (DECL) that is not preceded by `.' or `->'. */ tree finish_non_static_data_member (tree decl, tree object, tree qualifying_scope) { gcc_assert (TREE_CODE (decl) == FIELD_DECL); if (!object) { tree scope = qualifying_scope; if (scope == NULL_TREE) scope = context_for_name_lookup (decl); object = maybe_dummy_object (scope, NULL); } object = maybe_resolve_dummy (object, true); if (object == error_mark_node) return error_mark_node; /* DR 613/850: Can use non-static data members without an associated object in sizeof/decltype/alignof. */ if (is_dummy_object (object) && cp_unevaluated_operand == 0 && (!processing_template_decl || !current_class_ref)) { if (current_function_decl && DECL_STATIC_FUNCTION_P (current_function_decl)) error ("invalid use of member %qD in static member function", decl); else error ("invalid use of non-static data member %qD", decl); inform (DECL_SOURCE_LOCATION (decl), "declared here"); return error_mark_node; } if (current_class_ptr) TREE_USED (current_class_ptr) = 1; if (processing_template_decl && !qualifying_scope) { tree type = TREE_TYPE (decl); if (TREE_CODE (type) == REFERENCE_TYPE) /* Quals on the object don't matter. */; else if (PACK_EXPANSION_P (type)) /* Don't bother trying to represent this. */ type = NULL_TREE; else { /* Set the cv qualifiers. */ int quals = cp_type_quals (TREE_TYPE (object)); if (DECL_MUTABLE_P (decl)) quals &= ~TYPE_QUAL_CONST; quals |= cp_type_quals (TREE_TYPE (decl)); type = cp_build_qualified_type (type, quals); } return (convert_from_reference (build_min (COMPONENT_REF, type, object, decl, NULL_TREE))); } /* If PROCESSING_TEMPLATE_DECL is nonzero here, then QUALIFYING_SCOPE is also non-null. Wrap this in a SCOPE_REF for now. */ else if (processing_template_decl) return build_qualified_name (TREE_TYPE (decl), qualifying_scope, decl, /*template_p=*/false); else { tree access_type = TREE_TYPE (object); perform_or_defer_access_check (TYPE_BINFO (access_type), decl, decl, tf_warning_or_error); /* If the data member was named `C::M', convert `*this' to `C' first. */ if (qualifying_scope) { tree binfo = NULL_TREE; object = build_scoped_ref (object, qualifying_scope, &binfo); } return build_class_member_access_expr (object, decl, /*access_path=*/NULL_TREE, /*preserve_reference=*/false, tf_warning_or_error); } } /* If we are currently parsing a template and we encountered a typedef TYPEDEF_DECL that is being accessed though CONTEXT, this function adds the typedef to a list tied to the current template. At template instantiation time, that list is walked and access check performed for each typedef. LOCATION is the location of the usage point of TYPEDEF_DECL. */ void add_typedef_to_current_template_for_access_check (tree typedef_decl, tree context, location_t location) { tree template_info = NULL; tree cs = current_scope (); if (!is_typedef_decl (typedef_decl) || !context || !CLASS_TYPE_P (context) || !cs) return; if (CLASS_TYPE_P (cs) || TREE_CODE (cs) == FUNCTION_DECL) template_info = get_template_info (cs); if (template_info && TI_TEMPLATE (template_info) && !currently_open_class (context)) append_type_to_template_for_access_check (cs, typedef_decl, context, location); } /* DECL was the declaration to which a qualified-id resolved. Issue an error message if it is not accessible. If OBJECT_TYPE is non-NULL, we have just seen `x->' or `x.' and OBJECT_TYPE is the type of `*x', or `x', respectively. If the DECL was named as `A::B' then NESTED_NAME_SPECIFIER is `A'. */ void check_accessibility_of_qualified_id (tree decl, tree object_type, tree nested_name_specifier) { tree scope; tree qualifying_type = NULL_TREE; /* If we are parsing a template declaration and if decl is a typedef, add it to a list tied to the template. At template instantiation time, that list will be walked and access check performed. */ add_typedef_to_current_template_for_access_check (decl, nested_name_specifier ? nested_name_specifier : DECL_CONTEXT (decl), input_location); /* If we're not checking, return immediately. */ if (deferred_access_no_check) return; /* Determine the SCOPE of DECL. */ scope = context_for_name_lookup (decl); /* If the SCOPE is not a type, then DECL is not a member. */ if (!TYPE_P (scope)) return; /* Compute the scope through which DECL is being accessed. */ if (object_type /* OBJECT_TYPE might not be a class type; consider: class A { typedef int I; }; I *p; p->A::I::~I(); In this case, we will have "A::I" as the DECL, but "I" as the OBJECT_TYPE. */ && CLASS_TYPE_P (object_type) && DERIVED_FROM_P (scope, object_type)) /* If we are processing a `->' or `.' expression, use the type of the left-hand side. */ qualifying_type = object_type; else if (nested_name_specifier) { /* If the reference is to a non-static member of the current class, treat it as if it were referenced through `this'. */ tree ct; if (DECL_NONSTATIC_MEMBER_P (decl) && current_class_ptr && DERIVED_FROM_P (scope, ct = current_nonlambda_class_type ())) qualifying_type = ct; /* Otherwise, use the type indicated by the nested-name-specifier. */ else qualifying_type = nested_name_specifier; } else /* Otherwise, the name must be from the current class or one of its bases. */ qualifying_type = currently_open_derived_class (scope); if (qualifying_type /* It is possible for qualifying type to be a TEMPLATE_TYPE_PARM or similar in a default argument value. */ && CLASS_TYPE_P (qualifying_type) && !dependent_type_p (qualifying_type)) perform_or_defer_access_check (TYPE_BINFO (qualifying_type), decl, decl, tf_warning_or_error); } /* EXPR is the result of a qualified-id. The QUALIFYING_CLASS was the class named to the left of the "::" operator. DONE is true if this expression is a complete postfix-expression; it is false if this expression is followed by '->', '[', '(', etc. ADDRESS_P is true iff this expression is the operand of '&'. TEMPLATE_P is true iff the qualified-id was of the form "A::template B". TEMPLATE_ARG_P is true iff this qualified name appears as a template argument. */ tree finish_qualified_id_expr (tree qualifying_class, tree expr, bool done, bool address_p, bool template_p, bool template_arg_p, tsubst_flags_t complain) { gcc_assert (TYPE_P (qualifying_class)); if (error_operand_p (expr)) return error_mark_node; if ((DECL_P (expr) || BASELINK_P (expr)) && !mark_used (expr, complain)) return error_mark_node; if (template_p) check_template_keyword (expr); /* If EXPR occurs as the operand of '&', use special handling that permits a pointer-to-member. */ if (address_p && done) { if (TREE_CODE (expr) == SCOPE_REF) expr = TREE_OPERAND (expr, 1); expr = build_offset_ref (qualifying_class, expr, /*address_p=*/true, complain); return expr; } /* No need to check access within an enum. */ if (TREE_CODE (qualifying_class) == ENUMERAL_TYPE) return expr; /* Within the scope of a class, turn references to non-static members into expression of the form "this->...". */ if (template_arg_p) /* But, within a template argument, we do not want make the transformation, as there is no "this" pointer. */ ; else if (TREE_CODE (expr) == FIELD_DECL) { push_deferring_access_checks (dk_no_check); expr = finish_non_static_data_member (expr, NULL_TREE, qualifying_class); pop_deferring_access_checks (); } else if (BASELINK_P (expr) && !processing_template_decl) { /* See if any of the functions are non-static members. */ /* If so, the expression may be relative to 'this'. */ if (!shared_member_p (expr) && current_class_ptr && DERIVED_FROM_P (qualifying_class, current_nonlambda_class_type ())) expr = (build_class_member_access_expr (maybe_dummy_object (qualifying_class, NULL), expr, BASELINK_ACCESS_BINFO (expr), /*preserve_reference=*/false, complain)); else if (done) /* The expression is a qualified name whose address is not being taken. */ expr = build_offset_ref (qualifying_class, expr, /*address_p=*/false, complain); } else if (BASELINK_P (expr)) ; else { /* In a template, return a SCOPE_REF for most qualified-ids so that we can check access at instantiation time. But if we're looking at a member of the current instantiation, we know we have access and building up the SCOPE_REF confuses non-type template argument handling. */ if (processing_template_decl && !currently_open_class (qualifying_class)) expr = build_qualified_name (TREE_TYPE (expr), qualifying_class, expr, template_p); expr = convert_from_reference (expr); } return expr; } /* Begin a statement-expression. The value returned must be passed to finish_stmt_expr. */ tree begin_stmt_expr (void) { return push_stmt_list (); } /* Process the final expression of a statement expression. EXPR can be NULL, if the final expression is empty. Return a STATEMENT_LIST containing all the statements in the statement-expression, or ERROR_MARK_NODE if there was an error. */ tree finish_stmt_expr_expr (tree expr, tree stmt_expr) { if (error_operand_p (expr)) { /* The type of the statement-expression is the type of the last expression. */ TREE_TYPE (stmt_expr) = error_mark_node; return error_mark_node; } /* If the last statement does not have "void" type, then the value of the last statement is the value of the entire expression. */ if (expr) { tree type = TREE_TYPE (expr); if (processing_template_decl) { expr = build_stmt (input_location, EXPR_STMT, expr); expr = add_stmt (expr); /* Mark the last statement so that we can recognize it as such at template-instantiation time. */ EXPR_STMT_STMT_EXPR_RESULT (expr) = 1; } else if (VOID_TYPE_P (type)) { /* Just treat this like an ordinary statement. */ expr = finish_expr_stmt (expr); } else { /* It actually has a value we need to deal with. First, force it to be an rvalue so that we won't need to build up a copy constructor call later when we try to assign it to something. */ expr = force_rvalue (expr, tf_warning_or_error); if (error_operand_p (expr)) return error_mark_node; /* Update for array-to-pointer decay. */ type = TREE_TYPE (expr); /* Wrap it in a CLEANUP_POINT_EXPR and add it to the list like a normal statement, but don't convert to void or actually add the EXPR_STMT. */ if (TREE_CODE (expr) != CLEANUP_POINT_EXPR) expr = maybe_cleanup_point_expr (expr); add_stmt (expr); } /* The type of the statement-expression is the type of the last expression. */ TREE_TYPE (stmt_expr) = type; } return stmt_expr; } /* Finish a statement-expression. EXPR should be the value returned by the previous begin_stmt_expr. Returns an expression representing the statement-expression. */ tree finish_stmt_expr (tree stmt_expr, bool has_no_scope) { tree type; tree result; if (error_operand_p (stmt_expr)) { pop_stmt_list (stmt_expr); return error_mark_node; } gcc_assert (TREE_CODE (stmt_expr) == STATEMENT_LIST); type = TREE_TYPE (stmt_expr); result = pop_stmt_list (stmt_expr); TREE_TYPE (result) = type; if (processing_template_decl) { result = build_min (STMT_EXPR, type, result); TREE_SIDE_EFFECTS (result) = 1; STMT_EXPR_NO_SCOPE (result) = has_no_scope; } else if (CLASS_TYPE_P (type)) { /* Wrap the statement-expression in a TARGET_EXPR so that the temporary object created by the final expression is destroyed at the end of the full-expression containing the statement-expression. */ result = force_target_expr (type, result, tf_warning_or_error); } return result; } /* Returns the expression which provides the value of STMT_EXPR. */ tree stmt_expr_value_expr (tree stmt_expr) { tree t = STMT_EXPR_STMT (stmt_expr); if (TREE_CODE (t) == BIND_EXPR) t = BIND_EXPR_BODY (t); if (TREE_CODE (t) == STATEMENT_LIST && STATEMENT_LIST_TAIL (t)) t = STATEMENT_LIST_TAIL (t)->stmt; if (TREE_CODE (t) == EXPR_STMT) t = EXPR_STMT_EXPR (t); return t; } /* Return TRUE iff EXPR_STMT is an empty list of expression statements. */ bool empty_expr_stmt_p (tree expr_stmt) { tree body = NULL_TREE; if (expr_stmt == void_node) return true; if (expr_stmt) { if (TREE_CODE (expr_stmt) == EXPR_STMT) body = EXPR_STMT_EXPR (expr_stmt); else if (TREE_CODE (expr_stmt) == STATEMENT_LIST) body = expr_stmt; } if (body) { if (TREE_CODE (body) == STATEMENT_LIST) return tsi_end_p (tsi_start (body)); else return empty_expr_stmt_p (body); } return false; } /* Perform Koenig lookup. FN is the postfix-expression representing the function (or functions) to call; ARGS are the arguments to the call. Returns the functions to be considered by overload resolution. */ tree perform_koenig_lookup (tree fn, vec<tree, va_gc> *args, tsubst_flags_t complain) { tree identifier = NULL_TREE; tree functions = NULL_TREE; tree tmpl_args = NULL_TREE; bool template_id = false; if (TREE_CODE (fn) == TEMPLATE_ID_EXPR) { /* Use a separate flag to handle null args. */ template_id = true; tmpl_args = TREE_OPERAND (fn, 1); fn = TREE_OPERAND (fn, 0); } /* Find the name of the overloaded function. */ if (identifier_p (fn)) identifier = fn; else if (is_overloaded_fn (fn)) { functions = fn; identifier = DECL_NAME (get_first_fn (functions)); } else if (DECL_P (fn)) { functions = fn; identifier = DECL_NAME (fn); } /* A call to a namespace-scope function using an unqualified name. Do Koenig lookup -- unless any of the arguments are type-dependent. */ if (!any_type_dependent_arguments_p (args) && !any_dependent_template_arguments_p (tmpl_args)) { fn = lookup_arg_dependent (identifier, functions, args); if (!fn) { /* The unqualified name could not be resolved. */ if (complain) fn = unqualified_fn_lookup_error (identifier); else fn = identifier; } } if (fn && template_id) fn = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fn, tmpl_args); return fn; } /* Generate an expression for `FN (ARGS)'. This may change the contents of ARGS. If DISALLOW_VIRTUAL is true, the call to FN will be not generated as a virtual call, even if FN is virtual. (This flag is set when encountering an expression where the function name is explicitly qualified. For example a call to `X::f' never generates a virtual call.) Returns code for the call. */ tree finish_call_expr (tree fn, vec<tree, va_gc> **args, bool disallow_virtual, bool koenig_p, tsubst_flags_t complain) { tree result; tree orig_fn; vec<tree, va_gc> *orig_args = NULL; if (fn == error_mark_node) return error_mark_node; gcc_assert (!TYPE_P (fn)); orig_fn = fn; if (processing_template_decl) { /* If the call expression is dependent, build a CALL_EXPR node with no type; type_dependent_expression_p recognizes expressions with no type as being dependent. */ if (type_dependent_expression_p (fn) || any_type_dependent_arguments_p (*args) /* For a non-static member function that doesn't have an explicit object argument, we need to specifically test the type dependency of the "this" pointer because it is not included in *ARGS even though it is considered to be part of the list of arguments. Note that this is related to CWG issues 515 and 1005. */ || (TREE_CODE (fn) != COMPONENT_REF && non_static_member_function_p (fn) && current_class_ref && type_dependent_expression_p (current_class_ref))) { result = build_nt_call_vec (fn, *args); SET_EXPR_LOCATION (result, EXPR_LOC_OR_LOC (fn, input_location)); KOENIG_LOOKUP_P (result) = koenig_p; if (cfun) { do { tree fndecl = OVL_CURRENT (fn); if (TREE_CODE (fndecl) != FUNCTION_DECL || !TREE_THIS_VOLATILE (fndecl)) break; fn = OVL_NEXT (fn); } while (fn); if (!fn) current_function_returns_abnormally = 1; } return result; } orig_args = make_tree_vector_copy (*args); if (!BASELINK_P (fn) && TREE_CODE (fn) != PSEUDO_DTOR_EXPR && TREE_TYPE (fn) != unknown_type_node) fn = build_non_dependent_expr (fn); make_args_non_dependent (*args); } if (TREE_CODE (fn) == COMPONENT_REF) { tree member = TREE_OPERAND (fn, 1); if (BASELINK_P (member)) { tree object = TREE_OPERAND (fn, 0); return build_new_method_call (object, member, args, NULL_TREE, (disallow_virtual ? LOOKUP_NORMAL | LOOKUP_NONVIRTUAL : LOOKUP_NORMAL), /*fn_p=*/NULL, complain); } } /* Per 13.3.1.1, '(&f)(...)' is the same as '(f)(...)'. */ if (TREE_CODE (fn) == ADDR_EXPR && TREE_CODE (TREE_OPERAND (fn, 0)) == OVERLOAD) fn = TREE_OPERAND (fn, 0); if (is_overloaded_fn (fn)) fn = baselink_for_fns (fn); result = NULL_TREE; if (BASELINK_P (fn)) { tree object; /* A call to a member function. From [over.call.func]: If the keyword this is in scope and refers to the class of that member function, or a derived class thereof, then the function call is transformed into a qualified function call using (*this) as the postfix-expression to the left of the . operator.... [Otherwise] a contrived object of type T becomes the implied object argument. In this situation: struct A { void f(); }; struct B : public A {}; struct C : public A { void g() { B::f(); }}; "the class of that member function" refers to `A'. But 11.2 [class.access.base] says that we need to convert 'this' to B* as part of the access, so we pass 'B' to maybe_dummy_object. */ object = maybe_dummy_object (BINFO_TYPE (BASELINK_ACCESS_BINFO (fn)), NULL); if (processing_template_decl) { if (type_dependent_expression_p (object)) { tree ret = build_nt_call_vec (orig_fn, orig_args); release_tree_vector (orig_args); return ret; } object = build_non_dependent_expr (object); } result = build_new_method_call (object, fn, args, NULL_TREE, (disallow_virtual ? LOOKUP_NORMAL|LOOKUP_NONVIRTUAL : LOOKUP_NORMAL), /*fn_p=*/NULL, complain); } else if (is_overloaded_fn (fn)) { /* If the function is an overloaded builtin, resolve it. */ if (TREE_CODE (fn) == FUNCTION_DECL && (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL || DECL_BUILT_IN_CLASS (fn) == BUILT_IN_MD)) result = resolve_overloaded_builtin (input_location, fn, *args); if (!result) { if (warn_sizeof_pointer_memaccess && !vec_safe_is_empty (*args) && !processing_template_decl) { location_t sizeof_arg_loc[3]; tree sizeof_arg[3]; unsigned int i; for (i = 0; i < 3; i++) { tree t; sizeof_arg_loc[i] = UNKNOWN_LOCATION; sizeof_arg[i] = NULL_TREE; if (i >= (*args)->length ()) continue; t = (**args)[i]; if (TREE_CODE (t) != SIZEOF_EXPR) continue; if (SIZEOF_EXPR_TYPE_P (t)) sizeof_arg[i] = TREE_TYPE (TREE_OPERAND (t, 0)); else sizeof_arg[i] = TREE_OPERAND (t, 0); sizeof_arg_loc[i] = EXPR_LOCATION (t); } sizeof_pointer_memaccess_warning (sizeof_arg_loc, fn, *args, sizeof_arg, same_type_ignoring_top_level_qualifiers_p); } /* A call to a namespace-scope function. */ result = build_new_function_call (fn, args, koenig_p, complain); } } else if (TREE_CODE (fn) == PSEUDO_DTOR_EXPR) { if (!vec_safe_is_empty (*args)) error ("arguments to destructor are not allowed"); /* Mark the pseudo-destructor call as having side-effects so that we do not issue warnings about its use. */ result = build1 (NOP_EXPR, void_type_node, TREE_OPERAND (fn, 0)); TREE_SIDE_EFFECTS (result) = 1; } else if (CLASS_TYPE_P (TREE_TYPE (fn))) /* If the "function" is really an object of class type, it might have an overloaded `operator ()'. */ result = build_op_call (fn, args, complain); if (!result) /* A call where the function is unknown. */ result = cp_build_function_call_vec (fn, args, complain); if (processing_template_decl && result != error_mark_node) { if (INDIRECT_REF_P (result)) result = TREE_OPERAND (result, 0); result = build_call_vec (TREE_TYPE (result), orig_fn, orig_args); SET_EXPR_LOCATION (result, input_location); KOENIG_LOOKUP_P (result) = koenig_p; release_tree_vector (orig_args); result = convert_from_reference (result); } if (koenig_p) { /* Free garbage OVERLOADs from arg-dependent lookup. */ tree next = NULL_TREE; for (fn = orig_fn; fn && TREE_CODE (fn) == OVERLOAD && OVL_ARG_DEPENDENT (fn); fn = next) { if (processing_template_decl) /* In a template, we'll re-use them at instantiation time. */ OVL_ARG_DEPENDENT (fn) = false; else { next = OVL_CHAIN (fn); ggc_free (fn); } } } return result; } /* Finish a call to a postfix increment or decrement or EXPR. (Which is indicated by CODE, which should be POSTINCREMENT_EXPR or POSTDECREMENT_EXPR.) */ tree finish_increment_expr (tree expr, enum tree_code code) { return build_x_unary_op (input_location, code, expr, tf_warning_or_error); } /* Finish a use of `this'. Returns an expression for `this'. */ tree finish_this_expr (void) { tree result = NULL_TREE; if (current_class_ptr) { tree type = TREE_TYPE (current_class_ref); /* In a lambda expression, 'this' refers to the captured 'this'. */ if (LAMBDA_TYPE_P (type)) result = lambda_expr_this_capture (CLASSTYPE_LAMBDA_EXPR (type), true); else result = current_class_ptr; } if (result) /* The keyword 'this' is a prvalue expression. */ return rvalue (result); tree fn = current_nonlambda_function (); if (fn && DECL_STATIC_FUNCTION_P (fn)) error ("%<this%> is unavailable for static member functions"); else if (fn) error ("invalid use of %<this%> in non-member function"); else error ("invalid use of %<this%> at top level"); return error_mark_node; } /* Finish a pseudo-destructor expression. If SCOPE is NULL, the expression was of the form `OBJECT.~DESTRUCTOR' where DESTRUCTOR is the TYPE for the type given. If SCOPE is non-NULL, the expression was of the form `OBJECT.SCOPE::~DESTRUCTOR'. */ tree finish_pseudo_destructor_expr (tree object, tree scope, tree destructor, location_t loc) { if (object == error_mark_node || destructor == error_mark_node) return error_mark_node; gcc_assert (TYPE_P (destructor)); if (!processing_template_decl) { if (scope == error_mark_node) { error_at (loc, "invalid qualifying scope in pseudo-destructor name"); return error_mark_node; } if (is_auto (destructor)) destructor = TREE_TYPE (object); if (scope && TYPE_P (scope) && !check_dtor_name (scope, destructor)) { error_at (loc, "qualified type %qT does not match destructor name ~%qT", scope, destructor); return error_mark_node; } /* [expr.pseudo] says both: The type designated by the pseudo-destructor-name shall be the same as the object type. and: The cv-unqualified versions of the object type and of the type designated by the pseudo-destructor-name shall be the same type. We implement the more generous second sentence, since that is what most other compilers do. */ if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (object), destructor)) { error_at (loc, "%qE is not of type %qT", object, destructor); return error_mark_node; } } return build3_loc (loc, PSEUDO_DTOR_EXPR, void_type_node, object, scope, destructor); } /* Finish an expression of the form CODE EXPR. */ tree finish_unary_op_expr (location_t loc, enum tree_code code, tree expr, tsubst_flags_t complain) { tree result = build_x_unary_op (loc, code, expr, complain); if ((complain & tf_warning) && TREE_OVERFLOW_P (result) && !TREE_OVERFLOW_P (expr)) overflow_warning (input_location, result); return result; } /* Finish a compound-literal expression. TYPE is the type to which the CONSTRUCTOR in COMPOUND_LITERAL is being cast. */ tree finish_compound_literal (tree type, tree compound_literal, tsubst_flags_t complain) { if (type == error_mark_node) return error_mark_node; if (TREE_CODE (type) == REFERENCE_TYPE) { compound_literal = finish_compound_literal (TREE_TYPE (type), compound_literal, complain); return cp_build_c_cast (type, compound_literal, complain); } if (!TYPE_OBJ_P (type)) { if (complain & tf_error) error ("compound literal of non-object type %qT", type); return error_mark_node; } if (processing_template_decl) { TREE_TYPE (compound_literal) = type; /* Mark the expression as a compound literal. */ TREE_HAS_CONSTRUCTOR (compound_literal) = 1; return compound_literal; } type = complete_type (type); if (TYPE_NON_AGGREGATE_CLASS (type)) { /* Trying to deal with a CONSTRUCTOR instead of a TREE_LIST everywhere that deals with function arguments would be a pain, so just wrap it in a TREE_LIST. The parser set a flag so we know that it came from T{} rather than T({}). */ CONSTRUCTOR_IS_DIRECT_INIT (compound_literal) = 1; compound_literal = build_tree_list (NULL_TREE, compound_literal); return build_functional_cast (type, compound_literal, complain); } if (TREE_CODE (type) == ARRAY_TYPE && check_array_initializer (NULL_TREE, type, compound_literal)) return error_mark_node; compound_literal = reshape_init (type, compound_literal, complain); if (SCALAR_TYPE_P (type) && !BRACE_ENCLOSED_INITIALIZER_P (compound_literal) && !check_narrowing (type, compound_literal, complain)) return error_mark_node; if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type) == NULL_TREE) { cp_complete_array_type_or_error (&type, compound_literal, false, complain); if (type == error_mark_node) return error_mark_node; } compound_literal = digest_init (type, compound_literal, complain); if (TREE_CODE (compound_literal) == CONSTRUCTOR) TREE_HAS_CONSTRUCTOR (compound_literal) = true; /* Put static/constant array temporaries in static variables, but always represent class temporaries with TARGET_EXPR so we elide copies. */ if ((!at_function_scope_p () || CP_TYPE_CONST_P (type)) && TREE_CODE (type) == ARRAY_TYPE && !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type) && initializer_constant_valid_p (compound_literal, type)) { tree decl = create_temporary_var (type); DECL_INITIAL (decl) = compound_literal; TREE_STATIC (decl) = 1; if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type)) { /* 5.19 says that a constant expression can include an lvalue-rvalue conversion applied to "a glvalue of literal type that refers to a non-volatile temporary object initialized with a constant expression". Rather than try to communicate that this VAR_DECL is a temporary, just mark it constexpr. */ DECL_DECLARED_CONSTEXPR_P (decl) = true; DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true; TREE_CONSTANT (decl) = true; } cp_apply_type_quals_to_decl (cp_type_quals (type), decl); decl = pushdecl_top_level (decl); DECL_NAME (decl) = make_anon_name (); SET_DECL_ASSEMBLER_NAME (decl, DECL_NAME (decl)); /* Make sure the destructor is callable. */ tree clean = cxx_maybe_build_cleanup (decl, complain); if (clean == error_mark_node) return error_mark_node; return decl; } else return get_target_expr_sfinae (compound_literal, complain); } /* Return the declaration for the function-name variable indicated by ID. */ tree finish_fname (tree id) { tree decl; decl = fname_decl (input_location, C_RID_CODE (id), id); if (processing_template_decl && current_function_decl && decl != error_mark_node) decl = DECL_NAME (decl); return decl; } /* Finish a translation unit. */ void finish_translation_unit (void) { /* In case there were missing closebraces, get us back to the global binding level. */ pop_everything (); while (current_namespace != global_namespace) pop_namespace (); /* Do file scope __FUNCTION__ et al. */ finish_fname_decls (); } /* Finish a template type parameter, specified as AGGR IDENTIFIER. Returns the parameter. */ tree finish_template_type_parm (tree aggr, tree identifier) { if (aggr != class_type_node) { permerror (input_location, "template type parameters must use the keyword %<class%> or %<typename%>"); aggr = class_type_node; } return build_tree_list (aggr, identifier); } /* Finish a template template parameter, specified as AGGR IDENTIFIER. Returns the parameter. */ tree finish_template_template_parm (tree aggr, tree identifier) { tree decl = build_decl (input_location, TYPE_DECL, identifier, NULL_TREE); tree tmpl = build_lang_decl (TEMPLATE_DECL, identifier, NULL_TREE); DECL_TEMPLATE_PARMS (tmpl) = current_template_parms; DECL_TEMPLATE_RESULT (tmpl) = decl; DECL_ARTIFICIAL (decl) = 1; end_template_decl (); gcc_assert (DECL_TEMPLATE_PARMS (tmpl)); check_default_tmpl_args (decl, DECL_TEMPLATE_PARMS (tmpl), /*is_primary=*/true, /*is_partial=*/false, /*is_friend=*/0); return finish_template_type_parm (aggr, tmpl); } /* ARGUMENT is the default-argument value for a template template parameter. If ARGUMENT is invalid, issue error messages and return the ERROR_MARK_NODE. Otherwise, ARGUMENT itself is returned. */ tree check_template_template_default_arg (tree argument) { if (TREE_CODE (argument) != TEMPLATE_DECL && TREE_CODE (argument) != TEMPLATE_TEMPLATE_PARM && TREE_CODE (argument) != UNBOUND_CLASS_TEMPLATE) { if (TREE_CODE (argument) == TYPE_DECL) error ("invalid use of type %qT as a default value for a template " "template-parameter", TREE_TYPE (argument)); else error ("invalid default argument for a template template parameter"); return error_mark_node; } return argument; } /* Begin a class definition, as indicated by T. */ tree begin_class_definition (tree t) { if (error_operand_p (t) || error_operand_p (TYPE_MAIN_DECL (t))) return error_mark_node; if (processing_template_parmlist) { error ("definition of %q#T inside template parameter list", t); return error_mark_node; } /* According to the C++ ABI, decimal classes defined in ISO/IEC TR 24733 are passed the same as decimal scalar types. */ if (TREE_CODE (t) == RECORD_TYPE && !processing_template_decl) { tree ns = TYPE_CONTEXT (t); if (ns && TREE_CODE (ns) == NAMESPACE_DECL && DECL_CONTEXT (ns) == std_node && DECL_NAME (ns) && !strcmp (IDENTIFIER_POINTER (DECL_NAME (ns)), "decimal")) { const char *n = TYPE_NAME_STRING (t); if ((strcmp (n, "decimal32") == 0) || (strcmp (n, "decimal64") == 0) || (strcmp (n, "decimal128") == 0)) TYPE_TRANSPARENT_AGGR (t) = 1; } } /* A non-implicit typename comes from code like: template <typename T> struct A { template <typename U> struct A<T>::B ... This is erroneous. */ else if (TREE_CODE (t) == TYPENAME_TYPE) { error ("invalid definition of qualified type %qT", t); t = error_mark_node; } if (t == error_mark_node || ! MAYBE_CLASS_TYPE_P (t)) { t = make_class_type (RECORD_TYPE); pushtag (make_anon_name (), t, /*tag_scope=*/ts_current); } if (TYPE_BEING_DEFINED (t)) { t = make_class_type (TREE_CODE (t)); pushtag (TYPE_IDENTIFIER (t), t, /*tag_scope=*/ts_current); } maybe_process_partial_specialization (t); pushclass (t); TYPE_BEING_DEFINED (t) = 1; class_binding_level->defining_class_p = 1; if (flag_pack_struct) { tree v; TYPE_PACKED (t) = 1; /* Even though the type is being defined for the first time here, there might have been a forward declaration, so there might be cv-qualified variants of T. */ for (v = TYPE_NEXT_VARIANT (t); v; v = TYPE_NEXT_VARIANT (v)) TYPE_PACKED (v) = 1; } /* Reset the interface data, at the earliest possible moment, as it might have been set via a class foo; before. */ if (! TYPE_ANONYMOUS_P (t)) { struct c_fileinfo *finfo = \ get_fileinfo (LOCATION_FILE (input_location)); CLASSTYPE_INTERFACE_ONLY (t) = finfo->interface_only; SET_CLASSTYPE_INTERFACE_UNKNOWN_X (t, finfo->interface_unknown); } reset_specialization(); /* Make a declaration for this class in its own scope. */ build_self_reference (); return t; } /* Finish the member declaration given by DECL. */ void finish_member_declaration (tree decl) { if (decl == error_mark_node || decl == NULL_TREE) return; if (decl == void_type_node) /* The COMPONENT was a friend, not a member, and so there's nothing for us to do. */ return; /* We should see only one DECL at a time. */ gcc_assert (DECL_CHAIN (decl) == NULL_TREE); /* Set up access control for DECL. */ TREE_PRIVATE (decl) = (current_access_specifier == access_private_node); TREE_PROTECTED (decl) = (current_access_specifier == access_protected_node); if (TREE_CODE (decl) == TEMPLATE_DECL) { TREE_PRIVATE (DECL_TEMPLATE_RESULT (decl)) = TREE_PRIVATE (decl); TREE_PROTECTED (DECL_TEMPLATE_RESULT (decl)) = TREE_PROTECTED (decl); } /* Mark the DECL as a member of the current class, unless it's a member of an enumeration. */ if (TREE_CODE (decl) != CONST_DECL) DECL_CONTEXT (decl) = current_class_type; /* Check for bare parameter packs in the member variable declaration. */ if (TREE_CODE (decl) == FIELD_DECL) { if (check_for_bare_parameter_packs (TREE_TYPE (decl))) TREE_TYPE (decl) = error_mark_node; if (check_for_bare_parameter_packs (DECL_ATTRIBUTES (decl))) DECL_ATTRIBUTES (decl) = NULL_TREE; } /* [dcl.link] A C language linkage is ignored for the names of class members and the member function type of class member functions. */ if (DECL_LANG_SPECIFIC (decl) && DECL_LANGUAGE (decl) == lang_c) SET_DECL_LANGUAGE (decl, lang_cplusplus); /* Put functions on the TYPE_METHODS list and everything else on the TYPE_FIELDS list. Note that these are built up in reverse order. We reverse them (to obtain declaration order) in finish_struct. */ if (DECL_DECLARES_FUNCTION_P (decl)) { /* We also need to add this function to the CLASSTYPE_METHOD_VEC. */ if (add_method (current_class_type, decl, NULL_TREE)) { DECL_CHAIN (decl) = TYPE_METHODS (current_class_type); TYPE_METHODS (current_class_type) = decl; maybe_add_class_template_decl_list (current_class_type, decl, /*friend_p=*/0); } } /* Enter the DECL into the scope of the class, if the class isn't a closure (whose fields are supposed to be unnamed). */ else if (CLASSTYPE_LAMBDA_EXPR (current_class_type) || pushdecl_class_level (decl)) { if (TREE_CODE (decl) == USING_DECL) { /* For now, ignore class-scope USING_DECLS, so that debugging backends do not see them. */ DECL_IGNORED_P (decl) = 1; } /* All TYPE_DECLs go at the end of TYPE_FIELDS. Ordinary fields go at the beginning. The reason is that lookup_field_1 searches the list in order, and we want a field name to override a type name so that the "struct stat hack" will work. In particular: struct S { enum E { }; int E } s; s.E = 3; is valid. In addition, the FIELD_DECLs must be maintained in declaration order so that class layout works as expected. However, we don't need that order until class layout, so we save a little time by putting FIELD_DECLs on in reverse order here, and then reversing them in finish_struct_1. (We could also keep a pointer to the correct insertion points in the list.) */ if (TREE_CODE (decl) == TYPE_DECL) TYPE_FIELDS (current_class_type) = chainon (TYPE_FIELDS (current_class_type), decl); else { DECL_CHAIN (decl) = TYPE_FIELDS (current_class_type); TYPE_FIELDS (current_class_type) = decl; } maybe_add_class_template_decl_list (current_class_type, decl, /*friend_p=*/0); } if (pch_file) note_decl_for_pch (decl); } /* DECL has been declared while we are building a PCH file. Perform actions that we might normally undertake lazily, but which can be performed now so that they do not have to be performed in translation units which include the PCH file. */ void note_decl_for_pch (tree decl) { gcc_assert (pch_file); /* There's a good chance that we'll have to mangle names at some point, even if only for emission in debugging information. */ if (VAR_OR_FUNCTION_DECL_P (decl) && !processing_template_decl) mangle_decl (decl); } /* Finish processing a complete template declaration. The PARMS are the template parameters. */ void finish_template_decl (tree parms) { if (parms) end_template_decl (); else end_specialization (); } /* Finish processing a template-id (which names a type) of the form NAME < ARGS >. Return the TYPE_DECL for the type named by the template-id. If ENTERING_SCOPE is nonzero we are about to enter the scope of template-id indicated. */ tree finish_template_type (tree name, tree args, int entering_scope) { tree type; type = lookup_template_class (name, args, NULL_TREE, NULL_TREE, entering_scope, tf_warning_or_error | tf_user); if (type == error_mark_node) return type; else if (CLASS_TYPE_P (type) && !alias_type_or_template_p (type)) return TYPE_STUB_DECL (type); else return TYPE_NAME (type); } /* Finish processing a BASE_CLASS with the indicated ACCESS_SPECIFIER. Return a TREE_LIST containing the ACCESS_SPECIFIER and the BASE_CLASS, or NULL_TREE if an error occurred. The ACCESS_SPECIFIER is one of access_{default,public,protected_private}_node. For a virtual base we set TREE_TYPE. */ tree finish_base_specifier (tree base, tree access, bool virtual_p) { tree result; if (base == error_mark_node) { error ("invalid base-class specification"); result = NULL_TREE; } else if (! MAYBE_CLASS_TYPE_P (base)) { error ("%qT is not a class type", base); result = NULL_TREE; } else { if (cp_type_quals (base) != 0) { /* DR 484: Can a base-specifier name a cv-qualified class type? */ base = TYPE_MAIN_VARIANT (base); } result = build_tree_list (access, base); if (virtual_p) TREE_TYPE (result) = integer_type_node; } return result; } /* If FNS is a member function, a set of member functions, or a template-id referring to one or more member functions, return a BASELINK for FNS, incorporating the current access context. Otherwise, return FNS unchanged. */ tree baselink_for_fns (tree fns) { tree scope; tree cl; if (BASELINK_P (fns) || error_operand_p (fns)) return fns; scope = ovl_scope (fns); if (!CLASS_TYPE_P (scope)) return fns; cl = currently_open_derived_class (scope); if (!cl) cl = scope; cl = TYPE_BINFO (cl); return build_baselink (cl, cl, fns, /*optype=*/NULL_TREE); } /* Returns true iff DECL is a variable from a function outside the current one. */ static bool outer_var_p (tree decl) { return ((VAR_P (decl) || TREE_CODE (decl) == PARM_DECL) && DECL_FUNCTION_SCOPE_P (decl) && (DECL_CONTEXT (decl) != current_function_decl || parsing_nsdmi ())); } /* As above, but also checks that DECL is automatic. */ bool outer_automatic_var_p (tree decl) { return (outer_var_p (decl) && !TREE_STATIC (decl)); } /* DECL satisfies outer_automatic_var_p. Possibly complain about it or rewrite it for lambda capture. */ tree process_outer_var_ref (tree decl, tsubst_flags_t complain) { if (cp_unevaluated_operand) /* It's not a use (3.2) if we're in an unevaluated context. */ return decl; if (decl == error_mark_node) return decl; tree context = DECL_CONTEXT (decl); tree containing_function = current_function_decl; tree lambda_stack = NULL_TREE; tree lambda_expr = NULL_TREE; tree initializer = convert_from_reference (decl); /* Mark it as used now even if the use is ill-formed. */ if (!mark_used (decl, complain) && !(complain & tf_error)) return error_mark_node; /* Core issue 696: "[At the July 2009 meeting] the CWG expressed support for an approach in which a reference to a local [constant] automatic variable in a nested class or lambda body would enter the expression as an rvalue, which would reduce the complexity of the problem" FIXME update for final resolution of core issue 696. */ if (decl_maybe_constant_var_p (decl)) { if (processing_template_decl) /* In a template, the constant value may not be in a usable form, so wait until instantiation time. */ return decl; else if (decl_constant_var_p (decl)) { tree t = maybe_constant_value (convert_from_reference (decl)); if (TREE_CONSTANT (t)) return t; } } if (parsing_nsdmi ()) containing_function = NULL_TREE; else /* If we are in a lambda function, we can move out until we hit 1. the context, 2. a non-lambda function, or 3. a non-default capturing lambda function. */ while (context != containing_function && LAMBDA_FUNCTION_P (containing_function)) { tree closure = DECL_CONTEXT (containing_function); lambda_expr = CLASSTYPE_LAMBDA_EXPR (closure); if (TYPE_CLASS_SCOPE_P (closure)) /* A lambda in an NSDMI (c++/64496). */ break; if (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr) == CPLD_NONE) break; lambda_stack = tree_cons (NULL_TREE, lambda_expr, lambda_stack); containing_function = decl_function_context (containing_function); } if (lambda_expr && TREE_CODE (decl) == VAR_DECL && DECL_ANON_UNION_VAR_P (decl)) { if (complain & tf_error) error ("cannot capture member %qD of anonymous union", decl); return error_mark_node; } if (context == containing_function) { decl = add_default_capture (lambda_stack, /*id=*/DECL_NAME (decl), initializer); } else if (lambda_expr) { if (complain & tf_error) { error ("%qD is not captured", decl); tree closure = LAMBDA_EXPR_CLOSURE (lambda_expr); if (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr) == CPLD_NONE) inform (location_of (closure), "the lambda has no capture-default"); else if (TYPE_CLASS_SCOPE_P (closure)) inform (0, "lambda in local class %q+T cannot " "capture variables from the enclosing context", TYPE_CONTEXT (closure)); inform (input_location, "%q+#D declared here", decl); } return error_mark_node; } else { if (complain & tf_error) error (VAR_P (decl) ? G_("use of local variable with automatic storage from containing function") : G_("use of parameter from containing function")); inform (input_location, "%q+#D declared here", decl); return error_mark_node; } return decl; } /* ID_EXPRESSION is a representation of parsed, but unprocessed, id-expression. (See cp_parser_id_expression for details.) SCOPE, if non-NULL, is the type or namespace used to explicitly qualify ID_EXPRESSION. DECL is the entity to which that name has been resolved. *CONSTANT_EXPRESSION_P is true if we are presently parsing a constant-expression. In that case, *NON_CONSTANT_EXPRESSION_P will be set to true if this expression isn't permitted in a constant-expression, but it is otherwise not set by this function. *ALLOW_NON_CONSTANT_EXPRESSION_P is true if we are parsing a constant-expression, but a non-constant expression is also permissible. DONE is true if this expression is a complete postfix-expression; it is false if this expression is followed by '->', '[', '(', etc. ADDRESS_P is true iff this expression is the operand of '&'. TEMPLATE_P is true iff the qualified-id was of the form "A::template B". TEMPLATE_ARG_P is true iff this qualified name appears as a template argument. If an error occurs, and it is the kind of error that might cause the parser to abort a tentative parse, *ERROR_MSG is filled in. It is the caller's responsibility to issue the message. *ERROR_MSG will be a string with static storage duration, so the caller need not "free" it. Return an expression for the entity, after issuing appropriate diagnostics. This function is also responsible for transforming a reference to a non-static member into a COMPONENT_REF that makes the use of "this" explicit. Upon return, *IDK will be filled in appropriately. */ tree finish_id_expression (tree id_expression, tree decl, tree scope, cp_id_kind *idk, bool integral_constant_expression_p, bool allow_non_integral_constant_expression_p, bool *non_integral_constant_expression_p, bool template_p, bool done, bool address_p, bool template_arg_p, const char **error_msg, location_t location) { decl = strip_using_decl (decl); /* Initialize the output parameters. */ *idk = CP_ID_KIND_NONE; *error_msg = NULL; if (id_expression == error_mark_node) return error_mark_node; /* If we have a template-id, then no further lookup is required. If the template-id was for a template-class, we will sometimes have a TYPE_DECL at this point. */ else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR || TREE_CODE (decl) == TYPE_DECL) ; /* Look up the name. */ else { if (decl == error_mark_node) { /* Name lookup failed. */ if (scope && (!TYPE_P (scope) || (!dependent_type_p (scope) && !(identifier_p (id_expression) && IDENTIFIER_TYPENAME_P (id_expression) && dependent_type_p (TREE_TYPE (id_expression)))))) { /* If the qualifying type is non-dependent (and the name does not name a conversion operator to a dependent type), issue an error. */ qualified_name_lookup_error (scope, id_expression, decl, location); return error_mark_node; } else if (!scope) { /* It may be resolved via Koenig lookup. */ *idk = CP_ID_KIND_UNQUALIFIED; return id_expression; } else decl = id_expression; } /* If DECL is a variable that would be out of scope under ANSI/ISO rules, but in scope in the ARM, name lookup will succeed. Issue a diagnostic here. */ else decl = check_for_out_of_scope_variable (decl); /* Remember that the name was used in the definition of the current class so that we can check later to see if the meaning would have been different after the class was entirely defined. */ if (!scope && decl != error_mark_node && identifier_p (id_expression)) maybe_note_name_used_in_class (id_expression, decl); /* Disallow uses of local variables from containing functions, except within lambda-expressions. */ if (outer_automatic_var_p (decl)) { decl = process_outer_var_ref (decl, tf_warning_or_error); if (decl == error_mark_node) return error_mark_node; } /* Also disallow uses of function parameters outside the function body, except inside an unevaluated context (i.e. decltype). */ if (TREE_CODE (decl) == PARM_DECL && DECL_CONTEXT (decl) == NULL_TREE && !cp_unevaluated_operand) { *error_msg = "use of parameter outside function body"; return error_mark_node; } } /* If we didn't find anything, or what we found was a type, then this wasn't really an id-expression. */ if (TREE_CODE (decl) == TEMPLATE_DECL && !DECL_FUNCTION_TEMPLATE_P (decl)) { *error_msg = "missing template arguments"; return error_mark_node; } else if (TREE_CODE (decl) == TYPE_DECL || TREE_CODE (decl) == NAMESPACE_DECL) { *error_msg = "expected primary-expression"; return error_mark_node; } /* If the name resolved to a template parameter, there is no need to look it up again later. */ if ((TREE_CODE (decl) == CONST_DECL && DECL_TEMPLATE_PARM_P (decl)) || TREE_CODE (decl) == TEMPLATE_PARM_INDEX) { tree r; *idk = CP_ID_KIND_NONE; if (TREE_CODE (decl) == TEMPLATE_PARM_INDEX) decl = TEMPLATE_PARM_DECL (decl); r = convert_from_reference (DECL_INITIAL (decl)); if (integral_constant_expression_p && !dependent_type_p (TREE_TYPE (decl)) && !(INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (r)))) { if (!allow_non_integral_constant_expression_p) error ("template parameter %qD of type %qT is not allowed in " "an integral constant expression because it is not of " "integral or enumeration type", decl, TREE_TYPE (decl)); *non_integral_constant_expression_p = true; } return r; } else { bool dependent_p; /* If the declaration was explicitly qualified indicate that. The semantics of `A::f(3)' are different than `f(3)' if `f' is virtual. */ *idk = (scope ? CP_ID_KIND_QUALIFIED : (TREE_CODE (decl) == TEMPLATE_ID_EXPR ? CP_ID_KIND_TEMPLATE_ID : CP_ID_KIND_UNQUALIFIED)); /* [temp.dep.expr] An id-expression is type-dependent if it contains an identifier that was declared with a dependent type. The standard is not very specific about an id-expression that names a set of overloaded functions. What if some of them have dependent types and some of them do not? Presumably, such a name should be treated as a dependent name. */ /* Assume the name is not dependent. */ dependent_p = false; if (!processing_template_decl) /* No names are dependent outside a template. */ ; else if (TREE_CODE (decl) == CONST_DECL) /* We don't want to treat enumerators as dependent. */ ; /* A template-id where the name of the template was not resolved is definitely dependent. */ else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR && (identifier_p (TREE_OPERAND (decl, 0)))) dependent_p = true; /* For anything except an overloaded function, just check its type. */ else if (!is_overloaded_fn (decl)) dependent_p = dependent_type_p (TREE_TYPE (decl)); /* For a set of overloaded functions, check each of the functions. */ else { tree fns = decl; if (BASELINK_P (fns)) fns = BASELINK_FUNCTIONS (fns); /* For a template-id, check to see if the template arguments are dependent. */ if (TREE_CODE (fns) == TEMPLATE_ID_EXPR) { tree args = TREE_OPERAND (fns, 1); dependent_p = any_dependent_template_arguments_p (args); /* The functions are those referred to by the template-id. */ fns = TREE_OPERAND (fns, 0); } /* If there are no dependent template arguments, go through the overloaded functions. */ while (fns && !dependent_p) { tree fn = OVL_CURRENT (fns); /* Member functions of dependent classes are dependent. */ if (TREE_CODE (fn) == FUNCTION_DECL && type_dependent_expression_p (fn)) dependent_p = true; else if (TREE_CODE (fn) == TEMPLATE_DECL && dependent_template_p (fn)) dependent_p = true; fns = OVL_NEXT (fns); } } /* If the name was dependent on a template parameter, we will resolve the name at instantiation time. */ if (dependent_p) { /* Create a SCOPE_REF for qualified names, if the scope is dependent. */ if (scope) { if (TYPE_P (scope)) { if (address_p && done) decl = finish_qualified_id_expr (scope, decl, done, address_p, template_p, template_arg_p, tf_warning_or_error); else { tree type = NULL_TREE; if (DECL_P (decl) && !dependent_scope_p (scope)) type = TREE_TYPE (decl); decl = build_qualified_name (type, scope, id_expression, template_p); } } if (TREE_TYPE (decl)) decl = convert_from_reference (decl); return decl; } /* A TEMPLATE_ID already contains all the information we need. */ if (TREE_CODE (id_expression) == TEMPLATE_ID_EXPR) return id_expression; *idk = CP_ID_KIND_UNQUALIFIED_DEPENDENT; /* If we found a variable, then name lookup during the instantiation will always resolve to the same VAR_DECL (or an instantiation thereof). */ if (VAR_P (decl) || TREE_CODE (decl) == PARM_DECL) { mark_used (decl); return convert_from_reference (decl); } /* The same is true for FIELD_DECL, but we also need to make sure that the syntax is correct. */ else if (TREE_CODE (decl) == FIELD_DECL) { /* Since SCOPE is NULL here, this is an unqualified name. Access checking has been performed during name lookup already. Turn off checking to avoid duplicate errors. */ push_deferring_access_checks (dk_no_check); decl = finish_non_static_data_member (decl, NULL_TREE, /*qualifying_scope=*/NULL_TREE); pop_deferring_access_checks (); return decl; } return id_expression; } if (TREE_CODE (decl) == NAMESPACE_DECL) { error ("use of namespace %qD as expression", decl); return error_mark_node; } else if (DECL_CLASS_TEMPLATE_P (decl)) { error ("use of class template %qT as expression", decl); return error_mark_node; } else if (TREE_CODE (decl) == TREE_LIST) { /* Ambiguous reference to base members. */ error ("request for member %qD is ambiguous in " "multiple inheritance lattice", id_expression); print_candidates (decl); return error_mark_node; } /* Mark variable-like entities as used. Functions are similarly marked either below or after overload resolution. */ if ((VAR_P (decl) || TREE_CODE (decl) == PARM_DECL || TREE_CODE (decl) == CONST_DECL || TREE_CODE (decl) == RESULT_DECL) && !mark_used (decl)) return error_mark_node; /* Only certain kinds of names are allowed in constant expression. Template parameters have already been handled above. */ if (! error_operand_p (decl) && integral_constant_expression_p && ! decl_constant_var_p (decl) && TREE_CODE (decl) != CONST_DECL && ! builtin_valid_in_constant_expr_p (decl)) { if (!allow_non_integral_constant_expression_p) { error ("%qD cannot appear in a constant-expression", decl); return error_mark_node; } *non_integral_constant_expression_p = true; } tree wrap; if (VAR_P (decl) && !cp_unevaluated_operand && !processing_template_decl && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)) && DECL_THREAD_LOCAL_P (decl) && (wrap = get_tls_wrapper_fn (decl))) { /* Replace an evaluated use of the thread_local variable with a call to its wrapper. */ decl = build_cxx_call (wrap, 0, NULL, tf_warning_or_error); } else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR && variable_template_p (TREE_OPERAND (decl, 0))) { decl = finish_template_variable (decl); mark_used (decl); decl = convert_from_reference (decl); } else if (scope) { decl = (adjust_result_of_qualified_name_lookup (decl, scope, current_nonlambda_class_type())); if (TREE_CODE (decl) == FUNCTION_DECL) mark_used (decl); if (TYPE_P (scope)) decl = finish_qualified_id_expr (scope, decl, done, address_p, template_p, template_arg_p, tf_warning_or_error); else decl = convert_from_reference (decl); } else if (TREE_CODE (decl) == FIELD_DECL) { /* Since SCOPE is NULL here, this is an unqualified name. Access checking has been performed during name lookup already. Turn off checking to avoid duplicate errors. */ push_deferring_access_checks (dk_no_check); decl = finish_non_static_data_member (decl, NULL_TREE, /*qualifying_scope=*/NULL_TREE); pop_deferring_access_checks (); } else if (is_overloaded_fn (decl)) { tree first_fn; first_fn = get_first_fn (decl); if (TREE_CODE (first_fn) == TEMPLATE_DECL) first_fn = DECL_TEMPLATE_RESULT (first_fn); if (!really_overloaded_fn (decl) && !mark_used (first_fn)) return error_mark_node; if (!template_arg_p && TREE_CODE (first_fn) == FUNCTION_DECL && DECL_FUNCTION_MEMBER_P (first_fn) && !shared_member_p (decl)) { /* A set of member functions. */ decl = maybe_dummy_object (DECL_CONTEXT (first_fn), 0); return finish_class_member_access_expr (decl, id_expression, /*template_p=*/false, tf_warning_or_error); } decl = baselink_for_fns (decl); } else { if (DECL_P (decl) && DECL_NONLOCAL (decl) && DECL_CLASS_SCOPE_P (decl)) { tree context = context_for_name_lookup (decl); if (context != current_class_type) { tree path = currently_open_derived_class (context); perform_or_defer_access_check (TYPE_BINFO (path), decl, decl, tf_warning_or_error); } } decl = convert_from_reference (decl); } } /* Handle references (c++/56130). */ tree t = REFERENCE_REF_P (decl) ? TREE_OPERAND (decl, 0) : decl; if (TREE_DEPRECATED (t)) warn_deprecated_use (t, NULL_TREE); return decl; } /* Implement the __typeof keyword: Return the type of EXPR, suitable for use as a type-specifier. */ tree finish_typeof (tree expr) { tree type; if (type_dependent_expression_p (expr)) { type = cxx_make_type (TYPEOF_TYPE); TYPEOF_TYPE_EXPR (type) = expr; SET_TYPE_STRUCTURAL_EQUALITY (type); return type; } expr = mark_type_use (expr); type = unlowered_expr_type (expr); if (!type || type == unknown_type_node) { error ("type of %qE is unknown", expr); return error_mark_node; } return type; } /* Implement the __underlying_type keyword: Return the underlying type of TYPE, suitable for use as a type-specifier. */ tree finish_underlying_type (tree type) { tree underlying_type; if (processing_template_decl) { underlying_type = cxx_make_type (UNDERLYING_TYPE); UNDERLYING_TYPE_TYPE (underlying_type) = type; SET_TYPE_STRUCTURAL_EQUALITY (underlying_type); return underlying_type; } complete_type (type); if (TREE_CODE (type) != ENUMERAL_TYPE) { error ("%qT is not an enumeration type", type); return error_mark_node; } underlying_type = ENUM_UNDERLYING_TYPE (type); /* Fixup necessary in this case because ENUM_UNDERLYING_TYPE includes TYPE_MIN_VALUE and TYPE_MAX_VALUE information. See finish_enum_value_list for details. */ if (!ENUM_FIXED_UNDERLYING_TYPE_P (type)) underlying_type = c_common_type_for_mode (TYPE_MODE (underlying_type), TYPE_UNSIGNED (underlying_type)); return underlying_type; } /* Implement the __direct_bases keyword: Return the direct base classes of type */ tree calculate_direct_bases (tree type) { vec<tree, va_gc> *vector = make_tree_vector(); tree bases_vec = NULL_TREE; vec<tree, va_gc> *base_binfos; tree binfo; unsigned i; complete_type (type); if (!NON_UNION_CLASS_TYPE_P (type)) return make_tree_vec (0); base_binfos = BINFO_BASE_BINFOS (TYPE_BINFO (type)); /* Virtual bases are initialized first */ for (i = 0; base_binfos->iterate (i, &binfo); i++) { if (BINFO_VIRTUAL_P (binfo)) { vec_safe_push (vector, binfo); } } /* Now non-virtuals */ for (i = 0; base_binfos->iterate (i, &binfo); i++) { if (!BINFO_VIRTUAL_P (binfo)) { vec_safe_push (vector, binfo); } } bases_vec = make_tree_vec (vector->length ()); for (i = 0; i < vector->length (); ++i) { TREE_VEC_ELT (bases_vec, i) = BINFO_TYPE ((*vector)[i]); } return bases_vec; } /* Implement the __bases keyword: Return the base classes of type */ /* Find morally non-virtual base classes by walking binfo hierarchy */ /* Virtual base classes are handled separately in finish_bases */ static tree dfs_calculate_bases_pre (tree binfo, void * /*data_*/) { /* Don't walk bases of virtual bases */ return BINFO_VIRTUAL_P (binfo) ? dfs_skip_bases : NULL_TREE; } static tree dfs_calculate_bases_post (tree binfo, void *data_) { vec<tree, va_gc> **data = ((vec<tree, va_gc> **) data_); if (!BINFO_VIRTUAL_P (binfo)) { vec_safe_push (*data, BINFO_TYPE (binfo)); } return NULL_TREE; } /* Calculates the morally non-virtual base classes of a class */ static vec<tree, va_gc> * calculate_bases_helper (tree type) { vec<tree, va_gc> *vector = make_tree_vector(); /* Now add non-virtual base classes in order of construction */ dfs_walk_all (TYPE_BINFO (type), dfs_calculate_bases_pre, dfs_calculate_bases_post, &vector); return vector; } tree calculate_bases (tree type) { vec<tree, va_gc> *vector = make_tree_vector(); tree bases_vec = NULL_TREE; unsigned i; vec<tree, va_gc> *vbases; vec<tree, va_gc> *nonvbases; tree binfo; complete_type (type); if (!NON_UNION_CLASS_TYPE_P (type)) return make_tree_vec (0); /* First go through virtual base classes */ for (vbases = CLASSTYPE_VBASECLASSES (type), i = 0; vec_safe_iterate (vbases, i, &binfo); i++) { vec<tree, va_gc> *vbase_bases; vbase_bases = calculate_bases_helper (BINFO_TYPE (binfo)); vec_safe_splice (vector, vbase_bases); release_tree_vector (vbase_bases); } /* Now for the non-virtual bases */ nonvbases = calculate_bases_helper (type); vec_safe_splice (vector, nonvbases); release_tree_vector (nonvbases); /* Last element is entire class, so don't copy */ bases_vec = make_tree_vec (vector->length () - 1); for (i = 0; i < vector->length () - 1; ++i) { TREE_VEC_ELT (bases_vec, i) = (*vector)[i]; } release_tree_vector (vector); return bases_vec; } tree finish_bases (tree type, bool direct) { tree bases = NULL_TREE; if (!processing_template_decl) { /* Parameter packs can only be used in templates */ error ("Parameter pack __bases only valid in template declaration"); return error_mark_node; } bases = cxx_make_type (BASES); BASES_TYPE (bases) = type; BASES_DIRECT (bases) = direct; SET_TYPE_STRUCTURAL_EQUALITY (bases); return bases; } /* Perform C++-specific checks for __builtin_offsetof before calling fold_offsetof. */ tree finish_offsetof (tree expr, location_t loc) { /* If we're processing a template, we can't finish the semantics yet. Otherwise we can fold the entire expression now. */ if (processing_template_decl) { expr = build1 (OFFSETOF_EXPR, size_type_node, expr); SET_EXPR_LOCATION (expr, loc); return expr; } if (TREE_CODE (expr) == PSEUDO_DTOR_EXPR) { error ("cannot apply %<offsetof%> to destructor %<~%T%>", TREE_OPERAND (expr, 2)); return error_mark_node; } if (TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE || TREE_CODE (TREE_TYPE (expr)) == METHOD_TYPE || TREE_TYPE (expr) == unknown_type_node) { if (INDIRECT_REF_P (expr)) error ("second operand of %<offsetof%> is neither a single " "identifier nor a sequence of member accesses and " "array references"); else { if (TREE_CODE (expr) == COMPONENT_REF || TREE_CODE (expr) == COMPOUND_EXPR) expr = TREE_OPERAND (expr, 1); error ("cannot apply %<offsetof%> to member function %qD", expr); } return error_mark_node; } if (REFERENCE_REF_P (expr)) expr = TREE_OPERAND (expr, 0); if (TREE_CODE (expr) == COMPONENT_REF) { tree object = TREE_OPERAND (expr, 0); if (!complete_type_or_else (TREE_TYPE (object), object)) return error_mark_node; if (warn_invalid_offsetof && CLASS_TYPE_P (TREE_TYPE (object)) && CLASSTYPE_NON_STD_LAYOUT (TREE_TYPE (object)) && cp_unevaluated_operand == 0) pedwarn (loc, OPT_Winvalid_offsetof, "offsetof within non-standard-layout type %qT is undefined", TREE_TYPE (object)); } return fold_offsetof (expr); } /* Replace the AGGR_INIT_EXPR at *TP with an equivalent CALL_EXPR. This function is broken out from the above for the benefit of the tree-ssa project. */ void simplify_aggr_init_expr (tree *tp) { tree aggr_init_expr = *tp; /* Form an appropriate CALL_EXPR. */ tree fn = AGGR_INIT_EXPR_FN (aggr_init_expr); tree slot = AGGR_INIT_EXPR_SLOT (aggr_init_expr); tree type = TREE_TYPE (slot); tree call_expr; enum style_t { ctor, arg, pcc } style; if (AGGR_INIT_VIA_CTOR_P (aggr_init_expr)) style = ctor; #ifdef PCC_STATIC_STRUCT_RETURN else if (1) style = pcc; #endif else { gcc_assert (TREE_ADDRESSABLE (type)); style = arg; } call_expr = build_call_array_loc (input_location, TREE_TYPE (TREE_TYPE (TREE_TYPE (fn))), fn, aggr_init_expr_nargs (aggr_init_expr), AGGR_INIT_EXPR_ARGP (aggr_init_expr)); TREE_NOTHROW (call_expr) = TREE_NOTHROW (aggr_init_expr); CALL_EXPR_LIST_INIT_P (call_expr) = CALL_EXPR_LIST_INIT_P (aggr_init_expr); if (style == ctor) { /* Replace the first argument to the ctor with the address of the slot. */ cxx_mark_addressable (slot); CALL_EXPR_ARG (call_expr, 0) = build1 (ADDR_EXPR, build_pointer_type (type), slot); } else if (style == arg) { /* Just mark it addressable here, and leave the rest to expand_call{,_inline}. */ cxx_mark_addressable (slot); CALL_EXPR_RETURN_SLOT_OPT (call_expr) = true; call_expr = build2 (INIT_EXPR, TREE_TYPE (call_expr), slot, call_expr); } else if (style == pcc) { /* If we're using the non-reentrant PCC calling convention, then we need to copy the returned value out of the static buffer into the SLOT. */ push_deferring_access_checks (dk_no_check); call_expr = build_aggr_init (slot, call_expr, DIRECT_BIND | LOOKUP_ONLYCONVERTING, tf_warning_or_error); pop_deferring_access_checks (); call_expr = build2 (COMPOUND_EXPR, TREE_TYPE (slot), call_expr, slot); } if (AGGR_INIT_ZERO_FIRST (aggr_init_expr)) { tree init = build_zero_init (type, NULL_TREE, /*static_storage_p=*/false); init = build2 (INIT_EXPR, void_type_node, slot, init); call_expr = build2 (COMPOUND_EXPR, TREE_TYPE (call_expr), init, call_expr); } *tp = call_expr; } /* Emit all thunks to FN that should be emitted when FN is emitted. */ void emit_associated_thunks (tree fn) { /* When we use vcall offsets, we emit thunks with the virtual functions to which they thunk. The whole point of vcall offsets is so that you can know statically the entire set of thunks that will ever be needed for a given virtual function, thereby enabling you to output all the thunks with the function itself. */ if (DECL_VIRTUAL_P (fn) /* Do not emit thunks for extern template instantiations. */ && ! DECL_REALLY_EXTERN (fn)) { tree thunk; for (thunk = DECL_THUNKS (fn); thunk; thunk = DECL_CHAIN (thunk)) { if (!THUNK_ALIAS (thunk)) { use_thunk (thunk, /*emit_p=*/1); if (DECL_RESULT_THUNK_P (thunk)) { tree probe; for (probe = DECL_THUNKS (thunk); probe; probe = DECL_CHAIN (probe)) use_thunk (probe, /*emit_p=*/1); } } else gcc_assert (!DECL_THUNKS (thunk)); } } } /* Generate RTL for FN. */ bool expand_or_defer_fn_1 (tree fn) { /* When the parser calls us after finishing the body of a template function, we don't really want to expand the body. */ if (processing_template_decl) { /* Normally, collection only occurs in rest_of_compilation. So, if we don't collect here, we never collect junk generated during the processing of templates until we hit a non-template function. It's not safe to do this inside a nested class, though, as the parser may have local state that is not a GC root. */ if (!function_depth) ggc_collect (); return false; } gcc_assert (DECL_SAVED_TREE (fn)); /* We make a decision about linkage for these functions at the end of the compilation. Until that point, we do not want the back end to output them -- but we do want it to see the bodies of these functions so that it can inline them as appropriate. */ if (DECL_DECLARED_INLINE_P (fn) || DECL_IMPLICIT_INSTANTIATION (fn)) { if (DECL_INTERFACE_KNOWN (fn)) /* We've already made a decision as to how this function will be handled. */; else if (!at_eof) tentative_decl_linkage (fn); else import_export_decl (fn); /* If the user wants us to keep all inline functions, then mark this function as needed so that finish_file will make sure to output it later. Similarly, all dllexport'd functions must be emitted; there may be callers in other DLLs. */ if (DECL_DECLARED_INLINE_P (fn) && !DECL_REALLY_EXTERN (fn) && (flag_keep_inline_functions || (flag_keep_inline_dllexport && lookup_attribute ("dllexport", DECL_ATTRIBUTES (fn))))) { mark_needed (fn); DECL_EXTERNAL (fn) = 0; } } /* If this is a constructor or destructor body, we have to clone it. */ if (maybe_clone_body (fn)) { /* We don't want to process FN again, so pretend we've written it out, even though we haven't. */ TREE_ASM_WRITTEN (fn) = 1; /* If this is a constexpr function, keep DECL_SAVED_TREE. */ if (!DECL_DECLARED_CONSTEXPR_P (fn)) DECL_SAVED_TREE (fn) = NULL_TREE; return false; } /* There's no reason to do any of the work here if we're only doing semantic analysis; this code just generates RTL. */ if (flag_syntax_only) return false; return true; } void expand_or_defer_fn (tree fn) { if (expand_or_defer_fn_1 (fn)) { function_depth++; /* Expand or defer, at the whim of the compilation unit manager. */ cgraph_node::finalize_function (fn, function_depth > 1); emit_associated_thunks (fn); function_depth--; } } struct nrv_data { nrv_data () : visited (37) {} tree var; tree result; hash_table<pointer_hash <tree_node> > visited; }; /* Helper function for walk_tree, used by finalize_nrv below. */ static tree finalize_nrv_r (tree* tp, int* walk_subtrees, void* data) { struct nrv_data *dp = (struct nrv_data *)data; tree_node **slot; /* No need to walk into types. There wouldn't be any need to walk into non-statements, except that we have to consider STMT_EXPRs. */ if (TYPE_P (*tp)) *walk_subtrees = 0; /* Change all returns to just refer to the RESULT_DECL; this is a nop, but differs from using NULL_TREE in that it indicates that we care about the value of the RESULT_DECL. */ else if (TREE_CODE (*tp) == RETURN_EXPR) TREE_OPERAND (*tp, 0) = dp->result; /* Change all cleanups for the NRV to only run when an exception is thrown. */ else if (TREE_CODE (*tp) == CLEANUP_STMT && CLEANUP_DECL (*tp) == dp->var) CLEANUP_EH_ONLY (*tp) = 1; /* Replace the DECL_EXPR for the NRV with an initialization of the RESULT_DECL, if needed. */ else if (TREE_CODE (*tp) == DECL_EXPR && DECL_EXPR_DECL (*tp) == dp->var) { tree init; if (DECL_INITIAL (dp->var) && DECL_INITIAL (dp->var) != error_mark_node) init = build2 (INIT_EXPR, void_type_node, dp->result, DECL_INITIAL (dp->var)); else init = build_empty_stmt (EXPR_LOCATION (*tp)); DECL_INITIAL (dp->var) = NULL_TREE; SET_EXPR_LOCATION (init, EXPR_LOCATION (*tp)); *tp = init; } /* And replace all uses of the NRV with the RESULT_DECL. */ else if (*tp == dp->var) *tp = dp->result; /* Avoid walking into the same tree more than once. Unfortunately, we can't just use walk_tree_without duplicates because it would only call us for the first occurrence of dp->var in the function body. */ slot = dp->visited.find_slot (*tp, INSERT); if (*slot) *walk_subtrees = 0; else *slot = *tp; /* Keep iterating. */ return NULL_TREE; } /* Called from finish_function to implement the named return value optimization by overriding all the RETURN_EXPRs and pertinent CLEANUP_STMTs and replacing all occurrences of VAR with RESULT, the RESULT_DECL for the function. */ void finalize_nrv (tree *tp, tree var, tree result) { struct nrv_data data; /* Copy name from VAR to RESULT. */ DECL_NAME (result) = DECL_NAME (var); /* Don't forget that we take its address. */ TREE_ADDRESSABLE (result) = TREE_ADDRESSABLE (var); /* Finally set DECL_VALUE_EXPR to avoid assigning a stack slot at -O0 for the original var and debug info uses RESULT location for VAR. */ SET_DECL_VALUE_EXPR (var, result); DECL_HAS_VALUE_EXPR_P (var) = 1; data.var = var; data.result = result; cp_walk_tree (tp, finalize_nrv_r, &data, 0); } /* Create CP_OMP_CLAUSE_INFO for clause C. Returns true if it is invalid. */ bool cxx_omp_create_clause_info (tree c, tree type, bool need_default_ctor, bool need_copy_ctor, bool need_copy_assignment, bool need_dtor) { int save_errorcount = errorcount; tree info, t; /* Always allocate 3 elements for simplicity. These are the function decls for the ctor, dtor, and assignment op. This layout is known to the three lang hooks, cxx_omp_clause_default_init, cxx_omp_clause_copy_init, and cxx_omp_clause_assign_op. */ info = make_tree_vec (3); CP_OMP_CLAUSE_INFO (c) = info; if (need_default_ctor || need_copy_ctor) { if (need_default_ctor) t = get_default_ctor (type); else t = get_copy_ctor (type, tf_warning_or_error); if (t && !trivial_fn_p (t)) TREE_VEC_ELT (info, 0) = t; } if (need_dtor && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)) TREE_VEC_ELT (info, 1) = get_dtor (type, tf_warning_or_error); if (need_copy_assignment) { t = get_copy_assign (type); if (t && !trivial_fn_p (t)) TREE_VEC_ELT (info, 2) = t; } return errorcount != save_errorcount; } /* Helper function for handle_omp_array_sections. Called recursively to handle multiple array-section-subscripts. C is the clause, T current expression (initially OMP_CLAUSE_DECL), which is either a TREE_LIST for array-section-subscript (TREE_PURPOSE is low-bound expression if specified, TREE_VALUE length expression if specified, TREE_CHAIN is what it has been specified after, or some decl. TYPES vector is populated with array section types, MAYBE_ZERO_LEN set to true if any of the array-section-subscript could have length of zero (explicit or implicit), FIRST_NON_ONE is the index of the first array-section-subscript which is known not to have length of one. Given say: map(a[:b][2:1][:c][:2][:d][e:f][2:5]) FIRST_NON_ONE will be 3, array-section-subscript [:b], [2:1] and [:c] all are or may have length of 1, array-section-subscript [:2] is the first one knonwn not to have length 1. For array-section-subscript <= FIRST_NON_ONE we diagnose non-contiguous arrays if low bound isn't 0 or length isn't the array domain max + 1, for > FIRST_NON_ONE we can if MAYBE_ZERO_LEN is false. MAYBE_ZERO_LEN will be true in the above case though, as some lengths could be zero. */ static tree handle_omp_array_sections_1 (tree c, tree t, vec<tree> &types, bool &maybe_zero_len, unsigned int &first_non_one) { tree ret, low_bound, length, type; if (TREE_CODE (t) != TREE_LIST) { if (error_operand_p (t)) return error_mark_node; if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) return NULL_TREE; if (DECL_P (t)) error_at (OMP_CLAUSE_LOCATION (c), "%qD is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } else if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && TREE_CODE (t) == VAR_DECL && DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qD is threadprivate variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (type_dependent_expression_p (t)) return NULL_TREE; t = convert_from_reference (t); return t; } ret = handle_omp_array_sections_1 (c, TREE_CHAIN (t), types, maybe_zero_len, first_non_one); if (ret == error_mark_node || ret == NULL_TREE) return ret; type = TREE_TYPE (ret); low_bound = TREE_PURPOSE (t); length = TREE_VALUE (t); if ((low_bound && type_dependent_expression_p (low_bound)) || (length && type_dependent_expression_p (length))) return NULL_TREE; if (low_bound == error_mark_node || length == error_mark_node) return error_mark_node; if (low_bound && !INTEGRAL_TYPE_P (TREE_TYPE (low_bound))) { error_at (OMP_CLAUSE_LOCATION (c), "low bound %qE of array section does not have integral type", low_bound); return error_mark_node; } if (length && !INTEGRAL_TYPE_P (TREE_TYPE (length))) { error_at (OMP_CLAUSE_LOCATION (c), "length %qE of array section does not have integral type", length); return error_mark_node; } if (low_bound) low_bound = mark_rvalue_use (low_bound); if (length) length = mark_rvalue_use (length); if (low_bound && TREE_CODE (low_bound) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (low_bound)) > TYPE_PRECISION (sizetype)) low_bound = fold_convert (sizetype, low_bound); if (length && TREE_CODE (length) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (length)) > TYPE_PRECISION (sizetype)) length = fold_convert (sizetype, length); if (low_bound == NULL_TREE) low_bound = integer_zero_node; if (length != NULL_TREE) { if (!integer_nonzerop (length)) maybe_zero_len = true; if (first_non_one == types.length () && (TREE_CODE (length) != INTEGER_CST || integer_onep (length))) first_non_one++; } if (TREE_CODE (type) == ARRAY_TYPE) { if (length == NULL_TREE && (TYPE_DOMAIN (type) == NULL_TREE || TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL_TREE)) { error_at (OMP_CLAUSE_LOCATION (c), "for unknown bound array type length expression must " "be specified"); return error_mark_node; } if (TREE_CODE (low_bound) == INTEGER_CST && tree_int_cst_sgn (low_bound) == -1) { error_at (OMP_CLAUSE_LOCATION (c), "negative low bound in array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (length != NULL_TREE && TREE_CODE (length) == INTEGER_CST && tree_int_cst_sgn (length) == -1) { error_at (OMP_CLAUSE_LOCATION (c), "negative length in array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)) && TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (type))) == INTEGER_CST) { tree size = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (type)), size_one_node); if (TREE_CODE (low_bound) == INTEGER_CST) { if (tree_int_cst_lt (size, low_bound)) { error_at (OMP_CLAUSE_LOCATION (c), "low bound %qE above array section size " "in %qs clause", low_bound, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (tree_int_cst_equal (size, low_bound)) maybe_zero_len = true; else if (length == NULL_TREE && first_non_one == types.length () && tree_int_cst_equal (TYPE_MAX_VALUE (TYPE_DOMAIN (type)), low_bound)) first_non_one++; } else if (length == NULL_TREE) { maybe_zero_len = true; if (first_non_one == types.length ()) first_non_one++; } if (length && TREE_CODE (length) == INTEGER_CST) { if (tree_int_cst_lt (size, length)) { error_at (OMP_CLAUSE_LOCATION (c), "length %qE above array section size " "in %qs clause", length, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (TREE_CODE (low_bound) == INTEGER_CST) { tree lbpluslen = size_binop (PLUS_EXPR, fold_convert (sizetype, low_bound), fold_convert (sizetype, length)); if (TREE_CODE (lbpluslen) == INTEGER_CST && tree_int_cst_lt (size, lbpluslen)) { error_at (OMP_CLAUSE_LOCATION (c), "high bound %qE above array section size " "in %qs clause", lbpluslen, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } } } } else if (length == NULL_TREE) { maybe_zero_len = true; if (first_non_one == types.length ()) first_non_one++; } /* For [lb:] we will need to evaluate lb more than once. */ if (length == NULL_TREE && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND) { tree lb = cp_save_expr (low_bound); if (lb != low_bound) { TREE_PURPOSE (t) = lb; low_bound = lb; } } } else if (TREE_CODE (type) == POINTER_TYPE) { if (length == NULL_TREE) { error_at (OMP_CLAUSE_LOCATION (c), "for pointer type length expression must be specified"); return error_mark_node; } /* If there is a pointer type anywhere but in the very first array-section-subscript, the array section can't be contiguous. */ if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && TREE_CODE (TREE_CHAIN (t)) == TREE_LIST) { error_at (OMP_CLAUSE_LOCATION (c), "array section is not contiguous in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } } else { error_at (OMP_CLAUSE_LOCATION (c), "%qE does not have pointer or array type", ret); return error_mark_node; } if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND) types.safe_push (TREE_TYPE (ret)); /* We will need to evaluate lb more than once. */ tree lb = cp_save_expr (low_bound); if (lb != low_bound) { TREE_PURPOSE (t) = lb; low_bound = lb; } ret = grok_array_decl (OMP_CLAUSE_LOCATION (c), ret, low_bound, false); return ret; } /* Handle array sections for clause C. */ static bool handle_omp_array_sections (tree c) { bool maybe_zero_len = false; unsigned int first_non_one = 0; auto_vec<tree> types; tree first = handle_omp_array_sections_1 (c, OMP_CLAUSE_DECL (c), types, maybe_zero_len, first_non_one); if (first == error_mark_node) return true; if (first == NULL_TREE) return false; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND) { tree t = OMP_CLAUSE_DECL (c); tree tem = NULL_TREE; if (processing_template_decl) return false; /* Need to evaluate side effects in the length expressions if any. */ while (TREE_CODE (t) == TREE_LIST) { if (TREE_VALUE (t) && TREE_SIDE_EFFECTS (TREE_VALUE (t))) { if (tem == NULL_TREE) tem = TREE_VALUE (t); else tem = build2 (COMPOUND_EXPR, TREE_TYPE (tem), TREE_VALUE (t), tem); } t = TREE_CHAIN (t); } if (tem) first = build2 (COMPOUND_EXPR, TREE_TYPE (first), tem, first); OMP_CLAUSE_DECL (c) = first; } else { unsigned int num = types.length (), i; tree t, side_effects = NULL_TREE, size = NULL_TREE; tree condition = NULL_TREE; if (int_size_in_bytes (TREE_TYPE (first)) <= 0) maybe_zero_len = true; if (processing_template_decl && maybe_zero_len) return false; for (i = num, t = OMP_CLAUSE_DECL (c); i > 0; t = TREE_CHAIN (t)) { tree low_bound = TREE_PURPOSE (t); tree length = TREE_VALUE (t); i--; if (low_bound && TREE_CODE (low_bound) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (low_bound)) > TYPE_PRECISION (sizetype)) low_bound = fold_convert (sizetype, low_bound); if (length && TREE_CODE (length) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (length)) > TYPE_PRECISION (sizetype)) length = fold_convert (sizetype, length); if (low_bound == NULL_TREE) low_bound = integer_zero_node; if (!maybe_zero_len && i > first_non_one) { if (integer_nonzerop (low_bound)) goto do_warn_noncontiguous; if (length != NULL_TREE && TREE_CODE (length) == INTEGER_CST && TYPE_DOMAIN (types[i]) && TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])) && TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (types[i]))) == INTEGER_CST) { tree size; size = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])), size_one_node); if (!tree_int_cst_equal (length, size)) { do_warn_noncontiguous: error_at (OMP_CLAUSE_LOCATION (c), "array section is not contiguous in %qs " "clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return true; } } if (!processing_template_decl && length != NULL_TREE && TREE_SIDE_EFFECTS (length)) { if (side_effects == NULL_TREE) side_effects = length; else side_effects = build2 (COMPOUND_EXPR, TREE_TYPE (side_effects), length, side_effects); } } else if (processing_template_decl) continue; else { tree l; if (i > first_non_one && length && integer_nonzerop (length)) continue; if (length) l = fold_convert (sizetype, length); else { l = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])), size_one_node); l = size_binop (MINUS_EXPR, l, fold_convert (sizetype, low_bound)); } if (i > first_non_one) { l = fold_build2 (NE_EXPR, boolean_type_node, l, size_zero_node); if (condition == NULL_TREE) condition = l; else condition = fold_build2 (BIT_AND_EXPR, boolean_type_node, l, condition); } else if (size == NULL_TREE) { size = size_in_bytes (TREE_TYPE (types[i])); size = size_binop (MULT_EXPR, size, l); if (condition) size = fold_build3 (COND_EXPR, sizetype, condition, size, size_zero_node); } else size = size_binop (MULT_EXPR, size, l); } } if (!processing_template_decl) { if (side_effects) size = build2 (COMPOUND_EXPR, sizetype, side_effects, size); OMP_CLAUSE_DECL (c) = first; OMP_CLAUSE_SIZE (c) = size; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) return false; tree c2 = build_omp_clause (OMP_CLAUSE_LOCATION (c), OMP_CLAUSE_MAP); OMP_CLAUSE_SET_MAP_KIND (c2, GOMP_MAP_POINTER); if (!cxx_mark_addressable (t)) return false; OMP_CLAUSE_DECL (c2) = t; t = build_fold_addr_expr (first); t = fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, t); tree ptr = OMP_CLAUSE_DECL (c2); ptr = convert_from_reference (ptr); if (!POINTER_TYPE_P (TREE_TYPE (ptr))) ptr = build_fold_addr_expr (ptr); t = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, ptrdiff_type_node, t, fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, ptr)); OMP_CLAUSE_SIZE (c2) = t; OMP_CLAUSE_CHAIN (c2) = OMP_CLAUSE_CHAIN (c); OMP_CLAUSE_CHAIN (c) = c2; ptr = OMP_CLAUSE_DECL (c2); if (TREE_CODE (TREE_TYPE (ptr)) == REFERENCE_TYPE && POINTER_TYPE_P (TREE_TYPE (TREE_TYPE (ptr)))) { tree c3 = build_omp_clause (OMP_CLAUSE_LOCATION (c), OMP_CLAUSE_MAP); OMP_CLAUSE_SET_MAP_KIND (c3, GOMP_MAP_POINTER); OMP_CLAUSE_DECL (c3) = ptr; OMP_CLAUSE_DECL (c2) = convert_from_reference (ptr); OMP_CLAUSE_SIZE (c3) = size_zero_node; OMP_CLAUSE_CHAIN (c3) = OMP_CLAUSE_CHAIN (c2); OMP_CLAUSE_CHAIN (c2) = c3; } } } return false; } /* Return identifier to look up for omp declare reduction. */ tree omp_reduction_id (enum tree_code reduction_code, tree reduction_id, tree type) { const char *p = NULL; const char *m = NULL; switch (reduction_code) { case PLUS_EXPR: case MULT_EXPR: case MINUS_EXPR: case BIT_AND_EXPR: case BIT_XOR_EXPR: case BIT_IOR_EXPR: case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: reduction_id = ansi_opname (reduction_code); break; case MIN_EXPR: p = "min"; break; case MAX_EXPR: p = "max"; break; default: break; } if (p == NULL) { if (TREE_CODE (reduction_id) != IDENTIFIER_NODE) return error_mark_node; p = IDENTIFIER_POINTER (reduction_id); } if (type != NULL_TREE) m = mangle_type_string (TYPE_MAIN_VARIANT (type)); const char prefix[] = "omp declare reduction "; size_t lenp = sizeof (prefix); if (strncmp (p, prefix, lenp - 1) == 0) lenp = 1; size_t len = strlen (p); size_t lenm = m ? strlen (m) + 1 : 0; char *name = XALLOCAVEC (char, lenp + len + lenm); if (lenp > 1) memcpy (name, prefix, lenp - 1); memcpy (name + lenp - 1, p, len + 1); if (m) { name[lenp + len - 1] = '~'; memcpy (name + lenp + len, m, lenm); } return get_identifier (name); } /* Lookup OpenMP UDR ID for TYPE, return the corresponding artificial FUNCTION_DECL or NULL_TREE if not found. */ static tree omp_reduction_lookup (location_t loc, tree id, tree type, tree *baselinkp, vec<tree> *ambiguousp) { tree orig_id = id; tree baselink = NULL_TREE; if (identifier_p (id)) { cp_id_kind idk; bool nonint_cst_expression_p; const char *error_msg; id = omp_reduction_id (ERROR_MARK, id, type); tree decl = lookup_name (id); if (decl == NULL_TREE) decl = error_mark_node; id = finish_id_expression (id, decl, NULL_TREE, &idk, false, true, &nonint_cst_expression_p, false, true, false, false, &error_msg, loc); if (idk == CP_ID_KIND_UNQUALIFIED && identifier_p (id)) { vec<tree, va_gc> *args = NULL; vec_safe_push (args, build_reference_type (type)); id = perform_koenig_lookup (id, args, tf_none); } } else if (TREE_CODE (id) == SCOPE_REF) id = lookup_qualified_name (TREE_OPERAND (id, 0), omp_reduction_id (ERROR_MARK, TREE_OPERAND (id, 1), type), false, false); tree fns = id; if (id && is_overloaded_fn (id)) id = get_fns (id); for (; id; id = OVL_NEXT (id)) { tree fndecl = OVL_CURRENT (id); if (TREE_CODE (fndecl) == FUNCTION_DECL) { tree argtype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl))); if (same_type_p (TREE_TYPE (argtype), type)) break; } } if (id && BASELINK_P (fns)) { if (baselinkp) *baselinkp = fns; else baselink = fns; } if (id == NULL_TREE && CLASS_TYPE_P (type) && TYPE_BINFO (type)) { vec<tree> ambiguous = vNULL; tree binfo = TYPE_BINFO (type), base_binfo, ret = NULL_TREE; unsigned int ix; if (ambiguousp == NULL) ambiguousp = &ambiguous; for (ix = 0; BINFO_BASE_ITERATE (binfo, ix, base_binfo); ix++) { id = omp_reduction_lookup (loc, orig_id, BINFO_TYPE (base_binfo), baselinkp ? baselinkp : &baselink, ambiguousp); if (id == NULL_TREE) continue; if (!ambiguousp->is_empty ()) ambiguousp->safe_push (id); else if (ret != NULL_TREE) { ambiguousp->safe_push (ret); ambiguousp->safe_push (id); ret = NULL_TREE; } else ret = id; } if (ambiguousp != &ambiguous) return ret; if (!ambiguous.is_empty ()) { const char *str = _("candidates are:"); unsigned int idx; tree udr; error_at (loc, "user defined reduction lookup is ambiguous"); FOR_EACH_VEC_ELT (ambiguous, idx, udr) { inform (DECL_SOURCE_LOCATION (udr), "%s %#D", str, udr); if (idx == 0) str = get_spaces (str); } ambiguous.release (); ret = error_mark_node; baselink = NULL_TREE; } id = ret; } if (id && baselink) perform_or_defer_access_check (BASELINK_BINFO (baselink), id, id, tf_warning_or_error); return id; } /* Helper function for cp_parser_omp_declare_reduction_exprs and tsubst_omp_udr. Remove CLEANUP_STMT for data (omp_priv variable). Also append INIT_EXPR for DECL_INITIAL of omp_priv after its DECL_EXPR. */ tree cp_remove_omp_priv_cleanup_stmt (tree *tp, int *walk_subtrees, void *data) { if (TYPE_P (*tp)) *walk_subtrees = 0; else if (TREE_CODE (*tp) == CLEANUP_STMT && CLEANUP_DECL (*tp) == (tree) data) *tp = CLEANUP_BODY (*tp); else if (TREE_CODE (*tp) == DECL_EXPR) { tree decl = DECL_EXPR_DECL (*tp); if (!processing_template_decl && decl == (tree) data && DECL_INITIAL (decl) && DECL_INITIAL (decl) != error_mark_node) { tree list = NULL_TREE; append_to_statement_list_force (*tp, &list); tree init_expr = build2 (INIT_EXPR, void_type_node, decl, DECL_INITIAL (decl)); DECL_INITIAL (decl) = NULL_TREE; append_to_statement_list_force (init_expr, &list); *tp = list; } } return NULL_TREE; } /* Data passed from cp_check_omp_declare_reduction to cp_check_omp_declare_reduction_r. */ struct cp_check_omp_declare_reduction_data { location_t loc; tree stmts[7]; bool combiner_p; }; /* Helper function for cp_check_omp_declare_reduction, called via cp_walk_tree. */ static tree cp_check_omp_declare_reduction_r (tree *tp, int *, void *data) { struct cp_check_omp_declare_reduction_data *udr_data = (struct cp_check_omp_declare_reduction_data *) data; if (SSA_VAR_P (*tp) && !DECL_ARTIFICIAL (*tp) && *tp != DECL_EXPR_DECL (udr_data->stmts[udr_data->combiner_p ? 0 : 3]) && *tp != DECL_EXPR_DECL (udr_data->stmts[udr_data->combiner_p ? 1 : 4])) { location_t loc = udr_data->loc; if (udr_data->combiner_p) error_at (loc, "%<#pragma omp declare reduction%> combiner refers to " "variable %qD which is not %<omp_out%> nor %<omp_in%>", *tp); else error_at (loc, "%<#pragma omp declare reduction%> initializer refers " "to variable %qD which is not %<omp_priv%> nor " "%<omp_orig%>", *tp); return *tp; } return NULL_TREE; } /* Diagnose violation of OpenMP #pragma omp declare reduction restrictions. */ void cp_check_omp_declare_reduction (tree udr) { tree type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (udr))); gcc_assert (TREE_CODE (type) == REFERENCE_TYPE); type = TREE_TYPE (type); int i; location_t loc = DECL_SOURCE_LOCATION (udr); if (type == error_mark_node) return; if (ARITHMETIC_TYPE_P (type)) { static enum tree_code predef_codes[] = { PLUS_EXPR, MULT_EXPR, MINUS_EXPR, BIT_AND_EXPR, BIT_XOR_EXPR, BIT_IOR_EXPR, TRUTH_ANDIF_EXPR, TRUTH_ORIF_EXPR }; for (i = 0; i < 8; i++) { tree id = omp_reduction_id (predef_codes[i], NULL_TREE, NULL_TREE); const char *n1 = IDENTIFIER_POINTER (DECL_NAME (udr)); const char *n2 = IDENTIFIER_POINTER (id); if (strncmp (n1, n2, IDENTIFIER_LENGTH (id)) == 0 && (n1[IDENTIFIER_LENGTH (id)] == '~' || n1[IDENTIFIER_LENGTH (id)] == '\0')) break; } if (i == 8 && TREE_CODE (type) != COMPLEX_EXPR) { const char prefix_minmax[] = "omp declare reduction m"; size_t prefix_size = sizeof (prefix_minmax) - 1; const char *n = IDENTIFIER_POINTER (DECL_NAME (udr)); if (strncmp (IDENTIFIER_POINTER (DECL_NAME (udr)), prefix_minmax, prefix_size) == 0 && ((n[prefix_size] == 'i' && n[prefix_size + 1] == 'n') || (n[prefix_size] == 'a' && n[prefix_size + 1] == 'x')) && (n[prefix_size + 2] == '~' || n[prefix_size + 2] == '\0')) i = 0; } if (i < 8) { error_at (loc, "predeclared arithmetic type %qT in " "%<#pragma omp declare reduction%>", type); return; } } else if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == METHOD_TYPE || TREE_CODE (type) == ARRAY_TYPE) { error_at (loc, "function or array type %qT in " "%<#pragma omp declare reduction%>", type); return; } else if (TREE_CODE (type) == REFERENCE_TYPE) { error_at (loc, "reference type %qT in %<#pragma omp declare reduction%>", type); return; } else if (TYPE_QUALS_NO_ADDR_SPACE (type)) { error_at (loc, "const, volatile or __restrict qualified type %qT in " "%<#pragma omp declare reduction%>", type); return; } tree body = DECL_SAVED_TREE (udr); if (body == NULL_TREE || TREE_CODE (body) != STATEMENT_LIST) return; tree_stmt_iterator tsi; struct cp_check_omp_declare_reduction_data data; memset (data.stmts, 0, sizeof data.stmts); for (i = 0, tsi = tsi_start (body); i < 7 && !tsi_end_p (tsi); i++, tsi_next (&tsi)) data.stmts[i] = tsi_stmt (tsi); data.loc = loc; gcc_assert (tsi_end_p (tsi)); if (i >= 3) { gcc_assert (TREE_CODE (data.stmts[0]) == DECL_EXPR && TREE_CODE (data.stmts[1]) == DECL_EXPR); if (TREE_NO_WARNING (DECL_EXPR_DECL (data.stmts[0]))) return; data.combiner_p = true; if (cp_walk_tree (&data.stmts[2], cp_check_omp_declare_reduction_r, &data, NULL)) TREE_NO_WARNING (DECL_EXPR_DECL (data.stmts[0])) = 1; } if (i >= 6) { gcc_assert (TREE_CODE (data.stmts[3]) == DECL_EXPR && TREE_CODE (data.stmts[4]) == DECL_EXPR); data.combiner_p = false; if (cp_walk_tree (&data.stmts[5], cp_check_omp_declare_reduction_r, &data, NULL) || cp_walk_tree (&DECL_INITIAL (DECL_EXPR_DECL (data.stmts[3])), cp_check_omp_declare_reduction_r, &data, NULL)) TREE_NO_WARNING (DECL_EXPR_DECL (data.stmts[0])) = 1; if (i == 7) gcc_assert (TREE_CODE (data.stmts[6]) == DECL_EXPR); } } /* Helper function of finish_omp_clauses. Clone STMT as if we were making an inline call. But, remap the OMP_DECL1 VAR_DECL (omp_out resp. omp_orig) to PLACEHOLDER and OMP_DECL2 VAR_DECL (omp_in resp. omp_priv) to DECL. */ static tree clone_omp_udr (tree stmt, tree omp_decl1, tree omp_decl2, tree decl, tree placeholder) { copy_body_data id; hash_map<tree, tree> decl_map; decl_map.put (omp_decl1, placeholder); decl_map.put (omp_decl2, decl); memset (&id, 0, sizeof (id)); id.src_fn = DECL_CONTEXT (omp_decl1); id.dst_fn = current_function_decl; id.src_cfun = DECL_STRUCT_FUNCTION (id.src_fn); id.decl_map = &decl_map; id.copy_decl = copy_decl_no_change; id.transform_call_graph_edges = CB_CGE_DUPLICATE; id.transform_new_cfg = true; id.transform_return_to_modify = false; id.transform_lang_insert_block = NULL; id.eh_lp_nr = 0; walk_tree (&stmt, copy_tree_body_r, &id, NULL); return stmt; } /* Helper function of finish_omp_clauses, called via cp_walk_tree. Find OMP_CLAUSE_PLACEHOLDER (passed in DATA) in *TP. */ static tree find_omp_placeholder_r (tree *tp, int *, void *data) { if (*tp == (tree) data) return *tp; return NULL_TREE; } /* Helper function of finish_omp_clauses. Handle OMP_CLAUSE_REDUCTION C. Return true if there is some error and the clause should be removed. */ static bool finish_omp_reduction_clause (tree c, bool *need_default_ctor, bool *need_dtor) { tree t = OMP_CLAUSE_DECL (c); bool predefined = false; tree type = TREE_TYPE (t); if (TREE_CODE (type) == REFERENCE_TYPE) type = TREE_TYPE (type); if (type == error_mark_node) return true; else if (ARITHMETIC_TYPE_P (type)) switch (OMP_CLAUSE_REDUCTION_CODE (c)) { case PLUS_EXPR: case MULT_EXPR: case MINUS_EXPR: predefined = true; break; case MIN_EXPR: case MAX_EXPR: if (TREE_CODE (type) == COMPLEX_TYPE) break; predefined = true; break; case BIT_AND_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: if (FLOAT_TYPE_P (type) || TREE_CODE (type) == COMPLEX_TYPE) break; predefined = true; break; case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: if (FLOAT_TYPE_P (type)) break; predefined = true; break; default: break; } else if (TREE_CODE (type) == ARRAY_TYPE || TYPE_READONLY (type)) { error ("%qE has invalid type for %<reduction%>", t); return true; } else if (!processing_template_decl) { t = require_complete_type (t); if (t == error_mark_node) return true; OMP_CLAUSE_DECL (c) = t; } if (predefined) { OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = NULL_TREE; return false; } else if (processing_template_decl) return false; tree id = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); type = TYPE_MAIN_VARIANT (TREE_TYPE (t)); if (TREE_CODE (type) == REFERENCE_TYPE) type = TREE_TYPE (type); OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = NULL_TREE; if (id == NULL_TREE) id = omp_reduction_id (OMP_CLAUSE_REDUCTION_CODE (c), NULL_TREE, NULL_TREE); id = omp_reduction_lookup (OMP_CLAUSE_LOCATION (c), id, type, NULL, NULL); if (id) { if (id == error_mark_node) return true; id = OVL_CURRENT (id); mark_used (id); tree body = DECL_SAVED_TREE (id); if (!body) return true; if (TREE_CODE (body) == STATEMENT_LIST) { tree_stmt_iterator tsi; tree placeholder = NULL_TREE; int i; tree stmts[7]; tree atype = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (id))); atype = TREE_TYPE (atype); bool need_static_cast = !same_type_p (type, atype); memset (stmts, 0, sizeof stmts); for (i = 0, tsi = tsi_start (body); i < 7 && !tsi_end_p (tsi); i++, tsi_next (&tsi)) stmts[i] = tsi_stmt (tsi); gcc_assert (tsi_end_p (tsi)); if (i >= 3) { gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR && TREE_CODE (stmts[1]) == DECL_EXPR); placeholder = build_lang_decl (VAR_DECL, NULL_TREE, type); DECL_ARTIFICIAL (placeholder) = 1; DECL_IGNORED_P (placeholder) = 1; OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = placeholder; if (TREE_ADDRESSABLE (DECL_EXPR_DECL (stmts[0]))) cxx_mark_addressable (placeholder); if (TREE_ADDRESSABLE (DECL_EXPR_DECL (stmts[1])) && TREE_CODE (TREE_TYPE (OMP_CLAUSE_DECL (c))) != REFERENCE_TYPE) cxx_mark_addressable (OMP_CLAUSE_DECL (c)); tree omp_out = placeholder; tree omp_in = convert_from_reference (OMP_CLAUSE_DECL (c)); if (need_static_cast) { tree rtype = build_reference_type (atype); omp_out = build_static_cast (rtype, omp_out, tf_warning_or_error); omp_in = build_static_cast (rtype, omp_in, tf_warning_or_error); if (omp_out == error_mark_node || omp_in == error_mark_node) return true; omp_out = convert_from_reference (omp_out); omp_in = convert_from_reference (omp_in); } OMP_CLAUSE_REDUCTION_MERGE (c) = clone_omp_udr (stmts[2], DECL_EXPR_DECL (stmts[0]), DECL_EXPR_DECL (stmts[1]), omp_in, omp_out); } if (i >= 6) { gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR && TREE_CODE (stmts[4]) == DECL_EXPR); if (TREE_ADDRESSABLE (DECL_EXPR_DECL (stmts[3]))) cxx_mark_addressable (OMP_CLAUSE_DECL (c)); if (TREE_ADDRESSABLE (DECL_EXPR_DECL (stmts[4]))) cxx_mark_addressable (placeholder); tree omp_priv = convert_from_reference (OMP_CLAUSE_DECL (c)); tree omp_orig = placeholder; if (need_static_cast) { if (i == 7) { error_at (OMP_CLAUSE_LOCATION (c), "user defined reduction with constructor " "initializer for base class %qT", atype); return true; } tree rtype = build_reference_type (atype); omp_priv = build_static_cast (rtype, omp_priv, tf_warning_or_error); omp_orig = build_static_cast (rtype, omp_orig, tf_warning_or_error); if (omp_priv == error_mark_node || omp_orig == error_mark_node) return true; omp_priv = convert_from_reference (omp_priv); omp_orig = convert_from_reference (omp_orig); } if (i == 6) *need_default_ctor = true; OMP_CLAUSE_REDUCTION_INIT (c) = clone_omp_udr (stmts[5], DECL_EXPR_DECL (stmts[4]), DECL_EXPR_DECL (stmts[3]), omp_priv, omp_orig); if (cp_walk_tree (&OMP_CLAUSE_REDUCTION_INIT (c), find_omp_placeholder_r, placeholder, NULL)) OMP_CLAUSE_REDUCTION_OMP_ORIG_REF (c) = 1; } else if (i >= 3) { if (CLASS_TYPE_P (type) && !pod_type_p (type)) *need_default_ctor = true; else { tree init; tree v = convert_from_reference (t); if (AGGREGATE_TYPE_P (TREE_TYPE (v))) init = build_constructor (TREE_TYPE (v), NULL); else init = fold_convert (TREE_TYPE (v), integer_zero_node); OMP_CLAUSE_REDUCTION_INIT (c) = build2 (INIT_EXPR, TREE_TYPE (v), v, init); } } } } if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) *need_dtor = true; else { error ("user defined reduction not found for %qD", t); return true; } return false; } /* For all elements of CLAUSES, validate them vs OpenMP constraints. Remove any elements from the list that are invalid. */ tree finish_omp_clauses (tree clauses) { bitmap_head generic_head, firstprivate_head, lastprivate_head; bitmap_head aligned_head; tree c, t, *pc; bool branch_seen = false; bool copyprivate_seen = false; bitmap_obstack_initialize (NULL); bitmap_initialize (&generic_head, &bitmap_default_obstack); bitmap_initialize (&firstprivate_head, &bitmap_default_obstack); bitmap_initialize (&lastprivate_head, &bitmap_default_obstack); bitmap_initialize (&aligned_head, &bitmap_default_obstack); for (pc = &clauses, c = clauses; c ; c = *pc) { bool remove = false; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: goto check_dup_generic; case OMP_CLAUSE_PRIVATE: goto check_dup_generic; case OMP_CLAUSE_REDUCTION: goto check_dup_generic; case OMP_CLAUSE_COPYPRIVATE: copyprivate_seen = true; goto check_dup_generic; case OMP_CLAUSE_COPYIN: goto check_dup_generic; case OMP_CLAUSE_LINEAR: t = OMP_CLAUSE_DECL (c); if ((VAR_P (t) || TREE_CODE (t) == PARM_DECL) && !type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t)) && TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE) { error ("linear clause applied to non-integral non-pointer " "variable with %qT type", TREE_TYPE (t)); remove = true; break; } t = OMP_CLAUSE_LINEAR_STEP (c); if (t == NULL_TREE) t = integer_one_node; if (t == error_mark_node) { remove = true; break; } else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("linear step expression must be integral"); remove = true; break; } else { t = mark_rvalue_use (t); if (!processing_template_decl && (VAR_P (OMP_CLAUSE_DECL (c)) || TREE_CODE (OMP_CLAUSE_DECL (c)) == PARM_DECL)) { if (TREE_CODE (OMP_CLAUSE_DECL (c)) == PARM_DECL) t = maybe_constant_value (t); t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); if (TREE_CODE (TREE_TYPE (OMP_CLAUSE_DECL (c))) == POINTER_TYPE) { t = pointer_int_sum (OMP_CLAUSE_LOCATION (c), PLUS_EXPR, OMP_CLAUSE_DECL (c), t); t = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, sizetype, t, OMP_CLAUSE_DECL (c)); if (t == error_mark_node) { remove = true; break; } } else t = fold_convert (TREE_TYPE (OMP_CLAUSE_DECL (c)), t); } OMP_CLAUSE_LINEAR_STEP (c) = t; } goto check_dup_generic; check_dup_generic: t = OMP_CLAUSE_DECL (c); if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) break; if (DECL_P (t)) error ("%qD is not a variable in clause %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else error ("%qE is not a variable in clause %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t)) || bitmap_bit_p (&lastprivate_head, DECL_UID (t))) { error ("%qD appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&generic_head, DECL_UID (t)); break; case OMP_CLAUSE_FIRSTPRIVATE: t = OMP_CLAUSE_DECL (c); if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) break; if (DECL_P (t)) error ("%qD is not a variable in clause %<firstprivate%>", t); else error ("%qE is not a variable in clause %<firstprivate%>", t); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t))) { error ("%qD appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&firstprivate_head, DECL_UID (t)); break; case OMP_CLAUSE_LASTPRIVATE: t = OMP_CLAUSE_DECL (c); if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) break; if (DECL_P (t)) error ("%qD is not a variable in clause %<lastprivate%>", t); else error ("%qE is not a variable in clause %<lastprivate%>", t); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&lastprivate_head, DECL_UID (t))) { error ("%qD appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&lastprivate_head, DECL_UID (t)); break; case OMP_CLAUSE_IF: t = OMP_CLAUSE_IF_EXPR (c); t = maybe_convert_cond (t); if (t == error_mark_node) remove = true; else if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_IF_EXPR (c) = t; break; case OMP_CLAUSE_FINAL: t = OMP_CLAUSE_FINAL_EXPR (c); t = maybe_convert_cond (t); if (t == error_mark_node) remove = true; else if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_FINAL_EXPR (c) = t; break; case OMP_CLAUSE_NUM_THREADS: t = OMP_CLAUSE_NUM_THREADS_EXPR (c); if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("num_threads expression must be integral"); remove = true; } else { t = mark_rvalue_use (t); if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_NUM_THREADS_EXPR (c) = t; } break; case OMP_CLAUSE_SCHEDULE: t = OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c); if (t == NULL) ; else if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && (OMP_CLAUSE_SCHEDULE_KIND (c) != OMP_CLAUSE_SCHEDULE_CILKFOR) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("schedule chunk size expression must be integral"); remove = true; } else { t = mark_rvalue_use (t); if (!processing_template_decl) { if (OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_CILKFOR) { t = convert_to_integer (long_integer_type_node, t); if (t == error_mark_node) { remove = true; break; } } t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); } OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c) = t; } break; case OMP_CLAUSE_SIMDLEN: case OMP_CLAUSE_SAFELEN: t = OMP_CLAUSE_OPERAND (c, 0); if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("%qs length expression must be integral", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else { t = mark_rvalue_use (t); t = maybe_constant_value (t); if (!processing_template_decl) { if (TREE_CODE (t) != INTEGER_CST || tree_int_cst_sgn (t) != 1) { error ("%qs length expression must be positive constant" " integer expression", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } } OMP_CLAUSE_OPERAND (c, 0) = t; } break; case OMP_CLAUSE_NUM_TEAMS: t = OMP_CLAUSE_NUM_TEAMS_EXPR (c); if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("%<num_teams%> expression must be integral"); remove = true; } else { t = mark_rvalue_use (t); if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_NUM_TEAMS_EXPR (c) = t; } break; case OMP_CLAUSE_ASYNC: t = OMP_CLAUSE_ASYNC_EXPR (c); if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("%<async%> expression must be integral"); remove = true; } else { t = mark_rvalue_use (t); if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_ASYNC_EXPR (c) = t; } break; case OMP_CLAUSE_VECTOR_LENGTH: t = OMP_CLAUSE_VECTOR_LENGTH_EXPR (c); t = maybe_convert_cond (t); if (t == error_mark_node) remove = true; else if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_VECTOR_LENGTH_EXPR (c) = t; break; case OMP_CLAUSE_WAIT: t = OMP_CLAUSE_WAIT_EXPR (c); if (t == error_mark_node) remove = true; else if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_WAIT_EXPR (c) = t; break; case OMP_CLAUSE_THREAD_LIMIT: t = OMP_CLAUSE_THREAD_LIMIT_EXPR (c); if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("%<thread_limit%> expression must be integral"); remove = true; } else { t = mark_rvalue_use (t); if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_THREAD_LIMIT_EXPR (c) = t; } break; case OMP_CLAUSE_DEVICE: t = OMP_CLAUSE_DEVICE_ID (c); if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("%<device%> id must be integral"); remove = true; } else { t = mark_rvalue_use (t); if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_DEVICE_ID (c) = t; } break; case OMP_CLAUSE_DIST_SCHEDULE: t = OMP_CLAUSE_DIST_SCHEDULE_CHUNK_EXPR (c); if (t == NULL) ; else if (t == error_mark_node) remove = true; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("%<dist_schedule%> chunk size expression must be " "integral"); remove = true; } else { t = mark_rvalue_use (t); if (!processing_template_decl) t = fold_build_cleanup_point_expr (TREE_TYPE (t), t); OMP_CLAUSE_DIST_SCHEDULE_CHUNK_EXPR (c) = t; } break; case OMP_CLAUSE_ALIGNED: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) break; if (DECL_P (t)) error ("%qD is not a variable in %<aligned%> clause", t); else error ("%qE is not a variable in %<aligned%> clause", t); remove = true; } else if (!type_dependent_expression_p (t) && TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE && TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE && (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE || (!POINTER_TYPE_P (TREE_TYPE (TREE_TYPE (t))) && (TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != ARRAY_TYPE)))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE in %<aligned%> clause is neither a pointer nor " "an array nor a reference to pointer or array", t); remove = true; } else if (bitmap_bit_p (&aligned_head, DECL_UID (t))) { error ("%qD appears more than once in %<aligned%> clauses", t); remove = true; } else bitmap_set_bit (&aligned_head, DECL_UID (t)); t = OMP_CLAUSE_ALIGNED_ALIGNMENT (c); if (t == error_mark_node) remove = true; else if (t == NULL_TREE) break; else if (!type_dependent_expression_p (t) && !INTEGRAL_TYPE_P (TREE_TYPE (t))) { error ("%<aligned%> clause alignment expression must " "be integral"); remove = true; } else { t = mark_rvalue_use (t); t = maybe_constant_value (t); if (!processing_template_decl) { if (TREE_CODE (t) != INTEGER_CST || tree_int_cst_sgn (t) != 1) { error ("%<aligned%> clause alignment expression must be " "positive constant integer expression"); remove = true; } } OMP_CLAUSE_ALIGNED_ALIGNMENT (c) = t; } break; case OMP_CLAUSE_DEPEND: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) == TREE_LIST) { if (handle_omp_array_sections (c)) remove = true; break; } if (t == error_mark_node) remove = true; else if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) break; if (DECL_P (t)) error ("%qD is not a variable in %<depend%> clause", t); else error ("%qE is not a variable in %<depend%> clause", t); remove = true; } else if (!processing_template_decl && !cxx_mark_addressable (t)) remove = true; break; case OMP_CLAUSE_MAP: case OMP_CLAUSE_TO: case OMP_CLAUSE_FROM: case OMP_CLAUSE__CACHE_: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) == TREE_LIST) { if (handle_omp_array_sections (c)) remove = true; else { t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != TREE_LIST && !type_dependent_expression_p (t) && !cp_omp_mappable_type (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "array section does not have mappable type " "in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } } break; } if (t == error_mark_node) remove = true; else if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) break; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER) break; if (DECL_P (t)) error ("%qD is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else error ("%qE is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (TREE_CODE (t) == VAR_DECL && DECL_THREAD_LOCAL_P (t)) { error ("%qD is threadprivate variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (!processing_template_decl && TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE && !cxx_mark_addressable (t)) remove = true; else if (!(OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER) && !type_dependent_expression_p (t) && !cp_omp_mappable_type ((TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE) ? TREE_TYPE (TREE_TYPE (t)) : TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qD does not have a mappable type in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t))) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) error ("%qD appears more than once in motion clauses", t); else error ("%qD appears more than once in map clauses", t); remove = true; } else bitmap_set_bit (&generic_head, DECL_UID (t)); break; case OMP_CLAUSE_UNIFORM: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != PARM_DECL) { if (processing_template_decl) break; if (DECL_P (t)) error ("%qD is not an argument in %<uniform%> clause", t); else error ("%qE is not an argument in %<uniform%> clause", t); remove = true; break; } goto check_dup_generic; case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_MERGEABLE: case OMP_CLAUSE_PARALLEL: case OMP_CLAUSE_FOR: case OMP_CLAUSE_SECTIONS: case OMP_CLAUSE_TASKGROUP: case OMP_CLAUSE_PROC_BIND: case OMP_CLAUSE__CILK_FOR_COUNT_: break; case OMP_CLAUSE_INBRANCH: case OMP_CLAUSE_NOTINBRANCH: if (branch_seen) { error ("%<inbranch%> clause is incompatible with " "%<notinbranch%>"); remove = true; } branch_seen = true; break; default: gcc_unreachable (); } if (remove) *pc = OMP_CLAUSE_CHAIN (c); else pc = &OMP_CLAUSE_CHAIN (c); } for (pc = &clauses, c = clauses; c ; c = *pc) { enum omp_clause_code c_kind = OMP_CLAUSE_CODE (c); bool remove = false; bool need_complete_non_reference = false; bool need_default_ctor = false; bool need_copy_ctor = false; bool need_copy_assignment = false; bool need_implicitly_determined = false; bool need_dtor = false; tree type, inner_type; switch (c_kind) { case OMP_CLAUSE_SHARED: need_implicitly_determined = true; break; case OMP_CLAUSE_PRIVATE: need_complete_non_reference = true; need_default_ctor = true; need_dtor = true; need_implicitly_determined = true; break; case OMP_CLAUSE_FIRSTPRIVATE: need_complete_non_reference = true; need_copy_ctor = true; need_dtor = true; need_implicitly_determined = true; break; case OMP_CLAUSE_LASTPRIVATE: need_complete_non_reference = true; need_copy_assignment = true; need_implicitly_determined = true; break; case OMP_CLAUSE_REDUCTION: need_implicitly_determined = true; break; case OMP_CLAUSE_COPYPRIVATE: need_copy_assignment = true; break; case OMP_CLAUSE_COPYIN: need_copy_assignment = true; break; case OMP_CLAUSE_NOWAIT: if (copyprivate_seen) { error_at (OMP_CLAUSE_LOCATION (c), "%<nowait%> clause must not be used together " "with %<copyprivate%>"); *pc = OMP_CLAUSE_CHAIN (c); continue; } /* FALLTHRU */ default: pc = &OMP_CLAUSE_CHAIN (c); continue; } t = OMP_CLAUSE_DECL (c); if (processing_template_decl && !VAR_P (t) && TREE_CODE (t) != PARM_DECL) { pc = &OMP_CLAUSE_CHAIN (c); continue; } switch (c_kind) { case OMP_CLAUSE_LASTPRIVATE: if (!bitmap_bit_p (&firstprivate_head, DECL_UID (t))) { need_default_ctor = true; need_dtor = true; } break; case OMP_CLAUSE_REDUCTION: if (finish_omp_reduction_clause (c, &need_default_ctor, &need_dtor)) remove = true; else t = OMP_CLAUSE_DECL (c); break; case OMP_CLAUSE_COPYIN: if (!VAR_P (t) || !DECL_THREAD_LOCAL_P (t)) { error ("%qE must be %<threadprivate%> for %<copyin%>", t); remove = true; } break; default: break; } if (need_complete_non_reference || need_copy_assignment) { t = require_complete_type (t); if (t == error_mark_node) remove = true; else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE && need_complete_non_reference) { error ("%qE has reference type for %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } } if (need_implicitly_determined) { const char *share_name = NULL; if (VAR_P (t) && DECL_THREAD_LOCAL_P (t)) share_name = "threadprivate"; else switch (cxx_omp_predetermined_sharing (t)) { case OMP_CLAUSE_DEFAULT_UNSPECIFIED: break; case OMP_CLAUSE_DEFAULT_SHARED: /* const vars may be specified in firstprivate clause. */ if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE && cxx_omp_const_qual_no_mutable (t)) break; share_name = "shared"; break; case OMP_CLAUSE_DEFAULT_PRIVATE: share_name = "private"; break; default: gcc_unreachable (); } if (share_name) { error ("%qE is predetermined %qs for %qs", t, share_name, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } } /* We're interested in the base element, not arrays. */ inner_type = type = TREE_TYPE (t); while (TREE_CODE (inner_type) == ARRAY_TYPE) inner_type = TREE_TYPE (inner_type); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && TREE_CODE (inner_type) == REFERENCE_TYPE) inner_type = TREE_TYPE (inner_type); /* Check for special function availability by building a call to one. Save the results, because later we won't be in the right context for making these queries. */ if (CLASS_TYPE_P (inner_type) && COMPLETE_TYPE_P (inner_type) && (need_default_ctor || need_copy_ctor || need_copy_assignment || need_dtor) && !type_dependent_expression_p (t) && cxx_omp_create_clause_info (c, inner_type, need_default_ctor, need_copy_ctor, need_copy_assignment, need_dtor)) remove = true; if (remove) *pc = OMP_CLAUSE_CHAIN (c); else pc = &OMP_CLAUSE_CHAIN (c); } bitmap_obstack_release (NULL); return clauses; } /* For all variables in the tree_list VARS, mark them as thread local. */ void finish_omp_threadprivate (tree vars) { tree t; /* Mark every variable in VARS to be assigned thread local storage. */ for (t = vars; t; t = TREE_CHAIN (t)) { tree v = TREE_PURPOSE (t); if (error_operand_p (v)) ; else if (!VAR_P (v)) error ("%<threadprivate%> %qD is not file, namespace " "or block scope variable", v); /* If V had already been marked threadprivate, it doesn't matter whether it had been used prior to this point. */ else if (TREE_USED (v) && (DECL_LANG_SPECIFIC (v) == NULL || !CP_DECL_THREADPRIVATE_P (v))) error ("%qE declared %<threadprivate%> after first use", v); else if (! TREE_STATIC (v) && ! DECL_EXTERNAL (v)) error ("automatic variable %qE cannot be %<threadprivate%>", v); else if (! COMPLETE_TYPE_P (complete_type (TREE_TYPE (v)))) error ("%<threadprivate%> %qE has incomplete type", v); else if (TREE_STATIC (v) && TYPE_P (CP_DECL_CONTEXT (v)) && CP_DECL_CONTEXT (v) != current_class_type) error ("%<threadprivate%> %qE directive not " "in %qT definition", v, CP_DECL_CONTEXT (v)); else { /* Allocate a LANG_SPECIFIC structure for V, if needed. */ if (DECL_LANG_SPECIFIC (v) == NULL) { retrofit_lang_decl (v); /* Make sure that DECL_DISCRIMINATOR_P continues to be true after the allocation of the lang_decl structure. */ if (DECL_DISCRIMINATOR_P (v)) DECL_LANG_SPECIFIC (v)->u.base.u2sel = 1; } if (! DECL_THREAD_LOCAL_P (v)) { set_decl_tls_model (v, decl_default_tls_model (v)); /* If rtl has been already set for this var, call make_decl_rtl once again, so that encode_section_info has a chance to look at the new decl flags. */ if (DECL_RTL_SET_P (v)) make_decl_rtl (v); } CP_DECL_THREADPRIVATE_P (v) = 1; } } } /* Build an OpenMP structured block. */ tree begin_omp_structured_block (void) { return do_pushlevel (sk_omp); } tree finish_omp_structured_block (tree block) { return do_poplevel (block); } /* Generate OACC_DATA, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_DATA. */ tree finish_oacc_data (tree clauses, tree block) { tree stmt; block = finish_omp_structured_block (block); stmt = make_node (OACC_DATA); TREE_TYPE (stmt) = void_type_node; OACC_DATA_CLAUSES (stmt) = clauses; OACC_DATA_BODY (stmt) = block; return add_stmt (stmt); } /* Generate OACC_KERNELS, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_KERNELS. */ tree finish_oacc_kernels (tree clauses, tree block) { tree stmt; block = finish_omp_structured_block (block); stmt = make_node (OACC_KERNELS); TREE_TYPE (stmt) = void_type_node; OACC_KERNELS_CLAUSES (stmt) = clauses; OACC_KERNELS_BODY (stmt) = block; return add_stmt (stmt); } /* Generate OACC_PARALLEL, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_PARALLEL. */ tree finish_oacc_parallel (tree clauses, tree block) { tree stmt; block = finish_omp_structured_block (block); stmt = make_node (OACC_PARALLEL); TREE_TYPE (stmt) = void_type_node; OACC_PARALLEL_CLAUSES (stmt) = clauses; OACC_PARALLEL_BODY (stmt) = block; return add_stmt (stmt); } /* Similarly, except force the retention of the BLOCK. */ tree begin_omp_parallel (void) { keep_next_level (true); return begin_omp_structured_block (); } tree finish_omp_parallel (tree clauses, tree body) { tree stmt; body = finish_omp_structured_block (body); stmt = make_node (OMP_PARALLEL); TREE_TYPE (stmt) = void_type_node; OMP_PARALLEL_CLAUSES (stmt) = clauses; OMP_PARALLEL_BODY (stmt) = body; return add_stmt (stmt); } tree begin_omp_task (void) { keep_next_level (true); return begin_omp_structured_block (); } tree finish_omp_task (tree clauses, tree body) { tree stmt; body = finish_omp_structured_block (body); stmt = make_node (OMP_TASK); TREE_TYPE (stmt) = void_type_node; OMP_TASK_CLAUSES (stmt) = clauses; OMP_TASK_BODY (stmt) = body; return add_stmt (stmt); } /* Helper function for finish_omp_for. Convert Ith random access iterator into integral iterator. Return FALSE if successful. */ static bool handle_omp_for_class_iterator (int i, location_t locus, tree declv, tree initv, tree condv, tree incrv, tree *body, tree *pre_body, tree clauses, tree *lastp) { tree diff, iter_init, iter_incr = NULL, last; tree incr_var = NULL, orig_pre_body, orig_body, c; tree decl = TREE_VEC_ELT (declv, i); tree init = TREE_VEC_ELT (initv, i); tree cond = TREE_VEC_ELT (condv, i); tree incr = TREE_VEC_ELT (incrv, i); tree iter = decl; location_t elocus = locus; if (init && EXPR_HAS_LOCATION (init)) elocus = EXPR_LOCATION (init); switch (TREE_CODE (cond)) { case GT_EXPR: case GE_EXPR: case LT_EXPR: case LE_EXPR: case NE_EXPR: if (TREE_OPERAND (cond, 1) == iter) cond = build2 (swap_tree_comparison (TREE_CODE (cond)), TREE_TYPE (cond), iter, TREE_OPERAND (cond, 0)); if (TREE_OPERAND (cond, 0) != iter) cond = error_mark_node; else { tree tem = build_x_binary_op (EXPR_LOCATION (cond), TREE_CODE (cond), iter, ERROR_MARK, TREE_OPERAND (cond, 1), ERROR_MARK, NULL, tf_warning_or_error); if (error_operand_p (tem)) return true; } break; default: cond = error_mark_node; break; } if (cond == error_mark_node) { error_at (elocus, "invalid controlling predicate"); return true; } diff = build_x_binary_op (elocus, MINUS_EXPR, TREE_OPERAND (cond, 1), ERROR_MARK, iter, ERROR_MARK, NULL, tf_warning_or_error); if (error_operand_p (diff)) return true; if (TREE_CODE (TREE_TYPE (diff)) != INTEGER_TYPE) { error_at (elocus, "difference between %qE and %qD does not have integer type", TREE_OPERAND (cond, 1), iter); return true; } switch (TREE_CODE (incr)) { case PREINCREMENT_EXPR: case PREDECREMENT_EXPR: case POSTINCREMENT_EXPR: case POSTDECREMENT_EXPR: if (TREE_OPERAND (incr, 0) != iter) { incr = error_mark_node; break; } iter_incr = build_x_unary_op (EXPR_LOCATION (incr), TREE_CODE (incr), iter, tf_warning_or_error); if (error_operand_p (iter_incr)) return true; else if (TREE_CODE (incr) == PREINCREMENT_EXPR || TREE_CODE (incr) == POSTINCREMENT_EXPR) incr = integer_one_node; else incr = integer_minus_one_node; break; case MODIFY_EXPR: if (TREE_OPERAND (incr, 0) != iter) incr = error_mark_node; else if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR) { tree rhs = TREE_OPERAND (incr, 1); if (TREE_OPERAND (rhs, 0) == iter) { if (TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs, 1))) != INTEGER_TYPE) incr = error_mark_node; else { iter_incr = build_x_modify_expr (EXPR_LOCATION (rhs), iter, TREE_CODE (rhs), TREE_OPERAND (rhs, 1), tf_warning_or_error); if (error_operand_p (iter_incr)) return true; incr = TREE_OPERAND (rhs, 1); incr = cp_convert (TREE_TYPE (diff), incr, tf_warning_or_error); if (TREE_CODE (rhs) == MINUS_EXPR) { incr = build1 (NEGATE_EXPR, TREE_TYPE (diff), incr); incr = fold_if_not_in_template (incr); } if (TREE_CODE (incr) != INTEGER_CST && (TREE_CODE (incr) != NOP_EXPR || (TREE_CODE (TREE_OPERAND (incr, 0)) != INTEGER_CST))) iter_incr = NULL; } } else if (TREE_OPERAND (rhs, 1) == iter) { if (TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs, 0))) != INTEGER_TYPE || TREE_CODE (rhs) != PLUS_EXPR) incr = error_mark_node; else { iter_incr = build_x_binary_op (EXPR_LOCATION (rhs), PLUS_EXPR, TREE_OPERAND (rhs, 0), ERROR_MARK, iter, ERROR_MARK, NULL, tf_warning_or_error); if (error_operand_p (iter_incr)) return true; iter_incr = build_x_modify_expr (EXPR_LOCATION (rhs), iter, NOP_EXPR, iter_incr, tf_warning_or_error); if (error_operand_p (iter_incr)) return true; incr = TREE_OPERAND (rhs, 0); iter_incr = NULL; } } else incr = error_mark_node; } else incr = error_mark_node; break; default: incr = error_mark_node; break; } if (incr == error_mark_node) { error_at (elocus, "invalid increment expression"); return true; } incr = cp_convert (TREE_TYPE (diff), incr, tf_warning_or_error); for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_DECL (c) == iter) break; decl = create_temporary_var (TREE_TYPE (diff)); pushdecl (decl); add_decl_expr (decl); last = create_temporary_var (TREE_TYPE (diff)); pushdecl (last); add_decl_expr (last); if (c && iter_incr == NULL) { incr_var = create_temporary_var (TREE_TYPE (diff)); pushdecl (incr_var); add_decl_expr (incr_var); } gcc_assert (stmts_are_full_exprs_p ()); orig_pre_body = *pre_body; *pre_body = push_stmt_list (); if (orig_pre_body) add_stmt (orig_pre_body); if (init != NULL) finish_expr_stmt (build_x_modify_expr (elocus, iter, NOP_EXPR, init, tf_warning_or_error)); init = build_int_cst (TREE_TYPE (diff), 0); if (c && iter_incr == NULL) { finish_expr_stmt (build_x_modify_expr (elocus, incr_var, NOP_EXPR, incr, tf_warning_or_error)); incr = incr_var; iter_incr = build_x_modify_expr (elocus, iter, PLUS_EXPR, incr, tf_warning_or_error); } finish_expr_stmt (build_x_modify_expr (elocus, last, NOP_EXPR, init, tf_warning_or_error)); *pre_body = pop_stmt_list (*pre_body); cond = cp_build_binary_op (elocus, TREE_CODE (cond), decl, diff, tf_warning_or_error); incr = build_modify_expr (elocus, decl, NULL_TREE, PLUS_EXPR, elocus, incr, NULL_TREE); orig_body = *body; *body = push_stmt_list (); iter_init = build2 (MINUS_EXPR, TREE_TYPE (diff), decl, last); iter_init = build_x_modify_expr (elocus, iter, PLUS_EXPR, iter_init, tf_warning_or_error); if (iter_init != error_mark_node) iter_init = build1 (NOP_EXPR, void_type_node, iter_init); finish_expr_stmt (iter_init); finish_expr_stmt (build_x_modify_expr (elocus, last, NOP_EXPR, decl, tf_warning_or_error)); add_stmt (orig_body); *body = pop_stmt_list (*body); if (c) { OMP_CLAUSE_LASTPRIVATE_STMT (c) = push_stmt_list (); finish_expr_stmt (iter_incr); OMP_CLAUSE_LASTPRIVATE_STMT (c) = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (c)); } TREE_VEC_ELT (declv, i) = decl; TREE_VEC_ELT (initv, i) = init; TREE_VEC_ELT (condv, i) = cond; TREE_VEC_ELT (incrv, i) = incr; *lastp = last; return false; } /* Build and validate an OMP_FOR statement. CLAUSES, BODY, COND, INCR are directly for their associated operands in the statement. DECL and INIT are a combo; if DECL is NULL then INIT ought to be a MODIFY_EXPR, and the DECL should be extracted. PRE_BODY are optional statements that need to go before the loop into its sk_omp scope. */ tree finish_omp_for (location_t locus, enum tree_code code, tree declv, tree initv, tree condv, tree incrv, tree body, tree pre_body, tree clauses) { tree omp_for = NULL, orig_incr = NULL; tree decl = NULL, init, cond, incr, orig_decl = NULL_TREE, block = NULL_TREE; tree last = NULL_TREE; location_t elocus; int i; gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (initv)); gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (condv)); gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (incrv)); for (i = 0; i < TREE_VEC_LENGTH (declv); i++) { decl = TREE_VEC_ELT (declv, i); init = TREE_VEC_ELT (initv, i); cond = TREE_VEC_ELT (condv, i); incr = TREE_VEC_ELT (incrv, i); elocus = locus; if (decl == NULL) { if (init != NULL) switch (TREE_CODE (init)) { case MODIFY_EXPR: decl = TREE_OPERAND (init, 0); init = TREE_OPERAND (init, 1); break; case MODOP_EXPR: if (TREE_CODE (TREE_OPERAND (init, 1)) == NOP_EXPR) { decl = TREE_OPERAND (init, 0); init = TREE_OPERAND (init, 2); } break; default: break; } if (decl == NULL) { error_at (locus, "expected iteration declaration or initialization"); return NULL; } } if (init && EXPR_HAS_LOCATION (init)) elocus = EXPR_LOCATION (init); if (cond == NULL) { error_at (elocus, "missing controlling predicate"); return NULL; } if (incr == NULL) { error_at (elocus, "missing increment expression"); return NULL; } TREE_VEC_ELT (declv, i) = decl; TREE_VEC_ELT (initv, i) = init; } if (dependent_omp_for_p (declv, initv, condv, incrv)) { tree stmt; stmt = make_node (code); for (i = 0; i < TREE_VEC_LENGTH (declv); i++) { /* This is really just a place-holder. We'll be decomposing this again and going through the cp_build_modify_expr path below when we instantiate the thing. */ TREE_VEC_ELT (initv, i) = build2 (MODIFY_EXPR, void_type_node, TREE_VEC_ELT (declv, i), TREE_VEC_ELT (initv, i)); } TREE_TYPE (stmt) = void_type_node; OMP_FOR_INIT (stmt) = initv; OMP_FOR_COND (stmt) = condv; OMP_FOR_INCR (stmt) = incrv; OMP_FOR_BODY (stmt) = body; OMP_FOR_PRE_BODY (stmt) = pre_body; OMP_FOR_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, locus); return add_stmt (stmt); } if (processing_template_decl) orig_incr = make_tree_vec (TREE_VEC_LENGTH (incrv)); for (i = 0; i < TREE_VEC_LENGTH (declv); ) { decl = TREE_VEC_ELT (declv, i); init = TREE_VEC_ELT (initv, i); cond = TREE_VEC_ELT (condv, i); incr = TREE_VEC_ELT (incrv, i); if (orig_incr) TREE_VEC_ELT (orig_incr, i) = incr; elocus = locus; if (init && EXPR_HAS_LOCATION (init)) elocus = EXPR_LOCATION (init); if (!DECL_P (decl)) { error_at (elocus, "expected iteration declaration or initialization"); return NULL; } if (incr && TREE_CODE (incr) == MODOP_EXPR) { if (orig_incr) TREE_VEC_ELT (orig_incr, i) = incr; incr = cp_build_modify_expr (TREE_OPERAND (incr, 0), TREE_CODE (TREE_OPERAND (incr, 1)), TREE_OPERAND (incr, 2), tf_warning_or_error); } if (CLASS_TYPE_P (TREE_TYPE (decl))) { if (code == OMP_SIMD) { error_at (elocus, "%<#pragma omp simd%> used with class " "iteration variable %qE", decl); return NULL; } if (code == CILK_FOR && i == 0) orig_decl = decl; if (handle_omp_for_class_iterator (i, locus, declv, initv, condv, incrv, &body, &pre_body, clauses, &last)) return NULL; continue; } if (!INTEGRAL_TYPE_P (TREE_TYPE (decl)) && !TYPE_PTR_P (TREE_TYPE (decl))) { error_at (elocus, "invalid type for iteration variable %qE", decl); return NULL; } if (!processing_template_decl) { init = fold_build_cleanup_point_expr (TREE_TYPE (init), init); init = cp_build_modify_expr (decl, NOP_EXPR, init, tf_warning_or_error); } else init = build2 (MODIFY_EXPR, void_type_node, decl, init); if (cond && TREE_SIDE_EFFECTS (cond) && COMPARISON_CLASS_P (cond) && !processing_template_decl) { tree t = TREE_OPERAND (cond, 0); if (TREE_SIDE_EFFECTS (t) && t != decl && (TREE_CODE (t) != NOP_EXPR || TREE_OPERAND (t, 0) != decl)) TREE_OPERAND (cond, 0) = fold_build_cleanup_point_expr (TREE_TYPE (t), t); t = TREE_OPERAND (cond, 1); if (TREE_SIDE_EFFECTS (t) && t != decl && (TREE_CODE (t) != NOP_EXPR || TREE_OPERAND (t, 0) != decl)) TREE_OPERAND (cond, 1) = fold_build_cleanup_point_expr (TREE_TYPE (t), t); } if (decl == error_mark_node || init == error_mark_node) return NULL; TREE_VEC_ELT (declv, i) = decl; TREE_VEC_ELT (initv, i) = init; TREE_VEC_ELT (condv, i) = cond; TREE_VEC_ELT (incrv, i) = incr; i++; } if (IS_EMPTY_STMT (pre_body)) pre_body = NULL; if (code == CILK_FOR && !processing_template_decl) block = push_stmt_list (); omp_for = c_finish_omp_for (locus, code, declv, initv, condv, incrv, body, pre_body); if (omp_for == NULL) { if (block) pop_stmt_list (block); return NULL; } for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INCR (omp_for)); i++) { decl = TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_INIT (omp_for), i), 0); incr = TREE_VEC_ELT (OMP_FOR_INCR (omp_for), i); if (TREE_CODE (incr) != MODIFY_EXPR) continue; if (TREE_SIDE_EFFECTS (TREE_OPERAND (incr, 1)) && BINARY_CLASS_P (TREE_OPERAND (incr, 1)) && !processing_template_decl) { tree t = TREE_OPERAND (TREE_OPERAND (incr, 1), 0); if (TREE_SIDE_EFFECTS (t) && t != decl && (TREE_CODE (t) != NOP_EXPR || TREE_OPERAND (t, 0) != decl)) TREE_OPERAND (TREE_OPERAND (incr, 1), 0) = fold_build_cleanup_point_expr (TREE_TYPE (t), t); t = TREE_OPERAND (TREE_OPERAND (incr, 1), 1); if (TREE_SIDE_EFFECTS (t) && t != decl && (TREE_CODE (t) != NOP_EXPR || TREE_OPERAND (t, 0) != decl)) TREE_OPERAND (TREE_OPERAND (incr, 1), 1) = fold_build_cleanup_point_expr (TREE_TYPE (t), t); } if (orig_incr) TREE_VEC_ELT (OMP_FOR_INCR (omp_for), i) = TREE_VEC_ELT (orig_incr, i); } OMP_FOR_CLAUSES (omp_for) = clauses; if (block) { tree omp_par = make_node (OMP_PARALLEL); TREE_TYPE (omp_par) = void_type_node; OMP_PARALLEL_CLAUSES (omp_par) = NULL_TREE; tree bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (bind) = 1; BIND_EXPR_BODY (bind) = pop_stmt_list (block); OMP_PARALLEL_BODY (omp_par) = bind; if (OMP_FOR_PRE_BODY (omp_for)) { add_stmt (OMP_FOR_PRE_BODY (omp_for)); OMP_FOR_PRE_BODY (omp_for) = NULL_TREE; } init = TREE_VEC_ELT (OMP_FOR_INIT (omp_for), 0); decl = TREE_OPERAND (init, 0); cond = TREE_VEC_ELT (OMP_FOR_COND (omp_for), 0); incr = TREE_VEC_ELT (OMP_FOR_INCR (omp_for), 0); tree t = TREE_OPERAND (cond, 1), c, clauses, *pc; clauses = OMP_FOR_CLAUSES (omp_for); OMP_FOR_CLAUSES (omp_for) = NULL_TREE; for (pc = &clauses; *pc; ) if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_SCHEDULE) { gcc_assert (OMP_FOR_CLAUSES (omp_for) == NULL_TREE); OMP_FOR_CLAUSES (omp_for) = *pc; *pc = OMP_CLAUSE_CHAIN (*pc); OMP_CLAUSE_CHAIN (OMP_FOR_CLAUSES (omp_for)) = NULL_TREE; } else { gcc_assert (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE); pc = &OMP_CLAUSE_CHAIN (*pc); } if (TREE_CODE (t) != INTEGER_CST) { TREE_OPERAND (cond, 1) = get_temp_regvar (TREE_TYPE (t), t); c = build_omp_clause (input_location, OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = TREE_OPERAND (cond, 1); OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; } if (TREE_CODE (incr) == MODIFY_EXPR) { t = TREE_OPERAND (TREE_OPERAND (incr, 1), 1); if (TREE_CODE (t) != INTEGER_CST) { TREE_OPERAND (TREE_OPERAND (incr, 1), 1) = get_temp_regvar (TREE_TYPE (t), t); c = build_omp_clause (input_location, OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = TREE_OPERAND (TREE_OPERAND (incr, 1), 1); OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; } } t = TREE_OPERAND (init, 1); if (TREE_CODE (t) != INTEGER_CST) { TREE_OPERAND (init, 1) = get_temp_regvar (TREE_TYPE (t), t); c = build_omp_clause (input_location, OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = TREE_OPERAND (init, 1); OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; } if (orig_decl && orig_decl != decl) { c = build_omp_clause (input_location, OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = orig_decl; OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; } if (last) { c = build_omp_clause (input_location, OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = last; OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; } c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE); OMP_CLAUSE_DECL (c) = decl; OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; c = build_omp_clause (input_location, OMP_CLAUSE__CILK_FOR_COUNT_); OMP_CLAUSE_OPERAND (c, 0) = cilk_for_number_of_iterations (omp_for); OMP_CLAUSE_CHAIN (c) = clauses; OMP_PARALLEL_CLAUSES (omp_par) = finish_omp_clauses (c); add_stmt (omp_par); return omp_par; } else if (code == CILK_FOR && processing_template_decl) { tree c, clauses = OMP_FOR_CLAUSES (omp_for); if (orig_decl && orig_decl != decl) { c = build_omp_clause (input_location, OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = orig_decl; OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; } if (last) { c = build_omp_clause (input_location, OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = last; OMP_CLAUSE_CHAIN (c) = clauses; clauses = c; } OMP_FOR_CLAUSES (omp_for) = clauses; } return omp_for; } void finish_omp_atomic (enum tree_code code, enum tree_code opcode, tree lhs, tree rhs, tree v, tree lhs1, tree rhs1, bool seq_cst) { tree orig_lhs; tree orig_rhs; tree orig_v; tree orig_lhs1; tree orig_rhs1; bool dependent_p; tree stmt; orig_lhs = lhs; orig_rhs = rhs; orig_v = v; orig_lhs1 = lhs1; orig_rhs1 = rhs1; dependent_p = false; stmt = NULL_TREE; /* Even in a template, we can detect invalid uses of the atomic pragma if neither LHS nor RHS is type-dependent. */ if (processing_template_decl) { dependent_p = (type_dependent_expression_p (lhs) || (rhs && type_dependent_expression_p (rhs)) || (v && type_dependent_expression_p (v)) || (lhs1 && type_dependent_expression_p (lhs1)) || (rhs1 && type_dependent_expression_p (rhs1))); if (!dependent_p) { lhs = build_non_dependent_expr (lhs); if (rhs) rhs = build_non_dependent_expr (rhs); if (v) v = build_non_dependent_expr (v); if (lhs1) lhs1 = build_non_dependent_expr (lhs1); if (rhs1) rhs1 = build_non_dependent_expr (rhs1); } } if (!dependent_p) { bool swapped = false; if (rhs1 && cp_tree_equal (lhs, rhs)) { tree tem = rhs; rhs = rhs1; rhs1 = tem; swapped = !commutative_tree_code (opcode); } if (rhs1 && !cp_tree_equal (lhs, rhs1)) { if (code == OMP_ATOMIC) error ("%<#pragma omp atomic update%> uses two different " "expressions for memory"); else error ("%<#pragma omp atomic capture%> uses two different " "expressions for memory"); return; } if (lhs1 && !cp_tree_equal (lhs, lhs1)) { if (code == OMP_ATOMIC) error ("%<#pragma omp atomic update%> uses two different " "expressions for memory"); else error ("%<#pragma omp atomic capture%> uses two different " "expressions for memory"); return; } stmt = c_finish_omp_atomic (input_location, code, opcode, lhs, rhs, v, lhs1, rhs1, swapped, seq_cst); if (stmt == error_mark_node) return; } if (processing_template_decl) { if (code == OMP_ATOMIC_READ) { stmt = build_min_nt_loc (EXPR_LOCATION (orig_lhs), OMP_ATOMIC_READ, orig_lhs); OMP_ATOMIC_SEQ_CST (stmt) = seq_cst; stmt = build2 (MODIFY_EXPR, void_type_node, orig_v, stmt); } else { if (opcode == NOP_EXPR) stmt = build2 (MODIFY_EXPR, void_type_node, orig_lhs, orig_rhs); else stmt = build2 (opcode, void_type_node, orig_lhs, orig_rhs); if (orig_rhs1) stmt = build_min_nt_loc (EXPR_LOCATION (orig_rhs1), COMPOUND_EXPR, orig_rhs1, stmt); if (code != OMP_ATOMIC) { stmt = build_min_nt_loc (EXPR_LOCATION (orig_lhs1), code, orig_lhs1, stmt); OMP_ATOMIC_SEQ_CST (stmt) = seq_cst; stmt = build2 (MODIFY_EXPR, void_type_node, orig_v, stmt); } } stmt = build2 (OMP_ATOMIC, void_type_node, integer_zero_node, stmt); OMP_ATOMIC_SEQ_CST (stmt) = seq_cst; } finish_expr_stmt (stmt); } void finish_omp_barrier (void) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_BARRIER); vec<tree, va_gc> *vec = make_tree_vector (); tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error); release_tree_vector (vec); finish_expr_stmt (stmt); } void finish_omp_flush (void) { tree fn = builtin_decl_explicit (BUILT_IN_SYNC_SYNCHRONIZE); vec<tree, va_gc> *vec = make_tree_vector (); tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error); release_tree_vector (vec); finish_expr_stmt (stmt); } void finish_omp_taskwait (void) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_TASKWAIT); vec<tree, va_gc> *vec = make_tree_vector (); tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error); release_tree_vector (vec); finish_expr_stmt (stmt); } void finish_omp_taskyield (void) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_TASKYIELD); vec<tree, va_gc> *vec = make_tree_vector (); tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error); release_tree_vector (vec); finish_expr_stmt (stmt); } void finish_omp_cancel (tree clauses) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_CANCEL); int mask = 0; if (find_omp_clause (clauses, OMP_CLAUSE_PARALLEL)) mask = 1; else if (find_omp_clause (clauses, OMP_CLAUSE_FOR)) mask = 2; else if (find_omp_clause (clauses, OMP_CLAUSE_SECTIONS)) mask = 4; else if (find_omp_clause (clauses, OMP_CLAUSE_TASKGROUP)) mask = 8; else { error ("%<#pragma omp cancel must specify one of " "%<parallel%>, %<for%>, %<sections%> or %<taskgroup%> clauses"); return; } vec<tree, va_gc> *vec = make_tree_vector (); tree ifc = find_omp_clause (clauses, OMP_CLAUSE_IF); if (ifc != NULL_TREE) { tree type = TREE_TYPE (OMP_CLAUSE_IF_EXPR (ifc)); ifc = fold_build2_loc (OMP_CLAUSE_LOCATION (ifc), NE_EXPR, boolean_type_node, OMP_CLAUSE_IF_EXPR (ifc), build_zero_cst (type)); } else ifc = boolean_true_node; vec->quick_push (build_int_cst (integer_type_node, mask)); vec->quick_push (ifc); tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error); release_tree_vector (vec); finish_expr_stmt (stmt); } void finish_omp_cancellation_point (tree clauses) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_CANCELLATION_POINT); int mask = 0; if (find_omp_clause (clauses, OMP_CLAUSE_PARALLEL)) mask = 1; else if (find_omp_clause (clauses, OMP_CLAUSE_FOR)) mask = 2; else if (find_omp_clause (clauses, OMP_CLAUSE_SECTIONS)) mask = 4; else if (find_omp_clause (clauses, OMP_CLAUSE_TASKGROUP)) mask = 8; else { error ("%<#pragma omp cancellation point must specify one of " "%<parallel%>, %<for%>, %<sections%> or %<taskgroup%> clauses"); return; } vec<tree, va_gc> *vec = make_tree_vector_single (build_int_cst (integer_type_node, mask)); tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error); release_tree_vector (vec); finish_expr_stmt (stmt); } /* Begin a __transaction_atomic or __transaction_relaxed statement. If PCOMPOUND is non-null, this is for a function-transaction-block, and we should create an extra compound stmt. */ tree begin_transaction_stmt (location_t loc, tree *pcompound, int flags) { tree r; if (pcompound) *pcompound = begin_compound_stmt (0); r = build_stmt (loc, TRANSACTION_EXPR, NULL_TREE); /* Only add the statement to the function if support enabled. */ if (flag_tm) add_stmt (r); else error_at (loc, ((flags & TM_STMT_ATTR_RELAXED) != 0 ? G_("%<__transaction_relaxed%> without " "transactional memory support enabled") : G_("%<__transaction_atomic%> without " "transactional memory support enabled"))); TRANSACTION_EXPR_BODY (r) = push_stmt_list (); TREE_SIDE_EFFECTS (r) = 1; return r; } /* End a __transaction_atomic or __transaction_relaxed statement. If COMPOUND_STMT is non-null, this is for a function-transaction-block, and we should end the compound. If NOEX is non-NULL, we wrap the body in a MUST_NOT_THROW_EXPR with NOEX as condition. */ void finish_transaction_stmt (tree stmt, tree compound_stmt, int flags, tree noex) { TRANSACTION_EXPR_BODY (stmt) = pop_stmt_list (TRANSACTION_EXPR_BODY (stmt)); TRANSACTION_EXPR_OUTER (stmt) = (flags & TM_STMT_ATTR_OUTER) != 0; TRANSACTION_EXPR_RELAXED (stmt) = (flags & TM_STMT_ATTR_RELAXED) != 0; TRANSACTION_EXPR_IS_STMT (stmt) = 1; /* noexcept specifications are not allowed for function transactions. */ gcc_assert (!(noex && compound_stmt)); if (noex) { tree body = build_must_not_throw_expr (TRANSACTION_EXPR_BODY (stmt), noex); /* This may not be true when the STATEMENT_LIST is empty. */ if (EXPR_P (body)) SET_EXPR_LOCATION (body, EXPR_LOCATION (TRANSACTION_EXPR_BODY (stmt))); TREE_SIDE_EFFECTS (body) = 1; TRANSACTION_EXPR_BODY (stmt) = body; } if (compound_stmt) finish_compound_stmt (compound_stmt); } /* Build a __transaction_atomic or __transaction_relaxed expression. If NOEX is non-NULL, we wrap the body in a MUST_NOT_THROW_EXPR with NOEX as condition. */ tree build_transaction_expr (location_t loc, tree expr, int flags, tree noex) { tree ret; if (noex) { expr = build_must_not_throw_expr (expr, noex); if (EXPR_P (expr)) SET_EXPR_LOCATION (expr, loc); TREE_SIDE_EFFECTS (expr) = 1; } ret = build1 (TRANSACTION_EXPR, TREE_TYPE (expr), expr); if (flags & TM_STMT_ATTR_RELAXED) TRANSACTION_EXPR_RELAXED (ret) = 1; TREE_SIDE_EFFECTS (ret) = 1; SET_EXPR_LOCATION (ret, loc); return ret; } void init_cp_semantics (void) { } /* Build a STATIC_ASSERT for a static assertion with the condition CONDITION and the message text MESSAGE. LOCATION is the location of the static assertion in the source code. When MEMBER_P, this static assertion is a member of a class. */ void finish_static_assert (tree condition, tree message, location_t location, bool member_p) { if (message == NULL_TREE || message == error_mark_node || condition == NULL_TREE || condition == error_mark_node) return; if (check_for_bare_parameter_packs (condition)) condition = error_mark_node; if (type_dependent_expression_p (condition) || value_dependent_expression_p (condition)) { /* We're in a template; build a STATIC_ASSERT and put it in the right place. */ tree assertion; assertion = make_node (STATIC_ASSERT); STATIC_ASSERT_CONDITION (assertion) = condition; STATIC_ASSERT_MESSAGE (assertion) = message; STATIC_ASSERT_SOURCE_LOCATION (assertion) = location; if (member_p) maybe_add_class_template_decl_list (current_class_type, assertion, /*friend_p=*/0); else add_stmt (assertion); return; } /* Fold the expression and convert it to a boolean value. */ condition = instantiate_non_dependent_expr (condition); condition = cp_convert (boolean_type_node, condition, tf_warning_or_error); condition = maybe_constant_value (condition); if (TREE_CODE (condition) == INTEGER_CST && !integer_zerop (condition)) /* Do nothing; the condition is satisfied. */ ; else { location_t saved_loc = input_location; input_location = location; if (TREE_CODE (condition) == INTEGER_CST && integer_zerop (condition)) /* Report the error. */ error ("static assertion failed: %s", TREE_STRING_POINTER (message)); else if (condition && condition != error_mark_node) { error ("non-constant condition for static assertion"); if (require_potential_rvalue_constant_expression (condition)) cxx_constant_value (condition); } input_location = saved_loc; } } /* Implements the C++0x decltype keyword. Returns the type of EXPR, suitable for use as a type-specifier. ID_EXPRESSION_OR_MEMBER_ACCESS_P is true when EXPR was parsed as an id-expression or a class member access, FALSE when it was parsed as a full expression. */ tree finish_decltype_type (tree expr, bool id_expression_or_member_access_p, tsubst_flags_t complain) { tree type = NULL_TREE; if (!expr || error_operand_p (expr)) return error_mark_node; if (TYPE_P (expr) || TREE_CODE (expr) == TYPE_DECL || (TREE_CODE (expr) == BIT_NOT_EXPR && TYPE_P (TREE_OPERAND (expr, 0)))) { if (complain & tf_error) error ("argument to decltype must be an expression"); return error_mark_node; } /* Depending on the resolution of DR 1172, we may later need to distinguish instantiation-dependent but not type-dependent expressions so that, say, A<decltype(sizeof(T))>::U doesn't require 'typename'. */ if (instantiation_dependent_expression_p (expr)) { type = cxx_make_type (DECLTYPE_TYPE); DECLTYPE_TYPE_EXPR (type) = expr; DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (type) = id_expression_or_member_access_p; SET_TYPE_STRUCTURAL_EQUALITY (type); return type; } /* The type denoted by decltype(e) is defined as follows: */ expr = resolve_nondeduced_context (expr, complain); if (invalid_nonstatic_memfn_p (expr, complain)) return error_mark_node; if (type_unknown_p (expr)) { if (complain & tf_error) error ("decltype cannot resolve address of overloaded function"); return error_mark_node; } /* To get the size of a static data member declared as an array of unknown bound, we need to instantiate it. */ if (VAR_P (expr) && VAR_HAD_UNKNOWN_BOUND (expr) && DECL_TEMPLATE_INSTANTIATION (expr)) instantiate_decl (expr, /*defer_ok*/true, /*expl_inst_mem*/false); if (id_expression_or_member_access_p) { /* If e is an id-expression or a class member access (5.2.5 [expr.ref]), decltype(e) is defined as the type of the entity named by e. If there is no such entity, or e names a set of overloaded functions, the program is ill-formed. */ if (identifier_p (expr)) expr = lookup_name (expr); if (INDIRECT_REF_P (expr)) /* This can happen when the expression is, e.g., "a.b". Just look at the underlying operand. */ expr = TREE_OPERAND (expr, 0); if (TREE_CODE (expr) == OFFSET_REF || TREE_CODE (expr) == MEMBER_REF || TREE_CODE (expr) == SCOPE_REF) /* We're only interested in the field itself. If it is a BASELINK, we will need to see through it in the next step. */ expr = TREE_OPERAND (expr, 1); if (BASELINK_P (expr)) /* See through BASELINK nodes to the underlying function. */ expr = BASELINK_FUNCTIONS (expr); switch (TREE_CODE (expr)) { case FIELD_DECL: if (DECL_BIT_FIELD_TYPE (expr)) { type = DECL_BIT_FIELD_TYPE (expr); break; } /* Fall through for fields that aren't bitfields. */ case FUNCTION_DECL: case VAR_DECL: case CONST_DECL: case PARM_DECL: case RESULT_DECL: case TEMPLATE_PARM_INDEX: expr = mark_type_use (expr); type = TREE_TYPE (expr); break; case ERROR_MARK: type = error_mark_node; break; case COMPONENT_REF: case COMPOUND_EXPR: mark_type_use (expr); type = is_bitfield_expr_with_lowered_type (expr); if (!type) type = TREE_TYPE (TREE_OPERAND (expr, 1)); break; case BIT_FIELD_REF: gcc_unreachable (); case INTEGER_CST: case PTRMEM_CST: /* We can get here when the id-expression refers to an enumerator or non-type template parameter. */ type = TREE_TYPE (expr); break; default: /* Handle instantiated template non-type arguments. */ type = TREE_TYPE (expr); break; } } else { /* Within a lambda-expression: Every occurrence of decltype((x)) where x is a possibly parenthesized id-expression that names an entity of automatic storage duration is treated as if x were transformed into an access to a corresponding data member of the closure type that would have been declared if x were a use of the denoted entity. */ if (outer_automatic_var_p (expr) && current_function_decl && LAMBDA_FUNCTION_P (current_function_decl)) type = capture_decltype (expr); else if (error_operand_p (expr)) type = error_mark_node; else if (expr == current_class_ptr) /* If the expression is just "this", we want the cv-unqualified pointer for the "this" type. */ type = TYPE_MAIN_VARIANT (TREE_TYPE (expr)); else { /* Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is defined as T&; if an xvalue, T&&; otherwise, T. */ cp_lvalue_kind clk = lvalue_kind (expr); type = unlowered_expr_type (expr); gcc_assert (TREE_CODE (type) != REFERENCE_TYPE); /* For vector types, pick a non-opaque variant. */ if (TREE_CODE (type) == VECTOR_TYPE) type = strip_typedefs (type); if (clk != clk_none && !(clk & clk_class)) type = cp_build_reference_type (type, (clk & clk_rvalueref)); } } return type; } /* Called from trait_expr_value to evaluate either __has_nothrow_assign or __has_nothrow_copy, depending on assign_p. */ static bool classtype_has_nothrow_assign_or_copy_p (tree type, bool assign_p) { tree fns; if (assign_p) { int ix; ix = lookup_fnfields_1 (type, ansi_assopname (NOP_EXPR)); if (ix < 0) return false; fns = (*CLASSTYPE_METHOD_VEC (type))[ix]; } else if (TYPE_HAS_COPY_CTOR (type)) { /* If construction of the copy constructor was postponed, create it now. */ if (CLASSTYPE_LAZY_COPY_CTOR (type)) lazily_declare_fn (sfk_copy_constructor, type); if (CLASSTYPE_LAZY_MOVE_CTOR (type)) lazily_declare_fn (sfk_move_constructor, type); fns = CLASSTYPE_CONSTRUCTORS (type); } else return false; for (; fns; fns = OVL_NEXT (fns)) { tree fn = OVL_CURRENT (fns); if (assign_p) { if (copy_fn_p (fn) == 0) continue; } else if (copy_fn_p (fn) <= 0) continue; maybe_instantiate_noexcept (fn); if (!TYPE_NOTHROW_P (TREE_TYPE (fn))) return false; } return true; } /* Actually evaluates the trait. */ static bool trait_expr_value (cp_trait_kind kind, tree type1, tree type2) { enum tree_code type_code1; tree t; type_code1 = TREE_CODE (type1); switch (kind) { case CPTK_HAS_NOTHROW_ASSIGN: type1 = strip_array_types (type1); return (!CP_TYPE_CONST_P (type1) && type_code1 != REFERENCE_TYPE && (trait_expr_value (CPTK_HAS_TRIVIAL_ASSIGN, type1, type2) || (CLASS_TYPE_P (type1) && classtype_has_nothrow_assign_or_copy_p (type1, true)))); case CPTK_HAS_TRIVIAL_ASSIGN: /* ??? The standard seems to be missing the "or array of such a class type" wording for this trait. */ type1 = strip_array_types (type1); return (!CP_TYPE_CONST_P (type1) && type_code1 != REFERENCE_TYPE && (trivial_type_p (type1) || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_COPY_ASSIGN (type1)))); case CPTK_HAS_NOTHROW_CONSTRUCTOR: type1 = strip_array_types (type1); return (trait_expr_value (CPTK_HAS_TRIVIAL_CONSTRUCTOR, type1, type2) || (CLASS_TYPE_P (type1) && (t = locate_ctor (type1)) && (maybe_instantiate_noexcept (t), TYPE_NOTHROW_P (TREE_TYPE (t))))); case CPTK_HAS_TRIVIAL_CONSTRUCTOR: type1 = strip_array_types (type1); return (trivial_type_p (type1) || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_DFLT (type1))); case CPTK_HAS_NOTHROW_COPY: type1 = strip_array_types (type1); return (trait_expr_value (CPTK_HAS_TRIVIAL_COPY, type1, type2) || (CLASS_TYPE_P (type1) && classtype_has_nothrow_assign_or_copy_p (type1, false))); case CPTK_HAS_TRIVIAL_COPY: /* ??? The standard seems to be missing the "or array of such a class type" wording for this trait. */ type1 = strip_array_types (type1); return (trivial_type_p (type1) || type_code1 == REFERENCE_TYPE || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_COPY_CTOR (type1))); case CPTK_HAS_TRIVIAL_DESTRUCTOR: type1 = strip_array_types (type1); return (trivial_type_p (type1) || type_code1 == REFERENCE_TYPE || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_DESTRUCTOR (type1))); case CPTK_HAS_VIRTUAL_DESTRUCTOR: return type_has_virtual_destructor (type1); case CPTK_IS_ABSTRACT: return (ABSTRACT_CLASS_TYPE_P (type1)); case CPTK_IS_BASE_OF: return (NON_UNION_CLASS_TYPE_P (type1) && NON_UNION_CLASS_TYPE_P (type2) && (same_type_ignoring_top_level_qualifiers_p (type1, type2) || DERIVED_FROM_P (type1, type2))); case CPTK_IS_CLASS: return (NON_UNION_CLASS_TYPE_P (type1)); case CPTK_IS_EMPTY: return (NON_UNION_CLASS_TYPE_P (type1) && CLASSTYPE_EMPTY_P (type1)); case CPTK_IS_ENUM: return (type_code1 == ENUMERAL_TYPE); case CPTK_IS_FINAL: return (CLASS_TYPE_P (type1) && CLASSTYPE_FINAL (type1)); case CPTK_IS_LITERAL_TYPE: return (literal_type_p (type1)); case CPTK_IS_POD: return (pod_type_p (type1)); case CPTK_IS_POLYMORPHIC: return (CLASS_TYPE_P (type1) && TYPE_POLYMORPHIC_P (type1)); case CPTK_IS_STD_LAYOUT: return (std_layout_type_p (type1)); case CPTK_IS_TRIVIAL: return (trivial_type_p (type1)); case CPTK_IS_TRIVIALLY_ASSIGNABLE: return is_trivially_xible (MODIFY_EXPR, type1, type2); case CPTK_IS_TRIVIALLY_CONSTRUCTIBLE: return is_trivially_xible (INIT_EXPR, type1, type2); case CPTK_IS_TRIVIALLY_COPYABLE: return (trivially_copyable_p (type1)); case CPTK_IS_UNION: return (type_code1 == UNION_TYPE); default: gcc_unreachable (); return false; } } /* If TYPE is an array of unknown bound, or (possibly cv-qualified) void, or a complete type, returns true, otherwise false. */ static bool check_trait_type (tree type) { if (type == NULL_TREE) return true; if (TREE_CODE (type) == TREE_LIST) return (check_trait_type (TREE_VALUE (type)) && check_trait_type (TREE_CHAIN (type))); if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type) && COMPLETE_TYPE_P (TREE_TYPE (type))) return true; if (VOID_TYPE_P (type)) return true; return !!complete_type_or_else (strip_array_types (type), NULL_TREE); } /* Process a trait expression. */ tree finish_trait_expr (cp_trait_kind kind, tree type1, tree type2) { if (type1 == error_mark_node || type2 == error_mark_node) return error_mark_node; if (processing_template_decl) { tree trait_expr = make_node (TRAIT_EXPR); TREE_TYPE (trait_expr) = boolean_type_node; TRAIT_EXPR_TYPE1 (trait_expr) = type1; TRAIT_EXPR_TYPE2 (trait_expr) = type2; TRAIT_EXPR_KIND (trait_expr) = kind; return trait_expr; } switch (kind) { case CPTK_HAS_NOTHROW_ASSIGN: case CPTK_HAS_TRIVIAL_ASSIGN: case CPTK_HAS_NOTHROW_CONSTRUCTOR: case CPTK_HAS_TRIVIAL_CONSTRUCTOR: case CPTK_HAS_NOTHROW_COPY: case CPTK_HAS_TRIVIAL_COPY: case CPTK_HAS_TRIVIAL_DESTRUCTOR: case CPTK_HAS_VIRTUAL_DESTRUCTOR: case CPTK_IS_ABSTRACT: case CPTK_IS_EMPTY: case CPTK_IS_FINAL: case CPTK_IS_LITERAL_TYPE: case CPTK_IS_POD: case CPTK_IS_POLYMORPHIC: case CPTK_IS_STD_LAYOUT: case CPTK_IS_TRIVIAL: case CPTK_IS_TRIVIALLY_COPYABLE: if (!check_trait_type (type1)) return error_mark_node; break; case CPTK_IS_TRIVIALLY_ASSIGNABLE: case CPTK_IS_TRIVIALLY_CONSTRUCTIBLE: if (!check_trait_type (type1) || !check_trait_type (type2)) return error_mark_node; break; case CPTK_IS_BASE_OF: if (NON_UNION_CLASS_TYPE_P (type1) && NON_UNION_CLASS_TYPE_P (type2) && !same_type_ignoring_top_level_qualifiers_p (type1, type2) && !complete_type_or_else (type2, NULL_TREE)) /* We already issued an error. */ return error_mark_node; break; case CPTK_IS_CLASS: case CPTK_IS_ENUM: case CPTK_IS_UNION: break; default: gcc_unreachable (); } return (trait_expr_value (kind, type1, type2) ? boolean_true_node : boolean_false_node); } /* Do-nothing variants of functions to handle pragma FLOAT_CONST_DECIMAL64, which is ignored for C++. */ void set_float_const_decimal64 (void) { } void clear_float_const_decimal64 (void) { } bool float_const_decimal64_p (void) { return 0; } /* Return true if T designates the implied `this' parameter. */ bool is_this_parameter (tree t) { if (!DECL_P (t) || DECL_NAME (t) != this_identifier) return false; gcc_assert (TREE_CODE (t) == PARM_DECL || is_capture_proxy (t)); return true; } /* Insert the deduced return type for an auto function. */ void apply_deduced_return_type (tree fco, tree return_type) { tree result; if (return_type == error_mark_node) return; if (LAMBDA_FUNCTION_P (fco)) { tree lambda = CLASSTYPE_LAMBDA_EXPR (current_class_type); LAMBDA_EXPR_RETURN_TYPE (lambda) = return_type; } if (DECL_CONV_FN_P (fco)) DECL_NAME (fco) = mangle_conv_op_name_for_type (return_type); TREE_TYPE (fco) = change_return_type (return_type, TREE_TYPE (fco)); result = DECL_RESULT (fco); if (result == NULL_TREE) return; if (TREE_TYPE (result) == return_type) return; if (!processing_template_decl && !VOID_TYPE_P (return_type) && !complete_type_or_else (return_type, NULL_TREE)) return; /* We already have a DECL_RESULT from start_preparsed_function. Now we need to redo the work it and allocate_struct_function did to reflect the new type. */ gcc_assert (current_function_decl == fco); result = build_decl (input_location, RESULT_DECL, NULL_TREE, TYPE_MAIN_VARIANT (return_type)); DECL_ARTIFICIAL (result) = 1; DECL_IGNORED_P (result) = 1; cp_apply_type_quals_to_decl (cp_type_quals (return_type), result); DECL_RESULT (fco) = result; if (!processing_template_decl) { bool aggr = aggregate_value_p (result, fco); #ifdef PCC_STATIC_STRUCT_RETURN cfun->returns_pcc_struct = aggr; #endif cfun->returns_struct = aggr; } } /* DECL is a local variable or parameter from the surrounding scope of a lambda-expression. Returns the decltype for a use of the capture field for DECL even if it hasn't been captured yet. */ static tree capture_decltype (tree decl) { tree lam = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (current_function_decl)); /* FIXME do lookup instead of list walk? */ tree cap = value_member (decl, LAMBDA_EXPR_CAPTURE_LIST (lam)); tree type; if (cap) type = TREE_TYPE (TREE_PURPOSE (cap)); else switch (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lam)) { case CPLD_NONE: error ("%qD is not captured", decl); return error_mark_node; case CPLD_COPY: type = TREE_TYPE (decl); if (TREE_CODE (type) == REFERENCE_TYPE && TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE) type = TREE_TYPE (type); break; case CPLD_REFERENCE: type = TREE_TYPE (decl); if (TREE_CODE (type) != REFERENCE_TYPE) type = build_reference_type (TREE_TYPE (decl)); break; default: gcc_unreachable (); } if (TREE_CODE (type) != REFERENCE_TYPE) { if (!LAMBDA_EXPR_MUTABLE_P (lam)) type = cp_build_qualified_type (type, (cp_type_quals (type) |TYPE_QUAL_CONST)); type = build_reference_type (type); } return type; } #include "gt-cp-semantics.h"
atomic-7.c
/* { dg-do compile } */ double x, y; void f2(void) { #pragma omp atomic y++; #pragma omp atomic y--; #pragma omp atomic ++y; #pragma omp atomic --y; #pragma omp atomic y += 1; #pragma omp atomic y -= x; #pragma omp atomic y *= 3; #pragma omp atomic y /= 3; }
ocp_nlp_sqp.c
/* * Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, * Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, * Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, * Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl * * This file is part of acados. * * The 2-Clause BSD License * * 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.; */ #include "acados/ocp_nlp/ocp_nlp_sqp.h" // external #include <assert.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #if defined(ACADOS_WITH_OPENMP) #include <omp.h> #endif // blasfeo #include "blasfeo/include/blasfeo_d_aux.h" #include "blasfeo/include/blasfeo_d_aux_ext_dep.h" #include "blasfeo/include/blasfeo_d_blas.h" // acados #include "acados/ocp_nlp/ocp_nlp_common.h" #include "acados/ocp_nlp/ocp_nlp_dynamics_cont.h" #include "acados/ocp_nlp/ocp_nlp_reg_common.h" #include "acados/ocp_qp/ocp_qp_common.h" #include "acados/utils/mem.h" #include "acados/utils/print.h" #include "acados/utils/timing.h" #include "acados/utils/types.h" #include "acados_c/ocp_qp_interface.h" /************************************************ * options ************************************************/ acados_size_t ocp_nlp_sqp_opts_calculate_size(void *config_, void *dims_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; acados_size_t size = 0; size += sizeof(ocp_nlp_sqp_opts); size += ocp_nlp_opts_calculate_size(config, dims); return size; } void *ocp_nlp_sqp_opts_assign(void *config_, void *dims_, void *raw_memory) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; char *c_ptr = (char *) raw_memory; ocp_nlp_sqp_opts *opts = (ocp_nlp_sqp_opts *) c_ptr; c_ptr += sizeof(ocp_nlp_sqp_opts); opts->nlp_opts = ocp_nlp_opts_assign(config, dims, c_ptr); c_ptr += ocp_nlp_opts_calculate_size(config, dims); assert((char *) raw_memory + ocp_nlp_sqp_opts_calculate_size(config, dims) >= c_ptr); return opts; } void ocp_nlp_sqp_opts_initialize_default(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; // int ii; // this first !!! ocp_nlp_opts_initialize_default(config, dims, nlp_opts); // SQP opts opts->max_iter = 20; opts->tol_stat = 1e-8; opts->tol_eq = 1e-8; opts->tol_ineq = 1e-8; opts->tol_comp = 1e-8; opts->ext_qp_res = 0; opts->qp_warm_start = 0; opts->warm_start_first_qp = false; opts->rti_phase = 0; opts->initialize_t_slacks = 0; // overwrite default submodules opts // qp tolerance qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_stat", &opts->tol_stat); qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_eq", &opts->tol_eq); qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_ineq", &opts->tol_ineq); qp_solver->opts_set(qp_solver, opts->nlp_opts->qp_solver_opts, "tol_comp", &opts->tol_comp); return; } void ocp_nlp_sqp_opts_update(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_opts_update(config, dims, nlp_opts); return; } void ocp_nlp_sqp_opts_set(void *config_, void *opts_, const char *field, void* value) { ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = (ocp_nlp_sqp_opts *) opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; int ii; char module[MAX_STR_LEN]; char *ptr_module = NULL; int module_length = 0; // extract module name char *char_ = strchr(field, '_'); if (char_!=NULL) { module_length = char_-field; for (ii=0; ii<module_length; ii++) module[ii] = field[ii]; module[module_length] = '\0'; // add end of string ptr_module = module; } // pass options to QP module if ( ptr_module!=NULL && (!strcmp(ptr_module, "qp")) ) { ocp_nlp_opts_set(config, nlp_opts, field, value); if (!strcmp(field, "qp_warm_start")) { int* i_ptr = (int *) value; opts->qp_warm_start = *i_ptr; } } else // nlp opts { if (!strcmp(field, "max_iter")) { int* max_iter = (int *) value; opts->max_iter = *max_iter; } else if (!strcmp(field, "tol_stat")) { double* tol_stat = (double *) value; opts->tol_stat = *tol_stat; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_stat", value); } else if (!strcmp(field, "tol_eq")) { double* tol_eq = (double *) value; opts->tol_eq = *tol_eq; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_eq", value); } else if (!strcmp(field, "tol_ineq")) { double* tol_ineq = (double *) value; opts->tol_ineq = *tol_ineq; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_ineq", value); } else if (!strcmp(field, "tol_comp")) { double* tol_comp = (double *) value; opts->tol_comp = *tol_comp; // TODO: set accuracy of the qp_solver to the minimum of current QP accuracy and the one specified. config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "tol_comp", value); } else if (!strcmp(field, "ext_qp_res")) { int* ext_qp_res = (int *) value; opts->ext_qp_res = *ext_qp_res; } else if (!strcmp(field, "warm_start_first_qp")) { bool* warm_start_first_qp = (bool *) value; opts->warm_start_first_qp = *warm_start_first_qp; } else if (!strcmp(field, "rti_phase")) { int* rti_phase = (int *) value; if (*rti_phase < 0 || *rti_phase > 0) { printf("\nerror: ocp_nlp_sqp_opts_set: invalid value for rti_phase field."); printf("possible values are: 0\n"); exit(1); } else opts->rti_phase = *rti_phase; } else if (!strcmp(field, "initialize_t_slacks")) { int* initialize_t_slacks = (int *) value; if (*initialize_t_slacks != 0 && *initialize_t_slacks != 1) { printf("\nerror: ocp_nlp_sqp_opts_set: invalid value for initialize_t_slacks field, need int 0 or 1, got %d.", *initialize_t_slacks); exit(1); } opts->initialize_t_slacks = *initialize_t_slacks; } else { ocp_nlp_opts_set(config, nlp_opts, field, value); } } return; } void ocp_nlp_sqp_opts_set_at_stage(void *config_, void *opts_, size_t stage, const char *field, void* value) { ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = (ocp_nlp_sqp_opts *) opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_opts_set_at_stage(config, nlp_opts, stage, field, value); return; } /************************************************ * memory ************************************************/ acados_size_t ocp_nlp_sqp_memory_calculate_size(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; // int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; acados_size_t size = 0; size += sizeof(ocp_nlp_sqp_memory); // nlp mem size += ocp_nlp_memory_calculate_size(config, dims, nlp_opts); // stat int stat_m = opts->max_iter+1; int stat_n = 7; if (opts->ext_qp_res) stat_n += 4; size += stat_n*stat_m*sizeof(double); size += 3*8; // align make_int_multiple_of(8, &size); return size; } void *ocp_nlp_sqp_memory_assign(void *config_, void *dims_, void *opts_, void *raw_memory) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; // ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; // ocp_nlp_dynamics_config **dynamics = config->dynamics; // ocp_nlp_cost_config **cost = config->cost; // ocp_nlp_constraints_config **constraints = config->constraints; char *c_ptr = (char *) raw_memory; // int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; // initial align align_char_to(8, &c_ptr); ocp_nlp_sqp_memory *mem = (ocp_nlp_sqp_memory *) c_ptr; c_ptr += sizeof(ocp_nlp_sqp_memory); align_char_to(8, &c_ptr); // nlp mem mem->nlp_mem = ocp_nlp_memory_assign(config, dims, nlp_opts, c_ptr); c_ptr += ocp_nlp_memory_calculate_size(config, dims, nlp_opts); // stat mem->stat = (double *) c_ptr; mem->stat_m = opts->max_iter+1; mem->stat_n = 7; if (opts->ext_qp_res) mem->stat_n += 4; c_ptr += mem->stat_m*mem->stat_n*sizeof(double); mem->status = ACADOS_READY; align_char_to(8, &c_ptr); assert((char *) raw_memory + ocp_nlp_sqp_memory_calculate_size(config, dims, opts) >= c_ptr); return mem; } /************************************************ * workspace ************************************************/ acados_size_t ocp_nlp_sqp_workspace_calculate_size(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; acados_size_t size = 0; // sqp size += sizeof(ocp_nlp_sqp_workspace); // nlp size += ocp_nlp_workspace_calculate_size(config, dims, nlp_opts); // tmp qp in size += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // tmp qp out size += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); if (opts->ext_qp_res) { // qp res size += ocp_qp_res_calculate_size(dims->qp_solver->orig_dims); // qp res ws size += ocp_qp_res_workspace_calculate_size(dims->qp_solver->orig_dims); } return size; } static void ocp_nlp_sqp_cast_workspace(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_sqp_opts *opts, ocp_nlp_sqp_memory *mem, ocp_nlp_sqp_workspace *work) { ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_memory *nlp_mem = mem->nlp_mem; // sqp char *c_ptr = (char *) work; c_ptr += sizeof(ocp_nlp_sqp_workspace); // nlp work->nlp_work = ocp_nlp_workspace_assign(config, dims, nlp_opts, nlp_mem, c_ptr); c_ptr += ocp_nlp_workspace_calculate_size(config, dims, nlp_opts); // tmp qp in work->tmp_qp_in = ocp_qp_in_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // tmp qp out work->tmp_qp_out = ocp_qp_out_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); if (opts->ext_qp_res) { // qp res work->qp_res = ocp_qp_res_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_res_calculate_size(dims->qp_solver->orig_dims); // qp res ws work->qp_res_ws = ocp_qp_res_workspace_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_res_workspace_calculate_size(dims->qp_solver->orig_dims); } assert((char *) work + ocp_nlp_sqp_workspace_calculate_size(config, dims, opts) >= c_ptr); return; } /************************************************ * functions ************************************************/ int ocp_nlp_sqp(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { acados_timer timer0, timer1; acados_tic(&timer0); ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_sqp_memory *mem = mem_; ocp_nlp_in *nlp_in = nlp_in_; ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_res *nlp_res = nlp_mem->nlp_res; ocp_nlp_sqp_workspace *work = work_; ocp_nlp_sqp_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; ocp_qp_in *qp_in = nlp_mem->qp_in; ocp_qp_out *qp_out = nlp_mem->qp_out; // zero timers double tmp_time; mem->time_qp_sol = 0.0; mem->time_qp_solver_call = 0.0; mem->time_qp_xcond = 0.0; mem->time_lin = 0.0; mem->time_reg = 0.0; mem->time_glob = 0.0; mem->time_sim = 0.0; mem->time_sim_la = 0.0; mem->time_sim_ad = 0.0; int N = dims->N; int ii, qp_status; int qp_iter = 0; double alpha; #if defined(ACADOS_WITH_OPENMP) // backup number of threads int num_threads_bkp = omp_get_num_threads(); // set number of threads omp_set_num_threads(opts->nlp_opts->num_threads); #endif ocp_nlp_alias_memory_to_submodules(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // if (opts->initialize_t_slacks > 0) ocp_nlp_initialize_t_slacks(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // initialize QP ocp_nlp_initialize_submodules(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // main sqp loop int sqp_iter = 0; nlp_mem->sqp_iter = &sqp_iter; for (; sqp_iter < opts->max_iter; sqp_iter++) { // linearizate NLP and update QP matrices acados_tic(&timer1); ocp_nlp_approximate_qp_matrices(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); mem->time_lin += acados_toc(&timer1); #ifdef MEASURE_TIMINGS // get timings from integrator for (ii=0; ii<N; ii++) { config->dynamics[ii]->memory_get(config->dynamics[ii], dims->dynamics[ii], mem->nlp_mem->dynamics[ii], "time_sim", &tmp_time); mem->time_sim += tmp_time; config->dynamics[ii]->memory_get(config->dynamics[ii], dims->dynamics[ii], mem->nlp_mem->dynamics[ii], "time_sim_la", &tmp_time); mem->time_sim_la += tmp_time; config->dynamics[ii]->memory_get(config->dynamics[ii], dims->dynamics[ii], mem->nlp_mem->dynamics[ii], "time_sim_ad", &tmp_time); mem->time_sim_ad += tmp_time; } #endif // MEASURE_TIMINGS // update QP rhs for SQP (step prim var, abs dual var) ocp_nlp_approximate_qp_vectors_sqp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // compute nlp residuals ocp_nlp_res_compute(dims, nlp_in, nlp_out, nlp_res, nlp_mem); ocp_nlp_res_get_inf_norm(nlp_res, &nlp_out->inf_norm_res); if (nlp_opts->print_level > sqp_iter + 1) { printf("\n\nSQP: ocp_qp_in at iteration %d\n", sqp_iter); print_ocp_qp_in(qp_in); } // save statistics if (sqp_iter < mem->stat_m) { mem->stat[mem->stat_n*sqp_iter+0] = nlp_res->inf_norm_res_stat; mem->stat[mem->stat_n*sqp_iter+1] = nlp_res->inf_norm_res_eq; mem->stat[mem->stat_n*sqp_iter+2] = nlp_res->inf_norm_res_ineq; mem->stat[mem->stat_n*sqp_iter+3] = nlp_res->inf_norm_res_comp; } // exit conditions on residuals if ((nlp_res->inf_norm_res_stat < opts->tol_stat) & (nlp_res->inf_norm_res_eq < opts->tol_eq) & (nlp_res->inf_norm_res_ineq < opts->tol_ineq) & (nlp_res->inf_norm_res_comp < opts->tol_comp)) { #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif mem->status = ACADOS_SUCCESS; mem->sqp_iter = sqp_iter; mem->time_tot = acados_toc(&timer0); if (nlp_opts->print_level > 0) { printf("%i\t%e\t%e\t%e\t%e\t%d\t%d\t%e\n", sqp_iter, nlp_res->inf_norm_res_stat, nlp_res->inf_norm_res_eq, nlp_res->inf_norm_res_ineq, nlp_res->inf_norm_res_comp, qp_status, qp_iter, alpha); printf("\n\n"); } return mem->status; } // check for nans else if (isnan(nlp_res->inf_norm_res_stat) || isnan(nlp_res->inf_norm_res_eq) || isnan(nlp_res->inf_norm_res_ineq) || isnan(nlp_res->inf_norm_res_comp)) { #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif mem->status = ACADOS_FAILURE; mem->sqp_iter = sqp_iter; mem->time_tot = acados_toc(&timer0); return mem->status; } // regularize Hessian acados_tic(&timer1); config->regularize->regularize_hessian(config->regularize, dims->regularize, opts->nlp_opts->regularize, nlp_mem->regularize_mem); mem->time_reg += acados_toc(&timer1); // (typically) no warm start at first iteration if (sqp_iter == 0 && !opts->warm_start_first_qp) { int tmp_int = 0; config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "warm_start", &tmp_int); } if (0) // DEBUG printing { char filename[100]; sprintf(filename, "qp_prints/qp_in_%d.txt", sqp_iter); FILE *out_file = fopen(filename, "w"); print_ocp_qp_in_to_file(out_file, qp_in); fclose(out_file); } // solve qp acados_tic(&timer1); qp_status = qp_solver->evaluate(qp_solver, dims->qp_solver, qp_in, qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); mem->time_qp_sol += acados_toc(&timer1); qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_solver_call", &tmp_time); mem->time_qp_solver_call += tmp_time; qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_xcond", &tmp_time); mem->time_qp_xcond += tmp_time; // compute correct dual solution in case of Hessian regularization acados_tic(&timer1); config->regularize->correct_dual_sol(config->regularize, dims->regularize, opts->nlp_opts->regularize, nlp_mem->regularize_mem); mem->time_reg += acados_toc(&timer1); // restore default warm start if (sqp_iter==0) { config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "warm_start", &opts->qp_warm_start); } if (nlp_opts->print_level > sqp_iter + 1) { printf("\n\nSQP: ocp_qp_out at iteration %d\n", sqp_iter); print_ocp_qp_out(qp_out); } if (0) // DEBUG printing { char filename[100]; sprintf(filename, "qp_prints/qp_out_%d.txt", sqp_iter); FILE *out_file = fopen(filename, "w"); print_ocp_qp_out_to_file(out_file, qp_out); fclose(out_file); } // TODO move into QP solver memory ??? qp_info *qp_info_; ocp_qp_out_get(qp_out, "qp_info", &qp_info_); qp_iter = qp_info_->num_iter; // save statistics of last qp solver call if (sqp_iter+1 < mem->stat_m) { mem->stat[mem->stat_n*(sqp_iter+1)+4] = qp_status; mem->stat[mem->stat_n*(sqp_iter+1)+5] = qp_iter; } // compute external QP residuals (for debugging) if (opts->ext_qp_res) { ocp_qp_res_compute(qp_in, qp_out, work->qp_res, work->qp_res_ws); if (sqp_iter+1 < mem->stat_m) ocp_qp_res_compute_nrm_inf(work->qp_res, mem->stat+(mem->stat_n*(sqp_iter+1)+7)); } // exit conditions on QP status if ((qp_status!=ACADOS_SUCCESS) & (qp_status!=ACADOS_MAXITER)) { if (nlp_opts->print_level > 0) { printf("%i\t%e\t%e\t%e\t%e.\n", sqp_iter, nlp_res->inf_norm_res_stat, nlp_res->inf_norm_res_eq, nlp_res->inf_norm_res_ineq, nlp_res->inf_norm_res_comp ); printf("\n\n"); } // increment sqp_iter to return full statistics and improve output below. sqp_iter++; #ifndef ACADOS_SILENT printf("\nQP solver returned error status %d in SQP iteration %d, QP iteration %d.\n", qp_status, sqp_iter, qp_iter); #endif #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif if (nlp_opts->print_level > 1) { printf("\n Failed to solve the following QP:\n"); if (nlp_opts->print_level) print_ocp_qp_in(qp_in); } mem->status = ACADOS_QP_FAILURE; mem->sqp_iter = sqp_iter; mem->time_tot = acados_toc(&timer0); return mem->status; } /* globalization */ // NOTE on timings: currently all within globalization is accounted for within time_glob. // QP solver times could be also attributed there alternatively. Cleanest would be to save them seperately. acados_tic(&timer1); bool do_line_search = true; if (opts->nlp_opts->globalization_use_SOC && opts->nlp_opts->globalization == MERIT_BACKTRACKING) { // NOTE: following Waechter2006: // Do SOC // 1. if "the first trial step size alpha_k,0 has been rejected and // 2. if the infeasibility would have increased when accepting the previous step // NOTE: the "and" is interpreted as an "or" in the current implementation // preliminary line search alpha = ocp_nlp_line_search(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work, 1); if (alpha < 1.0) { // Second Order Correction (SOC): following Nocedal2006: p.557, eq. (18.51) -- (18.56) // Paragraph: APPROACH III: S l1 QP (SEQUENTIAL l1 QUADRATIC PROGRAMMING), // Section 18.8 TRUST-REGION SQP METHODS // - just no trust region radius here. if (nlp_opts->print_level > 0) printf("ocp_nlp_sqp: performing SOC, since alpha %e in prelim. line search\n\n", alpha); int *nb = qp_in->dim->nb; int *ng = qp_in->dim->ng; int *nx = dims->nx; int *nu = dims->nu; int *ns = dims->ns; // int *nv = dims->nv; // int *ni = dims->ni; /* evaluate constraints & dynamics at new step */ // The following (setting up ux + p in tmp_nlp_out and evaluation of constraints + dynamics) // is not needed anymore because done in prelim. line search with early termination) // NOTE: similar to ocp_nlp_evaluate_merit_fun // set up new linearization point in work->tmp_nlp_out // for (ii = 0; ii < N; ii++) // blasfeo_dveccp(nx[ii+1], nlp_out->pi+ii, 0, work->nlp_work->tmp_nlp_out->pi+ii, 0); // for (ii = 0; ii <= N; ii++) // blasfeo_dveccp(2*ni[ii], nlp_out->lam+ii, 0, work->nlp_work->tmp_nlp_out->lam+ii, 0); // // tmp_nlp_out = iterate + step // for (ii = 0; ii <= N; ii++) // blasfeo_daxpy(nv[ii], 1.0, qp_out->ux+ii, 0, nlp_out->ux+ii, 0, work->nlp_work->tmp_nlp_out->ux+ii, 0); // // evaluate // #if defined(ACADOS_WITH_OPENMP) // #pragma omp parallel for // #endif // for (ii=0; ii<N; ii++) // { // config->dynamics[ii]->compute_fun(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], // nlp_opts->dynamics[ii], nlp_mem->dynamics[ii], work->nlp_work->dynamics[ii]); // } // #if defined(ACADOS_WITH_OPENMP) // #pragma omp parallel for // #endif // for (ii=0; ii<=N; ii++) // { // config->constraints[ii]->compute_fun(config->constraints[ii], dims->constraints[ii], // nlp_in->constraints[ii], nlp_opts->constraints[ii], // nlp_mem->constraints[ii], work->nlp_work->constraints[ii]); // } // #if defined(ACADOS_WITH_OPENMP) // #pragma omp parallel for // #endif // update QP rhs // d_i = c_i(x_k + p_k) - \nabla c_i(x_k)^T * p_k struct blasfeo_dvec *tmp_fun_vec; for (ii = 0; ii <= N; ii++) { if (ii < N) { // b -- dynamics tmp_fun_vec = config->dynamics[ii]->memory_get_fun_ptr(nlp_mem->dynamics[ii]); // add - \nabla c_i(x_k)^T * p_k // c_i = f(x_k, u_k) - x_{k+1} (see dynamics module) blasfeo_dgemv_t(nx[ii]+nu[ii], nx[ii+1], -1.0, qp_in->BAbt+ii, 0, 0, qp_out->ux+ii, 0, -1.0, tmp_fun_vec, 0, qp_in->b+ii, 0); // NOTE: not sure why it is - tmp_fun_vec here! blasfeo_dvecad(nx[ii+1], 1.0, qp_out->ux+ii+1, nu[ii+1], qp_in->b+ii, 0); } /* INEQUALITIES */ // d -- constraints tmp_fun_vec = config->constraints[ii]->memory_get_fun_ptr(nlp_mem->constraints[ii]); /* SOC for bounds can be skipped (because linear) */ // NOTE: SOC can also be skipped for truely linear constraint, i.e. ng of nlp, now using ng of QP = (nh+ng) // upper & lower blasfeo_dveccp(ng[ii], tmp_fun_vec, nb[ii], qp_in->d+ii, nb[ii]); // lg blasfeo_dveccp(ng[ii], tmp_fun_vec, 2*nb[ii]+ng[ii], qp_in->d+ii, 2*nb[ii]+ng[ii]); // ug // general linear / linearized! // tmp_ni = D * u + C * x blasfeo_dgemv_t(nu[ii]+nx[ii], ng[ii], 1.0, qp_in->DCt+ii, 0, 0, qp_out->ux+ii, 0, 0.0, &work->nlp_work->tmp_ni, 0, &work->nlp_work->tmp_ni, 0); // d[nb:nb+ng] += tmp_ni (lower) blasfeo_dvecad(ng[ii], 1.0, &work->nlp_work->tmp_ni, 0, qp_in->d+ii, nb[ii]); // d[nb:nb+ng] -= tmp_ni blasfeo_dvecad(ng[ii], -1.0, &work->nlp_work->tmp_ni, 0, qp_in->d+ii, 2*nb[ii]+ng[ii]); // add slack contributions // d[nb:nb+ng] += slack[idx] // qp_in->idxs_rev for (int j = 0; j < nb[ii]+ng[ii]; j++) { int slack_index = qp_in->idxs_rev[ii][j]; if (slack_index >= 0) { // add slack contribution for lower and upper constraint // lower BLASFEO_DVECEL(qp_in->d+ii, j) -= BLASFEO_DVECEL(qp_out->ux+ii, slack_index+nx[ii]+nu[ii]); // upper BLASFEO_DVECEL(qp_in->d+ii, j+nb[ii]+ng[ii]) -= BLASFEO_DVECEL(qp_out->ux+ii, slack_index+nx[ii]+nu[ii]+ns[ii]); } } // NOTE: bounds on slacks can be skipped, since they are linear. // blasfeo_daxpy(2*ns[ii], -1.0, qp_out->ux+ii, nx[ii]+nu[ii], qp_in->d+ii, 2*nb[ii]+2*ng[ii], qp_in->d+ii, 2*nb[ii]+2*ng[ii]); // printf("SOC: qp_in->d final value\n"); // blasfeo_print_exp_dvec(2*nb[ii]+2*ng[ii], qp_in->d+ii, 0); } if (nlp_opts->print_level > sqp_iter + 1) { printf("\n\nSQP: SOC ocp_qp_in at iteration %d\n", sqp_iter); print_ocp_qp_in(qp_in); } if (0) // DEBUG printing { char filename[100]; sprintf(filename, "qp_prints/qp_in_%d_SOC.txt", sqp_iter); FILE *out_file = fopen(filename, "w"); print_ocp_qp_in_to_file(out_file, qp_in); fclose(out_file); } // solve QP // acados_tic(&timer1); qp_status = qp_solver->evaluate(qp_solver, dims->qp_solver, qp_in, qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); // tmp_time = acados_toc(&timer1); // mem->time_qp_sol += tmp_time; // qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_solver_call", &tmp_time); // mem->time_qp_solver_call += tmp_time; // qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_xcond", &tmp_time); // mem->time_qp_xcond += tmp_time; // compute correct dual solution in case of Hessian regularization // acados_tic(&timer1); config->regularize->correct_dual_sol(config->regularize, dims->regularize, opts->nlp_opts->regularize, nlp_mem->regularize_mem); // mem->time_reg += acados_toc(&timer1); ocp_qp_out_get(qp_out, "qp_info", &qp_info_); qp_iter = qp_info_->num_iter; // save statistics of last qp solver call // TODO: SOC QP solver call should be warm / hot started! if (sqp_iter+1 < mem->stat_m) { // mem->stat[mem->stat_n*(sqp_iter+1)+4] = qp_status; // add qp_iter; should maybe be in a seperate statistic mem->stat[mem->stat_n*(sqp_iter+1)+5] += qp_iter; } // compute external QP residuals (for debugging) if (opts->ext_qp_res) { ocp_qp_res_compute(qp_in, qp_out, work->qp_res, work->qp_res_ws); if (sqp_iter+1 < mem->stat_m) ocp_qp_res_compute_nrm_inf(work->qp_res, mem->stat+(mem->stat_n*(sqp_iter+1)+7)); } if (nlp_opts->print_level > sqp_iter + 1) { printf("\n\nSQP: SOC ocp_qp_out at iteration %d\n", sqp_iter); print_ocp_qp_out(qp_out); } if (0) // DEBUG printing { char filename[100]; sprintf(filename, "qp_prints/qp_out_%d_SOC.txt", sqp_iter); FILE *out_file = fopen(filename, "w"); print_ocp_qp_out_to_file(out_file, qp_out); fclose(out_file); } // exit conditions on QP status if ((qp_status!=ACADOS_SUCCESS) & (qp_status!=ACADOS_MAXITER)) { #ifndef ACADOS_SILENT printf("\nQP solver returned error status %d in SQP iteration %d for SOC QP in QP iteration %d.\n", qp_status, sqp_iter, qp_iter); #endif #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif if (nlp_opts->print_level > 1) { printf("\nFailed to solve the following QP:\n"); if (nlp_opts->print_level > sqp_iter + 1) print_ocp_qp_in(qp_in); } mem->status = ACADOS_QP_FAILURE; mem->sqp_iter = sqp_iter; mem->time_tot = acados_toc(&timer0); return mem->status; } } // if alpha prelim. line search < 1.0 else { do_line_search = false; } } if (do_line_search) { alpha = ocp_nlp_line_search(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work, 0); } mem->time_glob += acados_toc(&timer1); mem->stat[mem->stat_n*(sqp_iter+1)+6] = alpha; // update variables ocp_nlp_update_variables_sqp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work, alpha); if (nlp_opts->print_level > 0) { if (sqp_iter%10 == 0) { printf("# it\tstat\t\teq\t\tineq\t\tcomp\t\tqp_stat\tqp_iter\talpha\n"); } printf("%i\t%e\t%e\t%e\t%e\t%d\t%d\t%e\n", sqp_iter, nlp_res->inf_norm_res_stat, nlp_res->inf_norm_res_eq, nlp_res->inf_norm_res_ineq, nlp_res->inf_norm_res_comp, qp_status, qp_iter, alpha); } } // end SQP loop if (nlp_opts->print_level > 0) printf("\n\n"); // ocp_nlp_out_print(dims, nlp_out); // maximum number of iterations reached #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif mem->status = ACADOS_MAXITER; mem->sqp_iter = sqp_iter; mem->time_tot = acados_toc(&timer0); #ifndef ACADOS_SILENT printf("\n ocp_nlp_sqp: maximum iterations reached\n"); #endif return mem->status; } void ocp_nlp_sqp_memory_reset_qp_solver(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_sqp_memory *mem = mem_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_nlp_dims *dims = dims_; ocp_nlp_sqp_workspace *work = work_; ocp_nlp_workspace *nlp_work = work->nlp_work; // printf("in ocp_nlp_sqp_memory_reset_qp_solver\n\n"); config->qp_solver->memory_reset(qp_solver, dims->qp_solver, nlp_mem->qp_in, nlp_mem->qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); } int ocp_nlp_sqp_precompute(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_sqp_memory *mem = mem_; ocp_nlp_in *nlp_in = nlp_in_; // ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_nlp_sqp_workspace *work = work_; ocp_nlp_sqp_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; int N = dims->N; int status = ACADOS_SUCCESS; int ii; // TODO(all) add flag to enable/disable checks for (ii = 0; ii <= N; ii++) { int module_val; config->constraints[ii]->dims_get(config->constraints[ii], dims->constraints[ii], "ns", &module_val); if (dims->ns[ii] != module_val) { printf("ocp_nlp_sqp_precompute: inconsistent dimension ns for stage %d with constraint module, got %d, module: %d.", ii, dims->ns[ii], module_val); exit(1); } } // precompute for (ii = 0; ii < N; ii++) { // set T config->dynamics[ii]->model_set(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], "T", nlp_in->Ts+ii); // dynamics precompute status = config->dynamics[ii]->precompute(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], opts->nlp_opts->dynamics[ii], nlp_mem->dynamics[ii], nlp_work->dynamics[ii]); if (status != ACADOS_SUCCESS) return status; } return status; } void ocp_nlp_sqp_eval_param_sens(void *config_, void *dims_, void *opts_, void *mem_, void *work_, char *field, int stage, int index, void *sens_nlp_out_) { acados_timer timer0; acados_tic(&timer0); ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; ocp_nlp_sqp_memory *mem = mem_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_nlp_out *sens_nlp_out = sens_nlp_out_; ocp_nlp_sqp_workspace *work = work_; ocp_nlp_sqp_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; d_ocp_qp_copy_all(nlp_mem->qp_in, work->tmp_qp_in); d_ocp_qp_set_rhs_zero(work->tmp_qp_in); double one = 1.0; if ((!strcmp("ex", field)) & (stage==0)) { d_ocp_qp_set_el("lbx", stage, index, &one, work->tmp_qp_in); d_ocp_qp_set_el("ubx", stage, index, &one, work->tmp_qp_in); // d_ocp_qp_print(work->tmp_qp_in->dim, work->tmp_qp_in); config->qp_solver->eval_sens(config->qp_solver, dims->qp_solver, work->tmp_qp_in, work->tmp_qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); // d_ocp_qp_sol_print(work->tmp_qp_out->dim, work->tmp_qp_out); // exit(1); /* copy tmp_qp_out into sens_nlp_out */ int i; int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; // int *nz = dims->nz; for (i = 0; i <= N; i++) { blasfeo_dveccp(nv[i], work->tmp_qp_out->ux + i, 0, sens_nlp_out->ux + i, 0); if (i < N) blasfeo_dveccp(nx[i + 1], work->tmp_qp_out->pi + i, 0, sens_nlp_out->pi + i, 0); blasfeo_dveccp(2 * ni[i], work->tmp_qp_out->lam + i, 0, sens_nlp_out->lam + i, 0); blasfeo_dveccp(2 * ni[i], work->tmp_qp_out->t + i, 0, sens_nlp_out->t + i, 0); } } else { printf("\nerror: field %s at stage %d not available in ocp_nlp_sqp_eval_param_sens\n", field, stage); exit(1); } mem->time_solution_sensitivities = acados_toc(&timer0); return; } // TODO rename memory_get ??? void ocp_nlp_sqp_get(void *config_, void *dims_, void *mem_, const char *field, void *return_value_) { ocp_nlp_config *config = config_; ocp_nlp_dims *dims = dims_; ocp_nlp_sqp_memory *mem = mem_; if (!strcmp("sqp_iter", field)) { int *value = return_value_; *value = mem->sqp_iter; } else if (!strcmp("status", field)) { int *value = return_value_; *value = mem->status; } else if (!strcmp("time_tot", field) || !strcmp("tot_time", field)) { double *value = return_value_; *value = mem->time_tot; } else if (!strcmp("time_qp_sol", field) || !strcmp("time_qp", field)) { double *value = return_value_; *value = mem->time_qp_sol; } else if (!strcmp("time_qp_solver", field) || !strcmp("time_qp_solver_call", field)) { double *value = return_value_; *value = mem->time_qp_solver_call; } else if (!strcmp("time_qp_xcond", field)) { double *value = return_value_; *value = mem->time_qp_xcond; } else if (!strcmp("time_lin", field)) { double *value = return_value_; *value = mem->time_lin; } else if (!strcmp("time_reg", field)) { double *value = return_value_; *value = mem->time_reg; } else if (!strcmp("time_glob", field)) { double *value = return_value_; *value = mem->time_glob; } else if (!strcmp("time_solution_sensitivities", field)) { double *value = return_value_; *value = mem->time_solution_sensitivities; } else if (!strcmp("time_sim", field)) { double *value = return_value_; *value = mem->time_sim; } else if (!strcmp("time_sim_la", field)) { double *value = return_value_; *value = mem->time_sim_la; } else if (!strcmp("time_sim_ad", field)) { double *value = return_value_; *value = mem->time_sim_ad; } else if (!strcmp("stat", field)) { double **value = return_value_; *value = mem->stat; } else if (!strcmp("statistics", field)) { int n_row = mem->stat_m<mem->sqp_iter+1 ? mem->stat_m : mem->sqp_iter+1; double *value = return_value_; for (int ii=0; ii<n_row; ii++) { value[ii+0] = ii; for (int jj=0; jj<mem->stat_n; jj++) value[ii+(jj+1)*n_row] = mem->stat[jj+ii*mem->stat_n]; } } else if (!strcmp("stat_m", field)) { int *value = return_value_; *value = mem->stat_m; } else if (!strcmp("stat_n", field)) { int *value = return_value_; *value = mem->stat_n; } else if (!strcmp("nlp_mem", field)) { void **value = return_value_; *value = mem->nlp_mem; } else if (!strcmp("qp_xcond_dims", field)) { void **value = return_value_; *value = dims->qp_solver->xcond_dims; } else if (!strcmp("nlp_res", field)) { ocp_nlp_res **value = return_value_; *value = mem->nlp_mem->nlp_res; } else if (!strcmp("qp_xcond_in", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_solver_mem->xcond_qp_in; } else if (!strcmp("qp_xcond_out", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_solver_mem->xcond_qp_out; } else if (!strcmp("qp_in", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_in; } else if (!strcmp("qp_out", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_out; } else if (!strcmp("qp_iter", field)) { config->qp_solver->memory_get(config->qp_solver, mem->nlp_mem->qp_solver_mem, "iter", return_value_); } else if (!strcmp("qp_status", field)) { config->qp_solver->memory_get(config->qp_solver, mem->nlp_mem->qp_solver_mem, "status", return_value_); } else if (!strcmp("res_stat", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_stat; } else if (!strcmp("res_eq", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_eq; } else if (!strcmp("res_ineq", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_ineq; } else if (!strcmp("res_comp", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_comp; } else if (!strcmp("cost_value", field)) { double *value = return_value_; *value = mem->nlp_mem->cost_value; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_get\n", field); exit(1); } } void ocp_nlp_sqp_opts_get(void *config_, void *dims_, void *opts_, const char *field, void *return_value_) { // ocp_nlp_config *config = config_; ocp_nlp_sqp_opts *opts = opts_; if (!strcmp("nlp_opts", field)) { void **value = return_value_; *value = opts->nlp_opts; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_opts_get\n", field); exit(1); } } void ocp_nlp_sqp_work_get(void *config_, void *dims_, void *work_, const char *field, void *return_value_) { // ocp_nlp_config *config = config_; ocp_nlp_sqp_workspace *work = work_; if (!strcmp("nlp_work", field)) { void **value = return_value_; *value = work->nlp_work; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_work_get\n", field); exit(1); } } void ocp_nlp_sqp_config_initialize_default(void *config_) { ocp_nlp_config *config = (ocp_nlp_config *) config_; config->opts_calculate_size = &ocp_nlp_sqp_opts_calculate_size; config->opts_assign = &ocp_nlp_sqp_opts_assign; config->opts_initialize_default = &ocp_nlp_sqp_opts_initialize_default; config->opts_update = &ocp_nlp_sqp_opts_update; config->opts_set = &ocp_nlp_sqp_opts_set; config->opts_set_at_stage = &ocp_nlp_sqp_opts_set_at_stage; config->memory_calculate_size = &ocp_nlp_sqp_memory_calculate_size; config->memory_assign = &ocp_nlp_sqp_memory_assign; config->workspace_calculate_size = &ocp_nlp_sqp_workspace_calculate_size; config->evaluate = &ocp_nlp_sqp; config->memory_reset_qp_solver = &ocp_nlp_sqp_memory_reset_qp_solver; config->eval_param_sens = &ocp_nlp_sqp_eval_param_sens; config->config_initialize_default = &ocp_nlp_sqp_config_initialize_default; config->precompute = &ocp_nlp_sqp_precompute; config->get = &ocp_nlp_sqp_get; config->opts_get = &ocp_nlp_sqp_opts_get; config->work_get = &ocp_nlp_sqp_work_get; return; } // ??? @rien // for (int_t i = 0; i < N; i++) // { // ocp_nlp_dynamics_opts *dynamics_opts = opts->dynamics[i]; // sim_opts *opts = dynamics_opts->sim_solver; // if (opts->scheme == NULL) // continue; // opts->sens_adj = (opts->scheme->type != exact); // if (nlp_in->freezeSens) { // // freeze inexact sensitivities after first SQP iteration !! // opts->scheme->freeze = true; // } // }
fig6.22-overlap-comp-io.c
/* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. Copyright 2009 Sun Microsystems, Inc. All rights reserved. The contents of this file are subject to the terms of the BSD License("BSD")(the "License"). You can obtain a copy of the License at: http://www.opensparc.net/pubs/t1/licenses/BSD+_License.txt The BSD License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistribution of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistribution 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 Sun Microsystems, Inc. or the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. You acknowledge that this software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <float.h> #include <malloc.h> #include <unistd.h> #include <time.h> #define TRUE 1 #define FALSE 0 #define FABS(x) (x < 0 ? -x : x) #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int DefValN = 6; int DefValM = 10; char file_read[] = "fig6.22-file-io.bin"; enum STATUS {UNDEFINED, READ_IN_PROGRESS, READ_FINISHED, PROCESSING_IN_PROGRESS, PROCESSING_FINISHED} *execution_state; void read_input(int i); void signal_read(int i); void wait_read(int i); void process_data(int i); void signal_processed(int i); void wait_processed(int i); void write_output(int i); void do_compute(int i,int j); void get_cmd_line_options(int, char **); void init_memory(); void init_data(); void generate_input_file(); void compute_reference_results(); void print_header(); int check_results(); void print_state_array(int, char *, int); double *a, *b, **c, **ref; FILE *fp_write; int verbose; int N, M; int main(int argc, char **argv) { int error_count; /* ------------------------------------------------------------ This program runs fine using one thread, but if we do execute in parallel, at least 3 threads are needed. ------------------------------------------------------------ */ #ifdef _OPENMP int thread_count_error; (void) omp_set_dynamic(FALSE); if (omp_get_dynamic()) {printf("Warning: dynamic adjustment of threads has been set\n");} (void) omp_set_num_threads(3); (void) omp_set_nested(TRUE); if (! omp_get_nested()) {printf("Warning: nested parallelism not set\n");} #pragma omp parallel shared(thread_count_error) { #pragma omp single { if ( omp_get_num_threads() < 3 ) { printf("Fatal error - At least 3 threads are needed, but only %d available\n", omp_get_num_threads()); thread_count_error = TRUE; } else { thread_count_error = FALSE; } } } /*-- End of parallel region --*/ if ( thread_count_error == TRUE ) return(-1); #endif /* ------------------------------------------------------------ Initial, serial, phase. Get the command line options, allocate memory, initialize data, generate input file and print the header. ------------------------------------------------------------ */ (void) get_cmd_line_options(argc,argv); if (verbose) printf("Allocating memory for data structures\n"); (void) init_memory(); if (verbose) printf("Memory for data structures allocated\n"); if (verbose) printf("Initializing data structures\n"); (void) init_data(); if (verbose) printf("Data structures initialized\n"); (void) generate_input_file(); (void) compute_reference_results(); (void) print_header(); /* ------------------------------------------------------------ This implements the pipeline, overlapping I/O and computations. Each section block handles a specific phase. ------------------------------------------------------------ */ #pragma omp parallel sections { #pragma omp section { if (verbose) printf("TID = %d - in main: performs the read operations\n",omp_get_thread_num()); for (int i=0; i<N; i++) { (void) read_input(i); (void) signal_read(i); } } #pragma omp section { if (verbose) printf("TID = %d - in main: performs the computations\n",omp_get_thread_num()); for (int i=0; i<N; i++) { (void) wait_read(i); (void) process_data(i); (void) signal_processed(i); } } #pragma omp section { if (verbose) printf("TID = %d - in main: performs the write operations\n",omp_get_thread_num()); for (int i=0; i<N; i++) { (void) wait_processed(i); (void) write_output(i); } } } /*-- End of parallel sections --*/ if ( (error_count = check_results()) == 0 ) { printf("Program executed successfully\n"); } else { printf("FATAL ERROR: found %d differences in the result(s)\n",error_count); } free(a); free(b); free(c); free(ref); free(execution_state); return(0); } /*-- End of main program --*/ void read_input(int i) { FILE *fp_read; execution_state[i] = READ_IN_PROGRESS; #pragma omp flush print_state_array(omp_get_thread_num(),"read_input",i); /* ------------------------------------------------------------ Note that this is clumsy by design in order to get some time spent in the I/O part. ------------------------------------------------------------ */ if ( (fp_read = fopen(file_read,"r")) != NULL ) { if ( fseek(fp_read,(long) i*2*sizeof(double), SEEK_SET) == 0 ) { if ( fread(&a[i],sizeof(double),1,fp_read) != 1 ) { perror("read_input: array a"); exit(1); } if ( fread(&b[i],sizeof(double),1,fp_read) != 1 ) { perror("read_input: array b"); exit(1); } if (verbose) { printf("TID = %d - in read_input: a[%d]=%f b[%d]=%f\n", omp_get_thread_num(),i,a[i],i,b[i]); } } else { perror("read_input: seek error"); exit(1); } fclose(fp_read); } else { perror("read_input: open file for read"); } } /*-- End of read_input --*/ void signal_read(int i) { print_state_array(omp_get_thread_num(),"signal_read",i); execution_state[i] = READ_FINISHED; #pragma omp flush print_state_array(omp_get_thread_num(),"signal_read",i); } /*-- End of signal_read --*/ void wait_read(int i) { print_state_array(omp_get_thread_num(),"wait_read",i); #pragma omp flush while ( execution_state[i] != READ_FINISHED ) { print_state_array(omp_get_thread_num(),"wait_read",i); system("sleep 1"); #pragma omp flush } print_state_array(omp_get_thread_num(),"wait_read",i); } /*-- End of wait_read --*/ void process_data(int i) { int TID_LVL_1 = omp_get_thread_num(); execution_state[i] = PROCESSING_IN_PROGRESS; #pragma omp flush print_state_array(TID_LVL_1,"process_data",i); #pragma omp parallel for num_threads(4) for (int j=0 ; j<M; j++) { if (verbose) printf("TID:subTID = %d:%d - in process_data: iteration j=%d\n", TID_LVL_1,omp_get_thread_num(),j); do_compute(i,j); } } /*-- End of process_data --*/ void do_compute(int i,int j) { c[i][j] += a[i] + b[i]; if (verbose) { printf("\tin do_compute: updated c[%d][%d]\n",i,j); } } /*-- End of do_compute --*/ void signal_processed(int i) { execution_state[i] = PROCESSING_FINISHED; #pragma omp flush print_state_array(omp_get_thread_num(),"signal_processed",i); } /*-- End of signal_processed --*/ void wait_processed(int i) { print_state_array(omp_get_thread_num(),"wait_processed",i); #pragma omp flush while ( execution_state[i] != PROCESSING_FINISHED ) { print_state_array(omp_get_thread_num(),"wait_processed",i); system("sleep 1"); #pragma omp flush } print_state_array(omp_get_thread_num(),"wait_processed",i); } /*-- End of wait_processed --*/ void write_output(int i) { int CutOffPrint = 9; /*-- Limits number of values printed --*/ print_state_array(omp_get_thread_num(),"write_output",i); if (verbose) { printf("TID = %d - in write_output: i=%d\n",omp_get_thread_num(),i); printf("\tc[%d][]: ",i); if ( M < CutOffPrint ) { for (int j=0; j<M; j++) printf("%.2f ",c[i][j]); } else { for (int j=0; j<CutOffPrint; j++) printf("%.2f ",c[i][j]); printf("... %.2f ",c[i][M-1]); } printf("\n"); } } /*-- End of write_output --*/ void generate_input_file() { if ( (fp_write = fopen(file_read,"w")) != NULL ) { for(int i=0; i<N; i++) { fwrite(&a[i],sizeof(double),1,fp_write); fwrite(&b[i],sizeof(double),1,fp_write); } fclose(fp_write); } else { perror("generate_input_file: open file for write"); exit(1); } } /*-- End of generate_input --*/ void compute_reference_results() { for (int i=0; i<N; i++) for (int j=0; j<M; j++) ref[i][j] = 0.0; for (int i=0; i<N; i++) for (int j=0; j<M; j++) ref[i][j] += a[i] + b[i]; } /*-- End of compute_reference_results --*/ int check_results() { double rel_error; double TOL = DBL_EPSILON*10.0; int error_count = 0; for (int i=0; i<N; i++) for (int j=0; j<M; j++) { if (FABS(ref[i][j]) > DBL_MAX) rel_error = FABS( (c[i][j] - ref[i][j])/ref[i][j] ); else rel_error = FABS( c[i][j] - ref[i][j] ); if (rel_error > TOL ) { error_count++; printf("c[%d][%d] = %f ref[%d][%d] = %f rel. error = %e\n", i,j,c[i][j],i,j,ref[i][j],rel_error); } } return(error_count); } /*-- End of check_results --*/ void init_memory() { if ( (a = (double *) malloc(N*sizeof(double))) == NULL ) { perror("init_memory: memory allocation failure for a"); exit(1); } else { if (verbose) printf("\tAllocated memory for a\n"); } if ( (b = (double *) malloc(N*sizeof(double))) == NULL ) { perror("init_memory: memory allocation failure for b"); exit(1); } else { if (verbose) printf("\tAllocated memory for b\n"); } if ( (c = (double **) malloc(N*sizeof(double))) == NULL ) { perror("init_memory: memory allocation failure for c"); exit(1); } else { for (int i=0; i<N; i++) if ( (c[i] = malloc(M*sizeof(double))) == NULL ) { perror("init_memory: memory allocation failure for c"); exit(1); } } if (verbose) printf("\tAllocated memory for c\n"); if ( (ref = (double **) malloc(N*sizeof(double))) == NULL ) { perror("init_memory: memory allocation failure for ref"); exit(1); } else { for (int i=0; i<N; i++) if ( (ref[i] = malloc(M*sizeof(double))) == NULL ) { perror("init_memory: memory allocation failure for ref"); exit(1); } } if (verbose) printf("\tAllocated memory for ref\n"); if ( (execution_state = malloc(N*sizeof(int))) == NULL ) { perror("init_memory: memory allocation failure for execution_state"); exit(1); } else { if (verbose) printf("\tAllocated memory for execution_state\n"); } } /*-- End of init_memory --*/ void init_data() { for (int i=0; i<N; i++) a[i] = i+1; for (int i=0; i<N; i++) b[i] = a[N-1] + i+1; for (int i=0; i<N; i++) for (int j=0; j<M; j++) c[i][j] = 0.0; for (int i=0; i<N; i++) execution_state[i] = UNDEFINED; #pragma omp flush } /*-- End of init_data --*/ void get_cmd_line_options(int argc, char **argv) { char optstring[]="N:M:hv"; int c; extern char *optarg; extern int opterr; N = DefValN; M = DefValM; verbose = FALSE; if ( argc > 1 ) { opterr = 0; while ((c = getopt(argc, argv, optstring)) != EOF) { switch (c) { case 'N': N = atoi(optarg); break; case 'M': M = atoi(optarg); break; case 'v': verbose = TRUE; break; case 'h': printf("Usage:%s [-N <n>] [-M <m>] [-v] [-h]\n\n",argv[0]); printf("Options supported:\n"); printf(" <N> problem size (optional - default is %d)\n",DefValN); printf(" <M> problem size (optional - default is %d)\n",DefValM); printf(" <v> activates verbose mode (optional- by default it is off)\n"); printf(" <h> display this usage overview\n"); exit(0); break; case '?': printf("Warning: incomplete or incorrect option(s) ignored\n"); break; } /*-- End of switch over options --*/ } /*-- End of while --*/ } /*-- End of if over argc --*/ if (verbose) printf("N=%d M=%d\n",N,M); return; } /*-- End of get_cmd_line_options --*/ void print_state_array(int TID, char *name, int i) { static int first = TRUE; #pragma omp critical { if (first) { first = FALSE; #pragma omp flush printf("Thread ID Function Execution Status Array\n"); printf(" Value of i:"); for (int j=0; j<N; j++) printf("%3d",j); printf("\n\n"); } printf("%6d %-20s",TID,name); if ( i >= 0 ) { for (int j=0; j<i; j++) { #pragma omp flush printf(" %2d",execution_state[j]); } #pragma omp flush printf(" *%1d",execution_state[i]); } for (int j=i+1; j<N; j++) { #pragma omp flush printf(" %2d",execution_state[j]); } printf("\n"); } /*-- End of critical section --*/ return; } /*-- End of print_state_array --*/ void print_header() { printf("This program demonstrates how I/O can be overlapped with computations.\n"); printf("Several options are supported. Use the -h option for an overview.\n"); printf("\n"); printf("There are 3 distinct phases. Each phase is assigned to a different thread.\n"); printf("Correct execution is independent of the assignment of a phase to a specific thread.\n"); printf("\n"); printf("These are the different phases:\n"); printf("Input phase: read_input - signal_read\n"); printf("Computational phase: wait_read - process_data - signal_processed\n"); printf("Output phase: wait_processed - write_output\n"); printf("\n"); printf("The entire operation is splitted into chunks. A specific chunk is represented\n"); printf("by the value of iteration i. In total there are %d chunks\n",N); printf("\n"); printf("An internal status flag is used to pass on information between the threads\n"); printf("regarding a specific phase.\n"); printf("\n"); printf("Legend for status flag\n"); printf("\t%d - UNDEFINED\n" ,UNDEFINED); printf("\t%d - READ_IN_PROGRESS\n" ,READ_IN_PROGRESS); printf("\t%d - READ_FINISHED\n" ,READ_FINISHED); printf("\t%d - PROCESSING_IN_PROGRESS\n",PROCESSING_IN_PROGRESS); printf("\t%d - PROCESSING_FINISHED\n" ,PROCESSING_FINISHED); printf("\n"); printf("The table below displays what function a specific thread is executing,\n"); printf("as well as the value of the status flag for a values of i.\n"); printf("\n"); printf("The * symbol indicates the current value of i the function is working on\n"); printf("\n"); print_state_array(omp_get_thread_num(),"initialization",-1); } /*-- End of print_header --*/
GB_unop__atanh_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__atanh_fc64_fc64 // op(A') function: GB_unop_tran__atanh_fc64_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = catanh (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = catanh (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = catanh (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ATANH || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__atanh_fc64_fc64 ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_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++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = catanh (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__atanh_fc64_fc64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
cudaMesh.h
#ifndef CUDA_MESH_H #define CUDA_MESH_H /////////////////////////////////////////////////////////////////////////////// // // This file is a part of the PadallelFDTD Finite-Difference Time-Domain // simulation library. It is released under the MIT License. You should have // received a copy of the MIT License along with ParallelFDTD. If not, see // http://www.opensource.org/licenses/mit-license.php // // 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. // // For details, see the LICENSE file // // (C) 2013-2014 Jukka Saarelma // Aalto University School of Science // /////////////////////////////////////////////////////////////////////////////// #include "cudaUtils.h" #include <iostream> #include <stdio.h> #include <assert.h> #include <cuda.h> #include <cuda_runtime.h> #include <vector> #define INSIDE_SWITCH 7 #define FORWARD_POSITION_MASK 0X7F #define CENTERED_MASK 0x80 #define DIR_X 0x01 #define DIR_Y 0x02 #define DIR_Z 0x04 #define SIGN_X 0x10 #define SIGN_Y 0x20 #define SIGN_Z 0x40 // Forward Declaration class LongNode; class ShortNode; class Node; /////////////////////////////////////////////////////////////////////////////// /// \brief Class that handles the simulation domain. Class contains device /// pointers to different meshes which are used in the simulation. /// Different meshes are: <br> /// <i>position index mesh:</i> Contains the orientation of each node <br> /// <i>material index mesh:</i> Contains the material index of each node <br> /// <i>2 X Pressure mesh: </i>Either a single precision of double precision mesh of <br> /// pressure values for the current and past pressure values /// /////////////////////////////////////////////////////////////////////////////// class CudaMesh { public: CudaMesh() : double_(false), dif_order_(0), number_of_partitions_(0), partition_size_(0), h_material_coef_ptr_(NULL), number_of_unique_materials_(0), h_parameter_ptr_(NULL), num_elements_(0), dim_x_(0), dim_y_(0), dim_z_(0), dim_xy_(0), dx_(0), block_size_x_(0), block_size_y_(0), block_size_z_(0) {}; ~CudaMesh() {}; public: ////// Mesh bool double_; // mesh in double precision unsigned int dif_order_; // frequency depending boundaries std::vector<unsigned char*> position_idx_ptr_; std::vector<unsigned char*> material_idx_ptr_; std::vector<unsigned char*> packed_ptr_; // Different containers for the two precisions, more code // but straightforward interface with the CUDA code // optional TODO: Templating to reduce code // Single precision std::vector<float*> pressures_; std::vector<float*> pressures_past_; std::vector<float*> parameters_; std::vector<float*> materials_; // Double precision std::vector<double*> pressures_double_; std::vector<double*> pressures_past_double_; std::vector<double*> parameters_double_; std::vector<double*> materials_double_; // NEW template /* std::vector<T*> pressures_T_; std::vector<T*> pressures_past_T_; std::vector<T*> parameters_T_; std::vector<T*> materials_T_; */ // Volumetric boundaries // for now, save the whole node std::vector< Node* > nodes_; // Digital impedance filters not implemented std::vector<float*> dif_; std::vector< unsigned int > device_list_; std::vector< std::vector< unsigned int> > partition_indexing_; std::vector<unsigned int> memory_splits_; std::vector<unsigned int> number_of_partition_elements_; unsigned int number_of_partitions_; unsigned int partition_size_; /////// Materials float* h_material_coef_ptr_; ///< Material coefficient on host, not to be deallocated double* h_material_coef_ptr_double_; ///< Material coefficient on host, not to be deallocated unsigned int number_of_unique_materials_; ///< number of unique materials on the mesh // Parameters float* h_parameter_ptr_; ///< Simulation parameters on host, not to be deallocated double* h_parameter_ptr_double_; ///< Simulation parameters on host, not to be deallocated ///// Mesh properties unsigned int num_elements_; unsigned int num_air_elements_total_; unsigned int num_boundary_elements_total_; unsigned int dim_x_; unsigned int dim_y_; unsigned int dim_z_; unsigned int dim_xy_; float dx_; unsigned int block_size_x_; unsigned int block_size_y_; unsigned int block_size_z_; // Private Member functions void toBilbaoScheme(); void toKowalczykScheme(); public: void destroyPartitions() { c_log_msg(LOG_VERBOSE, "CudaMesh destructor"); for(unsigned int i = 0; i < this->number_of_partitions_; i++) { cudaSetDevice(i); destroyMem(position_idx_ptr_.at(i)); destroyMem(material_idx_ptr_.at(i)); if(this->isDouble()) { destroyMem(pressures_double_.at(i)); destroyMem(pressures_past_double_.at(i)); destroyMem(materials_double_.at(i)); destroyMem(parameters_double_.at(i)); } else { destroyMem(pressures_.at(i)); destroyMem(pressures_past_.at(i)); destroyMem(materials_.at(i)); destroyMem(parameters_.at(i)); } } cudasafe(cudaDeviceSynchronize(), "cudaDeviceSynchronize after destroy"); c_log_msg(LOG_VERBOSE, "CudaMesh destructor returning"); }; float* getPressurePtrAt(unsigned int partition_idx) {return this->pressures_.at(partition_idx);}; float* getPastPressurePtrAt(unsigned int partition_idx) {return this->pressures_past_.at(partition_idx);}; float* getMaterialPtrAt(unsigned int partition_idx) {return this->materials_.at(partition_idx);}; float* getParameterPtrAt(unsigned int partition_idx) {return this->parameters_.at(partition_idx);}; double* getMaterialPtrDoubleAt(unsigned int partition_idx) {return this->materials_double_.at(partition_idx);}; double* getParameterPtrDoubleAt(unsigned int partition_idx) {return this->parameters_double_.at(partition_idx);}; double* getPressureDoublePtrAt(unsigned int partition_idx) {return this->pressures_double_.at(partition_idx);}; double* getPastPressureDoublePtrAt(unsigned int partition_idx) {return this->pressures_past_double_.at(partition_idx);} unsigned char* getPositionIdxPtrAt(unsigned int partition_idx) {return this->position_idx_ptr_.at(partition_idx);} unsigned char* getMaterialIdxPtrAt(unsigned int partition_idx) {return this->material_idx_ptr_.at(partition_idx);} unsigned int getMemorySplitAt(unsigned int partition_idx) {return this->memory_splits_.at(partition_idx);} unsigned int getNumberOfElementsAt(unsigned int partition_idx) {return (unsigned int)this->partition_indexing_.at(partition_idx).size()*this->getDimXY();} unsigned int getNumberOfPartitions() {return (unsigned int)this->partition_indexing_.size();} unsigned int getPartitionSize() {return (unsigned int)this->partition_indexing_.at(0).size();} unsigned int getPartitionSize(int partition) { unsigned int ret = 0; unsigned int np = this->getNumberOfPartitions(); if(partition < (int)np) ret = (unsigned int)this->partition_indexing_.at(partition).size(); return ret;} unsigned int getFirstSliceIdx(int partition) {return this->partition_indexing_.at(partition).at(0);} unsigned int getDeviceAt(int i) {return this->device_list_.at(i);} unsigned int getBlockX() {return this->block_size_x_;} unsigned int getBlockY() {return this->block_size_y_;} unsigned int getBlockZ() {return this->block_size_z_;} unsigned int getDimX() {return this->dim_x_;} unsigned int getDimY() {return this->dim_y_;} unsigned int getDimZ() {return this->dim_z_;} unsigned int getDimXY() {return this->dim_xy_;} unsigned int getGridDimX() {return (this->dim_x_)/(this->block_size_x_);} unsigned int getGridDimY() {return (this->dim_y_)/(this->block_size_y_);} unsigned int getGridDimZ() {return (this->dim_z_)/(this->block_size_z_);} unsigned int getNumberOfElements() {return this->num_elements_;} unsigned int getNumberOfAirElements() {return this->num_air_elements_total_;} unsigned int getNumberOfBoundaryElements() {return this->num_boundary_elements_total_;} bool isDouble() const {return this->double_;} void setDouble(bool is_double) {this->double_ = is_double;} inline int getElementIndex(int x, int y, int z) { return this->getDimXY()*z+this->getDimX()*y+x; } inline void getElementIdxAndDevice(unsigned int x, unsigned int y, unsigned int z, int* dev_i, int* elem) { *dev_i = -1; *elem = -1; for(int i = 0; i < this->partition_indexing_.size(); i++) { if(z > *(this->partition_indexing_.at(i).end()-1)) continue; if(z < this->partition_indexing_.at(i).at(0)) break; unsigned int first = this->partition_indexing_.at(i).at(0); *elem = getElementIndex(x, y, z-first); *dev_i = i; break; } return; } inline int getDeviceOfElement(unsigned int x, unsigned int y, unsigned int z) { int ret = -1; for(int i = 0; i < this->partition_indexing_.size(); i++) { if(z > (int)*(this->partition_indexing_.at(i).end()-1)) continue; if(z < this->partition_indexing_.at(i).at(0)) break; ret = this->device_list_.at(i); } return ret; } std::vector< std::vector <unsigned int> > getPartitionIndexing(int num_parts, int dim) { int part_size = dim/num_parts; std::vector< std::vector<unsigned int> > ret; for(int i = 0; i < num_parts; i++) { int s_inc = 1; int e_inc = 1; if(i == 0) {s_inc =0;} if(i == num_parts-1) {e_inc = 0;} int current_size = part_size+s_inc+e_inc; // If at the last part, get rest of the slices if(i != 0 && i == num_parts-1) { int inc = dim-(i+1)*part_size; current_size += inc; } std::vector<unsigned int> slices(current_size, 0); for(int j = 0; j < current_size; j++) { slices.at(j) = i*part_size-s_inc+j; } //std::cout<<"getPartitionIndexing - size slice: "<<slices.size()<<std::endl; ret.push_back(slices); } // std::cout<<"getPartitionIndexing - size cont: "<<ret.size()<<std::endl; return ret; } template<typename T> std::vector<T*> splitPartitions(std::vector< std::vector<unsigned int> >& slices, int slice_dim) { std::vector<T*> ret; for(int i = 0; i < slices.size(); i++) { T* n_val = (T*)calloc(slice_dim*slices.at(i).size(), sizeof(T)); ret.push_back(n_val); } return ret; } // Set a sample on each slice corresponding to the index template<typename T> void setSample(unsigned int x, unsigned int y, unsigned int z, T sample, std::vector<T*>& domain, std::vector< std::vector<unsigned int> >& slices) { unsigned int s = (unsigned int)slices.size(); //#pragma omp parallel for for(int i = 0; i < s; i++) { if(z > *(slices.at(i).end()-1)) continue; if(z < slices.at(i).at(0)) break; cudaSetDevice(this->device_list_.at(i)); int first = slices.at(i).at(0); T* dest = domain.at(i)+getElementIndex(x, y, z-first); cudasafe(cudaMemcpy(dest, &sample, sizeof(T), cudaMemcpyHostToDevice), "setSample T : Memcopy To device"); } } template<typename T> void setSampleAt(unsigned int x, unsigned int y, unsigned int z, T sample, unsigned int partition, std::vector<T*>& domain) { unsigned int offset = getElementIndex(x,y,z); T* dest = domain.at(partition)+offset; cudasafe(cudaMemcpy(dest, &sample, sizeof(T), cudaMemcpyHostToDevice), "setSample T : Memcopy To device"); } template<typename T> void addSample(unsigned int x, unsigned int y, unsigned int z, T sample, std::vector<T*>& domain, std::vector< std::vector< unsigned int> >& slices){ unsigned int s = (unsigned int)slices.size(); //#pragma omp parallel for for(int i = 0; i < s; i++) { if(z > *(slices.at(i).end()-1)) continue; if(z < slices.at(i).at(0)) break; cudaSetDevice(this->device_list_.at(i)); int first = slices.at(i).at(0); T domain_smp = 0; T* dest = domain.at(i)+getElementIndex(x, y, z-first); cudasafe(cudaMemcpy(&domain_smp, dest, sizeof(T), cudaMemcpyDeviceToHost), "addSample T : Memcopy To Host"); domain_smp+=sample; cudasafe(cudaMemcpy(dest, &sample, sizeof(T), cudaMemcpyHostToDevice), "addSample T : Memcopy To Device"); } } template<typename T> T getSampleAt(int x, int y, int z, int partition, std::vector<T*>& domain) { T ret = 0; if(z > this->partition_indexing_.at(partition).size()) { std::cout<<"z "<<z<<" out of range "<<this->partition_indexing_.at(partition).size()<<std::endl; return ret; } cudaSetDevice(this->device_list_.at(partition)); int offset = this->getElementIndex(x,y,z); T* src = domain.at(partition)+offset; cudasafe(cudaMemcpy(&ret, src, sizeof(T), cudaMemcpyDeviceToHost), "getSampleAt T : Memcopy To Host"); return ret; } template<typename T> T getSample(unsigned int x, unsigned int y, unsigned int z, std::vector<T*>& domain, std::vector< std::vector< unsigned int> >& slices) { T ret = 0.0; for(int i = 0; i < slices.size(); i++) { cudaSetDevice(this->device_list_.at(i)); if(z > *(slices.at(i).end()-1)) continue; if(z < slices.at(i).at(0)) break; unsigned int first = slices.at(i).at(0); T* src = domain.at(i)+getElementIndex(x, y, z-first); cudasafe(cudaMemcpy(&ret, src, sizeof(T), cudaMemcpyDeviceToHost), "addSample T : Memcopy To Host"); break; } return ret; } template<typename T> T* getElement(unsigned int x, unsigned int y, unsigned int z, unsigned int& dev_i, std::vector<T*>& domain, std::vector< std::vector< unsigned int> >& slices) { T* ret = (T*)NULL; for(int i = 0; i < slices.size(); i++) { if(z > *(slices.at(i).end()-1)) continue; if(z < slices.at(i).at(0)) break; int first = slices.at(i).at(0); ret = domain.at(i)+getElementIndex(x, y, z-first); dev_i = i; break; } return ret; } template<typename T> T* getElementAt(unsigned int x, unsigned int y, unsigned int z, unsigned int partition, std::vector<T*>& domain, std::vector< std::vector< unsigned int> >& slices) { return domain.at(partition)+getElementIndex(x, y, z); } template<typename T> void switchHalos(std::vector<T*>& domain, std::vector< std::vector< unsigned int > >& slices) { unsigned int slice_s = this->getDimXY(); #pragma omp parallel for for(unsigned int i = 0; i < (unsigned int)slices.size()-1; i++) { unsigned int src_1 = *(slices.at(i).end()-2); unsigned int dest_1 = slices.at(i+1).at(0); unsigned int src_2 = slices.at(i+1).at(1); unsigned int dest_2 = *(slices.at(i).end()-1); unsigned int f_i = slices.at(i).at(0); unsigned int f_i1 = slices.at(i+1).at(0); T* s1 = domain.at(i)+(src_1-f_i)*slice_s; T* d1 = domain.at(i+1)+(dest_1-f_i1)*slice_s; T* s2 = domain.at(i+1)+(src_2-f_i1)*slice_s; T* d2 = domain.at(i)+(dest_2-f_i)*slice_s; unsigned int d_1 = this->getDeviceAt(i); unsigned int d_2 = this->getDeviceAt(i+1); cudasafe(cudaMemcpyPeer(d1, d_2, s1, d_1, slice_s*sizeof(T)), "CudaMesh::switchHalos - memcopyPeer i -> i+1"); cudasafe(cudaMemcpyPeer(d2, d_1, s2, d_2, slice_s*sizeof(T)), "CudaMesh::switchHalos - memcopyPeer i+1 -> i"); } cudaDeviceSynchronize(); } template <typename T> T* getElementAt(unsigned int x, unsigned int y, unsigned int z, unsigned int partition) { T* ret; if(this->isDouble()) ret = this->getElementAt(x,y,z, partition, this->pressures_double_, this->partition_indexing_); else ret = this->getElementAt(x,y,z, partition, this->pressures_, this->partition_indexing_); return ret; } /// Function return a pointer to the element from the partitions which /// correspond to the given coordinates. If sample is in halo element, /// halo indicates from which partition the sample is returned template <typename T> T* getElement(unsigned int x, unsigned int y, unsigned int z, unsigned int *halo) { T* ret; if(this->isDouble()) ret = this->getElement(x,y,z, *halo, this->pressures_double_, this->partition_indexing_); else ret = this->getElement(x,y,z, *halo, this->pressures_, this->partition_indexing_); return ret; } // Add sample to the existing pressure value of the mesh template <typename T> void addSample(T sample, unsigned int x, unsigned int y, unsigned int z) { if(this->isDouble()) { addSample(x,y,z, (double)sample, this->pressures_double_, this->partition_indexing_); } else { addSample(x,y,z, (float)sample, this->pressures_, this->partition_indexing_); } } // End function /////////////////////////////////////////////////////////////////////////////// /// \brief Set a sample in the mesh from a value from host memory /// \tparam The type of pressure data type, float / double /// \param sample Sample value to be assigned /// \param x, y, z The element coordinates in the mesh /////////////////////////////////////////////////////////////////////////////// template <typename T> void setSample(T sample, unsigned int x, unsigned int y, unsigned int z) { //c_log_msg(LOG_VERBOSE, "CudaMesh::setSample - %u %u %u",x,y,z); if(this->isDouble()) { setSample(x,y,z, (double)sample, this->pressures_double_, this->partition_indexing_); } else { setSample(x,y,z, (float)sample, this->pressures_, this->partition_indexing_); } } // End function /////////////////////////////////////////////////////////////////////////////// /// \brief Set a sample in the mesh from a value from host memory to a /// specific partition /// \tparam The type of pressure data type, float / double /// \param sample Sample value to be assigned /// \param x, y, z The element coordinates in the mesh /// \param partition Partition index, namely the device in which the memory lies /////////////////////////////////////////////////////////////////////////////// template <typename T> void setSampleAt(T sample, unsigned int x, unsigned int y, unsigned int z, unsigned int partition) { c_log_msg(LOG_VERBOSE, "CudaMesh::setSampleAt - %u %u %u partition %u",x,y,z, partition); if(this->isDouble()) { setSampleAt(x,y,z, (double)sample, partition, this->pressures_double_); } else { setSampleAt(x,y,z, (float)sample, partition, this->pressures_); } } /////////////////////////////////////////////////////////////////////////////// /// \brief Get a sample from the mesh /// \tparam The type of pressure data type, float / double /// \param x, y, z The element coordinates of the sample in the mesh /// \return sample value in host memory /////////////////////////////////////////////////////////////////////////////// template <typename T> T getSample(unsigned int x, unsigned int y, unsigned int z) { c_log_msg(LOG_VERBOSE, "CudaMesh::getSample - %u %u %u",x,y,z); T sample = (T)0.0; if(this->isDouble()) { sample = getSample<double>(x,y,z, this->pressures_double_, this->partition_indexing_); } else { sample = getSample<float>(x,y,z, this->pressures_, this->partition_indexing_); } return sample; } /////////////////////////////////////////////////////////////////////////////// /// \brief Get a position idx value from the mesh in a position in /// a specific partition /// \param x, y, z The element coordinates of the sample in the mesh /// \return position index value /////////////////////////////////////////////////////////////////////////////// template <typename T> T getSampleAt(unsigned int x, unsigned int y, unsigned int z, unsigned int partition) { c_log_msg(LOG_VERBOSE, "CudaMesh::getSampleAt - %u %u %u partition %u",x,y,z, partition); T sample = (T)0.0; if(this->isDouble()) { sample = getSampleAt(x,y,z, partition, this->pressures_double_); } else { sample = getSampleAt(x,y,z, partition, this->pressures_); } return sample; } /////////////////////////////////////////////////////////////////////////////// /// \brief Get a position idx value from the mesh /// \param x, y, z The element coordinates of the sample in the mesh /// \return position index value /////////////////////////////////////////////////////////////////////////////// unsigned char getPositionSample(unsigned int x, unsigned int y, unsigned int z) { c_log_msg(LOG_VERBOSE, "CudaMesh::getPositionSample - %u %u %u",x,y,z); unsigned char sample = 0; sample = getSample(x,y,z, this->position_idx_ptr_, this->partition_indexing_); return sample; } // This function is ridiculously slow template<typename T> T* getSlice(unsigned int slice, unsigned int orientation) { T* data = NULL; /* unsigned int dim_x = 0; unsigned int dim_y = 0; if(orientation == 0) {dim_x = this->getDimX(); dim_y = this->getDimY();}; if(orientation == 1) {dim_x = this->getDimX(); dim_y = this->getDimZ();}; if(orientation == 2) {dim_x = this->getDimY(); dim_y = this->getDimZ();}; */ if(orientation == 0) { unsigned int dev_i; T* start_address = (T*)NULL; start_address = this->getElement(0u,0u,slice, dev_i, this->pressures_, this->partition_indexing_); data= fromDevice(this->getDimXY(), start_address, this->device_list_.at(dev_i)); } // end orientation return data; } unsigned char* getPositionSlice(unsigned int slice, unsigned int orientation) { unsigned char* data = (unsigned char*)NULL; /* int dim_x, dim_y, dim_z: if(orientation == 0) {dim_x = this->getDimX(); dim_y = this->getDimY();}; if(orientation == 1) {dim_x = this->getDimX(); dim_y = this->getDimZ();}; if(orientation == 2) {dim_x = this->getDimY(); dim_y = this->getDimZ();}; */ if(orientation == 0) { unsigned char* start_address = NULL; unsigned int dev_i; start_address = this->getElement(0,0,slice, dev_i, this->position_idx_ptr_, this->partition_indexing_); data = fromDevice(this->getDimXY(), start_address, this->device_list_.at(dev_i)); } return data; } void makePartition(unsigned int number_of_partitions, std::vector<unsigned int> device_list = std::vector<unsigned int>()) { c_log_msg(LOG_INFO, "CudaMesh::makePartition - begin, number of partitions %d, dim z %u", number_of_partitions, this->getDimZ()); printMemInfo("CudaMesh::makePartition - memory before partition", getCurrentDevice()); if(device_list.size() == 0) { for(unsigned int i = 0; i < number_of_partitions; i++) device_list.push_back(i); } this->device_list_ = device_list; this->partition_indexing_ = getPartitionIndexing(number_of_partitions, this->getDimZ()); clock_t start_t; clock_t end_t; start_t = clock(); // Grab pointers to the meshes and clear the container for partitions unsigned char* d_position_idx = this->position_idx_ptr_.at(0); unsigned char* d_material_idx = this->material_idx_ptr_.at(0); this->position_idx_ptr_.clear(); this->material_idx_ptr_.clear(); // Go through devices and copy the part to each for(unsigned int k = 0; k < number_of_partitions; k ++) { int i = this->device_list_.at(k); cudaSetDevice(i); int offset = this->partition_indexing_.at(k).at(0)*this->getDimXY(); int size = (int)this->partition_indexing_.at(k).size()*this->getDimXY(); if(number_of_partitions > 1) { unsigned char* position_idx = valueToDevice(size+1+dim_x_, (unsigned char)0, i); unsigned char* material_idx = valueToDevice(size+1+dim_x_, (unsigned char)0, i); cudasafe(cudaMemcpyPeer(position_idx, i, d_position_idx+offset, 0, size*sizeof(unsigned char)), "CudaMesh::makePartition - memcpyPeer position"); cudasafe(cudaMemcpyPeer(material_idx, i, d_material_idx+offset, 0, size*sizeof(unsigned char)), "CudaMesh::makePartition - memcpyPeer material"); // Push the device pointer to containers this->position_idx_ptr_.push_back(position_idx); this->material_idx_ptr_.push_back(material_idx); } else { this->position_idx_ptr_.push_back(d_position_idx); this->material_idx_ptr_.push_back(d_material_idx); } } // End material / position partition // Free the original meshes from device 0 if number of partitions is > 1 if(number_of_partitions > 1) { destroyMem(d_position_idx); destroyMem(d_material_idx); } // Go through devices and allocate pressures for(unsigned int k = 0; k < number_of_partitions; k ++) { int i = this->device_list_.at(k); cudaSetDevice(i); int size = (int)this->partition_indexing_.at(k).size()*this->getDimXY(); if(this->isDouble()) { c_log_msg(LOG_DEBUG, "CudaMesh::makePartition - allocating double pressures dev %u", i); double* P = toDevice<double>(size+1+dim_x_, i); double* P_past = toDevice<double>(size+1+dim_x_, i); // Push the device pointers to containers this->pressures_double_.push_back(P); this->pressures_past_double_.push_back(P_past); // Allocate and copy material coefficients to all devices c_log_msg(LOG_DEBUG, "CudaMesh::makePartition - allocating double materials"); this->materials_double_.push_back(toDevice<double>(this->number_of_unique_materials_*20, this->h_material_coef_ptr_double_, i)); // Allocate and copy simulation parameters to all devices this->parameters_double_.push_back(toDevice<double>(10, this->h_parameter_ptr_double_, i)); } else { c_log_msg(LOG_DEBUG, "CudaMesh::makePartition - allocating float pressures dev %u", i); float* P = toDevice<float>(size+1+dim_x_, i); float* P_past = toDevice<float>(size+1+dim_x_, i); // Push the device pointers to containers this->pressures_.push_back(P); this->pressures_past_.push_back(P_past); this->materials_.push_back(toDevice<float>(this->number_of_unique_materials_*20, this->h_material_coef_ptr_, i)); // Allocate and copy simulation parameters to all devices this->parameters_.push_back(toDevice(4, this->h_parameter_ptr_, i)); } }// End partition loop end_t = clock()-start_t; c_log_msg(LOG_INFO,"CudaMesh::MakePartition - time: %f seconds", ((float)end_t/CLOCKS_PER_SEC)); } // End make partition /// \brief switch halo layers between partitions void switchHalos() { if(this->isDouble()) { this->switchHalos(this->pressures_double_, this->partition_indexing_); } else { this->switchHalos(this->pressures_, this->partition_indexing_); } cudasafe(cudaDeviceSynchronize(), "CudaMesh::switchHalos - Device synch after halo switch"); } /// \brief switch pointers of current and past pressure meshes void flipPressurePointers() { for(unsigned int i = 0; i < this->getNumberOfPartitions(); i++){ if(this->isDouble()) { double* temp = this->pressures_double_.at(i); this->pressures_double_.at(i) = this->pressures_past_double_.at(i); this->pressures_past_double_.at(i) = temp; } else { float* temp = this->pressures_.at(i); this->pressures_.at(i) = this->pressures_past_.at(i); this->pressures_past_.at(i) = temp; } } } /// \brief reset pressure values of the mesh to 0 void resetPressures() { for(unsigned int i = 0; i < this->getNumberOfPartitions(); i++){ float* temp = this->pressures_.at(i); float* temp_past = this->pressures_past_.at(i); unsigned int num_elements = this->getNumberOfElementsAt(i); resetData(num_elements, temp, i); resetData(num_elements, temp_past, i); } cudasafe(cudaDeviceSynchronize(), "Device synch after reset pressures"); } /// \brief on hold void switchAirAndZero(); /////////////////////////////////////////////////////////////////////////////// /// Setup the mesh data structure with voxelized geometry, simulation parameters /// and material parameters /// \param d_position_ptr Position indices defining the orientation of each node /// \param d_material_ptr Material indices defining the material index /// \param number_of_unique_materials Number of unique materials in the model /// \param material_coefficients material parameters used in the model /// \param voxelization_dim Dimensions of the voxelized geometry /// \param block_size Block size used which is to be used running FDTD kernels /// \param element_type Type of the position index /// 0: forward-difference, 1: centered-difference /// \return sample value in host memory /////////////////////////////////////////////////////////////////////////////// void setupMesh(unsigned char* d_position_ptr, unsigned char* d_material_ptr, unsigned int number_of_unique_materials, float* material_coefficients, float* parameter_ptr, uint3 voxelization_dim, uint3 block_size, unsigned int element_type); //////////////////////////////////////////////////////////////////////////////// /// Setup the mesh data structure with voxelized geometry, simulation parameters /// and material parameters /// \param d_position_ptr Position indices defining the orientation of each node /// \param d_material_ptr Material indices defining the material index /// \param number_of_unique_materials Number of unique materials in the model /// \param material_coefficients material parameters used in the model /// \param voxelization_dim Dimensions of the voxelized geometry /// \param block_size Block size used which is to be used running FDTD kernels /// \param element_type Type of the position index /// 0: forward-difference, 1: centered-difference /// \return sample value in host memory /////////////////////////////////////////////////////////////////////////////// void setupMeshDouble(unsigned char* d_position_ptr, unsigned char* d_material_ptr, unsigned int number_of_unique_materials, double* material_coefficients, double* parameter_ptr, uint3 voxelization_dim, uint3 block_size, unsigned int element_type); }; /// \brief Pad the mesh with zeros /// \param[in, out] d_mesh a /// \param[in, out] dim Dimensions of the mesh /// \param block_size_x, block_size_y, block_size_z New block sizes in which the /// new mesh dimensions are rounded to void padWithZeros(unsigned char** d_mesh, uint3* dim, unsigned int block_size_x, unsigned int block_size_y, unsigned int block_size_z); void padWithZeros(unsigned char** d_position_ptr, unsigned char** d_material_ptr, uint3* dim, unsigned int block_size_x, unsigned int block_size_y, unsigned int block_size_z); /// \brief on hold //void addMesh(CudaMesh& mesh_1, CudaMesh& mesh2, // int pos_x, int pos_y, int pos_z); //////// Kernels __global__ void padWithZerosKernel(unsigned char* d_mesh_new, unsigned char* d_mesh_old, unsigned int dim_x, unsigned int dim_y, unsigned int dim_z, unsigned int block_x, unsigned int block_y, unsigned int block_z, unsigned int slice); /// \brief Kernel setting the position index values to centered-difference scheme __global__ void toKowalczykKernel(unsigned char* d_position_ptr, unsigned char* d_material_ptr, unsigned int num_elems); /// \brief Kernel setting the position index values to forward-difference scheme __global__ void toBilbaoKernel(unsigned char* d_position_ptr, unsigned char* d_material_ptr, unsigned int num_elems); /// \brief Kernel calculating the number of air and boundary nodes __global__ void calcBoundaries(unsigned char* d_position_ptr, unsigned int* air, unsigned int* boundary, unsigned char air_value, unsigned char outside_value, unsigned int num_elems); /// \brief on hold __global__ void getBoundaryIndicesKernel(unsigned char* d_position_ptr, unsigned int* d_indices, unsigned char air, unsigned char out, unsigned int* pos); /// \brief on hold __global__ void checkInnerCorners(unsigned char* d_position_ptr, int dim_xy, int dim_x); /// \brief on hold __global__ void switchAirAndZeroKernel(unsigned char* d_position_ptr, unsigned int dim_xy, unsigned int dim_x); /// \brief on hold __global__ void validateSolids(unsigned char* d_position_ptr, unsigned char* d_position_ptr_new, unsigned char* d_material_ptr, int dim_x, int dim_xy, int dim_z); /// \brief on hold __global__ void validatePositionIndexes(unsigned char* d_position_ptr, unsigned char* d_position_ptr_new, unsigned char* d_material_ptr, int dim_x, int dim_xy, int dim_z); /// \brief A kernel to add a mesh to another, on hold __global__ void addSourceMesh(unsigned char* d_position_ptr_room, unsigned char* d_position_ptr_source, int dim_xy_room, int dim_x_room, int dim_xy_source, int dim_x_source, int pos_x, int pos_y, int pos_z); #endif
Fig_5.7_dynamicSchedule.c
#include <stdio.h> #include <math.h> #include <stdbool.h> #include <omp.h> #define ITER 50000000 // use a smaller value if available memory is small bool check_prime(int num) { int i; for (i = 2; i <= sqrt(num); i++) { if (num % i == 0) return false; } return true; } void main( ) { int sum = 0; #pragma omp parallel { int i; int id = omp_get_thread_num(); double tdata = omp_get_wtime(); #pragma omp for reduction (+:sum) schedule(dynamic) for (i = 2; i <= ITER ; i++) { if (check_prime(i)) sum++; } tdata = omp_get_wtime() - tdata; if (id == 0) printf("Number of prime numbers is %d in %f sec \n", sum, tdata); } }
pd_tv_mex.c
#include <inttypes.h> #include <math.h> #include <omp.h> #include "mex.h" #define MIN_VERBOSE (4) #define CONVERGENCE_MOD (10) /* preprocessor can't compare floating point numbers: */ /* THETA0 = 1 -> THETA = 0.0 */ /* THETA0 = 0 -> THETA = THETA */ #define THETA0 (0) #define THETA (1.0) #define OI (1 << 1) /* unused */ #define BI (1 << 2) /* unused */ #define FI (1 << 3) /* unused */ #define CI (1 << 4) /* unused */ #define OJ (1 << 5) /* unused */ #define BJ (1 << 6) /* unused */ #define FJ (1 << 7) /* unused */ #define CJ (1 << 8) /* unused */ #define OK (1 << 9) /* unused */ #define BK (1 << 10) /* unused */ #define FK (1 << 11) /* unused */ #define CK (1 << 12) /* unused */ #define INSIDE (CI + CJ + CK) #define OUTSIDE (OI + OJ + OK) #define MAX(a,b) (((a)>(b))?(a):(b)) #define MIN(a,b) (((a)<(b))?(a):(b)) struct PD { /* primal */ void *chi; void *eta; void *chi_; void *eta_; /* dual */ void *nu; void *p; /* misc */ void *f; void *m; void *mi; void *mb; /* unused */ void *chi0; void *eta0; }; void mx_pdd(struct PD *mxpd, const double lam, const double *h, const double tol, const uint32_t maxiter, const uint32_t verbose); void mx_pdf(struct PD *mxpd, const double lam, const double *h, const double tol, const uint32_t maxiter, const uint32_t verbose); void update_duald(struct PD *pd, const double lam, const double sigma, const double *h, const size_t *sz); void update_dualf(struct PD *pd, const double lam, const double sigma, const double *h, const size_t *sz); void update_primald(struct PD *pd, const double tau, const double *h, const size_t *sz); void update_primalf(struct PD *pd, const double tau, const double *h, const size_t *sz); uint8_t convergence_checkd(double *nr1, double *nr2, const double *chi, const double *chi0, const double *eta, const double *eta0, const double tol, const size_t N); uint8_t convergence_checkf(double *nr1, double *nr2, const float *chi, const float *chi0, const float *eta, const float *eta0, const double tol, const size_t N); void init_bitmask(uint32_t *mb, uint8_t *mi, const uint8_t *m, const size_t *sz); void mx_init(struct PD *pd, const mxArray *mxf, const mxArray *mxm); void mx_cleanup(struct PD *pd); void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs != 7) || (nlhs > 1)) { mexErrMsgTxt( "Usage: chi = pd_tv_mex(d2f, mask, vsz, lam, tol, maxiter, verbose);" ); return; } const double *h = (const double *)mxGetData(prhs[2]); const double lam = (const double)mxGetScalar(prhs[3]); const double tol = (const double)mxGetScalar(prhs[4]); const uint32_t maxiter = (const uint32_t)mxGetScalar(prhs[5]); const uint32_t verbose = (const uint32_t)mxGetScalar(prhs[6]); struct PD mxpd; mx_init(&mxpd, prhs[0], prhs[1]); if (mxIsSingle(prhs[0])) { mx_pdf(&mxpd, lam, h, tol, maxiter, verbose); } else { mx_pdd(&mxpd, lam, h, tol, maxiter, verbose); } plhs[0] = mxDuplicateArray(mxpd.chi); mx_cleanup(&mxpd); return; } void mx_pdf(struct PD *mxpd, const double lam, const double *h, const double tol, const uint32_t maxiter, const uint32_t verbose) { uint32_t i, l, pmod; double nr1, nr2; const size_t N = (const size_t)mxGetNumberOfElements(mxpd->f); const size_t *sz = (const size_t *)mxGetDimensions(mxpd->f); struct PD pd; pd.chi = (float *)mxGetData(mxpd->chi); pd.eta = (float *)mxGetData(mxpd->eta); pd.chi_ = (float *)mxGetData(mxpd->chi_); pd.eta_ = (float *)mxGetData(mxpd->eta_); pd.nu = (float *)mxGetData(mxpd->nu); pd.p = (float *)mxGetData(mxpd->p); pd.f = (float *)mxGetData(mxpd->f); pd.m = (uint8_t *)mxGetData(mxpd->m); pd.mi = (uint8_t *)mxGetData(mxpd->mi); pd.mb = (uint32_t *)mxGetData(mxpd->mb); pd.chi0 = (float *)mxGetData(mxpd->chi0); pd.eta0 = (float *)mxGetData(mxpd->eta0); float *f = pd.f; float *chi = pd.chi; float *eta = pd.eta; float *chi0 = pd.chi0; float *eta0 = pd.eta0; double gnrm = 4.0 * (1.0/(h[0]*h[0]) + 1.0/(h[1]*h[1]) + 1.0/(h[2]*h[2])); double wnrm = 6.0 * (1.0/(h[0]*h[0]) + 1.0/(h[1]*h[1]) + 2.0/(h[2]*h[2])) / 3.0; double K2 = gnrm*gnrm + wnrm*wnrm; const double tau = 1/sqrt(K2); const double sigma = 1/(tau*K2); #pragma omp parallel for private(l) schedule(static) for(l = 0; l < N; l += 1) { f[l] = ((float)sigma)*f[l]; } uint8_t flag = 0; nr1 = 1.0; nr2 = 1.0; pmod = maxiter / MIN(MAX(verbose, MIN_VERBOSE), maxiter); if (verbose) { mexPrintf("Iter\t\t||delta chi||\t||delta eta||\n"); } for(i = 0; i < maxiter; ++i) { if (((i+1) % CONVERGENCE_MOD) == 0) { #pragma omp parallel for private(l) schedule(static) for(l = 0; l < N; l += 1) { chi0[l] = chi[l]; eta0[l] = eta[l]; } } update_dualf(&pd, lam, sigma, h, sz); update_primalf(&pd, tau, h, sz); if (((i+1) % CONVERGENCE_MOD) == 0) { flag = convergence_checkf(&nr1, &nr2, chi, chi0, eta, eta0, tol, N); } if (verbose && (i == 0 || i == maxiter-1 || ((i+1) % pmod) == 0 || flag)) { mexPrintf("%5d/%d\t%.3e\t%.3e\n", i+1, maxiter, nr1, nr2); } if (flag) { break; } } return; } void mx_pdd(struct PD *mxpd, const double lam, const double *h, const double tol, const uint32_t maxiter, const uint32_t verbose) { uint32_t i, l, pmod; double nr1, nr2; const size_t N = (const size_t)mxGetNumberOfElements(mxpd->f); const size_t *sz = (const size_t *)mxGetDimensions(mxpd->f); struct PD pd; pd.chi = (double *)mxGetData(mxpd->chi); pd.eta = (double *)mxGetData(mxpd->eta); pd.chi_ = (double *)mxGetData(mxpd->chi_); pd.eta_ = (double *)mxGetData(mxpd->eta_); pd.nu = (double *)mxGetData(mxpd->nu); pd.p = (double *)mxGetData(mxpd->p); pd.f = (double *)mxGetData(mxpd->f); pd.m = (uint8_t *)mxGetData(mxpd->m); pd.mi = (uint8_t *)mxGetData(mxpd->mi); pd.mb = (uint32_t *)mxGetData(mxpd->mb); pd.chi0 = (double *)mxGetData(mxpd->chi0); pd.eta0 = (double *)mxGetData(mxpd->eta0); double *f = pd.f; double *chi = pd.chi; double *eta = pd.eta; double *chi0 = pd.chi0; double *eta0 = pd.eta0; double gnrm = 4.0 * (1.0/(h[0]*h[0]) + 1.0/(h[1]*h[1]) + 1.0/(h[2]*h[2])); double wnrm = 6.0 * (1.0/(h[0]*h[0]) + 1.0/(h[1]*h[1]) + 2.0/(h[2]*h[2])) / 3.0; double K2 = gnrm*gnrm + wnrm*wnrm; const double tau = 1/sqrt(K2); const double sigma = 1/(tau*K2); #pragma omp parallel for private(l) schedule(static) for(l = 0; l < N; l += 1) { f[l] = sigma*f[l]; } uint8_t flag = 0; nr1 = 1.0; nr2 = 1.0; pmod = maxiter / MIN(MAX(verbose, MIN_VERBOSE), maxiter); if (verbose) { mexPrintf("Iter\t\t||delta chi||\t||delta eta||\n"); } for(i = 0; i < maxiter; ++i) { if (((i+1) % CONVERGENCE_MOD) == 0) { #pragma omp parallel for private(l) schedule(static) for(l = 0; l < N; l += 1) { chi0[l] = chi[l]; eta0[l] = eta[l]; } } update_duald(&pd, lam, sigma, h, sz); update_primald(&pd, tau, h, sz); if (((i+1) % CONVERGENCE_MOD) == 0) { flag = convergence_checkd(&nr1, &nr2, chi, chi0, eta, eta0, tol, N); } if (verbose && (i == 0 || i == maxiter-1 || ((i+1) % pmod) == 0 || flag)) { mexPrintf("%5d/%d\t%.3e\t%.3e\n", i+1, maxiter, nr1, nr2); } if (flag) { break; } } return; } /* * nu <- nu + sigma*(laplace(eta_) - wave(chi_) + f) * p <- P_{||.||_inf <= lam}(p + sigma*grad(chi_)) */ void update_dualf(struct PD *pd, const double lam, const double sigma, const double *h, const size_t *sz) { size_t i, j, k; size_t l; float x; float *nu = (float *)pd->nu; float *p = (float *)pd->p; #if !THETA0 float *chi_ = (float *)pd->chi_; float *eta_ = (float *)pd->eta_; #else float *chi_ = (float *)pd->chi; float *eta_ = (float *)pd->eta; #endif float *f = (float *)pd->f; uint8_t *m = (uint8_t *)pd->mi; 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 NX = nx-1; const size_t NY = nx*(ny-1); const size_t NZ = nxny*(nz-1); const float hx = (float)(sigma/h[0]); const float hy = (float)(sigma/h[1]); const float hz = (float)(sigma/h[2]); const float lhx = (float)(sigma/(h[0]*h[0])); const float lhy = (float)(sigma/(h[1]*h[1])); const float lhz = (float)(sigma/(h[2]*h[2])); const float lhh = -2.0f*(lhx+lhy+lhz); const float whx = (float)(-sigma/(3.0*h[0]*h[0])); const float why = (float)(-sigma/(3.0*h[1]*h[1])); const float whz = (float)( sigma*2.0/(3.0*h[2]*h[2])); const float whh = -2.0f*(whx+why+whz); const float lam_ = (float)lam; const float lam2_ = (float)(lam*lam); float *p1 = &p[0*(nxny*nz)]; float *p2 = &p[1*(nxny*nz)]; float *p3 = &p[2*(nxny*nz)]; #pragma omp parallel for private(i,j,k,l,x) schedule(static) \ if (nxny*nz > 32*32*32) for(k = nxny; k < NZ; k += nxny) { for(j = nx; j < NY; j += nx) { l = 1 + j + k; for(i = 1; i < NX; ++i, ++l) { if (m[l] != 0) { nu[l] = nu[l] + ( /* laplace(eta_) */ (lhh*eta_[l] + lhx*(eta_[l-1] + eta_[l+1]) + lhy*(eta_[l-nx] + eta_[l+nx]) + lhz*(eta_[l-nxny] + eta_[l+nxny])) - /* - wave(chi_) */ (whh*chi_[l] + whx*(chi_[l-1] + chi_[l+1]) + why*(chi_[l-nx] + chi_[l+nx]) + whz*(chi_[l-nxny] + chi_[l+nxny])) + /* + f */ f[l] ); /* p + sigma*grad(chi_) */ p1[l] = p1[l] + hx*(chi_[l+1]-chi_[l]); p2[l] = p2[l] + hy*(chi_[l+nx]-chi_[l]); p3[l] = p3[l] + hz*(chi_[l+nxny]-chi_[l]); /* p <- P_{||.||_inf <= lam}(p) */ x = p1[l]*p1[l] + p2[l]*p2[l] + p3[l]*p3[l]; if (x > lam2_) { x = lam_/sqrtf(x); p1[l] = p1[l] * x; p2[l] = p2[l] * x; p3[l] = p3[l] * x; } } } } } return; } /* * nu <- nu + sigma*(laplace(eta_) - wave(chi_) + f) * p <- P_{||.||_inf <= lam}(p + sigma*grad(chi_)) */ void update_duald(struct PD *pd, const double lam, const double sigma, const double *h, const size_t *sz) { size_t i, j, k; size_t l; double x; double *nu = (double *)pd->nu; double *p = (double *)pd->p; #if !THETA0 double *chi_ = (double *)pd->chi_; double *eta_ = (double *)pd->eta_; #else double *chi_ = (double *)pd->chi; double *eta_ = (double *)pd->eta; #endif double *f = (double *)pd->f; uint8_t *m = (uint8_t *)pd->mi; 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 NX = nx-1; const size_t NY = nx*(ny-1); const size_t NZ = nxny*(nz-1); const double hx = sigma/h[0]; const double hy = sigma/h[1]; const double hz = sigma/h[2]; const double lhx = sigma/(h[0]*h[0]); const double lhy = sigma/(h[1]*h[1]); const double lhz = sigma/(h[2]*h[2]); const double lhh = -2.0*(lhx+lhy+lhz); const double whx = -sigma/(3.0*h[0]*h[0]); const double why = -sigma/(3.0*h[1]*h[1]); const double whz = sigma*2.0/(3.0*h[2]*h[2]); const double whh = -2.0*(whx+why+whz); const double lam2 = lam*lam; double *p1 = &p[0*(nxny*nz)]; double *p2 = &p[1*(nxny*nz)]; double *p3 = &p[2*(nxny*nz)]; #pragma omp parallel for private(i,j,k,l,x) schedule(static) \ if (nxny*nz > 32*32*32) for(k = nxny; k < NZ; k += nxny) { for(j = nx; j < NY; j += nx) { l = 1 + j + k; for(i = 1; i < NX; ++i, ++l) { if (m[l] != 0) { nu[l] = nu[l] + ( /* laplace(eta_) */ (lhh*eta_[l] + lhx*(eta_[l-1] + eta_[l+1]) + lhy*(eta_[l-nx] + eta_[l+nx]) + lhz*(eta_[l-nxny] + eta_[l+nxny])) - /* - wave(chi_) */ (whh*chi_[l] + whx*(chi_[l-1] + chi_[l+1]) + why*(chi_[l-nx] + chi_[l+nx]) + whz*(chi_[l-nxny] + chi_[l+nxny])) + /* + f */ f[l] ); /* p + sigma*grad(chi_) */ p1[l] = p1[l] + hx*(chi_[l+1]-chi_[l]); p2[l] = p2[l] + hy*(chi_[l+nx]-chi_[l]); p3[l] = p3[l] + hz*(chi_[l+nxny]-chi_[l]); /* p <- P_{||.||_inf <= lam}(p) */ x = p1[l]*p1[l] + p2[l]*p2[l] + p3[l]*p3[l]; if (x > lam2) { x = lam/sqrt(x); p1[l] = p1[l] * x; p2[l] = p2[l] * x; p3[l] = p3[l] * x; } } } } } return; } /* * eta <- (eta - tau*laplace(nu)) / (1 + tau) * chi <- chi - tau*(-div(p) - wave(nu)) * * eta_ <- eta_n+1 + THETA*(eta_n+1 - eta_n) * chi_ <- chi_n+1 + THETA*(chi_n+1 - chi_n) */ void update_primalf(struct PD *pd, const double tau, const double *h, const size_t *sz) { size_t i, j, k; size_t l; float x, y, z; float *chi = (float *)pd->chi; float *eta = (float *)pd->eta; #if !THETA0 float cn, en; float *chi_ = (float *)pd->chi_; float *eta_ = (float *)pd->eta_; #endif float *nu = (float *)pd->nu; float *p = (float *)pd->p; uint8_t *m = (uint8_t *)pd->m; 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 NX = nx-1; const size_t NY = nx*(ny-1); const size_t NZ = nxny*(nz-1); const float hx = (float)(tau/h[0]); const float hy = (float)(tau/h[1]); const float hz = (float)(tau/h[2]); const float lhx = (float)(tau/(h[0]*h[0])); const float lhy = (float)(tau/(h[1]*h[1])); const float lhz = (float)(tau/(h[2]*h[2])); const float lhh = -2.0f*(lhx+lhy+lhz); const float whx = (float)(-tau/(3.0*h[0]*h[0])); const float why = (float)(-tau/(3.0*h[1]*h[1])); const float whz = (float)( tau*2.0/(3.0*h[2]*h[2])); const float whh = -2.0f*(whx+why+whz); const float tau1 = (float)(1.0 / (1.0 + tau)); float *p1 = &p[0*(nxny*nz)]; float *p2 = &p[1*(nxny*nz)]; float *p3 = &p[2*(nxny*nz)]; #pragma omp parallel for private(i,j,k,l,x,y,z) schedule(static) \ if (nxny*nz > 32*32*32) for(k = nxny; k < NZ; k += nxny) { for(j = nx; j < NY; j += nx) { l = 1 + j + k; for(i = 1; i < NX; ++i, ++l) { if (m[l] != 0) { /* eta_ <- eta_n+1 + theta*(eta_n+1 - eta_n) */ /* chi_ <- chi_n+1 + theta*(chi_n+1 - chi_n) */ #if !THETA0 en = eta[l]; cn = chi[l]; #endif x = (nu[l-1] + nu[l+1]); y = (nu[l-nx] + nu[l+nx]); z = (nu[l-nxny] + nu[l+nxny]); /* eta_n+1 <- (eta_n - tau*laplace(nu)) / (1+tau) */ eta[l] = tau1 * ( eta[l] - lhh*nu[l] - lhx*x - lhy*y - lhz*z ); /* chi_n+1 <- chi_n - tau*(-div(p) - wave(nu)) */ chi[l] = chi[l] + ( /* div(p) */ hx*(p1[l]-p1[l-1]) + hy*(p2[l]-p2[l-nx]) + hz*(p3[l]-p3[l-nxny]) + /* wave(nu) */ (whh*nu[l] + whx*x + why*y + whz*z) ); /* eta_ <- eta_n+1 + theta*(eta_n+1 - eta_n) */ /* chi_ <- chi_n+1 + theta*(chi_n+1 - chi_n) */ #if !THETA0 eta_[l] = eta[l] + ((float)THETA)*(eta[l] - en); chi_[l] = chi[l] + ((float)THETA)*(chi[l] - cn); #endif } } } } return; } /* * eta <- (eta - tau*laplace(nu)) / (1 + tau) * chi <- chi - tau*(-div(p) - wave(nu)) * * eta_ <- eta_n+1 + THETA*(eta_n+1 - eta_n) * chi_ <- chi_n+1 + THETA*(chi_n+1 - chi_n) */ void update_primald(struct PD *pd, const double tau, const double *h, const size_t *sz) { size_t i, j, k; size_t l; double x, y, z; double *chi = (double *)pd->chi; double *eta = (double *)pd->eta; #if !THETA0 double cn, en; double *chi_ = (double *)pd->chi_; double *eta_ = (double *)pd->eta_; #endif double *nu = (double *)pd->nu; double *p = (double *)pd->p; uint8_t *m = (uint8_t *)pd->m; 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 NX = nx-1; const size_t NY = nx*(ny-1); const size_t NZ = nxny*(nz-1); const double hx = tau/h[0]; const double hy = tau/h[1]; const double hz = tau/h[2]; const double lhx = tau/(h[0]*h[0]); const double lhy = tau/(h[1]*h[1]); const double lhz = tau/(h[2]*h[2]); const double lhh = -2.0*(lhx+lhy+lhz); const double whx = -tau/(3.0*h[0]*h[0]); const double why = -tau/(3.0*h[1]*h[1]); const double whz = tau*2.0/(3.0*h[2]*h[2]); const double whh = -2.0*(whx+why+whz); const double tau1 = 1.0 / (1.0 + tau); double *p1 = &p[0*(nxny*nz)]; double *p2 = &p[1*(nxny*nz)]; double *p3 = &p[2*(nxny*nz)]; #pragma omp parallel for private(i,j,k,l,x,y,z) schedule(static) \ if (nxny*nz > 32*32*32) for(k = nxny; k < NZ; k += nxny) { for(j = nx; j < NY; j += nx) { l = 1 + j + k; for(i = 1; i < NX; ++i, ++l) { if (m[l] != 0) { /* eta_ <- eta_n+1 + theta*(eta_n+1 - eta_n) */ /* chi_ <- chi_n+1 + theta*(chi_n+1 - chi_n) */ #if !THETA0 en = eta[l]; cn = chi[l]; #endif x = (nu[l-1] + nu[l+1]); y = (nu[l-nx] + nu[l+nx]); z = (nu[l-nxny] + nu[l+nxny]); /* eta_n+1 <- (eta_n - tau*laplace(nu)) / (1+tau) */ eta[l] = tau1 * ( eta[l] - lhh*nu[l] - lhx*x - lhy*y - lhz*z ); /* chi_n+1 <- chi_n - tau*(-div(p) - wave(nu)) */ chi[l] = chi[l] + ( /* div(p) */ hx*(p1[l]-p1[l-1]) + hy*(p2[l]-p2[l-nx]) + hz*(p3[l]-p3[l-nxny]) + /* wave(nu) */ (whh*nu[l] + whx*x + why*y + whz*z) ); /* eta_ <- eta_n+1 + theta*(eta_n+1 - eta_n) */ /* chi_ <- chi_n+1 + theta*(chi_n+1 - chi_n) */ #if !THETA0 eta_[l] = eta[l] + ((double)THETA)*(eta[l] - en); chi_[l] = chi[l] + ((double)THETA)*(chi[l] - cn); #endif } } } } return; } uint8_t convergence_checkd(double *nr1, double *nr2, const double *chi, const double *chi0, const double *eta, const double *eta0, const double tol, const size_t N) { size_t l; double n1 = 0.0; double n2 = 0.0; double d1 = 0.0; double d2 = 0.0; /* can do naive summation for this */ /* pairwise summation norm is with the multigrid stuff */ #pragma omp parallel for private(l) \ reduction(+: n1, n2, d1, d2) schedule(static) for(l = 0; l < N; l += 1) { d1 += chi[l]*chi[l]; d2 += eta[l]*eta[l]; n1 += (chi[l]-chi0[l]) * (chi[l]-chi0[l]); n2 += (eta[l]-eta0[l]) * (eta[l]-eta0[l]); } n1 = sqrt(n1/d1); n2 = sqrt(n2/d2); *nr1 = n1; *nr2 = n2; return (uint8_t)((n1 < tol) && (n2 < 2.0*tol)); } uint8_t convergence_checkf(double *nr1, double *nr2, const float *chi, const float *chi0, const float *eta, const float *eta0, const double tol, const size_t N) { size_t l; double n1 = 0.0; double n2 = 0.0; double d1 = 0.0; double d2 = 0.0; /* can do naive summation for this */ /* pairwise summation norm is with the multigrid stuff */ #pragma omp parallel for private(l) \ reduction(+: n1, n2, d1, d2) schedule(static) for(l = 0; l < N; l += 1) { d1 += ((double)chi[l]) * ((double)chi[l]); d2 += ((double)eta[l]) * ((double)eta[l]); n1 += ((double)(chi[l]-chi0[l])) * ((double)chi[l]-chi0[l]); n2 += ((double)(eta[l]-eta0[l])) * ((double)eta[l]-eta0[l]); } n1 = sqrt(n1/d1); n2 = sqrt(n2/d2); *nr1 = n1; *nr2 = n2; return (uint8_t)((n1 < tol) && (n2 < 2.0*tol)); } void init_bitmask(uint32_t *mb, uint8_t *mi, const uint8_t *m, const size_t *sz) { size_t i, j, k; size_t l; uint8_t b, f, o; 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 NX = nx-1; const size_t NY = nx*(ny-1); const size_t NZ = nxny*(nz-1); /* * 0 b f c * -------------- * i 1 2 3 4 * j 5 6 7 8 * k 9 10 11 12 */ #pragma omp parallel for private(i,j,k,l,b,f,o) schedule(static) \ if (nxny*nz > 32*32*32) for(k = 0; k <= NZ; k += nxny) { for(j = 0; j <= NY; j += nx) { l = j + k; for(i = 0; i <= NX; ++i, ++l) { o = 3; f = (i < NX) && m[l+1]; mb[l] |= f ? (1 << o) : 0; o = 2; b = (i > 0) && m[l-1]; mb[l] |= b ? (1 << o) : 0; o = 1; mb[l] |= (1 << (o + 2*f + b)); o = 7; f = (j < NY) && m[l+nx]; mb[l] |= f ? (1 << o) : 0; o = 6; b = (j > 0) && m[l-nx]; mb[l] |= b ? (1 << o) : 0; o = 5; mb[l] |= (1 << (o + 2*f + b)); o = 11; f = (k < NZ) && m[l+nxny]; mb[l] |= f ? (1 << o) : 0; o = 10; b = (k > 0) && m[l-nxny]; mb[l] |= b ? (1 << o) : 0; o = 9; mb[l] |= (1 << (o + 2*f + b)); mb[l] = ((mb[l] & OUTSIDE) == OUTSIDE) ? 0 : mb[l]; mi[l] = ((mb[l] & INSIDE) == INSIDE); } } } return; } void mx_init(struct PD *pd, const mxArray *mxf, const mxArray *mxm) { mxClassID T = mxGetClassID(mxf); const size_t *sz = (const size_t *)mxGetDimensions(mxf); const size_t szp[4] = {sz[0], sz[1], sz[2], 3}; pd->chi = mxCreateNumericArray(3, sz, T, mxREAL); pd->eta = mxCreateNumericArray(3, sz, T, mxREAL); #if !THETA0 pd->chi_ = mxCreateNumericArray(3, sz, T, mxREAL); pd->eta_ = mxCreateNumericArray(3, sz, T, mxREAL); #else pd->chi_ = NULL; pd->eta_ = NULL; #endif pd->nu = mxCreateNumericArray(3, sz, T, mxREAL); pd->p = mxCreateNumericArray(4, szp, T, mxREAL); pd->f = mxDuplicateArray(mxf); pd->m = mxDuplicateArray(mxm); pd->mi = mxCreateNumericArray(3, sz, mxUINT8_CLASS, mxREAL); pd->mb = mxCreateNumericArray(3, sz, mxUINT32_CLASS, mxREAL); pd->chi0 = mxCreateNumericArray(3, sz, T, mxREAL); pd->eta0 = mxCreateNumericArray(3, sz, T, mxREAL); uint8_t *m = (uint8_t *)mxGetData(pd->m); uint8_t *mi = (uint8_t *)mxGetData(pd->mi); uint32_t *mb = (uint32_t *)mxGetData(pd->mb); init_bitmask(mb, mi, m, sz); return; } void mx_cleanup(struct PD *pd) { if (NULL != pd->chi) { mxDestroyArray(pd->chi); pd->chi = NULL; } if (NULL != pd->eta) { mxDestroyArray(pd->eta); pd->eta = NULL; } if (NULL != pd->chi_) { mxDestroyArray(pd->chi_); pd->chi_ = NULL; } if (NULL != pd->eta_) { mxDestroyArray(pd->eta_); pd->eta_ = NULL; } if (NULL != pd->nu) { mxDestroyArray(pd->nu); pd->nu = NULL; } if (NULL != pd->p) { mxDestroyArray(pd->p); pd->p = NULL; } if (NULL != pd->f) { mxDestroyArray(pd->f); pd->f = NULL; } if (NULL != pd->m) { mxDestroyArray(pd->m); pd->m = NULL; } if (NULL != pd->mi) { mxDestroyArray(pd->mi); pd->mi = NULL; } if (NULL != pd->mb) { mxDestroyArray(pd->mb); pd->mb = NULL; } if (NULL != pd->chi0) { mxDestroyArray(pd->chi0); pd->chi0 = NULL; } if (NULL != pd->eta0) { mxDestroyArray(pd->eta0); pd->eta0 = NULL; } return; }
GB_unop__identity_int32_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_int32_uint64) // op(A') function: GB (_unop_tran__identity_int32_uint64) // C type: int32_t // A type: uint64_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ int32_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) \ int32_t z = (int32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = (int32_t) aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int32_uint64) ( int32_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] ; int32_t z = (int32_t) aij ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint64_t aij = Ax [p] ; int32_t z = (int32_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_int32_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
DelayedUpdate.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2019 QMCPACK developers. // // File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // // File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory ////////////////////////////////////////////////////////////////////////////////////// #ifndef QMCPLUSPLUS_DELAYED_UPDATE_H #define QMCPLUSPLUS_DELAYED_UPDATE_H #include <OhmmsPETE/OhmmsVector.h> #include <OhmmsPETE/OhmmsMatrix.h> #include "Numerics/OhmmsBlas.h" #include "QMCWaveFunctions/Fermion/DiracMatrix.h" #include "Numerics/BlasThreadingEnv.h" #include "config.h" namespace qmcplusplus { /** implements delayed update on CPU using BLAS * @tparam T base precision for most computation * @tparam T_FP high precision for matrix inversion, T_FP >= T */ template<typename T, typename T_FP> class DelayedUpdate { /// define real type using real_type = typename scalar_traits<T>::real_type; /// orbital values of delayed electrons Matrix<T> U; /// rows of Ainv corresponding to delayed electrons Matrix<T> V; /// Matrix inverse of B, at maximum KxK Matrix<T> Binv; /// scratch space, used during inverse update Matrix<T> tempMat; /// temporal scratch space used by SM-1 Vector<T> temp; /// new column of B Vector<T> p; /// list of delayed electrons std::vector<int> delay_list; /// current number of delays, increase one for each acceptance, reset to 0 after updating Ainv int delay_count; /// matrix inversion engine DiracMatrix<T_FP, T> detEng; public: /// default constructor DelayedUpdate() : delay_count(0) {} /** resize the internal storage * @param norb number of electrons/orbitals * @param delay, maximum delay 0<delay<=norb */ inline void resize(int norb, int delay) { V.resize(delay, norb); U.resize(delay, norb); p.resize(delay); temp.resize(norb); tempMat.resize(norb, delay); Binv.resize(delay, delay); delay_list.resize(delay); } /** compute the inverse of the transpose of matrix A * @param logdetT orbital value matrix * @param Ainv inverse matrix */ inline void invert_transpose(const Matrix<T>& logdetT, Matrix<T>& Ainv, real_type& LogValue, real_type& PhaseValue) { detEng.invert_transpose(logdetT, Ainv, LogValue, PhaseValue); // safe mechanism delay_count = 0; } /** initialize internal objects when Ainv is refreshed * @param Ainv inverse matrix */ inline void initializeInv(const Matrix<T>& Ainv) { // safe mechanism delay_count = 0; } inline int getDelayCount() const { return delay_count; } /** compute the row of up-to-date Ainv * @param Ainv inverse matrix * @param rowchanged the row id corresponding to the proposed electron */ template<typename VVT> inline void getInvRow(const Matrix<T>& Ainv, int rowchanged, VVT& invRow) { if (delay_count == 0) { // Ainv is fresh, directly access Ainv std::copy_n(Ainv[rowchanged], invRow.size(), invRow.data()); return; } const T cone(1); const T czero(0); const int norb = Ainv.rows(); const int lda_Binv = Binv.cols(); // save Ainv[rowchanged] to invRow std::copy_n(Ainv[rowchanged], norb, invRow.data()); // multiply V (NxK) Binv(KxK) U(KxN) invRow right to the left BLAS::gemv('T', norb, delay_count, cone, U.data(), norb, invRow.data(), 1, czero, p.data(), 1); BLAS::gemv('N', delay_count, delay_count, cone, Binv.data(), lda_Binv, p.data(), 1, czero, Binv[delay_count], 1); BLAS::gemv('N', norb, delay_count, -cone, V.data(), norb, Binv[delay_count], 1, cone, invRow.data(), 1); } /** accept a move with the update delayed * @param Ainv inverse matrix * @param rowchanged the row id corresponding to the proposed electron * @param psiV new orbital values * * Before delay_count reaches the maximum delay, only Binv is updated with a recursive algorithm */ template<typename VVT> inline void acceptRow(Matrix<T>& Ainv, int rowchanged, const VVT& psiV) { const T cminusone(-1); const T czero(0); const int norb = Ainv.rows(); const int lda_Binv = Binv.cols(); std::copy_n(Ainv[rowchanged], norb, V[delay_count]); std::copy_n(psiV.data(), norb, U[delay_count]); delay_list[delay_count] = rowchanged; // the new Binv is [[X Y] [Z x]] BLAS::gemv('T', norb, delay_count + 1, cminusone, V.data(), norb, psiV.data(), 1, czero, p.data(), 1); // x T y = -p[delay_count]; for (int i = 0; i < delay_count; i++) y += Binv[delay_count][i] * p[i]; Binv[delay_count][delay_count] = y = T(1) / y; // Y BLAS::gemv('T', delay_count, delay_count, y, Binv.data(), lda_Binv, p.data(), 1, czero, Binv.data() + delay_count, lda_Binv); // X BLAS::ger(delay_count, delay_count, cminusone, Binv[delay_count], 1, Binv.data() + delay_count, lda_Binv, Binv.data(), lda_Binv); // Z for (int i = 0; i < delay_count; i++) Binv[delay_count][i] *= -y; delay_count++; // update Ainv when maximal delay is reached if (delay_count == lda_Binv) updateInvMat(Ainv); } /** update the full Ainv and reset delay_count * @param Ainv inverse matrix */ inline void updateInvMat(Matrix<T>& Ainv) { if (delay_count == 0) return; // update the inverse matrix const T cone(1); const T czero(0); const int norb = Ainv.rows(); if (delay_count == 1) { // this is a special case invoking the Fahy's variant of Sherman-Morrison update. // Only use the first norb elements of tempMat as a temporal array BLAS::gemv('T', norb, norb, cone, Ainv.data(), norb, U[0], 1, czero, temp.data(), 1); temp[delay_list[0]] -= cone; BLAS::ger(norb, norb, -Binv[0][0], V[0], 1, temp.data(), 1, Ainv.data(), norb); } else { const int lda_Binv = Binv.cols(); // number of threads at the next level, forced to 1 if the problem is small. const int num_threads = (norb < 256 ? 1 : getNextLevelNumThreads()); if (num_threads == 1 || BlasThreadingEnv::NestedThreadingSupported()) { // threading depends on BLAS BlasThreadingEnv knob(num_threads); BLAS::gemm('T', 'N', delay_count, norb, norb, cone, U.data(), norb, Ainv.data(), norb, czero, tempMat.data(), lda_Binv); for (int i = 0; i < delay_count; i++) tempMat(delay_list[i], i) -= cone; BLAS::gemm('N', 'N', norb, delay_count, delay_count, cone, V.data(), norb, Binv.data(), lda_Binv, czero, U.data(), norb); BLAS::gemm('N', 'N', norb, norb, delay_count, -cone, U.data(), norb, tempMat.data(), lda_Binv, cone, Ainv.data(), norb); } else { // manually threaded version of the above GEMM calls #pragma omp parallel { const int block_size = getAlignedSize<T>((norb + num_threads - 1) / num_threads); int num_block = (norb + block_size - 1) / block_size; #pragma omp for for (int ix = 0; ix < num_block; ix++) { int x_offset = ix * block_size; BLAS::gemm('T', 'N', delay_count, std::min(norb - x_offset, block_size), norb, cone, U.data(), norb, Ainv[x_offset], norb, czero, tempMat[x_offset], lda_Binv); } #pragma omp master for (int i = 0; i < delay_count; i++) tempMat(delay_list[i], i) -= cone; #pragma omp for for (int iy = 0; iy < num_block; iy++) { int y_offset = iy * block_size; BLAS::gemm('N', 'N', std::min(norb - y_offset, block_size), delay_count, delay_count, cone, V.data() + y_offset, norb, Binv.data(), lda_Binv, czero, U.data() + y_offset, norb); } #pragma omp for collapse(2) nowait for (int iy = 0; iy < num_block; iy++) for (int ix = 0; ix < num_block; ix++) { int x_offset = ix * block_size; int y_offset = iy * block_size; BLAS::gemm('N', 'N', std::min(norb - y_offset, block_size), std::min(norb - x_offset, block_size), delay_count, -cone, U.data() + y_offset, norb, tempMat[x_offset], lda_Binv, cone, Ainv[x_offset] + y_offset, norb); } } } } delay_count = 0; } }; } // namespace qmcplusplus #endif // QMCPLUSPLUS_DELAYED_UPDATE_H
zip_fmt_plug.c
/* * ZIP cracker patch for JtR. Hacked together during June of 2011 * by Dhiru Kholia <dhiru.kholia at gmail.com> for GSoC. * * This software is Copyright (c) 2011, Dhiru Kholia <dhiru.kholia at gmail.com>, * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without modification, * are permitted. * * http://www.winzip.com/aes_info.htm (There is a 1 in 65,536 chance that an * incorrect password will yield a matching verification value; therefore, a * matching verification value cannot be absolutely relied on to indicate a * correct password.). The alternative is to implement/use a full unzip engine. * * This format significantly improved, Summer of 2014, JimF. Changed the signature * to the $zip2$, and added logic to properly make this format work. Now there is no * false positives any more. Now it properly cracks the passwords. There is * an hmac-sha1 'key' that is also processed (and the decryption key), in the pbkdf2 * call. Now we use this hmac-sha1 key, process the compressed and encrypted buffer, * compare to a 10 byte checksum (which is now the binary blob), and we KNOW that we * have cracked or not cracked the key. The $zip$ was broken before, so that signature * has simply been retired as DOA. This format is now much like the pkzip format. * it may have all data contained within the hash string, OR it may have some, and * have a file pointer on where to get the rest of the data. * * optimizations still that can be done. * 1. decrypt and inflate some data for really large buffers, BEFORE doing the * hmac-sha1 call. The inflate algorithm is pretty self checking for 'valid' * data, so a few hundred bytes of checking and we are 99.999% sure we have the * right password, before starting an expensive hmac (for instance if the zip blob * was 50mb). * 2. Put in the 'file magic' logic we have for pkzip. There is a place holder for it, * but the logic has not been added. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_zip; #elif FMT_REGISTERS_H john_register_one(&fmt_zip); #else #include <string.h> #include <assert.h> #include <errno.h> #include <ctype.h> #include "arch.h" #include "crc32.h" #include "misc.h" #include "params.h" #include "common.h" #include "formats.h" #include "johnswap.h" #include "memory.h" #include "pkzip.h" #include "pbkdf2_hmac_sha1.h" #include "dyna_salt.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 // Tuned on core i7 #endif static int omp_t = 1; #endif #include "hmac_sha.h" #include "memdbg.h" #define KEY_LENGTH(mode) (8 * ((mode) & 3) + 8) #define SALT_LENGTH(mode) (4 * ((mode) & 3) + 4) typedef struct my_salt_t { dyna_salt dsalt; uint32_t comp_len; struct { uint16_t type : 4; uint16_t mode : 4; } v; unsigned char passverify[2]; unsigned char salt[SALT_LENGTH(3)]; //uint64_t data_key; // MSB of md5(data blob). We lookup using this. unsigned char datablob[1]; } my_salt; #define FORMAT_LABEL "ZIP" #define FORMAT_NAME "WinZip" #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 32/" ARCH_BITS_STR #endif #define PLAINTEXT_LENGTH 125 #define BINARY_ALIGN sizeof(ARCH_WORD_32) #define SALT_SIZE sizeof(my_salt*) #define SALT_ALIGN sizeof(my_salt*) #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static unsigned char (*crypt_key)[((WINZIP_BINARY_SIZE+3)/4)*4]; static my_salt *saved_salt; // filename:$zip2$*Ty*Mo*Ma*Sa*Va*Le*DF*Au*$/zip2$ // Ty = type (0) and ignored. // Mo = mode (1 2 3 for 128/192/256 bit // Ma = magic (file magic). This is reserved for now. See pkzip_fmt_plug.c or zip2john.c for information. // For now, this must be a '0' // Sa = salt(hex). 8, 12 or 16 bytes of salt (depends on mode) // Va = Verification bytes(hex) (2 byte quick checker) // Le = real compr len (hex) length of compressed/encrypted data (field DF) // DF = compressed data DF can be L*2 hex bytes, and if so, then it is the ENTIRE file blob written 'inline'. // However, if the data blob is too long, then a .zip ZIPDATA_FILE_PTR_RECORD structure will be the 'contents' of DF // Au = Authentication code (hex) a 10 byte hex value that is the hmac-sha1 of data over D. This is the binary() value // ZIPDATA_FILE_PTR_RECORD (this can be the 'DF' of this above hash line. // *ZFILE*Fn*Oh*Ob* (Note, the leading and trailing * are the * that 'wrap' the DF object. // ZFILE This is the literal string ZFILE // Fn This is the name of the .zip file. NOTE the user will need to keep the .zip file in proper locations (same as // was seen when running zip2john. If the file is removed, this hash line will no longer be valid. // Oh Offset to the zip central header record for this blob. // Ob Offset to the start of the blob data static void init(struct fmt_main *self) { #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); } static void done(void) { MEM_FREE(crypt_key); MEM_FREE(saved_key); } static void *get_salt(char *ciphertext) { int i; my_salt salt, *psalt; static unsigned char *ptr; /* extract data from "ciphertext" */ c8 *copy_mem = strdup(ciphertext); c8 *cp, *p; if (!ptr) ptr = mem_alloc_tiny(sizeof(my_salt*),sizeof(my_salt*)); p = copy_mem + WINZIP_TAG_LENGTH+1; /* skip over "$zip2$*" */ memset(&salt, 0, sizeof(salt)); cp = strtokm(p, "*"); // type salt.v.type = atoi((const char*)cp); cp = strtokm(NULL, "*"); // mode salt.v.mode = atoi((const char*)cp); cp = strtokm(NULL, "*"); // file_magic enum (ignored) cp = strtokm(NULL, "*"); // salt for (i = 0; i < SALT_LENGTH(salt.v.mode); i++) salt.salt[i] = (atoi16[ARCH_INDEX(cp[i<<1])]<<4) | atoi16[ARCH_INDEX(cp[(i<<1)+1])]; cp = strtokm(NULL, "*"); // validator salt.passverify[0] = (atoi16[ARCH_INDEX(cp[0])]<<4) | atoi16[ARCH_INDEX(cp[1])]; salt.passverify[1] = (atoi16[ARCH_INDEX(cp[2])]<<4) | atoi16[ARCH_INDEX(cp[3])]; cp = strtokm(NULL, "*"); // data len sscanf((const char *)cp, "%x", &salt.comp_len); // later we will store the data blob in our own static data structure, and place the 64 bit LSB of the // MD5 of the data blob into a field in the salt. For the first POC I store the entire blob and just // make sure all my test data is small enough to fit. cp = strtokm(NULL, "*"); // data blob // Ok, now create the allocated salt record we are going to return back to John, using the dynamic // sized data buffer. psalt = (my_salt*)mem_calloc(1, sizeof(my_salt) + salt.comp_len); psalt->v.type = salt.v.type; psalt->v.mode = salt.v.mode; psalt->comp_len = salt.comp_len; psalt->dsalt.salt_alloc_needs_free = 1; // we used mem_calloc, so JtR CAN free our pointer when done with them. memcpy(psalt->salt, salt.salt, sizeof(salt.salt)); psalt->passverify[0] = salt.passverify[0]; psalt->passverify[1] = salt.passverify[1]; // set the JtR core linkage stuff for this dyna_salt psalt->dsalt.salt_cmp_offset = SALT_CMP_OFF(my_salt, comp_len); psalt->dsalt.salt_cmp_size = SALT_CMP_SIZE(my_salt, comp_len, datablob, psalt->comp_len); if (strcmp((const char*)cp, "ZFILE")) { for (i = 0; i < psalt->comp_len; i++) psalt->datablob[i] = (atoi16[ARCH_INDEX(cp[i<<1])]<<4) | atoi16[ARCH_INDEX(cp[(i<<1)+1])]; } else { c8 *Fn, *Oh, *Ob; long len; uint32_t id; FILE *fp; Fn = strtokm(NULL, "*"); Oh = strtokm(NULL, "*"); Ob = strtokm(NULL, "*"); fp = fopen((const char*)Fn, "rb"); if (!fp) { psalt->v.type = 1; // this will tell the format to 'skip' this salt, it is garbage goto Bail; } sscanf((const char*)Oh, "%lx", &len); if (fseek(fp, len, SEEK_SET)) { fclose(fp); psalt->v.type = 1; goto Bail; } id = fget32LE(fp); if (id != 0x04034b50U) { fclose(fp); psalt->v.type = 1; goto Bail; } sscanf((const char*)Ob, "%lx", &len); if (fseek(fp, len, SEEK_SET)) { fclose(fp); psalt->v.type = 1; goto Bail; } if (fread(psalt->datablob, 1, psalt->comp_len, fp) != psalt->comp_len) { fclose(fp); psalt->v.type = 1; goto Bail; } fclose(fp); } Bail:; MEM_FREE(copy_mem); memcpy(ptr, &psalt, sizeof(my_salt*)); return (void*)ptr; } static void set_salt(void *salt) { saved_salt = *((my_salt**)salt); } static void set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static int get_hash_0(int index) { return ((ARCH_WORD_32*)&(crypt_key[index]))[0] & PH_MASK_0; } static int get_hash_1(int index) { return ((ARCH_WORD_32*)&(crypt_key[index]))[0] & PH_MASK_1; } static int get_hash_2(int index) { return ((ARCH_WORD_32*)&(crypt_key[index]))[0] & PH_MASK_2; } static int get_hash_3(int index) { return ((ARCH_WORD_32*)&(crypt_key[index]))[0] & PH_MASK_3; } static int get_hash_4(int index) { return ((ARCH_WORD_32*)&(crypt_key[index]))[0] & PH_MASK_4; } static int get_hash_5(int index) { return ((ARCH_WORD_32*)&(crypt_key[index]))[0] & PH_MASK_5; } static int get_hash_6(int index) { return ((ARCH_WORD_32*)&(crypt_key[index]))[0] & PH_MASK_6; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index; if (saved_salt->v.type) { // This salt passed valid() but failed get_salt(). // Should never happen. memset(crypt_key, 0, count * WINZIP_BINARY_SIZE); return count; } #ifdef _OPENMP #pragma omp parallel for default(none) private(index) shared(count, saved_key, saved_salt, crypt_key) #endif for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) { #ifdef SIMD_COEF_32 unsigned char pwd_ver[64*MAX_KEYS_PER_CRYPT]; int lens[MAX_KEYS_PER_CRYPT], i; unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = strlen(saved_key[i+index]); pin[i] = (unsigned char*)saved_key[i+index]; pout[i] = &pwd_ver[i*(2+2*KEY_LENGTH(saved_salt->v.mode))]; } pbkdf2_sha1_sse((const unsigned char **)pin, lens, saved_salt->salt, SALT_LENGTH(saved_salt->v.mode), KEYING_ITERATIONS, pout, 2, 2*KEY_LENGTH(saved_salt->v.mode)); for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { if (!memcmp(pout[i], saved_salt->passverify, 2)) { pbkdf2_sha1_sse((const unsigned char **)pin, lens, saved_salt->salt, SALT_LENGTH(saved_salt->v.mode), KEYING_ITERATIONS, pout, KEY_LENGTH(saved_salt->v.mode), KEY_LENGTH(saved_salt->v.mode)); hmac_sha1(pout[i], KEY_LENGTH(saved_salt->v.mode), (const unsigned char*)saved_salt->datablob, saved_salt->comp_len, crypt_key[index+i], WINZIP_BINARY_SIZE); } else memset(crypt_key[index+i], 0, WINZIP_BINARY_SIZE); } #else union { unsigned char pwd_ver[64]; ARCH_WORD_32 w; } x; unsigned char *pwd_ver = x.pwd_ver; pbkdf2_sha1((unsigned char *)saved_key[index], strlen(saved_key[index]), saved_salt->salt, SALT_LENGTH(saved_salt->v.mode), KEYING_ITERATIONS, pwd_ver, 2, 2*KEY_LENGTH(saved_salt->v.mode)); if (!memcmp(pwd_ver, saved_salt->passverify, 2)) { pbkdf2_sha1((unsigned char *)saved_key[index], strlen(saved_key[index]), saved_salt->salt, SALT_LENGTH(saved_salt->v.mode), KEYING_ITERATIONS, pwd_ver, KEY_LENGTH(saved_salt->v.mode), KEY_LENGTH(saved_salt->v.mode)); hmac_sha1(pwd_ver, KEY_LENGTH(saved_salt->v.mode), (const unsigned char*)saved_salt->datablob, saved_salt->comp_len, crypt_key[index], WINZIP_BINARY_SIZE); } else memset(crypt_key[index], 0, WINZIP_BINARY_SIZE); #endif } return count; } static int cmp_all(void *binary, int count) { int i; for (i = 0; i < count; i++) if (((ARCH_WORD_32*)&(crypt_key[i]))[0] == ((ARCH_WORD_32*)binary)[0]) return 1; return 0; } static int cmp_one(void *binary, int index) { return (((ARCH_WORD_32*)&(crypt_key[index]))[0] == ((ARCH_WORD_32*)binary)[0]); } static int cmp_exact(char *source, int index) { void *b = winzip_common_binary(source); return !memcmp(b, crypt_key[index], sizeof(crypt_key[index])); } struct fmt_main fmt_zip = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, WINZIP_BENCHMARK_COMMENT, WINZIP_BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, 4, // WINZIP_BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_DYNA_SALT, { NULL }, winzip_common_tests }, { init, done, fmt_default_reset, fmt_default_prepare, winzip_common_valid, fmt_default_split, winzip_common_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_dyna_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
nestedomp.c
#include <stdio.h> #include <unistd.h> #ifdef THREADED_OMP #include <omp.h> #endif #include "../gptl.h" int main () { int m, n; /* inner, outer nested loop indices */ int t; /* linear thread number */ const int msize = 2; /* dimension M */ double value; /* return from GPTLget_wallclock */ int ret; void sub (const int, const int, const int); #ifdef THREADED_OMP omp_set_num_threads (6); /* 3 outer x 2 inner threads */ omp_set_nested (1); #endif ret = GPTLinitialize (); #pragma omp parallel for private (n) num_threads(3) for (n = 0; n < 3; ++n) { #pragma omp parallel for private (m, ret) num_threads(2) for (m = 0; m < msize; ++m) { ret = GPTLstart ("sub"); sub (m, n, msize); ret = GPTLstop ("sub"); } } #ifdef THREADED_OMP for (n = 0; n < 3; ++n) { for (m = 0; m < msize; ++m) { t = n*msize + m; ret = GPTLget_wallclock ("sub", t, &value); if (ret != 0) { printf ("Failure to get wallclock for t=%d\n", t); return 1; } } } #endif ret = GPTLpr (0); return 0; } void sub (const int m, const int n, const int msize) { int sleep_usecs = (useconds_t) (n*msize + m) * 1000; (void) usleep (sleep_usecs); }
cpu_ctc.h
#pragma once #include <tuple> #include <cmath> #include <limits> #include <algorithm> #include <numeric> #if !defined(CTC_DISABLE_OMP) && !defined(APPLE) #include <omp.h> #endif #include "ctc_helper.h" template<typename ProbT> class CpuCTC { public: // Noncopyable CpuCTC(int alphabet_size, int minibatch, void* workspace, int num_threads, int blank_label) : alphabet_size_(alphabet_size), minibatch_(minibatch), num_threads_(num_threads), workspace_(workspace), blank_label_(blank_label) { #if defined(CTC_DISABLE_OMP) || defined(APPLE) #else if (num_threads > 0) { omp_set_num_threads(num_threads); } else { num_threads_ = omp_get_max_threads(); } #endif }; CpuCTC(const CpuCTC&) = delete; CpuCTC& operator=(const CpuCTC&) = delete; ctcStatus_t cost_and_grad(const ProbT* const activations, ProbT *grads, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths); ctcStatus_t score_forward(const ProbT* const activations, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths); private: class CpuCTC_metadata { private: int setup_labels(const int* const labels, int blank_label, int L, int S); public: CpuCTC_metadata(int L, int S, int T, int mb, int alphabet_size, void* workspace, size_t bytes_used, int blank_label, const int* const labels); ProbT* alphas; ProbT* betas; int* labels_w_blanks; int* e_inc; int* s_inc; ProbT* output; int repeats; }; int alphabet_size_; // Number of characters plus blank int minibatch_; int num_threads_; int blank_label_; void* workspace_; void softmax(const ProbT* const activations, ProbT* probs, const int* const input_lengths); std::tuple<ProbT, bool> cost_and_grad_kernel(ProbT *grad, const ProbT* const probs, const int* const labels, int T, int L, int mb, size_t bytes_used); ProbT compute_alphas(const ProbT* probs, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas); ProbT compute_betas_and_grad(ProbT* grad, const ProbT* const probs, ProbT log_partition, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas, ProbT* betas, ProbT* output); }; template<typename ProbT> CpuCTC<ProbT>::CpuCTC_metadata::CpuCTC_metadata(int L, int S, int T, int mb, int alphabet_size, void* workspace, size_t bytes_used, int blank_label, const int* const labels) { alphas = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * S * T; std::fill(alphas, alphas + S * T, ctc_helper::neg_inf<ProbT>()); betas = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * S; std::fill(betas, betas + S, ctc_helper::neg_inf<ProbT>()); labels_w_blanks = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; e_inc = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; s_inc = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; output = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * alphabet_size; repeats = setup_labels(labels, blank_label, L, S); } template<typename ProbT> int CpuCTC<ProbT>::CpuCTC_metadata::setup_labels(const int* const labels, int blank_label, int L, int S) { int e_counter = 0; int s_counter = 0; s_inc[s_counter++] = 1; int repeats = 0; for (int i = 1; i < L; ++i) { if (labels[i-1] == labels[i]) { s_inc[s_counter++] = 1; s_inc[s_counter++] = 1; e_inc[e_counter++] = 1; e_inc[e_counter++] = 1; ++repeats; } else { s_inc[s_counter++] = 2; e_inc[e_counter++] = 2; } } e_inc[e_counter++] = 1; for (int i = 0; i < L; ++i) { labels_w_blanks[2 * i] = blank_label; labels_w_blanks[2 * i + 1] = labels[i]; } labels_w_blanks[S - 1] = blank_label; return repeats; } template<typename ProbT> void CpuCTC<ProbT>::softmax(const ProbT* const activations, ProbT* probs, const int* const input_lengths) { #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { for(int c = 0; c < input_lengths[mb]; ++c) { int col_offset = (mb + minibatch_ * c) * alphabet_size_; ProbT max_activation = -std::numeric_limits<ProbT>::infinity(); for(int r = 0; r < alphabet_size_; ++r) max_activation = std::max(max_activation, activations[r + col_offset]); ProbT denom = ProbT(0.); for(int r = 0; r < alphabet_size_; ++r) { probs[r + col_offset] = std::exp(activations[r + col_offset] - max_activation); denom += probs[r + col_offset]; } for(int r = 0; r < alphabet_size_; ++r) { probs[r + col_offset] /= denom; } } } } template<typename ProbT> std::tuple<ProbT, bool> CpuCTC<ProbT>::cost_and_grad_kernel(ProbT *grad, const ProbT* const probs, const int* const labels, int T, int L, int mb, size_t bytes_used) { const int S = 2*L + 1; // Number of labels with blanks CpuCTC_metadata ctcm(L, S, T, mb, alphabet_size_, workspace_, bytes_used, blank_label_, labels); bool over_threshold = false; if (L + ctcm.repeats > T) { return std::make_tuple(ProbT(0), over_threshold); // TODO, not right to return 0 } ProbT llForward = compute_alphas(probs, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas); ProbT llBackward = compute_betas_and_grad(grad, probs, llForward, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas, ctcm.betas, ctcm.output); ProbT diff = std::abs(llForward - llBackward); if (diff > ctc_helper::threshold) { over_threshold = true; } return std::make_tuple(-llForward, over_threshold); } // Computes forward probabilities template<typename ProbT> ProbT CpuCTC<ProbT>::compute_alphas(const ProbT* probs, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas) { int start = (((S /2) + repeats - T) < 0) ? 0 : 1, end = S > 1 ? 2 : 1; for (int i = start; i < end; ++i) { alphas[i] = probs[labels[i]]; } for(int t = 1; t < T; ++t) { int remain = (S / 2) + repeats - (T - t); if(remain >= 0) start += s_inc[remain]; if(t <= (S / 2) + repeats) end += e_inc[t - 1]; int startloop = start; int idx1 = t * S, idx2 = (t - 1) * S, idx3 = t * (alphabet_size_ * minibatch_); if (start == 0) { alphas[idx1] = alphas[idx2] + probs[blank_label_ + idx3]; startloop += 1; } for(int i = startloop; i < end; ++i) { ProbT prev_sum = ctc_helper::log_plus<ProbT>()(alphas[i + idx2], alphas[(i-1) + idx2]); // Skip two if not on blank and not on repeat. if (labels[i] != blank_label_ && i != 1 && labels[i] != labels[i-2]) prev_sum = ctc_helper::log_plus<ProbT>()(prev_sum, alphas[(i-2) + idx2]); alphas[i + idx1] = prev_sum + probs[labels[i] + idx3]; } } ProbT loglike = ctc_helper::neg_inf<ProbT>(); for(int i = start; i < end; ++i) { loglike = ctc_helper::log_plus<ProbT>()(loglike, alphas[i + (T - 1) * S]); } return loglike; } // Starting from T, we sweep backward over the alpha array computing one column // of betas as we go. At each position we can update product alpha * beta and then // sum into the gradient associated with each label. // NOTE computes gradient w.r.t UNNORMALIZED final layer activations. // Assumed passed in grads are already zeroed! template<typename ProbT> ProbT CpuCTC<ProbT>::compute_betas_and_grad(ProbT* grad, const ProbT* const probs, ProbT log_partition, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas, ProbT* betas, ProbT* output) { int start = S > 1 ? (S - 2) : 0, end = (T > (S / 2) + repeats) ? S : S-1; std::fill(output, output + alphabet_size_, ctc_helper::neg_inf<ProbT>()); //set the starting values in the beta column at the very right edge for (int i = start; i < end; ++i) { betas[i] = probs[labels[i] + (T - 1) * (alphabet_size_ * minibatch_)]; //compute alpha * beta in log space at this position in (S, T) space alphas[i + (T - 1) * S] += betas[i]; //update the gradient associated with this label //essentially performing a reduce-by-key in a sequential manner output[labels[i]] = ctc_helper::log_plus<ProbT>()(alphas[i + (T - 1) * S], output[labels[i]]); } //update the gradient wrt to each unique label /* for (int i = 0; i < alphabet_size_; ++i) { int idx3 = (T - 1) * alphabet_size_ * minibatch_ + i; if (output[i] == 0.0 || output[i] == ctc_helper::neg_inf<ProbT>() || probs[idx3] == 0.0) { grad[idx3] = probs[idx3]; } else { grad[idx3] = probs[idx3] - std::exp(output[i] - std::log(probs[idx3]) - log_partition); } }*/ for (int i = 0; i < alphabet_size_; ++i) { int idx3 = (T - 1) * alphabet_size_ * minibatch_ + i; grad[idx3] = std::exp(output[i] - probs[idx3] - log_partition); } //loop from the second to last column all the way to the left for(int t = T - 2; t >= 0; --t) { int remain = (S / 2) + repeats - (T - t); if(remain >= -1) start -= s_inc[remain + 1]; if(t < (S / 2) + repeats) end -= e_inc[t]; int endloop = end == S ? end - 1 : end; int idx1 = t * S, idx3 = t * (alphabet_size_ * minibatch_); std::fill(output, output + alphabet_size_, ctc_helper::neg_inf<ProbT>()); for(int i = start; i < endloop; ++i) { ProbT next_sum = ctc_helper::log_plus<ProbT>()(betas[i], betas[(i+1)]); // Skip two if not on blank and not on repeat. if (labels[i] != blank_label_ && i != (S-2) && labels[i] != labels[i+2]){ next_sum = ctc_helper::log_plus<ProbT>()(next_sum, betas[(i+2)]); } betas[i] = next_sum + probs[labels[i] + idx3]; //compute alpha * beta in log space alphas[i + idx1] += betas[i]; //update the gradient associated with this label output[labels[i]] = ctc_helper::log_plus<ProbT>()(alphas[i + idx1], output[labels[i]]); } if (end == S) { betas[(S-1)] = betas[(S-1)] + probs[blank_label_ + idx3]; alphas[(S-1) + idx1] += betas[(S-1)]; output[labels[S-1]] = ctc_helper::log_plus<ProbT>()(alphas[S-1 + idx1], output[labels[S-1]]); } //go over the unique labels and compute the final grad // wrt to each one at this time step /* for (int i = 0; i < alphabet_size_; ++i) { if (output[i] == 0.0 || output[i] == ctc_helper::neg_inf<ProbT>() || probs[idx3] == 0.0) { grad[idx3] = probs[idx3]; } else { grad[idx3] = probs[idx3] - std::exp(output[i] - std::log(probs[idx3]) - log_partition); } ++idx3; }*/ for (int i = 0; i < alphabet_size_; ++i) { grad[idx3] = std::exp(output[i] - probs[idx3] - log_partition); ++idx3; } } ProbT loglike = ctc_helper::neg_inf<ProbT>(); for(int i = start; i < end; ++i) { loglike = ctc_helper::log_plus<ProbT>()(loglike, betas[i]); } return loglike; } template<typename ProbT> ctcStatus_t CpuCTC<ProbT>::cost_and_grad(const ProbT* const activations, ProbT *grads, ProbT *costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths) { if (activations == nullptr || grads == nullptr || costs == nullptr || flat_labels == nullptr || label_lengths == nullptr || input_lengths == nullptr ) return CTC_STATUS_INVALID_VALUE; ProbT* probs = static_cast<ProbT *>(workspace_); int maxT = *std::max_element(input_lengths, input_lengths + minibatch_); size_t bytes_used = sizeof(ProbT) * minibatch_ * alphabet_size_ * maxT; //per minibatch memory size_t per_minibatch_bytes = 0; int maxL = *std::max_element(label_lengths, label_lengths + minibatch_);; int maxS = 2 * maxL + 1; //output per_minibatch_bytes += sizeof(float) * alphabet_size_; //alphas per_minibatch_bytes += sizeof(float) * maxS * maxT; //betas per_minibatch_bytes += sizeof(float) * maxS; //labels w/blanks, e_inc, s_inc per_minibatch_bytes += 3 * sizeof(int) * maxS; softmax(activations, probs, input_lengths); #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { const int T = input_lengths[mb]; // Length of utterance (time) const int L = label_lengths[mb]; // Number of labels in transcription bool mb_status; std::tie(costs[mb], mb_status) = cost_and_grad_kernel(grads + mb * alphabet_size_, probs + mb * alphabet_size_, flat_labels + std::accumulate(label_lengths, label_lengths + mb, 0), T, L, mb, bytes_used + mb * per_minibatch_bytes); } return CTC_STATUS_SUCCESS; } template<typename ProbT> ctcStatus_t CpuCTC<ProbT>::score_forward(const ProbT* const activations, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths) { if (activations == nullptr || costs == nullptr || flat_labels == nullptr || label_lengths == nullptr || input_lengths == nullptr ) return CTC_STATUS_INVALID_VALUE; ProbT* probs = static_cast<ProbT *>(workspace_); int maxT = *std::max_element(input_lengths, input_lengths + minibatch_); size_t bytes_used = sizeof(ProbT) * minibatch_ * alphabet_size_ * maxT; //per minibatch memory size_t per_minibatch_bytes = 0; int maxL = *std::max_element(label_lengths, label_lengths + minibatch_); int maxS = 2 * maxL + 1; //output per_minibatch_bytes += sizeof(float) * alphabet_size_; //alphas per_minibatch_bytes += sizeof(float) * maxS * maxT; //betas per_minibatch_bytes += sizeof(float) * maxS; //labels w/blanks, e_inc, s_inc per_minibatch_bytes += 3 * sizeof(int) * maxS; softmax(activations, probs, input_lengths); #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { const int T = input_lengths[mb]; // Length of utterance (time) const int L = label_lengths[mb]; // Number of labels in transcription const int S = 2*L + 1; // Number of labels with blanks CpuCTC_metadata ctcm(L, S, T, mb, alphabet_size_, workspace_, bytes_used + mb * per_minibatch_bytes, blank_label_, flat_labels + std::accumulate(label_lengths, label_lengths + mb, 0)); if (L + ctcm.repeats > T) costs[mb] = ProbT(0); else { costs[mb] = -compute_alphas(probs + mb * alphabet_size_, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas); } } return CTC_STATUS_SUCCESS; }
omptarget.h
//===---- omptarget.h - OpenMP GPU initialization ---------------- CUDA -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the declarations of all library macros, types, // and functions. // //===----------------------------------------------------------------------===// #ifndef OMPTARGET_H #define OMPTARGET_H #include "common/allocator.h" #include "common/debug.h" // debug #include "common/state-queue.h" #include "common/support.h" #include "interface.h" // interfaces with omp, compiler, and user #include "target_impl.h" #define OMPTARGET_NVPTX_VERSION 1.1 // used by the library for the interface with the app #define DISPATCH_FINISHED 0 #define DISPATCH_NOTFINISHED 1 // used by dynamic scheduling #define FINISHED 0 #define NOT_FINISHED 1 #define LAST_CHUNK 2 #define BARRIER_COUNTER 0 #define ORDERED_COUNTER 1 // Worker slot type which is initialized with the default worker slot // size of 4*32 bytes. struct __kmpc_data_sharing_slot { __kmpc_data_sharing_slot *Next; __kmpc_data_sharing_slot *Prev; void *PrevSlotStackPtr; void *DataEnd; char Data[DS_Worker_Warp_Slot_Size]; }; //////////////////////////////////////////////////////////////////////////////// // task ICV and (implicit & explicit) task state class omptarget_nvptx_TaskDescr { public: // methods for flags INLINE omp_sched_t GetRuntimeSched() const; INLINE void SetRuntimeSched(omp_sched_t sched); INLINE int InParallelRegion() const { return items.flags & TaskDescr_InPar; } INLINE int InL2OrHigherParallelRegion() const { return items.flags & TaskDescr_InParL2P; } INLINE int IsParallelConstruct() const { return items.flags & TaskDescr_IsParConstr; } INLINE int IsTaskConstruct() const { return !IsParallelConstruct(); } // methods for other fields INLINE uint16_t &ThreadId() { return items.threadId; } INLINE uint64_t &RuntimeChunkSize() { return items.runtimeChunkSize; } INLINE omptarget_nvptx_TaskDescr *GetPrevTaskDescr() const { return prev; } INLINE void SetPrevTaskDescr(omptarget_nvptx_TaskDescr *taskDescr) { prev = taskDescr; } // init & copy INLINE void InitLevelZeroTaskDescr(); INLINE void InitLevelOneTaskDescr(omptarget_nvptx_TaskDescr *parentTaskDescr); INLINE void Copy(omptarget_nvptx_TaskDescr *sourceTaskDescr); INLINE void CopyData(omptarget_nvptx_TaskDescr *sourceTaskDescr); INLINE void CopyParent(omptarget_nvptx_TaskDescr *parentTaskDescr); INLINE void CopyForExplicitTask(omptarget_nvptx_TaskDescr *parentTaskDescr); INLINE void CopyToWorkDescr(omptarget_nvptx_TaskDescr *masterTaskDescr); INLINE void CopyFromWorkDescr(omptarget_nvptx_TaskDescr *workTaskDescr); INLINE void CopyConvergentParent(omptarget_nvptx_TaskDescr *parentTaskDescr, uint16_t tid, uint16_t tnum); INLINE void SaveLoopData(); INLINE void RestoreLoopData() const; private: // bits for flags: (6 used, 2 free) // 3 bits (SchedMask) for runtime schedule // 1 bit (InPar) if this thread has encountered one or more parallel region // 1 bit (IsParConstr) if ICV for a parallel region (false = explicit task) // 1 bit (InParL2+) if this thread has encountered L2 or higher parallel // region static const uint8_t TaskDescr_SchedMask = (0x1 | 0x2 | 0x4); static const uint8_t TaskDescr_InPar = 0x10; static const uint8_t TaskDescr_IsParConstr = 0x20; static const uint8_t TaskDescr_InParL2P = 0x40; struct SavedLoopDescr_items { int64_t loopUpperBound; int64_t nextLowerBound; int64_t chunk; int64_t stride; kmp_sched_t schedule; } loopData; struct TaskDescr_items { uint8_t flags; // 6 bit used (see flag above) uint8_t unused; uint16_t threadId; // thread id uint64_t runtimeChunkSize; // runtime chunk size } items; omptarget_nvptx_TaskDescr *prev; }; // build on kmp typedef struct omptarget_nvptx_ExplicitTaskDescr { omptarget_nvptx_TaskDescr taskDescr; // omptarget_nvptx task description (must be first) kmp_TaskDescr kmpTaskDescr; // kmp task description (must be last) } omptarget_nvptx_ExplicitTaskDescr; //////////////////////////////////////////////////////////////////////////////// // Descriptor of a parallel region (worksharing in general) class omptarget_nvptx_WorkDescr { public: // access to data INLINE omptarget_nvptx_TaskDescr *WorkTaskDescr() { return &masterTaskICV; } private: omptarget_nvptx_TaskDescr masterTaskICV; }; //////////////////////////////////////////////////////////////////////////////// class omptarget_nvptx_TeamDescr { public: // access to data INLINE omptarget_nvptx_TaskDescr *LevelZeroTaskDescr() { return &levelZeroTaskDescr; } INLINE omptarget_nvptx_WorkDescr &WorkDescr() { return workDescrForActiveParallel; } // init INLINE void InitTeamDescr(); INLINE __kmpc_data_sharing_slot *GetPreallocatedSlotAddr(int wid) { worker_rootS[wid].DataEnd = &worker_rootS[wid].Data[0] + DS_Worker_Warp_Slot_Size; // We currently do not have a next slot. worker_rootS[wid].Next = 0; worker_rootS[wid].Prev = 0; worker_rootS[wid].PrevSlotStackPtr = 0; return (__kmpc_data_sharing_slot *)&worker_rootS[wid]; } private: omptarget_nvptx_TaskDescr levelZeroTaskDescr; // icv for team master initial thread omptarget_nvptx_WorkDescr workDescrForActiveParallel; // one, ONLY for the active par ALIGN(16) __kmpc_data_sharing_slot worker_rootS[DS_Max_Warp_Number]; }; //////////////////////////////////////////////////////////////////////////////// // thread private data (struct of arrays for better coalescing) // tid refers here to the global thread id // do not support multiple concurrent kernel a this time class omptarget_nvptx_ThreadPrivateContext { public: // task INLINE omptarget_nvptx_TaskDescr *Level1TaskDescr(int tid) { return &levelOneTaskDescr[tid]; } INLINE void SetTopLevelTaskDescr(int tid, omptarget_nvptx_TaskDescr *taskICV) { topTaskDescr[tid] = taskICV; } INLINE omptarget_nvptx_TaskDescr *GetTopLevelTaskDescr(int tid) const; // parallel INLINE uint16_t &NumThreadsForNextParallel(int tid) { return nextRegion.tnum[tid]; } // schedule (for dispatch) INLINE kmp_sched_t &ScheduleType(int tid) { return schedule[tid]; } INLINE int64_t &Chunk(int tid) { return chunk[tid]; } INLINE int64_t &LoopUpperBound(int tid) { return loopUpperBound[tid]; } INLINE int64_t &NextLowerBound(int tid) { return nextLowerBound[tid]; } INLINE int64_t &Stride(int tid) { return stride[tid]; } INLINE omptarget_nvptx_TeamDescr &TeamContext() { return teamContext; } INLINE void InitThreadPrivateContext(int tid); INLINE uint64_t &Cnt() { return cnt; } private: // team context for this team omptarget_nvptx_TeamDescr teamContext; // task ICV for implicit threads in the only parallel region omptarget_nvptx_TaskDescr levelOneTaskDescr[MAX_THREADS_PER_TEAM]; // pointer where to find the current task ICV (top of the stack) omptarget_nvptx_TaskDescr *topTaskDescr[MAX_THREADS_PER_TEAM]; union { // Only one of the two is live at the same time. // parallel uint16_t tnum[MAX_THREADS_PER_TEAM]; } nextRegion; // schedule (for dispatch) kmp_sched_t schedule[MAX_THREADS_PER_TEAM]; // remember schedule type for #for int64_t chunk[MAX_THREADS_PER_TEAM]; int64_t loopUpperBound[MAX_THREADS_PER_TEAM]; // state for dispatch with dyn/guided OR static (never use both at a time) int64_t nextLowerBound[MAX_THREADS_PER_TEAM]; int64_t stride[MAX_THREADS_PER_TEAM]; uint64_t cnt; }; /// Memory manager for statically allocated memory. class omptarget_nvptx_SimpleMemoryManager { private: struct MemDataTy { volatile unsigned keys[OMP_STATE_COUNT]; } MemData[MAX_SM] ALIGN(128); INLINE static uint32_t hash(unsigned key) { return key & (OMP_STATE_COUNT - 1); } public: INLINE void Release(); INLINE const void *Acquire(const void *buf, size_t size); }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // global data tables //////////////////////////////////////////////////////////////////////////////// extern omptarget_nvptx_SimpleMemoryManager omptarget_nvptx_simpleMemoryManager; extern uint32_t EXTERN_SHARED(usedMemIdx); extern uint32_t EXTERN_SHARED(usedSlotIdx); #if _OPENMP extern uint8_t parallelLevel[MAX_THREADS_PER_TEAM / WARPSIZE]; #pragma omp allocate(parallelLevel) allocator(omp_pteam_mem_alloc) #else extern uint8_t EXTERN_SHARED(parallelLevel)[MAX_THREADS_PER_TEAM / WARPSIZE]; #endif extern uint16_t EXTERN_SHARED(threadLimit); extern uint16_t EXTERN_SHARED(threadsInTeam); extern uint16_t EXTERN_SHARED(nThreads); extern omptarget_nvptx_ThreadPrivateContext * EXTERN_SHARED(omptarget_nvptx_threadPrivateContext); extern int8_t EXTERN_SHARED(execution_param); extern void *EXTERN_SHARED(ReductionScratchpadPtr); //////////////////////////////////////////////////////////////////////////////// // work function (outlined parallel/simd functions) and arguments. // needed for L1 parallelism only. //////////////////////////////////////////////////////////////////////////////// typedef void *omptarget_nvptx_WorkFn; extern omptarget_nvptx_WorkFn EXTERN_SHARED(omptarget_nvptx_workFn); //////////////////////////////////////////////////////////////////////////////// // get private data structures //////////////////////////////////////////////////////////////////////////////// INLINE omptarget_nvptx_TeamDescr &getMyTeamDescriptor(); INLINE omptarget_nvptx_WorkDescr &getMyWorkDescriptor(); INLINE omptarget_nvptx_TaskDescr * getMyTopTaskDescriptor(bool isSPMDExecutionMode); INLINE omptarget_nvptx_TaskDescr *getMyTopTaskDescriptor(int globalThreadId); //////////////////////////////////////////////////////////////////////////////// // inlined implementation //////////////////////////////////////////////////////////////////////////////// INLINE uint32_t __kmpc_impl_ffs(uint32_t x) { return __builtin_ffs(x); } INLINE uint32_t __kmpc_impl_popc(uint32_t x) { return __builtin_popcount(x); } INLINE uint32_t __kmpc_impl_ffs(uint64_t x) { return __builtin_ffsl(x); } INLINE uint32_t __kmpc_impl_popc(uint64_t x) { return __builtin_popcountl(x); } #include "common/omptargeti.h" #endif
GB_unop__isfinite_bool_fc64.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__isfinite_bool_fc64 // op(A') function: GB_unop_tran__isfinite_bool_fc64 // C type: bool // A type: GxB_FC64_t // cast: GxB_FC64_t cij = (aij) // unaryop: cij = GB_cisfinite (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_cisfinite (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = (aij) ; \ Cx [pC] = GB_cisfinite (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_ISFINITE || GxB_NO_BOOL || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__isfinite_bool_fc64 ( bool *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = GB_cisfinite (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 ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = GB_cisfinite (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__isfinite_bool_fc64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__ainv_int32_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_int32_uint32 // op(A') function: GB_tran__ainv_int32_uint32 // C type: int32_t // A type: uint32_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = -aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, aij) \ int32_t z = (int32_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_INT32 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int32_uint32 ( int32_t *Cx, // Cx and Ax may be aliased uint32_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_int32_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
fib-tasks.c
#include <err.h> #include <stdio.h> #include <stdlib.h> int fib(int n); int main(int argc, char *argv[]) { int i, sum = 0, n, max; if (argc != 3) errx(EXIT_FAILURE, "expecting n and max"); n = atoi(argv[1]); max = atoi(argv[2]); for (i = 0; i < n; i++) { #pragma omp parallel #pragma omp single { int x, result; x = rand() % max; printf("%d: fib(%d) = ", i, x); result = fib(x); printf("%d\n", result); } } return EXIT_SUCCESS; } int fib(int n) { int result; if (n <= 1) { result = 1; } else { int f1, f2; if (n > 10) { #pragma omp task shared(f1) f1 = fib(n-1); f2 = fib(n-2); #pragma omp taskwait result = f1 + f2; } else { f1 = fib(n-1); f2 = fib(n-2); result = f1 + f2; } } return result; }
viz.h
#pragma once #include "viz_base.h" #include "intersection_tools.h" using Segment3 = K::Segment_3; std::vector<Viewpoint> watchingView( const Tree& tree, const std::vector<Viewpoint>& traj, const Point3& p, const double& viewDis) { std::vector<Viewpoint> out; #pragma omp parallel for for (int i = 0; i < static_cast<int>(traj.size()); ++i) { Viewpoint vp = traj.at(i); Point3 base = cgaltools::eigen_2_cgal_point(vp.pos_mesh); auto direction = cgaltools::eigen_2_cgal_vector(vp.direction); const double dis = sqrt(CGAL::squared_distance(p, base)); if (dis > viewDis - 0.1 && dis < viewDis + 0.1) { Vector3 viewseg(base, p); Vector3 unitViewSeg = viewseg / sqrt(viewseg.squared_length()); viewseg = unitViewSeg * (viewDis - 0.1); Point3 survey(base + viewseg); Segment3 viewSeg(base, survey); auto intersection = tree.any_intersection(viewSeg); if (!intersection) { if (double aco = acos(unitViewSeg * direction) < M_PI / 6) { #pragma omp critical { out.push_back(vp); } } } } } return out; } class My_Visualizer: public Visualizer { public: // Original points. PointSet3 sample_points; // Initial views. std::vector<Viewpoint> sample_views; // The points whose REC is larger than a threshold. PointSet3 validPts; // The final views std::vector<Viewpoint> m_viewpoint; // The points whose REC is small. PointSet3 lowRECPts; // AABB tree Tree trey; // The points and their initial views, one point by five views. std::vector<std::pair<PointSet3, std::vector<Viewpoint>>> one2One; // The points and the views which can watch them. std::vector<std::pair<PointSet3, std::vector<Viewpoint>>> infooo; int showdetail; int lastdetail; int o2o; int lasto2o; My_Visualizer(const std::string& v_model_path):Visualizer(v_model_path) { m_thread = new std::thread(&My_Visualizer::run, this); //render_loop.join(); return; } void run() { auto proxy_model = pangolin::LoadGeometry(m_model_path); pangolin::CreateWindowAndBind("Main", 1600, 900); glEnable(GL_DEPTH_TEST); s_cam = pangolin::OpenGlRenderState( pangolin::ProjectionMatrix(1600, 900, 800, 450, 800, 450, 1, 99999), pangolin::ModelViewLookAt(40, 40, 40, 0, 0, 0, pangolin::AxisZ) ); // Create Interactive View in window pangolin::Handler3D handler1(s_cam, pangolin::AxisZ); pangolin::View& d_cam1 = pangolin::CreateDisplay() .SetBounds(0.0, 1.0, pangolin::Attach::Pix(180), 1.0f, -2000.f / 1600.f) .SetHandler(&handler1); pangolin::CreatePanel("ui") .SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(180)); pangolin::Var<int> slide_point_size("ui.size", 1, 0, 15); pangolin::Var<bool> checkbox_mesh("ui.mesh", true, true); pangolin::Var<bool> checkbox_sample_points("ui.sample_points", false, true); pangolin::Var<bool> lowREC("ui.low REC", false, true); pangolin::Var<bool> checkbox_first_pass_viewpoint("ui.viewpoint", false, true); pangolin::Var<bool> checkbox_sample_points_with_reconstructability("ui.points_r", false, true); pangolin::Var<double> slide_bar_reconstructability("ui.r",1.f, 0.f, 50.f); pangolin::Var<bool> checkbox_sample_points_with_zero_reconstructability("ui.zero_reconstructability", false, true); pangolin::Var<std::string> showd("ui.sh", "0"); pangolin::Var<bool> showde("ui.showDET", false, true); pangolin::Var<bool> validpts("validpts", false, true); pangolin::Var<std::string> o2oinput("ui.o2o", "0"); pangolin::Var<bool> showo2o("ui.showo2o", false, true); while (!pangolin::ShouldQuit()) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.56f, 0.56f, 0.56f, 1); m_point_size = slide_point_size.Get(); showdetail = std::stoi(showd.Get()); o2o = std::stoi(o2oinput.Get()); lock(); d_cam1.Activate(s_cam); pangolin::glDrawAxis(1000); // Render if (checkbox_mesh) draw_obj(proxy_model); if (checkbox_sample_points) draw_point_cloud(sample_points); if (validpts) draw_point_cloud(validPts); if (lowREC) draw_point_cloud(lowRECPts); if (checkbox_first_pass_viewpoint) draw_viewpoint(m_viewpoint, 1); if (checkbox_sample_points_with_reconstructability) { auto reconstructability_map = sample_points.property_map<double>("reconstructability").first; if(!sample_points.property_map<double>("reconstructability").second) { std::cout << "No reconstructability map"<<std::endl; } else { glPointSize(m_point_size); glBegin(GL_POINTS); for (int i_point = 0; i_point < sample_points.size(); ++i_point) { Eigen::Vector3d color = std::min(reconstructability_map[i_point],slide_bar_reconstructability.Get())/slide_bar_reconstructability.Get()*Eigen::Vector3d(1,1,1); glColor3d(color.x(),color.y(),color.z()); glVertex3d(sample_points.point(i_point).x(), sample_points.point(i_point).y(), sample_points.point(i_point).z()); } glEnd(); } } if (checkbox_sample_points_with_zero_reconstructability) { if(!sample_points.property_map<double>("reconstructability").second) { std::cout << "No reconstructability map"<<std::endl; } else { auto reconstructability_map = sample_points.property_map<double>("reconstructability").first; glPointSize(m_point_size); glBegin(GL_POINTS); glColor3d(0.f, 0.f, 0.f); for (int i_point = 0; i_point < sample_points.size(); ++i_point) if(reconstructability_map[i_point] == 0) glVertex3d(sample_points.point(i_point).x(), sample_points.point(i_point).y(), sample_points.point(i_point).z()); glEnd(); } } if(showde) { draw_point_cloud(infooo.at(showdetail).first); draw_viewpoint(infooo.at(showdetail).second, 1); } if(showo2o) { /*if (lasto2o != o2o) { std::cout << one2One.at(o2o).second.size() << std::endl; }*/ draw_point_cloud(one2One.at(o2o).first); draw_viewpoint(one2One.at(o2o).second); } m_render_function(); lastdetail = showdetail; lasto2o = o2o; unlock(); // Swap frames and Process Events pangolin::FinishFrame(); } // unset the current context from the main thread pangolin::GetBoundWindow(); } void lock() { m_mutex.lock(); } void unlock() { m_mutex.unlock(); } };
CycladesPartitioner.h
/* * Copyright 2016 [See AUTHORS file for list of authors] * * 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 _CYCLADES_PARTITIONER_ #define _CYCLADES_PARTITIONER_ DEFINE_int32(cyclades_batch_size, 5000, "Batch size for cyclades."); #include "../DatapointPartitions/DatapointPartitions.h" #include "Partitioner.h" #include <unordered_map> class CycladesPartitioner : public Partitioner { private: int model_size; int **tree; int UnionFind(int a, int *p) { int root = a; while (p[a] != a) { a = p[a]; } while (root != a) { int root2 = p[root]; p[root] = a; root = root2; } return a; } void ComputeCC(const std::vector<Datapoint *> & datapoints, int start_index, int end_index, std::unordered_map<int, std::vector<Datapoint *>> &components, int *tree) { // Initialize tree for union find. for (int i = 0; i < model_size + FLAGS_cyclades_batch_size; i++) { tree[i] = i; } // CC Computation. for (int i = start_index; i < end_index; i++) { Datapoint *point = datapoints[i]; int target = UnionFind(i-start_index, tree); for (auto const & coordinate : point->GetCoordinates()) { int coordinate_src = UnionFind(coordinate + end_index-start_index, tree); tree[coordinate_src] = target; } } for (int i = 0; i < end_index-start_index; i++) { components[UnionFind(i, tree)].push_back(datapoints[i+start_index]); } } public: CycladesPartitioner(Model *model) : Partitioner() { model_size = model->NumParameters(); tree = new int *[FLAGS_n_threads]; for (int i = 0; i < FLAGS_n_threads; i++) { tree[i] = new int[model_size + FLAGS_cyclades_batch_size]; } } ~CycladesPartitioner() { for (int i = 0; i < FLAGS_n_threads; i++) { delete [] tree[i]; } delete [] tree; }; // Basic partitioner return partition with 1 batch, each thread gets an equal // split of a shuffled portion of the datapoints. DatapointPartitions Partition(const std::vector<Datapoint *> &datapoints, int n_threads) { DatapointPartitions partitions(n_threads); // Shuffle the datapoints. std::vector<Datapoint *> datapoints_copy(datapoints); // Calculate overall number of batches. int num_total_batches = ceil((double)datapoints_copy.size() / (double)FLAGS_cyclades_batch_size); // Process FLAGS_cyclades_batch_size pointer per iteration, computing CCS on them. std::vector<std::unordered_map<int, std::vector<Datapoint *>>> components(num_total_batches); #pragma omp parallel for for (int datapoint_count = 0; datapoint_count < datapoints_copy.size(); datapoint_count += FLAGS_cyclades_batch_size) { // Current batch index. int batch_index = datapoint_count / FLAGS_cyclades_batch_size; int start = datapoint_count; int end = std::min(datapoint_count + FLAGS_cyclades_batch_size, (int)datapoints_copy.size()); // Compute components. ComputeCC(datapoints_copy, start, end, components[batch_index], tree[omp_get_thread_num()]); } // Load balance the connected components (load balance within the batch, not across it). for (int batch = 0; batch < num_total_batches; batch++) { for (std::unordered_map<int, std::vector<Datapoint *>>::iterator it = components[batch].begin(); it != components[batch].end(); it++) { partitions.AddDatapointsToLeastLoadedThread(it->second); } partitions.StartNewBatch(); } return partitions; } }; #endif
type3_georel.kernel_runtime.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include "local_header.h" #include "openmp_pscmc_inc.h" #include "type3_georel.kernel_inc.h" int openmp_relng_1st_goto_init (openmp_pscmc_env * pe ,openmp_relng_1st_goto_struct * kerstr ){ return 0 ;} void openmp_relng_1st_goto_get_struct_len (size_t * len ){ ((len)[0] = sizeof(openmp_relng_1st_goto_struct )); } int openmp_relng_1st_goto_get_num_compute_units (openmp_relng_1st_goto_struct * kerstr ){ return omp_get_max_threads ( ) ;} int openmp_relng_1st_goto_get_xlen (){ return 1 ;} int openmp_relng_1st_goto_exec (openmp_relng_1st_goto_struct * kerstr ,long scmc_internal_g_xlen ,long scmc_internal_g_ylen ){ #pragma omp parallel { int xid ; int yid ; int numt = omp_get_num_threads ( ) ; int tid = omp_get_thread_num ( ) ; int ysingle = ( ( scmc_internal_g_ylen + ( numt - 1 ) ) / numt ) ; int ymin = ( tid * ysingle ) ; int ymax = ( ( 1 + tid ) * ysingle ) ; for ((yid = tid) ; ( yid < scmc_internal_g_ylen ) ; (yid = ( yid + numt ))) { for ((xid = 0) ; ( xid < scmc_internal_g_xlen ) ; (xid = ( xid + 1 ))) { openmp_relng_1st_goto_scmc_kernel ( ( kerstr )->inoutput , ( kerstr )->xyzw , ( kerstr )->cu_cache , ( kerstr )->cu_xyzw , ( kerstr )->xoffset , ( kerstr )->yoffset , ( kerstr )->zoffset , ( kerstr )->fieldE , ( kerstr )->fieldB , ( kerstr )->fieldB1 , ( kerstr )->FoutJ , ( ( kerstr )->XLEN)[0] , ( ( kerstr )->YLEN)[0] , ( ( kerstr )->ZLEN)[0] , ( ( kerstr )->ovlp)[0] , ( ( kerstr )->numvec)[0] , ( ( kerstr )->num_ele)[0] , ( ( kerstr )->grid_cache_len)[0] , ( ( kerstr )->cu_cache_length)[0] , ( ( kerstr )->DELTA_X)[0] , ( ( kerstr )->DELTA_Y)[0] , ( ( kerstr )->DELTA_Z)[0] , ( ( kerstr )->Mass0)[0] , ( ( kerstr )->Charge0)[0] , ( ( kerstr )->Deltat)[0] , ( ( kerstr )->Tori_X0)[0] , ( ( kerstr )->Solve_Err)[0] , yid , scmc_internal_g_ylen ); }}} return 0 ;} int openmp_relng_1st_goto_scmc_set_parameter_inoutput (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->inoutput = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_xyzw (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xyzw = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_cu_cache (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->cu_cache = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_cu_xyzw (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->cu_xyzw = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_xoffset (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->xoffset = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_yoffset (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->yoffset = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_zoffset (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->zoffset = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_fieldE (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->fieldE = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_fieldB (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->fieldB = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_fieldB1 (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->fieldB1 = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_FoutJ (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->FoutJ = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_XLEN (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->XLEN = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_YLEN (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->YLEN = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_ZLEN (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ZLEN = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_ovlp (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->ovlp = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_numvec (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->numvec = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_num_ele (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->num_ele = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_grid_cache_len (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->grid_cache_len = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_cu_cache_length (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->cu_cache_length = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_DELTA_X (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->DELTA_X = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_DELTA_Y (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->DELTA_Y = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_DELTA_Z (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->DELTA_Z = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_Mass0 (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->Mass0 = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_Charge0 (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->Charge0 = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_Deltat (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->Deltat = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_Tori_X0 (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->Tori_X0 = pm->d_data); } int openmp_relng_1st_goto_scmc_set_parameter_Solve_Err (openmp_relng_1st_goto_struct * kerstr ,openmp_pscmc_mem * pm ){ ( ( kerstr )->Solve_Err = pm->d_data); }
MatUtil.c
#include "MatUtil.h" void GenMatrix(int *mat, const size_t N) { int i; for(i = 0; i < N*N; i ++) mat[i] = rand()%32 - 1; for(i = 0; i < N; i++) mat[i*N + i] = 0; } bool CmpArray(const int *l, const int *r, const size_t eleNum) { int i; for(i = 0; i < eleNum; i ++) if(l[i] != r[i]) { printf("ERROR: l[%d] = %d, r[%d] = %d\n", i, l[i], i, r[i]); return false; } return true; } /* Sequential (Single Thread) APSP on CPU. */ void ST_APSP(int *mat, const size_t N) { int i,j,k; for(k = 0; k < N; k ++) for(i = 0; i < N; i ++) for(j = 0; j < N; j ++) { int i0 = i*N + j; int i1 = i*N + k; int i2 = k*N + j; if(mat[i1] != -1 && mat[i2] != -1) { int sum = (mat[i1] + mat[i2]); if (mat[i0] == -1 || sum < mat[i0]) mat[i0] = sum; } } } /* Parallel (Single Thread) APSP on CPU. */ void parallel(int *mat, const size_t N) { int i,j,k; for(k = 0; k < N; k ++) #pragma omp parallel for private(i,j) schedule(dynamic,5) for(i = 0; i < N; i ++) for(j = 0; j < N; j ++) { int i0 = i*N + j; int i1 = i*N + k; int i2 = k*N + j; if(mat[i1] != -1 && mat[i2] != -1) { int sum = (mat[i1] + mat[i2]); if (mat[i0] == -1 || sum < mat[i0]) mat[i0] = sum; } } }
rmse.c
/*************************************************************************/ /** File: rmse.c **/ /** Description: calculate root mean squared error of particular **/ /** clustering. **/ /** Author: Sang-Ha Lee **/ /** University of Virginia. **/ /** **/ /** Note: euclid_dist_2() and find_nearest_point() adopted from **/ /** Minebench code. **/ /** **/ /*************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <float.h> #include <math.h> #include <omp.h> #include "kmeans.h" extern double wtime(void); /*----< euclid_dist_2() >----------------------------------------------------*/ /* multi-dimensional spatial Euclid distance square */ __inline float euclid_dist_2(float *pt1, float *pt2, int numdims) { int i; float ans=0.0; for (i=0; i<numdims; i++) ans += (pt1[i]-pt2[i]) * (pt1[i]-pt2[i]); return(ans); } /*----< find_nearest_point() >-----------------------------------------------*/ __inline int find_nearest_point(float *pt, /* [nfeatures] */ int nfeatures, float **pts, /* [npts][nfeatures] */ int npts) { int index, i; float max_dist=FLT_MAX; /* find the cluster center id with min distance to pt */ for (i=0; i<npts; i++) { float dist; dist = euclid_dist_2(pt, pts[i], nfeatures); /* no need square root */ if (dist < max_dist) { max_dist = dist; index = i; } } return(index); } /*----< rms_err(): calculates RMSE of clustering >-------------------------------------*/ float rms_err (float **feature, /* [npoints][nfeatures] */ int nfeatures, int npoints, float **cluster_centres, /* [nclusters][nfeatures] */ int nclusters) { int i; int nearest_cluster_index; /* cluster center id with min distance to pt */ float sum_euclid = 0.0; /* sum of Euclidean distance squares */ float ret; /* return value */ /* calculate and sum the sqaure of euclidean distance*/ #pragma omp parallel for \ shared(feature,cluster_centres) \ firstprivate(npoints,nfeatures,nclusters) \ private(i, nearest_cluster_index) \ schedule (static) for (i=0; i<npoints; i++) { nearest_cluster_index = find_nearest_point(feature[i], nfeatures, cluster_centres, nclusters); sum_euclid += euclid_dist_2(feature[i], cluster_centres[nearest_cluster_index], nfeatures); } /* divide by n, then take sqrt */ ret = sqrt(sum_euclid / npoints); return(ret); }
builder.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef BUILDER_H_ #define BUILDER_H_ #include <algorithm> #include <parallel/algorithm> #include <cinttypes> #include <fstream> #include <functional> #include <type_traits> #include <utility> #include <set> #include <omp.h> #include <cassert> #include "command_line.h" #include "generator.h" #include "graph.h" #include "platform_atomics.h" #include "pvector.h" #include "reader.h" #include "timer.h" #include "util.h" #include "sliding_queue.h" /* GAP Benchmark Suite Class: BuilderBase Author: Scott Beamer Given arguements from the command line (cli), returns a built graph - MakeGraph() will parse cli and obtain edgelist and call MakeGraphFromEL(edgelist) to perform actual graph construction - edgelist can be from file (reader) or synthetically generated (generator) - Common case: BuilderBase typedef'd (w/ params) to be Builder (benchmark.h) */ template <typename NodeID_, typename DestID_ = NodeID_, typename WeightT_ = NodeID_, bool invert = true> class BuilderBase { typedef EdgePair<NodeID_, DestID_> Edge; typedef pvector<Edge> EdgeList; const CLBase &cli_; bool symmetrize_; bool needs_weights_; int64_t num_nodes_ = -1; public: explicit BuilderBase(const CLBase &cli) : cli_(cli) { symmetrize_ = cli_.symmetrize(); needs_weights_ = !std::is_same<NodeID_, DestID_>::value; } DestID_ GetSource(EdgePair<NodeID_, NodeID_> e) { return e.u; } DestID_ GetSource(EdgePair<NodeID_, NodeWeight<NodeID_, WeightT_>> e) { return NodeWeight<NodeID_, WeightT_>(e.u, e.v.w); } NodeID_ FindMaxNodeID(const EdgeList &el) { NodeID_ max_seen = 0; #pragma omp parallel for reduction(max : max_seen) for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; max_seen = std::max(max_seen, e.u); max_seen = std::max(max_seen, (NodeID_) e.v); } return max_seen; } pvector<NodeID_> CountDegrees(const EdgeList &el, bool transpose) { pvector<NodeID_> degrees(num_nodes_, 0); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) fetch_and_add(degrees[e.u], 1); if (symmetrize_ || (!symmetrize_ && transpose)) fetch_and_add(degrees[(NodeID_) e.v], 1); } return degrees; } static pvector<SGOffset> PrefixSum(const pvector<NodeID_> &degrees) { pvector<SGOffset> sums(degrees.size() + 1); SGOffset total = 0; for (size_t n=0; n < degrees.size(); n++) { sums[n] = total; total += degrees[n]; } sums[degrees.size()] = total; return sums; } static pvector<SGOffset> ParallelPrefixSum(const pvector<NodeID_> &degrees) { const size_t block_size = 1<<20; const size_t num_blocks = (degrees.size() + block_size - 1) / block_size; pvector<SGOffset> local_sums(num_blocks); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset lsum = 0; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) lsum += degrees[i]; local_sums[block] = lsum; } pvector<SGOffset> bulk_prefix(num_blocks+1); SGOffset total = 0; for (size_t block=0; block < num_blocks; block++) { bulk_prefix[block] = total; total += local_sums[block]; } bulk_prefix[num_blocks] = total; pvector<SGOffset> prefix(degrees.size() + 1); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset local_total = bulk_prefix[block]; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) { prefix[i] = local_total; local_total += degrees[i]; } } prefix[degrees.size()] = bulk_prefix[num_blocks]; return prefix; } // Removes self-loops and redundant edges // Side effect: neighbor IDs will be sorted void SquishCSR(const CSRGraph<NodeID_, DestID_, invert> &g, bool transpose, DestID_*** sq_index, DestID_** sq_neighs) { pvector<NodeID_> diffs(g.num_nodes()); DestID_ *n_start, *n_end; #pragma omp parallel for private(n_start, n_end) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) { n_start = g.in_neigh(n).begin(); n_end = g.in_neigh(n).end(); } else { n_start = g.out_neigh(n).begin(); n_end = g.out_neigh(n).end(); } std::sort(n_start, n_end); DestID_ *new_end = std::unique(n_start, n_end); new_end = std::remove(n_start, new_end, n); diffs[n] = new_end - n_start; } pvector<SGOffset> sq_offsets = ParallelPrefixSum(diffs); *sq_neighs = new DestID_[sq_offsets[g.num_nodes()]]; *sq_index = CSRGraph<NodeID_, DestID_>::GenIndex(sq_offsets, *sq_neighs); #pragma omp parallel for private(n_start) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) n_start = g.in_neigh(n).begin(); else n_start = g.out_neigh(n).begin(); std::copy(n_start, n_start+diffs[n], (*sq_index)[n]); } } CSRGraph<NodeID_, DestID_, invert> SquishGraph( const CSRGraph<NodeID_, DestID_, invert> &g) { DestID_ **out_index, *out_neighs, **in_index, *in_neighs; SquishCSR(g, false, &out_index, &out_neighs); if (g.directed()) { if (invert) SquishCSR(g, true, &in_index, &in_neighs); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs, in_index, in_neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs); } } /* Graph Bulding Steps (for CSR): - Read edgelist once to determine vertex degrees (CountDegrees) - Determine vertex offsets by a prefix sum (ParallelPrefixSum) - Allocate storage and set points according to offsets (GenIndex) - Copy edges into storage */ void MakeCSR(const EdgeList &el, bool transpose, DestID_*** index, DestID_** neighs) { pvector<NodeID_> degrees = CountDegrees(el, transpose); pvector<SGOffset> offsets = ParallelPrefixSum(degrees); *neighs = new DestID_[offsets[num_nodes_]]; *index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, *neighs); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) (*neighs)[fetch_and_add(offsets[e.u], 1)] = e.v; if (symmetrize_ || (!symmetrize_ && transpose)) (*neighs)[fetch_and_add(offsets[static_cast<NodeID_>(e.v)], 1)] = GetSource(e); } } CSRGraph<NodeID_, DestID_, invert> MakeGraphFromEL(EdgeList &el) { DestID_ **index = nullptr, **inv_index = nullptr; DestID_ *neighs = nullptr, *inv_neighs = nullptr; Timer t; t.Start(); if (num_nodes_ == -1) num_nodes_ = FindMaxNodeID(el)+1; //#if 0 //TEMP if (needs_weights_) Generator<NodeID_, DestID_, WeightT_>::InsertWeights(el); //#endif MakeCSR(el, false, &index, &neighs); if (!symmetrize_ && invert) MakeCSR(el, true, &inv_index, &inv_neighs); t.Stop(); PrintTime("Build Time", t.Seconds()); if (symmetrize_) return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs); else return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs, inv_index, inv_neighs); } #if 0 //will complete the code later CSRGraph<NodeID_, DestID_, invert> relabelForSpatialLocality( const CSRGraph<NodeID_, DestID_, invert> &g) { if (g.directed()) { // Will add support soon } else { Timer t; t.start(); /* STEP I: make a map between new and old vertex labels */ long long counter = 0; //keep track of local counts std::map<NodeID_, int64_t> reMap[128]; //Conservatively assuming we will never use more than 128 threads /* relabel vertices in parallel (using local counter) */ #pragma omp parallel for firstprivate(count) for (NodeID_ v = 0; v < g.num_nodes(); v++) { if (reMap[omp_get_thread_num()].find(v) == reMap.end()) { // vertex hasn't been labelled reMap.insert(std::pair<NodeID_, int64_t>(v, counter)); counter++; } for (NodeID_ u : g.in_neigh(v)) { if (reMap[omp_get_thread_num()].find(u) == reMap.end()) { // vertex hasn't been labelled reMap.insert(std::pair<NodeID_, int64_t>(u, counter)); counter++; } } } /* Update counts based on maximum count for each thread */ int64_t offset = 0; for (int i = 0; i < 128; i++) { if (reMap[i].size() != 0) { // adding offset to all counts of current map std::map<NodeID_, int64_t>::iterator it, it_end; #pragma omp parallel for for (it = reMap[i].begin(), it_end = reMap[i].end(); it != it_end; it++) { it->second += offset; } // finding maximum value of current set int64_t maxVal = 0; #pragma omp parallel for reduction(max: maxVal) for (it = reMap[i].begin(), it_end = reMap[i].end(); it != it_end; it++) { if (it->second > maxVal) { maxVal = it->second; } } offset = maxVal; } } /* Merge local containers */ std::map <NodeID_, int64_t> merged_reMap; for (int i = 0; i < 128; i++) { if (reMap[i].size() != 0) { merged_reMap.insert(reMap[i].begin(), reMap[i].end()); } } /* STEP II: rewrite CSR based on this reMap */ DestID_* neighs = new DestID_[2 * g.num_edges()]; DestID_** index = CSRGraph<NodeID_, DestID_>::relabelIndex(offsets, neighs, reMap); } } #endif CSRGraph<NodeID_, DestID_, invert> MakeGraph() { CSRGraph<NodeID_, DestID_, invert> g; { // extra scope to trigger earlier deletion of el (save memory) EdgeList el; if (cli_.filename() != "") { Reader<NodeID_, DestID_, WeightT_, invert> r(cli_.filename()); if ((r.GetSuffix() == ".sg") || (r.GetSuffix() == ".wsg")) { return r.ReadSerializedGraph(); } else { el = r.ReadFile(needs_weights_); } } else if (cli_.scale() != -1) { Generator<NodeID_, DestID_> gen(cli_.scale(), cli_.degree()); el = gen.GenerateEL(cli_.uniform()); } g = MakeGraphFromEL(el); } #if 0 if (cli_.relabel() == 1) { g_new = relabelForSpatialLocality(g); } #endif return SquishGraph(g); } // Relabels (and rebuilds) graph by order of decreasing degree static CSRGraph<NodeID_, DestID_, invert> RelabelByDegree( const CSRGraph<NodeID_, DestID_, invert> &g) { if (g.directed()) { std::cout << "Cannot relabel directed graph" << std::endl; std::exit(-11); } Timer t; t.Start(); typedef std::pair<int64_t, NodeID_> degree_node_p; pvector<degree_node_p> degree_id_pairs(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); std::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> new_ids(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[n] = degree_id_pairs[n].first; new_ids[degree_id_pairs[n].second] = n; } pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; std::sort(index[new_ids[u]], index[new_ids[u]+1]); } t.Stop(); PrintTime("Relabel", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } /* CSR-segmenting as proposed in the Cagra paper Partitions the graphs and produces a sub-graph within a specified range of vertices. The following implementation assumes use in pull implementation and that only the partitioned CSC is required */ static CSRGraph<NodeID_, DestID_, invert> graphSlicer( const CSRGraph<NodeID_, DestID_, invert> &g, NodeID_ startID, NodeID_ stopID, bool outDegree = false, bool modifyBothDestlists = false) { /* create a partition of a graph in the range [startID, stopID) */ Timer t; t.Start(); //NOTE: that pull implementation should specify outDegree == false // and push implementations should use outDegree == true if (g.directed() == true) { /* Step I : For the requested range [startID, stopID), construct the reduced degree per vertex */ pvector<NodeID_> degrees(g.num_nodes()); //note that stopID is not included in the range #pragma omp parallel for schedule(dynamic,1024) for (NodeID_ n = 0; n < g.num_nodes(); ++n) { if (outDegree == true) { NodeID_ newDegree(0); for (NodeID_ m : g.out_neigh(n)) { if(m >= startID && m < stopID) { ++newDegree; } } degrees[n] = newDegree; } else { NodeID_ newDegree(0); for (NodeID_ m : g.in_neigh(n)) { if(m >= startID && m < stopID) { ++newDegree; } } degrees[n] = newDegree; } } /* Step II : Construct a trimmed offset list */ pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); if (outDegree == true) { #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u = 0; u < g.num_nodes(); ++u) { for (NodeID_ v : g.out_neigh(u)) { if (v >= startID && v < stopID) { neighs[offsets[u]++] = v; } } } } else { #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u = 0; u < g.num_nodes(); ++u) { for (NodeID_ v : g.in_neigh(u)) { if (v >= startID && v < stopID) { neighs[offsets[u]++] = v; } } } } /* Step III : Populate the inv dest lists (for push-pull implementations) */ DestID_* inv_neighs(nullptr); DestID_** inv_index(nullptr); if (modifyBothDestlists == true) { //allocate space pvector<NodeID_> inv_degrees(g.num_nodes()); #pragma omp parallel for for (NodeID_ u = 0; u < g.num_nodes(); ++u) { if (outDegree == true) { inv_degrees[u] = g.in_degree(u); } else { inv_degrees[u] = g.out_degree(u); } } pvector<SGOffset> inv_offsets = ParallelPrefixSum(inv_degrees); inv_neighs = new DestID_[inv_offsets[g.num_nodes()]]; inv_index = CSRGraph<NodeID_, DestID_>::GenIndex(inv_offsets, inv_neighs); //populate the inv dest list #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u = 0; u < g.num_nodes(); ++u) { if (outDegree == true) { for (NodeID_ v : g.in_neigh(u)) { inv_neighs[inv_offsets[u]++] = v; } } else { for (NodeID_ v : g.out_neigh(u)) { inv_neighs[inv_offsets[u]++] = v; } } } } #if 0 else { inv_neighs = neighs; inv_index = index; } #endif /* Step IV : return the appropriate graph */ if (outDegree == true) { t.Stop(); PrintTime("Slice-time", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs, inv_index, inv_neighs); } else { t.Stop(); PrintTime("Slice-time", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), inv_index, inv_neighs, index, neighs); } } else { /* Step I : For the requested range [startID, stopID), construct the reduced degree per vertex */ pvector<NodeID_> degrees(g.num_nodes()); //note that stopID is not included in the range #pragma omp parallel for schedule(dynamic,1024) for (NodeID_ n = 0; n < g.num_nodes(); ++n) { NodeID_ newDegree(0); for (NodeID_ m : g.out_neigh(n)) { if(m >= startID && m < stopID) { ++newDegree; //if neighbor is in current partition } } degrees[n] = newDegree; } /* Step II : Construct a trimmed offset list */ pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u = 0; u < g.num_nodes(); ++u) { for (NodeID_ v : g.out_neigh(u)) { if (v >= startID && v < stopID) { neighs[offsets[u]++] = v; } } } /* Step III : return the appropriate graph */ t.Stop(); PrintTime("Slice-time", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } } static CSRGraph<NodeID_, DestID_, invert> quantizeGraph( const CSRGraph<NodeID_, DestID_, invert> &g, NodeID_ numTiles) { NodeID_ tileSz = g.num_nodes() / numTiles; if (numTiles > g.num_nodes()) tileSz = 1; else if (g.num_nodes() % numTiles != 0) tileSz += 1; pvector<NodeID_> degrees(g.num_nodes(), 0); #pragma omp parallel for for (NodeID_ n = 0; n < g.num_nodes(); ++n) { std::set<NodeID_> uniqNghs; for (NodeID_ ngh : g.out_neigh(n)) { uniqNghs.insert(ngh / tileSz); } degrees[n] = uniqNghs.size(); assert(degrees[n] <= numTiles); } pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { std::set<NodeID_> uniqNghs; for (NodeID_ ngh : g.out_neigh(u)) { uniqNghs.insert(ngh / tileSz); } auto it = uniqNghs.begin(); for (NodeID_ i = 0; i < static_cast<NodeID_>(uniqNghs.size()); ++i) { neighs[offsets[u]++] = *it; it++; } } return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } // Proper degree sorting static CSRGraph<NodeID_, DestID_, invert> DegSort ( const CSRGraph<NodeID_, DestID_, invert> &g, bool outDegree, pvector<NodeID_> &new_ids, bool createOnlyDegList, bool createBothCSRs) { Timer t; t.Start(); typedef std::pair<int64_t, NodeID_> degree_node_p; pvector<degree_node_p> degree_id_pairs(g.num_nodes()); if (g.directed() == true) { /* Step I: Create a list of degrees */ #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { if (outDegree == true) { degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); } else { degree_id_pairs[n] = std::make_pair(g.in_degree(n), n); } } /* Step II: Sort based on degree order */ __gnu_parallel::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); //TODO:Use parallel sort /* Step III: assigned remap for the hub vertices */ #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { new_ids[degree_id_pairs[n].second] = n; } /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> inv_degrees(g.num_nodes()); if (outDegree == true) { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); inv_degrees[new_ids[n]] = g.in_degree(n); } } else { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.in_degree(n); inv_degrees[new_ids[n]] = g.out_degree(n); } } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(inv_degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree == true) { for (NodeID_ v : g.in_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; } else { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; } std::sort(index[new_ids[u]], index[new_ids[u]+1]); //sort neighbors of each vertex } DestID_* inv_neighs(nullptr); DestID_** inv_index(nullptr); if (createOnlyDegList == true || createBothCSRs == true) { // making the inverse list (in-degrees in this case) pvector<SGOffset> inv_offsets = ParallelPrefixSum(degrees); inv_neighs = new DestID_[inv_offsets[g.num_nodes()]]; inv_index = CSRGraph<NodeID_, DestID_>::GenIndex(inv_offsets, inv_neighs); if (createBothCSRs == true) { #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree == true) { for (NodeID_ v : g.out_neigh(u)) inv_neighs[inv_offsets[new_ids[u]]++] = new_ids[v]; } else { for (NodeID_ v : g.in_neigh(u)) inv_neighs[inv_offsets[new_ids[u]]++] = new_ids[v]; } std::sort(inv_index[new_ids[u]], inv_index[new_ids[u]+1]); //sort neighbors of each vertex } } } t.Stop(); PrintTime("DegSort time", t.Seconds()); if (outDegree == true) { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), inv_index, inv_neighs, index, neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs, inv_index, inv_neighs); } } else { /* Undirected graphs - no need to make separate lists for in and out degree */ /* Step I: Create a list of degrees */ #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); } /* Step II: Sort based on degree order */ __gnu_parallel::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); //TODO:Use parallel sort /* Step III: assigned remap for the hub vertices */ #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { new_ids[degree_id_pairs[n].second] = n; } /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; std::sort(index[new_ids[u]], index[new_ids[u]+1]); } t.Stop(); PrintTime("DegSort time", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } } static CSRGraph<NodeID_, DestID_, invert> RandOrder ( const CSRGraph<NodeID_, DestID_, invert> &g, pvector<NodeID_> &new_ids, bool createOnlyDegList, bool createBothCSRs) { Timer t; t.Start(); std::srand(0); //so that the random graph generated is the same everytime bool outDegree = true; if (g.directed() == true) { //Step I: create a random permutation - SLOW implementation pvector<NodeID_> claimedVtxs(g.num_nodes(), 0); //#pragma omp parallel for for (NodeID_ v = 0; v < g.num_nodes(); ++v) { while (true) { NodeID_ randID = std::rand() % g.num_nodes(); if (claimedVtxs[randID] != 1) { if (compare_and_swap(claimedVtxs[randID], 0, 1) == true) { new_ids[v] = randID; break; } else continue; } } } #pragma omp parallel for for (NodeID_ v = 0; v < g.num_nodes(); ++v) assert(new_ids[v] != -1); /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> inv_degrees(g.num_nodes()); if (outDegree == true) { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); inv_degrees[new_ids[n]] = g.in_degree(n); } } else { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.in_degree(n); inv_degrees[new_ids[n]] = g.out_degree(n); } } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(inv_degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree == true) { for (NodeID_ v : g.in_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; } else { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; } std::sort(index[new_ids[u]], index[new_ids[u]+1]); //sort neighbors of each vertex } DestID_* inv_neighs(nullptr); DestID_** inv_index(nullptr); if (createOnlyDegList == true || createBothCSRs == true) { // making the inverse list (in-degrees in this case) pvector<SGOffset> inv_offsets = ParallelPrefixSum(degrees); inv_neighs = new DestID_[inv_offsets[g.num_nodes()]]; inv_index = CSRGraph<NodeID_, DestID_>::GenIndex(inv_offsets, inv_neighs); if (createBothCSRs == true) { #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree == true) { for (NodeID_ v : g.out_neigh(u)) inv_neighs[inv_offsets[new_ids[u]]++] = new_ids[v]; } else { for (NodeID_ v : g.in_neigh(u)) inv_neighs[inv_offsets[new_ids[u]]++] = new_ids[v]; } std::sort(inv_index[new_ids[u]], inv_index[new_ids[u]+1]); //sort neighbors of each vertex } } } t.Stop(); PrintTime("RandOrder time", t.Seconds()); if (outDegree == true) { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), inv_index, inv_neighs, index, neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs, inv_index, inv_neighs); } } else { /* Undirected graphs - no need to make separate lists for in and out degree */ //Step I: create a random permutation - SLOW implementation pvector<NodeID_> claimedVtxs(g.num_nodes(), 0); //#pragma omp parallel for for (NodeID_ v = 0; v < g.num_nodes(); ++v) { while (true) { NodeID_ randID = std::rand() % g.num_nodes(); if (claimedVtxs[randID] != 1) { if (compare_and_swap(claimedVtxs[randID], 0, 1) == true) { new_ids[v] = randID; break; } else continue; } } } #pragma omp parallel for for (NodeID_ v = 0; v < g.num_nodes(); ++v) assert(new_ids[v] != -1); /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; std::sort(index[new_ids[u]], index[new_ids[u]+1]); } t.Stop(); PrintTime("RandOrder time", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } } /* Return a compressed transpose matrix (Rereference Matrix) */ static void makeOffsetMatrix(const CSRGraph<NodeID_, DestID_, invert> &g, pvector<uint8_t> &offsetMatrix, int numVtxPerLine, int numEpochs, bool traverseCSR = true) { if (g.directed() == false) traverseCSR = true; Timer tm; #if 0 /* Step 0: Sanity check that neighborhoods are sorted */ #pragma omp parallel for schedule(dynamic, 64) for (NodeID_ v = 0; v < g.num_nodes(); ++v) { NodeID_ maxNgh {-1}; for (NodeID ngh: g.out_neigh(v)) { assert(ngh > maxNgh); maxNgh = ngh; } } #endif /* Step I: Collect quantized edges & Compact vertices into "super vertices" */ tm.Start(); NodeID_ numCacheLines = (g.num_nodes() + numVtxPerLine - 1) / numVtxPerLine; NodeID_ epochSz = (g.num_nodes() + numEpochs - 1) / numEpochs; pvector<NodeID_> lastRef(numCacheLines * numEpochs, -1); NodeID_ chunkSz = 64 / numVtxPerLine; if (chunkSz == 0) chunkSz = 1; #pragma omp parallel for schedule(dynamic, chunkSz) for (NodeID_ c = 0; c < numCacheLines; ++c) { NodeID_ startVtx = c * numVtxPerLine; NodeID_ endVtx = (c+1) * numVtxPerLine; if (c == numCacheLines - 1) endVtx = g.num_nodes(); for (NodeID_ v = startVtx; v < endVtx; ++v) { if (traverseCSR == true) { for (NodeID_ ngh : g.out_neigh(v)) { NodeID_ nghEpoch = ngh / epochSz; lastRef[(c * numEpochs) + nghEpoch] = std::max(ngh, lastRef[(c * numEpochs) + nghEpoch]); } } else { for (NodeID_ ngh : g.in_neigh(v)) { NodeID_ nghEpoch = ngh / epochSz; lastRef[(c * numEpochs) + nghEpoch] = std::max(ngh, lastRef[(c * numEpochs) + nghEpoch]); } } } } tm.Stop(); std::cout << "[CSR-HYBRID-PREPROCESSING] Time to quantize nghs and compact vertices = " << tm.Seconds() << std::endl; assert(numEpochs == 256); /* Step II: Converting adjacency matrix into offsets */ tm.Start(); uint8_t maxReref = 127; //because MSB is reserved for identifying between reref val (1) & switch point (0) NodeID_ subEpochSz = (epochSz + 127) / 128; //Using remaining 7 bits to identify intra-epoch information pvector<uint8_t> compressedOffsets(numCacheLines * numEpochs); uint8_t mask = 1; uint8_t orMask = mask << 7; uint8_t andMask = ~(orMask); assert(orMask == 128 && andMask == 127); #pragma omp parallel for schedule (static) for (NodeID_ c = 0; c < numCacheLines; ++c) { { // first set values for the last epoch NodeID_ e = numEpochs - 1; if (lastRef[(c * numEpochs) + e] != -1) { compressedOffsets[(c * numEpochs) + e] = maxReref; compressedOffsets[(c * numEpochs) + e] &= andMask; } else { compressedOffsets[(c * numEpochs) + e] = maxReref; compressedOffsets[(c * numEpochs) + e] |= orMask; } } //Now back track and set values for all epochs for (NodeID_ e = numEpochs - 2; e >= 0; --e) { if (lastRef[(c * numEpochs) + e] != -1) { // There was a ref this epoch - store the quantized val of the lastRef NodeID_ subEpochDist = lastRef[(c * numEpochs) + e] - (e * epochSz); assert(subEpochDist >= 0); NodeID_ lastRefQ = (subEpochDist / subEpochSz); assert(lastRefQ <= maxReref); compressedOffsets[(c * numEpochs) + e] = static_cast<uint8_t>(lastRefQ); compressedOffsets[(c * numEpochs) + e] &= andMask; } else { if ((compressedOffsets[(c * numEpochs) + e + 1] & orMask) != 0) { //No access next epoch as well - add inter-epoch distance uint8_t nextRef = compressedOffsets[(c * numEpochs) + e + 1] & andMask; if (nextRef == maxReref) compressedOffsets[(c * numEpochs) + e] = maxReref; else compressedOffsets[(c * numEpochs) + e] = nextRef + 1; } else { //There is an access next epoch - so inter-epoch distance is set to next epoch compressedOffsets[(c * numEpochs) + e] = 1; } compressedOffsets[(c * numEpochs) + e] |= orMask; } } } tm.Stop(); std::cout << "[CSR-HYBRID-PREPROCESSING] Time to convert to offsets matrix = " << tm.Seconds() << std::endl; /* Step III: Transpose edgePresent*/ tm.Start(); #pragma omp parallel for schedule (static) for (NodeID_ c = 0; c < numCacheLines; ++c) { for (NodeID_ e = 0; e < numEpochs; ++e) { offsetMatrix[(e * numCacheLines) + c] = compressedOffsets[(c * numEpochs) + e]; } } tm.Stop(); std::cout << "[CSR-HYBRID-PREPROCESSING] Time to transpose offsets matrix = " << tm.Seconds() << std::endl; /* // Sanity check - The following conditions will be checked // 1. If the MSB bit in an epoch is zero, then there should be a reference to the cacheline in that epoch // 2. If the MSB bit in an epoch is zero, then the remaining 7 bits should capture the last reference within the epoch // 3. If the MSB bit in an epoch is 1, then there should be no reference to the cacheline in that epoch // 4. If the MSB bit in an epoch is 1, then use the information in the remaining 7 bits to ascertain which epoch a line will be accessed next if (traverseCSR == true) { //Step I: compute per-cacheline neighborhoods std::vector<std::set<NodeID_> > lineNghs; lineNghs.resize(numCacheLines); #pragma omp parallel for schedule(dynamic, 8) for (NodeID_ c = 0; c < numCacheLines; ++c) { NodeID_ startVtx = c * numVtxPerLine; NodeID_ endVtx = (c+1) * numVtxPerLine; if (c == numCacheLines - 1) endVtx = g.num_nodes(); for (NodeID_ v = startVtx; v < endVtx; ++v) { for (NodeID_ ngh : g.out_neigh(v)) { lineNghs[c].insert(ngh); } } } //Step II: Check conditions 1 & 3 for epoch data structure #pragma omp parallel for schedule(static) for (NodeID_ c = 0; c < numCacheLines; ++c) { for (NodeID_ e = 0; e < numEpochs; ++e) { if ((compressedOffsets[(c * numEpochs) + e] & orMask) != 0) { // Cond 3: There should be no reference this epoch NodeID_ epochStart = e * epochSz; NodeID_ epochEnd = (e + 1) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochStart); if (it != lineNghs[c].end()) { NodeID_ lastRef = *it; assert(lastRef >= epochEnd); } } else { // Cond 1: There must be a reference this epoch NodeID_ epochStart = e * epochSz; NodeID_ epochEnd = (e + 1) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochStart); assert(it != lineNghs[c].end()); NodeID_ lastRef = *it; assert(lastRef < epochEnd); } } } //Step III: Check conditions 2 & 4 for epoch data structure #pragma omp parallel for schedule(static) for (NodeID_ c = 0; c < numCacheLines; ++c) { for (NodeID_ e = 0; e < numEpochs; ++e) { if ((compressedOffsets[(c * numEpochs) + e] & orMask) != 0) { // Cond 4: The inter-epoch info points to the next epoch uint8_t interEpochDist = compressedOffsets[(c * numEpochs) + e] & andMask; NodeID_ epochStart = (e + interEpochDist) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochStart); if (it != lineNghs[c].end()) { NodeID_ lastRef = *it; assert(lastRef >= epochStart); //minimum condition //because of quantization we cant be sure exactly which epoch (or if ever) the line will be accessed } } else { // Cond 2: We track the correct intra-Epoch lastRef NodeID_ epochStart = e * epochSz; NodeID_ epochEnd = (e + 1) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochEnd); it--; NodeID_ lastRef = *it; assert(lastRef < epochEnd && lastRef >= epochStart); NodeID_ subEpochDist = (*it) - epochStart; uint8_t subEpochDistQ = subEpochDist / subEpochSz; uint8_t intraEpochDist = compressedOffsets[(c * numEpochs) + e] & andMask; if (e != numEpochs - 1) assert(intraEpochDist == subEpochDistQ); } } } } else { //Step I: compute per-cacheline neighborhoods std::vector<std::set<NodeID_> > lineNghs; lineNghs.resize(numCacheLines); #pragma omp parallel for schedule(dynamic, 8) for (NodeID_ c = 0; c < numCacheLines; ++c) { NodeID_ startVtx = c * numVtxPerLine; NodeID_ endVtx = (c+1) * numVtxPerLine; if (c == numCacheLines - 1) endVtx = g.num_nodes(); for (NodeID_ v = startVtx; v < endVtx; ++v) { for (NodeID_ ngh : g.in_neigh(v)) { lineNghs[c].insert(ngh); } } } //Step II: Check conditions 1 & 3 for epoch data structure #pragma omp parallel for schedule(static) for (NodeID_ c = 0; c < numCacheLines; ++c) { for (NodeID_ e = 0; e < numEpochs; ++e) { if ((compressedOffsets[(c * numEpochs) + e] & orMask) != 0) { // Cond 3: There should be no reference this epoch NodeID_ epochStart = e * epochSz; NodeID_ epochEnd = (e + 1) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochStart); if (it != lineNghs[c].end()) { NodeID_ lastRef = *it; assert(lastRef >= epochEnd); } } else { // Cond 1: There must be a reference this epoch NodeID_ epochStart = e * epochSz; NodeID_ epochEnd = (e + 1) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochStart); assert(it != lineNghs[c].end()); NodeID_ lastRef = *it; assert(lastRef < epochEnd); } } } //Step III: Check conditions 2 & 4 for epoch data structure #pragma omp parallel for schedule(static) for (NodeID_ c = 0; c < numCacheLines; ++c) { for (NodeID_ e = 0; e < numEpochs; ++e) { if ((compressedOffsets[(c * numEpochs) + e] & orMask) != 0) { // Cond 4: The inter-epoch info points to the next epoch uint8_t interEpochDist = compressedOffsets[(c * numEpochs) + e] & andMask; NodeID_ epochStart = (e + interEpochDist) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochStart); if (it != lineNghs[c].end()) { NodeID_ lastRef = *it; assert(lastRef >= epochStart); //minimum condition //because of quantization we cant be sure exactly which epoch (or if ever) the line will be accessed } } else { // Cond 2: We track the correct intra-Epoch lastRef NodeID_ epochStart = e * epochSz; NodeID_ epochEnd = (e + 1) * epochSz; auto it = std::lower_bound(lineNghs[c].begin(), lineNghs[c].end(), epochEnd); it--; NodeID_ lastRef = *it; assert(lastRef < epochEnd && lastRef >= epochStart); NodeID_ subEpochDist = (*it) - epochStart; uint8_t subEpochDistQ = subEpochDist / subEpochSz; uint8_t intraEpochDist = compressedOffsets[(c * numEpochs) + e] & andMask; if (e != numEpochs - 1) assert(intraEpochDist == subEpochDistQ); } } } } */ } }; #endif // BUILDER_H_
net_md5_fmt_plug.c
/* Cracker for RIPv2 MD5 authentication hashes. * * This software is Copyright (c) 2013, Dhiru Kholia <dhiru [at] openwall.com>, * and it is hereby released to the general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * Added linkage to dynamic (type dynamic_39) for any salt 230 bytes or less, * by Jim Fougeron. Any salts > 239 bytes will still be handled by this full * format. dynamic is limited to 256 bytes, which 'should' get us 240 bytes * of salt. I think we might be able to get 239 bytes (due to a few issues). * 240 byte salts fail. So, for peace of mind, I am limiting to 230 byte salts * within dynamic. This is the FIRST format that is hybrid fat-thin. */ #if AC_BUILT #include "autoconfig.h" #endif #ifndef DYNAMIC_DISABLED #if FMT_EXTERNS_H extern struct fmt_main fmt_netmd5; #elif FMT_REGISTERS_H john_register_one(&fmt_netmd5); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 2048 // XXX #endif #endif #include "formats.h" #include "dynamic.h" #include "md5.h" #include "misc.h" #include "common.h" #include "params.h" #include "options.h" #include "memdbg.h" #define FORMAT_LABEL "net-md5" #define FORMAT_NAME "\"Keyed MD5\" RIPv2, OSPF, BGP, SNMPv2" #define FORMAT_TAG "$netmd5$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 // RIPv2 truncates (or null pads) passwords to length 16 #define PLAINTEXT_LENGTH 16 #define BINARY_SIZE 16 #define BINARY_ALIGN sizeof(ARCH_WORD_32) #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN MEM_ALIGN_WORD #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define MAX_SALT_LEN 1024 static struct fmt_tests tests[] = { /* RIPv2 MD5 authentication hashes */ { "02020000ffff0003002c01145267d48d000000000000000000020000ac100100ffffff000000000000000001ffff0001$1e372a8a233c6556253a0909bc3dcce6", "quagga"}, {FORMAT_TAG "02020000ffff0003002c01145267d48f000000000000000000020000ac100100ffffff000000000000000001ffff0001$ed9f940c3276afcc06d15babe8a1b61b", "quagga"}, {FORMAT_TAG "02020000ffff0003002c01145267d490000000000000000000020000ac100100ffffff000000000000000001ffff0001$c9f7763f80fcfcc2bbbca073be1f5df7", "quagga"}, {FORMAT_TAG "02020000ffff0003002c01145267d49a000000000000000000020000ac100200ffffff000000000000000001ffff0001$3f6a72deeda200806230298af0797997", "quagga"}, {FORMAT_TAG "02020000ffff0003002c01145267d49b000000000000000000020000ac100200ffffff000000000000000001ffff0001$b69184bacccc752cadf78cac455bd0de", "quagga"}, {FORMAT_TAG "02020000ffff0003002c01145267d49d000000000000000000020000ac100100ffffff000000000000000001ffff0001$6442669c577e7662188865a54c105d0e", "quagga"}, {FORMAT_TAG "02020000ffff0003002c01145267e076000000000000000000020000ac100200ffffff000000000000000001ffff0001$4afe22cf1750d9af8775b25bcf9cfb8c", "abcdefghijklmnop"}, {FORMAT_TAG "02020000ffff0003002c01145267e077000000000000000000020000ac100200ffffff000000000000000001ffff0001$326b12f6da03048a655ea4d8f7e3e123", "abcdefghijklmnop"}, {FORMAT_TAG "02020000ffff0003002c01145267e2ab000000000000000000020000ac100100ffffff000000000000000001ffff0001$ad76c40e70383f6993f54b4ba6492a26", "abcdefghijklmnop"}, /* OSPFv2 MD5 authentication hashes */ {"$netmd5$0201002cac1001010000000000000002000001105267ff8fffffff00000a0201000000280000000000000000$445ecbb27272bd791a757a6c85856150", "abcdefghijklmnop"}, {FORMAT_TAG "0201002cac1001010000000000000002000001105267ff98ffffff00000a0201000000280000000000000000$d4c248b417b8cb1490e02c5e99eb0ad1", "abcdefghijklmnop"}, {FORMAT_TAG "0201002cac1001010000000000000002000001105267ffa2ffffff00000a0201000000280000000000000000$528d9bf98be8213482af7295307625bf", "abcdefghijklmnop"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static void get_ptr(); static void init(struct fmt_main *self); static void done(void); #define MAGIC 0xfe5dd5ef static struct custom_salt { ARCH_WORD_32 magic; int length; unsigned char salt[MAX_SALT_LEN]; // fixd len, but should be OK } *cur_salt; static int dyna_salt_seen=0; static char Conv_Buf[300]; // max salt length we will pass to dyna is 230. 300 is MORE than enough. static struct fmt_main *pDynamicFmt, *pNetMd5_Dyna; /* this function converts a 'native' net-md5 signature string into a $dynamic_39$ syntax string */ static char *Convert(char *Buf, char *ciphertext) { char *cp, *cp2; if (text_in_dynamic_format_already(pDynamicFmt, ciphertext)) return ciphertext; cp = strchr(&ciphertext[2], '$'); if (!cp) return "*"; cp2 = strchr(&cp[1], '$'); if (!cp2) return "*"; snprintf(Buf, sizeof(Conv_Buf), "$dynamic_39$%s$HEX%*.*s", &cp2[1], (int)(cp2-cp), (int)(cp2-cp), cp); return Buf; } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q = NULL; int len; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += TAG_LENGTH; q = strrchr(ciphertext, '$'); if (!q) return 0; q = q + 1; if ((q - p - 1) > MAX_SALT_LEN * 2) return 0; len = strspn(q, HEXCHARS_lc); if (len != BINARY_SIZE * 2 || len != strlen(q)) { get_ptr(); return pDynamicFmt->methods.valid(ciphertext, pDynamicFmt); } if (strspn(p, HEXCHARS_lc) != q - p - 1) return 0; return 1; } static void *get_salt(char *ciphertext) { static char *pBuf=NULL; struct custom_salt *cs; char *orig_ct = ciphertext; int i, len; if (!pBuf) pBuf = (char *)mem_alloc_tiny(sizeof(struct custom_salt), MEM_ALIGN_WORD); cs = (struct custom_salt*) pBuf; memset(cs, 0, sizeof(*cs)); if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) ciphertext += TAG_LENGTH; len = (strrchr(ciphertext, '$') - ciphertext) / 2; for (i = 0; i < len; i++) cs->salt[i] = (atoi16[ARCH_INDEX(ciphertext[2 * i])] << 4) | atoi16[ARCH_INDEX(ciphertext[2 * i + 1])]; if (len < 230) { // return our memset buffer (putting the dyna salt pointer into it). // This keeps the 'pre-cleaned salt() warning from hitting this format) //return pDynamicFmt->methods.salt(Convert(Conv_Buf, orig_ct)); memcpy((char*)cs, pDynamicFmt->methods.salt(Convert(Conv_Buf, orig_ct)), pDynamicFmt->params.salt_size); dyna_salt_seen=1; return cs; } cs->magic = MAGIC; cs->length = len; return cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; if (text_in_dynamic_format_already(pDynamicFmt, ciphertext)) // returns proper 16 bytes, so we do not need to copy into our buffer. return pDynamicFmt->methods.binary(ciphertext); p = strrchr(ciphertext, '$') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int get_hash_0(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[0](index); return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[1](index); return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[2](index); return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[3](index); return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[4](index); return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[5](index); return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { if (cur_salt->magic != MAGIC) return pDynamicFmt->methods.get_hash[6](index); return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; get_ptr(); if (cur_salt->magic != MAGIC) { pDynamicFmt->methods.set_salt(salt); } } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; if (cur_salt->magic != MAGIC) { return pDynamicFmt->methods.crypt_all(pcount, salt); } #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, cur_salt->salt, cur_salt->length); MD5_Update(&ctx, saved_key[index], PLAINTEXT_LENGTH); MD5_Final((unsigned char*)crypt_out[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index = 0; if (cur_salt->magic != MAGIC) { return pDynamicFmt->methods.cmp_all(binary, count); } for (; index < count; index++) if (((ARCH_WORD_32*)binary)[0] == crypt_out[index][0]) return 1; return 0; } static int cmp_one(void *binary, int index) { if (cur_salt->magic != MAGIC) { return pDynamicFmt->methods.cmp_one(binary, index); } return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void netmd5_set_key(char *key, int index) { if(dyna_salt_seen) pDynamicFmt->methods.set_key(key, index); /* strncpy will pad with zeros, which is needed */ strncpy(saved_key[index], key, sizeof(saved_key[0])); } static char *get_key(int index) { return saved_key[index]; } static char *prepare(char *fields[10], struct fmt_main *self) { static char buf[sizeof(cur_salt->salt)*2+TAG_LENGTH+1]; char *hash = fields[1]; if (strncmp(hash, FORMAT_TAG, TAG_LENGTH) && valid(hash, self)) { get_ptr(); if (text_in_dynamic_format_already(pDynamicFmt, hash)) return hash; sprintf(buf, "%s%s", FORMAT_TAG, hash); return buf; } return hash; } struct fmt_main fmt_netmd5 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { NULL }, tests }, { init, done, fmt_default_reset, prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, netmd5_set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; static void get_ptr() { if (!pDynamicFmt) { char *Buf; pNetMd5_Dyna = mem_alloc_tiny(sizeof(fmt_netmd5), 16); memcpy(pNetMd5_Dyna, &fmt_netmd5, sizeof(fmt_netmd5)); pDynamicFmt = dynamic_THIN_FORMAT_LINK(pNetMd5_Dyna, Convert(Conv_Buf, tests[1].ciphertext), "net-md5", 0); fmt_netmd5.params.min_keys_per_crypt = pDynamicFmt->params.min_keys_per_crypt; fmt_netmd5.params.max_keys_per_crypt = pDynamicFmt->params.max_keys_per_crypt; Buf = mem_alloc_tiny(strlen(fmt_netmd5.params.algorithm_name) + 4 + strlen("dynamic_39") + 1, 1); sprintf(Buf, "%s or %s", fmt_netmd5.params.algorithm_name, "dynamic_39"); fmt_netmd5.params.algorithm_name = Buf; //pDynamicFmt->methods.init(pDynamicFmt); } } static void init(struct fmt_main *self) { // We have to allocate our dyna_39 object first, because we get 'modified' min/max counts from there. get_ptr(); if (self->private.initialized == 0) { pDynamicFmt = dynamic_THIN_FORMAT_LINK(pNetMd5_Dyna, Convert(Conv_Buf, tests[1].ciphertext), "net-md5", 1); self->private.initialized = 1; } saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); pDynamicFmt->methods.done(); } #endif /* plugin stanza */ #endif /* DYNAMIC_DISABLED */
paint.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP AAA IIIII N N TTTTT % % P P A A I NN N T % % PPPP AAAAA I N N N T % % P A A I N NN T % % P A A IIIII N N T % % % % % % Methods to Paint on an Image % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o o d f i l l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FloodfillPaintImage() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. The fuzz member of % image defines how much tolerance is acceptable to consider two colors as % the same. For example, set fuzz to 10 and the color red at intensities of % 100 and 102 respectively are now interpreted as the same color for the % purposes of the floodfill. % % The format of the FloodfillPaintImage method is: % % MagickBooleanType FloodfillPaintImage(Image *image, % const DrawInfo *draw_info,const PixelInfo target, % const ssize_t x_offset,const ssize_t y_offset, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o target: the RGB value of the target color. % % o x_offset,y_offset: the starting location of the operation. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType FloodfillPaintImage(Image *image, const DrawInfo *draw_info,const PixelInfo *target,const ssize_t x_offset, const ssize_t y_offset,const MagickBooleanType invert, ExceptionInfo *exception) { #define MaxStacksize 524288UL #define PushSegmentStack(up,left,right,delta) \ { \ if (s >= (segment_stack+MaxStacksize)) \ ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \ else \ { \ if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \ { \ s->x1=(double) (left); \ s->y1=(double) (up); \ s->x2=(double) (right); \ s->y2=(double) (delta); \ s++; \ } \ } \ } CacheView *floodplane_view, *image_view; Image *floodplane_image; MagickBooleanType skip, status; MemoryInfo *segment_info; PixelInfo fill_color, pixel; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); if ((image->alpha_trait == UndefinedPixelTrait) && (draw_info->fill.alpha_trait != UndefinedPixelTrait)) (void) SetImageAlpha(image,OpaqueAlpha,exception); /* Set floodfill state. */ floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); floodplane_image->alpha_trait=UndefinedPixelTrait; floodplane_image->colorspace=GRAYColorspace; (void) QueryColorCompliance("#000",AllCompliance, &floodplane_image->background_color,exception); (void) SetImageBackgroundColor(floodplane_image,exception); segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack)); if (segment_info == (MemoryInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info); /* Push initial segment on stack. */ status=MagickTrue; start=0; s=segment_stack; PushSegmentStack(y_offset,x_offset,x_offset,1); PushSegmentStack(y_offset+1,x_offset,x_offset,-1); GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception); while (s > segment_stack) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception); q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; p+=x1*GetPixelChannels(image); q+=x1*GetPixelChannels(floodplane_image); for (x=x1; x >= 0; x--) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert) break; SetPixelGray(floodplane_image,QuantumRange,q); p-=GetPixelChannels(image); q-=GetPixelChannels(floodplane_image); } if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,image->columns- x,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for ( ; x < (ssize_t) image->columns; x++) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert) break; SetPixelGray(floodplane_image,QuantumRange,q); p+=GetPixelChannels(image); q+=GetPixelChannels(floodplane_image); } status=SyncCacheViewAuthenticPixels(floodplane_view,exception); if (status == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for ( ; x <= x2; x++) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert) break; p+=GetPixelChannels(image); q+=GetPixelChannels(floodplane_image); } } start=x; } while (x <= x2); } status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Tile fill color onto floodplane. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelGray(floodplane_image,p) != 0) { GetFillColor(draw_info,x,y,&fill_color,exception); SetPixelViaPixelInfo(image,&fill_color,q); } p+=GetPixelChannels(floodplane_image); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } floodplane_view=DestroyCacheView(floodplane_view); image_view=DestroyCacheView(image_view); segment_info=RelinquishVirtualMemory(segment_info); floodplane_image=DestroyImage(floodplane_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GradientImage() applies a continuously smooth color transitions along a % vector from one color to another. % % Note, the interface of this method will change in the future to support % more than one transistion. % % The format of the GradientImage method is: % % MagickBooleanType GradientImage(Image *image,const GradientType type, % const SpreadMethod method,const PixelInfo *start_color, % const PixelInfo *stop_color,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the gradient type: linear or radial. % % o spread: the gradient spread meathod: pad, reflect, or repeat. % % o start_color: the start color. % % o stop_color: the stop color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GradientImage(Image *image, const GradientType type,const SpreadMethod method,const StopInfo *stops, const size_t number_stops,ExceptionInfo *exception) { const char *artifact; DrawInfo *draw_info; GradientInfo *gradient; MagickBooleanType status; /* Set gradient start-stop end points. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(stops != (const StopInfo *) NULL); assert(number_stops > 0); draw_info=AcquireDrawInfo(); gradient=(&draw_info->gradient); gradient->type=type; gradient->bounding_box.width=image->columns; gradient->bounding_box.height=image->rows; artifact=GetImageArtifact(image,"gradient:bounding-box"); if (artifact != (const char *) NULL) (void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box); gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; artifact=GetImageArtifact(image,"gradient:direction"); if (artifact != (const char *) NULL) { GravityType direction; direction=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,artifact); switch (direction) { case NorthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case WestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case EastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case SouthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->rows-1; break; } case SouthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->columns-1; break; } case SouthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; break; } default: break; } } artifact=GetImageArtifact(image,"gradient:angle"); if (artifact != (const char *) NULL) gradient->angle=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"gradient:vector"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", &gradient->gradient_vector.x1,&gradient->gradient_vector.y1, &gradient->gradient_vector.x2,&gradient->gradient_vector.y2); if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) && (GetImageArtifact(image,"gradient:direction") == (const char *) NULL) && (GetImageArtifact(image,"gradient:extent") == (const char *) NULL) && (GetImageArtifact(image,"gradient:vector") == (const char *) NULL)) if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0)) gradient->gradient_vector.x2=0.0; gradient->center.x=(double) gradient->gradient_vector.x2/2.0; gradient->center.y=(double) gradient->gradient_vector.y2/2.0; artifact=GetImageArtifact(image,"gradient:center"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x, &gradient->center.y); artifact=GetImageArtifact(image,"gradient:angle"); if ((type == LinearGradient) && (artifact != (const char *) NULL)) { double sine, cosine, distance; /* Reference https://drafts.csswg.org/css-images-3/#linear-gradients. */ sine=sin((double) DegreesToRadians(gradient->angle-90.0)); cosine=cos((double) DegreesToRadians(gradient->angle-90.0)); distance=fabs((double) (image->columns-1.0)*cosine)+ fabs((double) (image->rows-1.0)*sine); gradient->gradient_vector.x1=0.5*((image->columns-1.0)-distance*cosine); gradient->gradient_vector.y1=0.5*((image->rows-1.0)-distance*sine); gradient->gradient_vector.x2=0.5*((image->columns-1.0)+distance*cosine); gradient->gradient_vector.y2=0.5*((image->rows-1.0)+distance*sine); } gradient->radii.x=(double) MagickMax((image->columns-1.0),(image->rows-1.0))/ 2.0; gradient->radii.y=gradient->radii.x; artifact=GetImageArtifact(image,"gradient:extent"); if (artifact != (const char *) NULL) { if (LocaleCompare(artifact,"Circle") == 0) { gradient->radii.x=(double) MagickMax((image->columns-1.0), (image->rows-1.0))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Diagonal") == 0) { gradient->radii.x=(double) (sqrt((image->columns-1.0)* (image->columns-1.0)+(image->rows-1.0)*(image->rows-1.0)))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Ellipse") == 0) { gradient->radii.x=(double) (image->columns-1.0)/2.0; gradient->radii.y=(double) (image->rows-1.0)/2.0; } if (LocaleCompare(artifact,"Maximum") == 0) { gradient->radii.x=(double) MagickMax((image->columns-1.0), (image->rows-1.0))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Minimum") == 0) { gradient->radii.x=(double) (MagickMin((image->columns-1.0), (image->rows-1.0)))/2.0; gradient->radii.y=gradient->radii.x; } } artifact=GetImageArtifact(image,"gradient:radii"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x, &gradient->radii.y); gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y); gradient->spread=method; /* Define the gradient to fill between the stops. */ gradient->number_stops=number_stops; gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops, sizeof(*gradient->stops)); if (gradient->stops == (StopInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) CopyMagickMemory(gradient->stops,stops,(size_t) number_stops* sizeof(*stops)); /* Draw a gradient on the image. */ status=DrawGradientImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O i l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OilPaintImage() applies a special effect filter that simulates an oil % painting. Each pixel is replaced by the most frequent color occurring % in a circular region defined by radius. % % The format of the OilPaintImage method is: % % Image *OilPaintImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the circular neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ static size_t **DestroyHistogramThreadSet(size_t **histogram) { register ssize_t i; assert(histogram != (size_t **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (histogram[i] != (size_t *) NULL) histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]); histogram=(size_t **) RelinquishMagickMemory(histogram); return(histogram); } static size_t **AcquireHistogramThreadSet(const size_t count) { register ssize_t i; size_t **histogram, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); histogram=(size_t **) AcquireQuantumMemory(number_threads,sizeof(*histogram)); if (histogram == (size_t **) NULL) return((size_t **) NULL); (void) ResetMagickMemory(histogram,0,number_threads*sizeof(*histogram)); for (i=0; i < (ssize_t) number_threads; i++) { histogram[i]=(size_t *) AcquireQuantumMemory(count,sizeof(**histogram)); if (histogram[i] == (size_t *) NULL) return(DestroyHistogramThreadSet(histogram)); } return(histogram); } MagickExport Image *OilPaintImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define NumberPaintBins 256 #define OilPaintImageTag "OilPaint/Image" CacheView *image_view, *paint_view; Image *linear_image, *paint_image; MagickBooleanType status; MagickOffsetType progress; size_t **histograms, width; ssize_t center, y; /* Initialize painted image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth2D(radius,sigma); linear_image=CloneImage(image,0,0,MagickTrue,exception); paint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (paint_image != (Image *) NULL) linear_image=DestroyImage(paint_image); return((Image *) NULL); } if (SetImageStorageClass(paint_image,DirectClass,exception) == MagickFalse) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); return((Image *) NULL); } histograms=AcquireHistogramThreadSet(NumberPaintBins); if (histograms == (size_t **) NULL) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Oil paint image. */ status=MagickTrue; progress=0; center=(ssize_t) GetPixelChannels(linear_image)*(linear_image->columns+width)* (width/2L)+GetPixelChannels(linear_image)*(width/2L); image_view=AcquireVirtualCacheView(linear_image,exception); paint_view=AcquireAuthenticCacheView(paint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(linear_image,paint_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register size_t *histogram; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (width/2L),linear_image->columns+width,width,exception); q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } histogram=histograms[GetOpenMPThreadId()]; for (x=0; x < (ssize_t) linear_image->columns; x++) { register ssize_t i, u; size_t count; ssize_t j, k, n, v; /* Assign most frequent color. */ k=0; j=0; count=0; (void) ResetMagickMemory(histogram,0,NumberPaintBins* sizeof(*histogram)); for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { n=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity( linear_image,p+GetPixelChannels(linear_image)*(u+k)))); histogram[n]++; if (histogram[n] > count) { j=k+u; count=histogram[n]; } } k+=(ssize_t) (linear_image->columns+width); } for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++) { PixelChannel channel = GetPixelChannelChannel(linear_image,i); PixelTrait traits = GetPixelChannelTraits(linear_image,channel); PixelTrait paint_traits=GetPixelChannelTraits(paint_image,channel); if ((traits == UndefinedPixelTrait) || (paint_traits == UndefinedPixelTrait)) continue; if (((paint_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(linear_image,p) <= (QuantumRange/2))) { SetPixelChannel(paint_image,channel,p[center+i],q); continue; } SetPixelChannel(paint_image,channel,p[j*GetPixelChannels(linear_image)+ i],q); } p+=GetPixelChannels(linear_image); q+=GetPixelChannels(paint_image); } if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse) status=MagickFalse; if (linear_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OilPaintImage) #endif proceed=SetImageProgress(linear_image,OilPaintImageTag,progress++, linear_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } paint_view=DestroyCacheView(paint_view); image_view=DestroyCacheView(image_view); histograms=DestroyHistogramThreadSet(histograms); linear_image=DestroyImage(linear_image); if (status == MagickFalse) paint_image=DestroyImage(paint_image); return(paint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p a q u e P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpaquePaintImage() changes any pixel that matches color with the color % defined by fill argument. % % By default color must match a particular pixel color exactly. However, in % many cases two colors may differ by a small amount. Fuzz defines how much % tolerance is acceptable to consider two colors as the same. For example, % set fuzz to 10 and the color red at intensities of 100 and 102 respectively % are now interpreted as the same color. % % The format of the OpaquePaintImage method is: % % MagickBooleanType OpaquePaintImage(Image *image,const PixelInfo *target, % const PixelInfo *fill,const MagickBooleanType invert, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o fill: the replacement color. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OpaquePaintImage(Image *image, const PixelInfo *target,const PixelInfo *fill,const MagickBooleanType invert, ExceptionInfo *exception) { #define OpaquePaintImageTag "Opaque/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo conform_fill, conform_target, zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (PixelInfo *) NULL); assert(fill != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); ConformPixelInfo(image,fill,&conform_fill,exception); ConformPixelInfo(image,target,&conform_target,exception); /* Make image color opaque. */ status=MagickTrue; progress=0; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&conform_target) != invert) { PixelTrait traits; traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelRed(image,conform_fill.red,q); traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelGreen(image,conform_fill.green,q); traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelBlue(image,conform_fill.blue,q); traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelBlack(image,conform_fill.black,q); traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelAlpha(image,conform_fill.alpha,q); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OpaquePaintImage) #endif proceed=SetImageProgress(image,OpaquePaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, in % many cases two colors may differ by a small amount. Fuzz defines how much % tolerance is acceptable to consider two colors as the same. For example, % set fuzz to 10 and the color red at intensities of 100 and 102 respectively % are now interpreted as the same color. % % The format of the TransparentPaintImage method is: % % MagickBooleanType TransparentPaintImage(Image *image, % const PixelInfo *target,const Quantum opacity, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o target: the target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransparentPaintImage(Image *image, const PixelInfo *target,const Quantum opacity,const MagickBooleanType invert, ExceptionInfo *exception) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Make image color transparent. */ status=MagickTrue; progress=0; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert) SetPixelAlpha(image,opacity,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransparentPaintImage) #endif proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e C h r o m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImageChroma() changes the opacity value associated with any % pixel that matches color to the value defined by opacity. % % As there is one fuzz value for the all the channels, TransparentPaintImage() % is not suitable for the operations like chroma, where the tolerance for % similarity of two color component (RGB) can be different. Thus we define % this method to take two target pixels (one low and one high) and all the % pixels of an image which are lying between these two pixels are made % transparent. % % The format of the TransparentPaintImageChroma method is: % % MagickBooleanType TransparentPaintImageChroma(Image *image, % const PixelInfo *low,const PixelInfo *high,const Quantum opacity, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low: the low target color. % % o high: the high target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image, const PixelInfo *low,const PixelInfo *high,const Quantum opacity, const MagickBooleanType invert,ExceptionInfo *exception) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(high != (PixelInfo *) NULL); assert(low != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Make image color transparent. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType match; PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); match=((pixel.red >= low->red) && (pixel.red <= high->red) && (pixel.green >= low->green) && (pixel.green <= high->green) && (pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue : MagickFalse; if (match != invert) SetPixelAlpha(image,opacity,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransparentPaintImageChroma) #endif proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
sort.c
#include "sort.h" #include "types.h" #include "utils.h" #include <omp.h> #include <stdio.h> #include <string.h> #define INSERTION_SORT_THRESH 100 /** * @brief Sort the indices contained in the array sorted_indices * from start to end using insertion sort. The indices are sorted * according to the corresponding element in items_count. * * @param items_count array of key-value pairs * @param num_items length of items_count * @param sorted_indices array of indices that are going to be sorted * @param start start position of the sub-array to sort * @param end end position of the sub-array to sort */ void insertion_sort(hashmap_element *items_count, int num_items, int *sorted_indices, int start, int end) { int i, j, i_val, j_val; for (i = start + 1; i <= end; i++) { bool stop = false; i_val = items_count[sorted_indices[i]].value; int tmp = sorted_indices[i]; for (j = i; j > 0 && !stop; j--) { j_val = items_count[sorted_indices[j - 1]].value; if (j_val > i_val) { sorted_indices[j] = sorted_indices[j - 1]; } else { stop = true; } } if (stop) j++; sorted_indices[j] = tmp; } } /** * @brief Swap elements in position i and j in the array a * * @param a array where to swap the elements * @param i position of the first element to swap * @param j position of the second element to swap */ void swap(int *a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } /** * @brief Perform the pivot operation of the quicksort algorithm on * the sub-array sorted_indices from start to end (included). * * The indices which value in items_count is smaller than the value of * the pivot are moved to the left of the pivot, * the ones with a value greater or equal are moved to its right. * * @param items_count array of key-value pairs * @param num_items length of items_count * @param sorted_indices array of indices that are going to be sorted * @param start start position of the sub-array to sort * @param end end position of the sub-array to sort * @param m position of the pivot * @return the new position of the pivot */ int pivot(hashmap_element *items_count, int num_items, int *sorted_indices, int start, int end, int m) { swap(sorted_indices, start, m); int i, j = start, i_value, pivot = sorted_indices[start], pivot_value; // i_key_length = ulength(keys[pivot]); pivot_value = items_count[pivot].value; for (i = j + 1; i <= end; i++) { i_value = items_count[sorted_indices[i]].value; if (i_value < pivot_value) { j++; swap(sorted_indices, i, j); } } sorted_indices[start] = sorted_indices[j]; sorted_indices[j] = pivot; return j; } /** * @brief Chooses a pivot according to the Median-of-three heuristic. * * The pivot is chosen as the median of the first, middle and last element of * the sub-array sorted_indices from start to end, according to the * corresponding value in items_count. These three indices are swapped, so that * the median at the end is in position start. * * * @param items_count array of key-value pairs * @param num_items length of items_count * @param sorted_indices array of indices that are going to be sorted * @param start start position of the sub-array to sort * @param end end position of the sub-array to sort * @return the position of the pivot */ int choose_pivot(hashmap_element *items_count, int num_items, int *sorted_indices, int start, int end) { int m = (start + end) / 2; int v[3]; v[0] = items_count[sorted_indices[start]].value; v[1] = items_count[sorted_indices[m]].value; v[2] = items_count[sorted_indices[end]].value; if (v[0] > v[2]) { swap(v, 0, 2); swap(sorted_indices, start, end); } if (v[1] > v[2]) { swap(v, 1, 2); swap(sorted_indices, m, end); } if (v[1] > v[0]) { swap(v, 1, 0); swap(sorted_indices, m, start); } return start; } /** * @brief Subroutine that performs a parallel version of the QuickSort * algoritm. * * @param items_count array of key-value pairs * @param num_items length of items_count * @param sorted_indices array of indices that are going to be sorted * @param start start position of the sub-array to sort * @param end end position of the sub-array to sort * @param stack stack containing the jobs that need to be done by free threads * @param num_busy_threads Number of currently busy threads * @param num_threads Number of threads that perform the sorting */ void parallel_quick_sort(hashmap_element *items_count, int num_items, int *sorted_indices, int start, int end, cvector_vector_type(int) * stack, int *num_busy_threads, int *num_threads) { bool idle = true; while (true) { if (end - start < INSERTION_SORT_THRESH) { insertion_sort(items_count, num_items, sorted_indices, start, end); start = end; } while (start >= end) { #pragma omp critical { if (!cvector_empty((*stack))) { if (idle) (*num_busy_threads)++; idle = false; start = (*stack)[cvector_size((*stack)) - 1]; cvector_pop_back((*stack)); end = (*stack)[cvector_size((*stack)) - 1]; cvector_pop_back((*stack)); } else { if (!idle) (*num_busy_threads)--; idle = true; } } if (*num_busy_threads == 0) { return; } } int m = choose_pivot(items_count, num_items, sorted_indices, start, end); int i = pivot(items_count, num_items, sorted_indices, start, end, m); #pragma omp critical { cvector_push_back((*stack), i - 1); cvector_push_back((*stack), start); // push(pair(q, i - 1)); } /* iteratively sort elements right of pivot */ start = i + 1; } } /** * @brief Puts in the array sorted_indices the indices of the elements of * the array items_count from position start to end, after they are sorted * according to their value field. * * The array items_count is not modified. The algorithm implement a * parallel version of Quicksort, described in the paper * Süß M, Leopold C. A user’s experience with parallel sorting and OpenMP. * InProceedings of the Sixth European Workshop on OpenMP-EWOMP’04 2004 Oct 18 * (pp. 23-38). * * @param items_count array of key-value pairs * @param num_items length of items_count * @param sorted_indices array of indices that are going to be sorted * @param start start position of the sub-array to sort * @param end end position of the sub-array to sort * @param num_threads Number of threads that perform the sorting */ void sort(hashmap_element *items_count, int num_items, int *sorted_indices, int start, int end, int num_threads) { cvector_vector_type(int) stack = NULL; int num_busy_threads = 0; int i; #pragma omp parallel default(none) \ shared(items_count, num_items, sorted_indices, start, end, stack, \ num_threads, num_busy_threads) private(i) num_threads(num_threads) { #pragma omp for for (i = start; i <= end; i++) { sorted_indices[i] = i; } if (omp_get_thread_num() == 0) { parallel_quick_sort(items_count, num_items, sorted_indices, start, end, &stack, &num_busy_threads, &num_threads); } else { parallel_quick_sort(items_count, num_items, sorted_indices, start, start, &stack, &num_busy_threads, &num_threads); } } cvector_free(stack); }
parallel_levelset_distance_calculator.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // // #if !defined(KRATOS_PARALLEL_DISTANCE_CALCULATOR_H_INCLUDED ) #define KRATOS_PARALLEL_DISTANCE_CALCULATOR_H_INCLUDED // System includes #include <string> #include <iostream> // External includes // Project includes #include "includes/define.h" #include "utilities/geometry_utilities.h" #include "includes/deprecated_variables.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ template< unsigned int TDim> class ParallelDistanceCalculator { public: ///@name Type Definitions ///@{ KRATOS_DEFINE_LOCAL_FLAG(CALCULATE_EXACT_DISTANCES_TO_PLANE); /// Pointer definition of ParallelDistanceCalculator KRATOS_CLASS_POINTER_DEFINITION(ParallelDistanceCalculator); ///@} ///@name Life Cycle ///@{ /// Default constructor. ParallelDistanceCalculator() {}; /// Destructor. virtual ~ParallelDistanceCalculator() {}; ///Function to calculate a signed distance function suitable for calculations using the Level Set Method ///the function assumes given a "signed distance" distributions and recomputes the distances ///respecting as accurately as possible the position of the zero of the original distributions ///@param rModelPart is the ModelPart on which we will operate ///@param rDistanceVar is the Variable that we will use in calculating the distance ///@param rAreaVar is the Variable that we will use for L2 projections ///@param max_levels is the number of maximum "layers" of element that will be used in the calculation of the distances ///@param max_distance distances will not be computed after reaching this limit void CalculateDistances(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, const unsigned int max_levels, const double max_distance, Flags Options = NOT_CALCULATE_EXACT_DISTANCES_TO_PLANE) { KRATOS_TRY Check(rModelPart, rDistanceVar, rAreaVar); ResetVariables(rModelPart,rDistanceVar, max_distance); CalculateExactDistancesOnDividedElements(rModelPart, rDistanceVar, rAreaVar, max_distance, Options); ExtendDistancesByLayer(rModelPart, rDistanceVar, rAreaVar, max_levels, max_distance); AssignDistanceSign(rModelPart, rDistanceVar, rAreaVar, max_distance); KRATOS_CATCH("") } ///Function to calculate a signed distance function suitable for calculations using the Level Set Method ///The difference of this function with previous one is the fact that it wont recalculate the exact distance ///in divided elements in order to preserve the current distance. ///the function assumes given a "signed distance" distributions and recomputes the distances ///respecting as accurately as possible the position of the zero of the original distributions ///@param rModelPart is the ModelPart on which we will operate ///@param rDistanceVar is the Variable that we will use in calculating the distance ///@param rAreaVar is the Variable that we will use for L2 projections ///@param max_levels is the number of maximum "layers" of element that will be used in the calculation of the distances ///@param max_distance distances will not be computed after reaching this limit void CalculateInterfacePreservingDistances(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, const unsigned int max_levels, const double max_distance) { KRATOS_TRY Check(rModelPart, rDistanceVar, rAreaVar); ResetVariables(rModelPart,rDistanceVar, max_distance); AbsDistancesOnDividedElements(rModelPart, rDistanceVar, rAreaVar, max_distance); ExtendDistancesByLayer(rModelPart, rDistanceVar, rAreaVar, max_levels, max_distance); AssignDistanceSign(rModelPart, rDistanceVar, rAreaVar, max_distance); KRATOS_CATCH("") } /// A simplified version of CalculateDistances to be used when the rDistanceVar == 0 surface is described by a set of nodes /** * @param rModelPart is the ModelPart on which we will operate * @param rDistanceVar is the Variable that we will use in calculating the distance * @param rAreaVar is the Variable that we will use for L2 projections * @param max_levels is the number of maximum "layers" of element that will be used in the calculation of the distances * @param max_distance distances will not be computed after reaching this limit * @see ParallelDistanceCalculator::CalculateDistances */ void CalculateDistancesLagrangianSurface(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, const unsigned int max_levels, const double max_distance) { KRATOS_TRY bool is_distributed = false; if(rModelPart.GetCommunicator().TotalProcesses() > 1) is_distributed = true; //check that variables needed are in the model part if(!(rModelPart.NodesBegin()->SolutionStepsDataHas(rDistanceVar)) ) KRATOS_THROW_ERROR(std::logic_error,"distance Variable is not in the model part",""); if(!(rModelPart.NodesBegin()->SolutionStepsDataHas(rAreaVar)) ) KRATOS_THROW_ERROR(std::logic_error,"Area Variable is not in the model part",""); if(is_distributed == true) if(!(rModelPart.NodesBegin()->SolutionStepsDataHas(PARTITION_INDEX)) ) KRATOS_THROW_ERROR(std::logic_error,"PARTITION_INDEX Variable is not in the model part",""); array_1d<double,TDim+1> visited; const int elem_size = rModelPart.Elements().size(); const int node_size = rModelPart.Nodes().size(); // set to zero the distance #pragma omp parallel for for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; double& area = it->FastGetSolutionStepValue(rAreaVar); area = 0.0; double& is_visited = it->GetValue(IS_VISITED); double& distance = it->FastGetSolutionStepValue(rDistanceVar); it->GetValue(rDistanceVar) = it->FastGetSolutionStepValue(rDistanceVar); if(is_visited != 1.0) { distance = 0.0; } else area = 1.0; // else if(dist < 0.0) // KRATOS_THROW_ERROR(std::logic_error,"ATTENTION: prescribed distance function set to a number smaller than 0!!",""); } array_1d<double,TDim+1> N; BoundedMatrix <double, TDim+1,TDim> DN_DX; // Extend the distances layer by layer up to a maximum level of layers for(unsigned int level=0; level<max_levels; level++) { //loop on active elements and advance the distance computation #pragma omp parallel for private(DN_DX,visited) for(int i = 0; i<elem_size; i++) { PointerVector< Element>::iterator it=rModelPart.ElementsBegin()+i; Geometry<Node<3> >&geom = it->GetGeometry(); for(unsigned int j=0; j<TDim+1; j++) visited[j] = (static_cast<const Node<3> & >(geom[j])).GetValue(IS_VISITED); if(IsActive(visited)) { double Volume; GeometryUtils::CalculateGeometryData(geom,DN_DX,N,Volume); AddDistanceToNodes(rDistanceVar,rAreaVar,geom,DN_DX,Volume); } } //mpi sync variables if(is_distributed == true) { #pragma omp parallel for private(DN_DX) for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; if(it->GetValue(IS_VISITED) == 1.0) { double& distance = it->FastGetSolutionStepValue(rDistanceVar); it->GetValue(rDistanceVar) = distance; distance = 0.0; } else it->GetValue(rDistanceVar) = 0.0; } rModelPart.GetCommunicator().AssembleCurrentData(rAreaVar); rModelPart.GetCommunicator().AssembleCurrentData(rDistanceVar); #pragma omp parallel for private(DN_DX) for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; it->FastGetSolutionStepValue(rDistanceVar) += it->GetValue(rDistanceVar); } rModelPart.GetCommunicator().Barrier(); } //finalize the computation of the distance #pragma omp parallel for private(DN_DX) for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; double& area = it->FastGetSolutionStepValue(rAreaVar); double& is_visited = it->GetValue(IS_VISITED); if(area > 1e-20 && is_visited != 1.0) //this implies that node was computed at the current level and not before { double& distance = it->FastGetSolutionStepValue(rDistanceVar); distance /= area; is_visited = 1.0; } } } //*****************************************************************+ //*****************************************************************+ //*****************************************************************+ //assign the sign to the distance function according to the original distribution. Set to max for nodes that were not calculated #pragma omp parallel for for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; const double area = it->FastGetSolutionStepValue(rAreaVar); double& dist = it->FastGetSolutionStepValue(rDistanceVar); if(dist > max_distance || area <1e-20) dist = max_distance; // if(it->GetValue(IS_FLUID) == 1.0) // dist = -fabs(dist); // else // dist = fabs(dist); } KRATOS_CATCH("") } //********************************************************************************** //********************************************************************************** double FindMaximumEdgeSize(ModelPart& r_model_part) { KRATOS_TRY double h_max = 0.0; for(ModelPart::ElementsContainerType::iterator it=r_model_part.ElementsBegin(); it!=r_model_part.ElementsEnd(); it++) { Geometry<Node<3> >&geom = it->GetGeometry(); double h = 0.0; for(unsigned int i=0; i<TDim+1; i++) { double xc = geom[i].X(); double yc = geom[i].Y(); double zc = geom[i].Z(); for(unsigned int j=i+1; j<TDim+1; j++) { double x = geom[j].X(); double y = geom[j].Y(); double z = geom[j].Z(); double l = (x - xc)*(x - xc); l += (y - yc)*(y - yc); l += (z - zc)*(z - zc); if (l > h) h = l; } } h = sqrt(h); if(h > h_max) h_max = h; } r_model_part.GetCommunicator().MaxAll(h_max); return h_max; KRATOS_CATCH(""); } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const { std::stringstream buffer; buffer << "ParallelDistanceCalculator" << TDim << "D"; return buffer.str(); }; /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { rOStream << "ParallelDistanceCalculator" << TDim << "D"; }; /// Print object's data. virtual void PrintData(std::ostream& rOStream) const {}; ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ //******************************************************************* bool IsDivided(array_1d<double,TDim+1>& dist) { unsigned int positive = 0; unsigned int negative = 0; for(unsigned int i=0; i<TDim+1; i++) { if(dist[i] >= 0) positive++; else negative++; } bool is_divided = false; if(positive > 0 && negative>0) is_divided = true; return is_divided; } //******************************************************************* bool IsActive(array_1d<double,TDim+1>& visited) { unsigned int positive = 0; for(unsigned int i=0; i<TDim+1; i++) if(visited[i] > 0.9999999999) //node was considered positive++; bool is_active = false; if(positive == TDim) is_active = true; return is_active; } //******************************************************************* void ComputeExactDistances(const BoundedMatrix <double, TDim+1,TDim>& DN_DX, const double& Area, Geometry<Node<3> >& geom, const array_1d<double,TDim+1>& distances, array_1d<double,TDim+1>& exact_dist ) { array_1d<double,TDim> grad_d; array_1d<double,3> coord_on_0 = ZeroVector(3); array_1d<double,3> temp; //compute the gradient of the distance and normalize it noalias(grad_d) = prod(trans(DN_DX),distances); double norm = norm_2(grad_d); grad_d /= norm; //find one division point on one edge for(unsigned int i = 1; i<TDim+1; i++) { if(distances[0]*distances[i]<=0.0) //if the edge is divided { double delta_d = fabs(distances[i]) + fabs(distances[0]); if(delta_d>1e-20) { double Ni = fabs(distances[0]) / delta_d; double N0 = fabs(distances[i]) / delta_d; noalias(coord_on_0) = N0 * geom[0].Coordinates(); noalias(coord_on_0) += Ni * geom[i].Coordinates(); } else noalias(coord_on_0) = geom[0].Coordinates(); break; } } //now calculate the distance of all the nodes from the elemental free surface for(unsigned int i = 0; i<TDim+1; i++) { noalias(temp) = geom[i].Coordinates(); noalias(temp) -= coord_on_0 ; double real_distance = 0.0; for(unsigned int k=0; k<TDim; k++) real_distance += temp[k]*grad_d[k]; real_distance = fabs(real_distance); exact_dist[i] = real_distance; } } //******************************************************************* void AddDistanceToNodesNew(const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, Geometry<Node<3> >& geom, const BoundedMatrix <double, TDim+1,TDim>& DN_DX, const double& Volume ) { unsigned int unknown_node_index = 0; array_1d<double,TDim> d; double nodal_vol = Volume/static_cast<double>(TDim+1); double avg_dist = 0.0; Matrix coord_a(3,3); int row = 0; int reference_node_index; //compute discriminant and find the index of the unknown node noalias(d) = ZeroVector(TDim); for (unsigned int iii = 0; iii < TDim + 1; iii++) { double node_is_known = geom[iii].GetValue(IS_VISITED); if (node_is_known == 1) //identyfing the known node { reference_node_index = iii; for(int i_coord = 0 ; i_coord < 3 ; i_coord++) coord_a(row,i_coord) = geom[iii].Coordinates()[i_coord]; d[row] = geom[iii].FastGetSolutionStepValue(rDistanceVar); avg_dist += d[row]; row++; } else unknown_node_index = iii; } avg_dist /= static_cast<double>(TDim); Matrix inverse_a(3,3); double det_a; MathUtils<double>::InvertMatrix3(coord_a,inverse_a,det_a); array_1d<double,TDim> x; // normal to the surface noalias(x) = prod(inverse_a,d); double norm_x = norm_2(x); x /= norm_x; array_1d<double,TDim> v = geom[unknown_node_index].Coordinates() - geom[reference_node_index].Coordinates(); double distance = inner_prod(x,v); distance += geom[reference_node_index].FastGetSolutionStepValue(rDistanceVar); //KRATOS_WATCH(coord_a) //KRATOS_WATCH(distance) geom[unknown_node_index].SetLock(); geom[unknown_node_index].FastGetSolutionStepValue(rDistanceVar) += distance*nodal_vol; geom[unknown_node_index].FastGetSolutionStepValue(rAreaVar) += nodal_vol; geom[unknown_node_index].UnSetLock(); //GeometryUtils::CalculateTetrahedraDistances(element_geometry, dist); } //******************************************************************* void AddDistanceToNodes(const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, Geometry<Node<3> >& geom, const BoundedMatrix <double, TDim+1,TDim>& DN_DX, const double& Volume ) { unsigned int unknown_node_index = 0; array_1d<double,TDim> d; double nodal_vol = Volume/static_cast<double>(TDim+1); double avg_dist = 0.0; //compute discriminant and find the index of the unknown node noalias(d) = ZeroVector(TDim); for (unsigned int iii = 0; iii < TDim + 1; iii++) { double node_is_known = geom[iii].GetValue(IS_VISITED); if (node_is_known == 1) //identyfing the unknown node { const double distance = geom[iii].FastGetSolutionStepValue(rDistanceVar); avg_dist += distance; for (unsigned int jjj = 0; jjj < TDim; jjj++) d[jjj] += DN_DX(iii, jjj) * distance; } else unknown_node_index = iii; } avg_dist /= static_cast<double>(TDim); //finalizing computation of discriminant double c = -1.0; double a = 0.0; double b = 0.0; for (unsigned int jjj = 0; jjj < TDim; jjj++) { a += DN_DX(unknown_node_index, jjj) * DN_DX(unknown_node_index, jjj); b += d[jjj] * DN_DX(unknown_node_index, jjj); c += d[jjj] * d[jjj]; } b *= 2.0; //here we require (a*x^2 + b*x + c)^2 to be minimum (x represents the unknown distance) //this implies setting to zero //(a*x^2 + b*x + c)*(2ax+b) = 0 double distance; double discriminant = b * b - 4.0 * a*c; if (discriminant < 0.0) //here we solve (2ax+b) = 0 { // double numerator = 0.0; // double denominator = 0.0; // for(unsigned int i=0; i<TDim+1; i++) // { // for (unsigned int jjj = 0; jjj < TDim; jjj++) // { // if(i != unknown_node_index) // numerator += DN_DX(unknown_node_index, jjj) * DN_DX(i, jjj); // else // denominator += DN_DX(unknown_node_index, jjj)*DN_DX(unknown_node_index, jjj); // } // } // distance = - numerator/denominator; // // KRATOS_WATCH(geom[unknown_node_index].Id()); // KRATOS_WATCH(discriminant); distance = -b / (2.0*a); //avg_dist ; // } else //in this case we solve (a*x^2 + b*x + c)=0 { //(accurate) computation of the distance //requires the solution of a*x^2+b*x+c=0 double q, root1, root2; double sqrt_det = sqrt(discriminant); if (a != 0.0) { if (b > 0) q = -0.5 * (b + sqrt_det); else q = -0.5 * (b - sqrt_det); root1 = q / a; root2 = c / q; if (root1 > root2) distance = root1; else distance = root2; } else //in this case we have a linear equation { distance = -c / b; } } if(distance < 0.0) distance = 1e-15; geom[unknown_node_index].SetLock(); geom[unknown_node_index].FastGetSolutionStepValue(rDistanceVar) += distance*nodal_vol; geom[unknown_node_index].FastGetSolutionStepValue(rAreaVar) += nodal_vol; geom[unknown_node_index].UnSetLock(); } ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ void Check(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar) { KRATOS_TRY bool is_distributed = false; if(rModelPart.GetCommunicator().TotalProcesses() > 1) is_distributed = true; //check that variables needed are in the model part if(!(rModelPart.NodesBegin()->SolutionStepsDataHas(rDistanceVar)) ) KRATOS_THROW_ERROR(std::logic_error,"distance Variable is not in the model part",""); if(!(rModelPart.NodesBegin()->SolutionStepsDataHas(rAreaVar)) ) KRATOS_THROW_ERROR(std::logic_error,"Area Variable is not in the model part",""); if(is_distributed == true) if(!(rModelPart.NodesBegin()->SolutionStepsDataHas(PARTITION_INDEX)) ) KRATOS_THROW_ERROR(std::logic_error,"PARTITION_INDEX Variable is not in the model part","") KRATOS_CATCH("") } void ResetVariables(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const double MaxDistance) { KRATOS_TRY //reset the variables needed const int node_size = rModelPart.Nodes().size(); #pragma omp parallel for for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; //it->FastGetSolutionStepValue(rAreaVar) = 0.0; double& dist = it->FastGetSolutionStepValue(rDistanceVar); it->SetValue(rDistanceVar,dist); //here we copy the distance function to the fixed database if(dist < 0.0) it->SetValue(IS_FLUID,1.0); else it->SetValue(IS_FLUID,0.0); dist = MaxDistance; it->SetValue(IS_VISITED,0); } KRATOS_CATCH("") } void CalculateExactDistancesOnDividedElements(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, const double MaxDistance, Flags Options) { KRATOS_TRY //identify the list of elements divided by the original distance distribution and recompute an "exact" distance //attempting to mantain the original position of the free surface //note that the backup value is used in calculating the position of the free surface and the divided elements array_1d<double,TDim+1> dist, exact_dist; array_1d<double,TDim+1> visited; // double lumping_factor = 1.0/double(TDim+1); int elem_size = rModelPart.Elements().size(); #pragma omp parallel for private(dist,exact_dist) firstprivate(elem_size) for (int i = 0; i < elem_size; i++) { PointerVector< Element>::iterator it = rModelPart.ElementsBegin() + i; Geometry<Node < 3 > >& element_geometry = it->GetGeometry(); for (unsigned int j = 0; j < TDim + 1; j++) dist[j] = element_geometry[j].GetValue(rDistanceVar); bool is_divided = IsDivided(dist); if (is_divided == true) { if (Options.Is(CALCULATE_EXACT_DISTANCES_TO_PLANE)) GeometryUtils::CalculateExactDistancesToPlane(element_geometry, dist); else GeometryUtils::CalculateTetrahedraDistances(element_geometry, dist); // loop over nodes and apply the new distances. for (unsigned int i_node = 0; i_node < element_geometry.size(); i_node++) { double& distance = element_geometry[i_node].GetSolutionStepValue(rDistanceVar); double new_distance = dist[i_node]; element_geometry[i_node].SetLock(); if (fabs(distance) > fabs(new_distance)) distance = new_distance; element_geometry[i_node].GetValue(IS_VISITED) = 1; element_geometry[i_node].UnSetLock(); } } } //mpi sync variables rModelPart.GetCommunicator().AssembleNonHistoricalData(IS_VISITED); rModelPart.GetCommunicator().AssembleCurrentData(rAreaVar); rModelPart.GetCommunicator().SynchronizeCurrentDataToMin(rDistanceVar); const int node_size = rModelPart.Nodes().size(); #pragma omp parallel for for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; double& nodal_dist = it->FastGetSolutionStepValue(rDistanceVar); double& is_visited = it->GetValue(IS_VISITED); if(is_visited == 0.00) { nodal_dist = 0.00; it->GetSolutionStepValue(rAreaVar) = 0.00; } else if(is_visited >= 1.00) // This is due to the fact that I'm using the assemble instead of sync { is_visited = 1.00; it->GetSolutionStepValue(rAreaVar) = 1.00; // This is not correct } } KRATOS_CATCH("") } void AbsDistancesOnDividedElements(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, const double MaxDistance) { KRATOS_TRY //identify the list of elements divided by the original distance distribution and recompute an "exact" distance //attempting to mantain the original position of the free surface //note that the backup value is used in calculating the position of the free surface and the divided elements array_1d<double,TDim+1> dist, exact_dist; array_1d<double,TDim+1> visited; int elem_size = rModelPart.Elements().size(); #pragma omp parallel for private(dist,exact_dist) firstprivate(elem_size) for (int i = 0; i < elem_size; i++) { PointerVector< Element>::iterator it = rModelPart.ElementsBegin() + i; Geometry<Node < 3 > >& element_geometry = it->GetGeometry(); for (unsigned int j = 0; j < TDim + 1; j++) dist[j] = element_geometry[j].GetValue(rDistanceVar); bool is_divided = IsDivided(dist); if (is_divided == true) { // loop over nodes and apply the new distances. for (unsigned int i_node = 0; i_node < element_geometry.size(); i_node++) { double& distance = element_geometry[i_node].GetSolutionStepValue(rDistanceVar); double new_distance = dist[i_node]; element_geometry[i_node].SetLock(); distance = fabs(new_distance); element_geometry[i_node].GetValue(IS_VISITED) = 1; element_geometry[i_node].UnSetLock(); } } } //mpi sync variables rModelPart.GetCommunicator().AssembleNonHistoricalData(IS_VISITED); rModelPart.GetCommunicator().AssembleCurrentData(rAreaVar); rModelPart.GetCommunicator().SynchronizeCurrentDataToMin(rDistanceVar); const int node_size = rModelPart.Nodes().size(); #pragma omp parallel for for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; double& nodal_dist = it->FastGetSolutionStepValue(rDistanceVar); double& is_visited = it->GetValue(IS_VISITED); if(is_visited == 0.00) { nodal_dist = 0.00; it->GetSolutionStepValue(rAreaVar) = 0.00; } else if(is_visited >= 1.00) // This is due to the fact that I'm using the assemble instead of sync { is_visited = 1.00; it->GetSolutionStepValue(rAreaVar) = 1.00; // This is not correct } } KRATOS_CATCH("") } void ExtendDistancesByLayer(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, const unsigned int max_levels, const double MaxDistance) { KRATOS_TRY array_1d<double,TDim+1> visited; array_1d<double,TDim+1> N; BoundedMatrix <double, TDim+1,TDim> DN_DX; const int elem_size = rModelPart.Elements().size(); const int node_size = rModelPart.Nodes().size(); //*****************************************************************+ //*****************************************************************+ //*****************************************************************+ //now extend the distances layer by layer up to a maximum level of layers for(unsigned int level=0; level<max_levels; level++) { //loop on active elements and advance the distance computation #pragma omp parallel for private(DN_DX,visited) for(int i = 0; i<elem_size; i++) { PointerVector< Element>::iterator it=rModelPart.ElementsBegin()+i; Geometry<Node<3> >&geom = it->GetGeometry(); for(unsigned int j=0; j<TDim+1; j++) visited[j] = geom[j].GetValue(IS_VISITED); if(IsActive(visited)) { double Volume; GeometryUtils::CalculateGeometryData(geom,DN_DX,N,Volume); AddDistanceToNodes(rDistanceVar,rAreaVar,geom,DN_DX,Volume); } } bool is_distributed = false; if(rModelPart.GetCommunicator().TotalProcesses() > 1) is_distributed = true; //mpi sync variables if(is_distributed == true) { #pragma omp parallel for private(DN_DX) for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; if(it->GetValue(IS_VISITED) == 1.0) { double& distance = it->FastGetSolutionStepValue(rDistanceVar); it->GetValue(rDistanceVar) = distance; distance = 0.0; } else it->GetValue(rDistanceVar) = 0.0; } rModelPart.GetCommunicator().AssembleCurrentData(rAreaVar); rModelPart.GetCommunicator().AssembleCurrentData(rDistanceVar); #pragma omp parallel for private(DN_DX) for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; it->FastGetSolutionStepValue(rDistanceVar) += it->GetValue(rDistanceVar); } rModelPart.GetCommunicator().Barrier(); } //finalize the computation of the distance #pragma omp parallel for private(DN_DX) for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; double& area = it->FastGetSolutionStepValue(rAreaVar); double& is_visited = it->GetValue(IS_VISITED); if(area > 1e-20 && is_visited != 1.0) //this implies that node was computed at the current level and not before { double& distance = it->FastGetSolutionStepValue(rDistanceVar); distance /= area; is_visited = 1.0; } } } KRATOS_CATCH("") } void AssignDistanceSign(ModelPart& rModelPart, const Variable<double>& rDistanceVar, const Variable<double>& rAreaVar, const double MaxDistance) { KRATOS_TRY //*****************************************************************+ //*****************************************************************+ //*****************************************************************+ //assign the sign to the distance function according to the original distribution. Set to max for nodes that were not calculated const int node_size = rModelPart.Nodes().size(); #pragma omp parallel for for(int i = 0; i<node_size; i++) { ModelPart::NodesContainerType::iterator it=rModelPart.NodesBegin()+i; const double area = it->FastGetSolutionStepValue(rAreaVar); double& dist = it->FastGetSolutionStepValue(rDistanceVar); if(dist < 0.0) KRATOS_THROW_ERROR(std::logic_error,"IMPOSSIBLE negative distance found !!",""); if(dist > MaxDistance || area <1e-20) //if(dist > max_distance) dist = MaxDistance; if(it->GetValue(IS_FLUID) == 1.0) dist = -fabs(dist); else dist = fabs(dist); } KRATOS_CATCH("") } ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. ParallelDistanceCalculator<TDim>& operator=(ParallelDistanceCalculator<TDim> const& rOther) {}; /// Copy constructor. ParallelDistanceCalculator(ParallelDistanceCalculator<TDim> const& rOther) {}; ///@} }; // Class ParallelDistanceCalculator ///@} ///@name Type Definitions ///@{ template< unsigned int TDim> const Kratos::Flags ParallelDistanceCalculator<TDim>::CALCULATE_EXACT_DISTANCES_TO_PLANE(Kratos::Flags::Create(0)); template< unsigned int TDim> const Kratos::Flags ParallelDistanceCalculator<TDim>::NOT_CALCULATE_EXACT_DISTANCES_TO_PLANE(Kratos::Flags::Create(0, false)); ///@} ///@name Input and output ///@{ /// input stream function template<unsigned int TDim> inline std::istream& operator >> (std::istream& rIStream, ParallelDistanceCalculator<TDim>& rThis) { return rIStream; } /// output stream function template<unsigned int TDim> inline std::ostream& operator << (std::ostream& rOStream, const ParallelDistanceCalculator<TDim>& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_PARALLEL_DISTANCE_CALCULATOR_H_INCLUDED defined
problem.c
/****************************************************************************** * * * PROBLEM.C * * * * INITIAL CONDITIONS FOR COMPTONIZATION * * * ******************************************************************************/ #include "decs.h" // Problem-specific variables to set at runtime void set_problem_params() { } // Initialize dynamical variables void init_prob() { double Te0 = 5.e7; // K double ne0 = 2.5e17; // cm^-3 double nr0 = 2.536851e18; // cm^-3 double ur0 = 4.731013e8; // erg cm^-3 double nu0 = ur0/(HPL*nr0); double Nr0 = 30000; double u0 = ne0*KBOL*Te0/(gam-1.); double Tf = (HPL*nr0*nu0 + 2.*ne0*KBOL*Te0/(gam-1.))/(3.*nr0*KBOL + 2.*ne0*KBOL/(gam-1.)); printf("nu0 = %e cm^-3\n", nu0); printf("Tf = %e K\n", Tf); ZLOOP { P[i][j][k][RHO] = 1.e0; P[i][j][k][UU] = 2.*u0/U_unit; P[i][j][k][U1] = 0.; P[i][j][k][U2] = 0.; P[i][j][k][U3] = 0.; P[i][j][k][B1] = 0.; P[i][j][k][B2] = 0.; P[i][j][k][B3] = 0.; } #pragma omp parallel { double X[NDIM], K_tetrad[NDIM]; double Ucon[NDIM], Ucov[NDIM], Bcon[NDIM], Bcov[NDIM]; double Econ[NDIM][NDIM], Ecov[NDIM][NDIM]; struct of_photon *ph = photon_lists[omp_get_thread_num()]; struct of_microphysics micro; ZLOOP { coord(i, j, k, CENT, X); get_fluid_zone(i, j, k, P, extra, &micro, Ucon, Ucov, Bcon, Bcov); make_tetrad(i, j, k, Ucon, Bcon, ggeom[i][j][CENT].gcov, Econ, Ecov); for (int n = 0; n < Nr0/(N1*N2*N3*nthreads); n++) { struct of_photon *phadd = safe_malloc(sizeof(struct of_photon)); phadd->X[2][0] = 0.; for (int mu = 1; mu < NDIM; mu++) { phadd->X[2][mu] = X[mu]; } // Monoenergetic, uniform in solid angle double cth = 2.*get_rand() - 1.; double th = acos(cth); double sth = sin(th); double phi = 2.*M_PI*get_rand(); double cphi = cos(phi); double sphi = sin(phi); double E = HPL*nu0/(ME*CL*CL); K_tetrad[0] = -E; K_tetrad[1] = E*cth; K_tetrad[2] = E*cphi*sth; K_tetrad[3] = E*sphi*sth; tetrad_to_coord(Ecov, K_tetrad, phadd->Kcov[2]); K_tetrad[0] *= -1.; tetrad_to_coord(Econ, K_tetrad, phadd->Kcon[2]); phadd->t0 = 0.; phadd->origin[0] = nstep; phadd->origin[1] = i; phadd->origin[2] = j; phadd->origin[3] = k; phadd->w = nr0*dx[1]*dx[2]*dx[3]*L_unit*L_unit*L_unit/(Nr0/(N1*N2*N3)); phadd->nscatt = 0; phadd->type = 0; phadd->next = ph; ph = phadd; } } photon_lists[omp_get_thread_num()] = ph; } // omp parallel }
GB_binop__ne_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__ne_int64) // A.*B function (eWiseMult): GB (_AemultB_08__ne_int64) // A.*B function (eWiseMult): GB (_AemultB_02__ne_int64) // A.*B function (eWiseMult): GB (_AemultB_04__ne_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ne_int64) // A*D function (colscale): GB (_AxD__ne_int64) // D*A function (rowscale): GB (_DxB__ne_int64) // C+=B function (dense accum): GB (_Cdense_accumB__ne_int64) // C+=b function (dense accum): GB (_Cdense_accumb__ne_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ne_int64) // C=scalar+B GB (_bind1st__ne_int64) // C=scalar+B' GB (_bind1st_tran__ne_int64) // C=A+scalar GB (_bind2nd__ne_int64) // C=A'+scalar GB (_bind2nd_tran__ne_int64) // C type: bool // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_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) \ int64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_NE || GxB_NO_INT64 || GxB_NO_NE_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__ne_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__ne_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ne_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__ne_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__ne_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ne_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__ne_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__ne_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__ne_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__ne_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__ne_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__ne_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; 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 = 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) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__ne_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // 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 = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__ne_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Example_SIMD.7.c
/* * @@name: SIMD.7c * @@type: C * @@compilable: yes * @@linkable: yes * @@expect: success * @@version: omp_4.0 */ #include <stdio.h> #include <stdlib.h> #define N 45 int a[N], b[N], c[N]; #pragma omp declare simd inbranch int fib( int n ) { if (n <= 1) return n; else { return fib(n-1) + fib(n-2); } } int main(void) { int i; #pragma omp simd for (i=0; i < N; i++) b[i] = i; #pragma omp simd for (i=0; i < N; i++) { a[i] = fib(b[i]); } printf("Done a[%d] = %d\n", N-1, a[N-1]); return 0; }
ep.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - EP This benchmark is an OpenMP C version of the NPB EP code. The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Information on OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Author: P. O. Frederickson D. H. Bailey A. C. Woo OpenMP C version: S. Satoh 3.0 structure translation: M. Popov --------------------------------------------------------------------*/ #include "../common/npb-C.h" #include "npbparams.h" /* parameters */ #define MK 16 #define MM (M - MK) #define NN (1 << MM) #define NK (1 << MK) #define NQ 10 #define EPSILON 1.0e-8 #define A 1220703125.0 #define S 271828183.0 #define TIMERS_ENABLED FALSE /* global variables */ /* common /storage/ */ static double x[2*NK]; #pragma omp threadprivate(x) static double q[NQ]; /*-------------------------------------------------------------------- program EMBAR c-------------------------------------------------------------------*/ /* c This is the serial version of the APP Benchmark 1, c the "embarassingly parallel" benchmark. c c M is the Log_2 of the number of complex pairs of uniform (0, 1) random c numbers. MK is the Log_2 of the size of each batch of uniform random c numbers. MK can be set for convenience on a given system, since it does c not affect the results. */ int main(int argc, char **argv) { double Mops, t1, t2, t3, t4, x1, x2, sx, sy, tm, an, tt, gc; double dum[3] = { 1.0, 1.0, 1.0 }; int np, ierr, node, no_nodes, i, ik, kk, l, k, nit, ierrcode, no_large_nodes, np_add, k_offset, j; int nthreads = 1; boolean verified; char size[13+1]; /* character*13 */ /* c Because the size of the problem is too large to store in a 32-bit c integer for some classes, we put it into a string (for printing). c Have to strip off the decimal point put in there by the floating c point print statement (internal file) */ printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - EP Benchmark\n"); sprintf(size, "%12.0f", pow(2.0, M+1)); for (j = 13; j >= 1; j--) { if (size[j] == '.') size[j] = ' '; } printf(" Number of random numbers generated: %13s\n", size); verified = FALSE; /* c Compute the number of "batches" of random number pairs generated c per processor. Adjust if the number of processors does not evenly c divide the total number */ np = NN; /* c Call the random number generator functions and initialize c the x-array to reduce the effects of paging on the timings. c Also, call all mathematical functions that are used. Make c sure these initializations cannot be eliminated as dead code. */ vranlc(0, &(dum[0]), dum[1], &(dum[2])); dum[0] = randlc(&(dum[1]), dum[2]); #pragma omp parallel for default(shared) private(i) for (i = 0; i < 2*NK; i++) x[i] = -1.0e99; Mops = log(sqrt(fabs(max(1.0, 1.0)))); timer_clear(1); timer_clear(2); timer_clear(3); timer_start(1); vranlc(0, &t1, A, x); /* Compute AN = A ^ (2 * NK) (mod 2^46). */ t1 = A; for ( i = 1; i <= MK+1; i++) { t2 = randlc(&t1, t1); } an = t1; tt = S; gc = 0.0; sx = 0.0; sy = 0.0; for ( i = 0; i <= NQ - 1; i++) { q[i] = 0.0; } /* c Each instance of this loop may be performed independently. We compute c the k offsets separately to take into account the fact that some nodes c have more numbers to generate than others */ k_offset = -1; #pragma omp parallel copyin(x) { double t1, t2, t3, t4, x1, x2; int kk, i, ik, l; double qq[NQ]; /* private copy of q[0:NQ-1] */ for (i = 0; i < NQ; i++) qq[i] = 0.0; #pragma omp for reduction(+:sx,sy) schedule(static) for (k = 1; k <= np; k++) { kk = k_offset + k; t1 = S; t2 = an; /* Find starting seed t1 for this kk. */ for (i = 1; i <= 100; i++) { ik = kk / 2; if (2 * ik != kk) t3 = randlc(&t1, t2); if (ik == 0) break; t3 = randlc(&t2, t2); kk = ik; } /* Compute uniform pseudorandom numbers. */ if (TIMERS_ENABLED == TRUE) timer_start(3); vranlc(2*NK, &t1, A, x-1); if (TIMERS_ENABLED == TRUE) timer_stop(3); /* c Compute Gaussian deviates by acceptance-rejection method and c tally counts in concentric square annuli. This loop is not c vectorizable. */ if (TIMERS_ENABLED == TRUE) timer_start(2); for ( i = 0; i < NK; i++) { x1 = 2.0 * x[2*i] - 1.0; x2 = 2.0 * x[2*i+1] - 1.0; t1 = pow2(x1) + pow2(x2); if (t1 <= 1.0) { t2 = sqrt(-2.0 * log(t1) / t1); t3 = (x1 * t2); /* Xi */ t4 = (x2 * t2); /* Yi */ l = max(fabs(t3), fabs(t4)); qq[l] += 1.0; /* counts */ sx = sx + t3; /* sum of Xi */ sy = sy + t4; /* sum of Yi */ } } if (TIMERS_ENABLED == TRUE) timer_stop(2); } #pragma omp critical { for (i = 0; i <= NQ - 1; i++) q[i] += qq[i]; } #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end of parallel region */ for (i = 0; i <= NQ-1; i++) { gc = gc + q[i]; } timer_stop(1); tm = timer_read(1); nit = 0; if (M == 24) { if((fabs((sx- (-3.247834652034740e3))/sx) <= EPSILON) && (fabs((sy- (-6.958407078382297e3))/sy) <= EPSILON)) { verified = TRUE; } } else if (M == 25) { if ((fabs((sx- (-2.863319731645753e3))/sx) <= EPSILON) && (fabs((sy- (-6.320053679109499e3))/sy) <= EPSILON)) { verified = TRUE; } } else if (M == 28) { if ((fabs((sx- (-4.295875165629892e3))/sx) <= EPSILON) && (fabs((sy- (-1.580732573678431e4))/sy) <= EPSILON)) { verified = TRUE; } } else if (M == 30) { if ((fabs((sx- (4.033815542441498e4))/sx) <= EPSILON) && (fabs((sy- (-2.660669192809235e4))/sy) <= EPSILON)) { verified = TRUE; } } else if (M == 32) { if ((fabs((sx- (4.764367927995374e4))/sx) <= EPSILON) && (fabs((sy- (-8.084072988043731e4))/sy) <= EPSILON)) { verified = TRUE; } } Mops = pow(2.0, M+1)/tm/1000000.0; printf("EP Benchmark Results: \n" "CPU Time = %10.4f\n" "N = 2^%5d\n" "No. Gaussian Pairs = %15.0f\n" "Sums = %25.15e %25.15e\n" "Counts:\n", tm, M, gc, sx, sy); for (i = 0; i <= NQ-1; i++) { printf("%3d %15.0f\n", i, q[i]); } c_print_results("EP", CLASS, M+1, 0, 0, nit, nthreads, tm, Mops, "Random numbers generated", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7); if (TIMERS_ENABLED == TRUE) { printf("Total time: %f", timer_read(1)); printf("Gaussian pairs: %f", timer_read(2)); printf("Random numbers: %f", timer_read(3)); } }
GB_binop__pair_uint16.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__pair_uint16) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__pair_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__pair_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_uint16) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint16_t // A type: uint16_t // A pattern? 1 // B type: uint16_t // B pattern? 1 // BinaryOp: cij = 1 #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ ; // true if values of A are not used #define GB_A_IS_PATTERN \ 1 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ ; // true if values of B are not used #define GB_B_IS_PATTERN \ 1 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = 1 ; // 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_PAIR || GxB_NO_UINT16 || GxB_NO_PAIR_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__pair_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__pair_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__pair_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__pair_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint16_t alpha_scalar ; uint16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ; beta_scalar = (*((uint16_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
broadcast_reduce-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015-2017 by Contributors * \file broadcast_reduce-inl.h * \brief CPU-specific Function definition of broadcast and reduce operators */ #ifndef MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_INL_H_ #define MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_INL_H_ #include <mxnet/operator_util.h> #include <algorithm> #include <vector> #include <string> #include <utility> #include "../mshadow_op.h" #include "../operator_common.h" namespace mxnet { namespace op { namespace broadcast { using namespace mshadow; const int MAX_DIM = 5; template<int ndim> MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) { Shape<ndim> stride; index_t cumprod = 1; #pragma unroll for (int i = ndim - 1; i >= 0; --i) { stride[i] = (shape[i] > 1) ? cumprod : 0; cumprod *= shape[i]; } return stride; } template<int ndim> MSHADOW_XINLINE void unravel_dot(const index_t idx, const Shape<ndim>& shape, const Shape<ndim>& stridej, const Shape<ndim>& stridek, index_t* j, index_t* k) { *j = 0; *k = 0; #pragma unroll for (index_t i = ndim-1, idx_t = idx; i >=0; --i) { const auto tmp = idx_t / shape[i]; const auto coord = idx_t - tmp*shape[i]; *j += coord*stridej[i]; *k += coord*stridek[i]; idx_t = tmp; } } template<int ndim> MSHADOW_XINLINE Shape<ndim> unravel(const index_t idx, const Shape<ndim>& shape) { Shape<ndim> ret; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret[i] = j - tmp*shape[i]; j = tmp; } return ret; } template<int ndim> MSHADOW_XINLINE index_t ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) { index_t ret = 0; #pragma unroll for (index_t i = 0; i < ndim; ++i) { ret = ret * shape[i] + (shape[i] > 1) * coord[i]; } return ret; } template<int ndim> MSHADOW_XINLINE int diff(const Shape<ndim>& small, const Shape<ndim>& big, Shape<ndim>* dims, Shape<ndim>* stride) { int mdim = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { mdim += small[i] != big[i]; (*dims)[i] = (*stride)[i] = 1; } index_t s = 1; #pragma unroll for (int i = ndim - 1, j = mdim; i >= 0; --i) { if (small[i] != big[i]) { --j; (*stride)[j] = s; (*dims)[j] = big[i]; } s *= big[i]; } return mdim; } template<int ndim> MSHADOW_XINLINE index_t unravel_dot(const index_t idx, const Shape<ndim>& shape, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret += (j - tmp*shape[i])*stride[i]; j = tmp; } return ret; } template<int ndim> MSHADOW_XINLINE index_t dot(const Shape<ndim>& coord, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) ret += coord[i] * stride[i]; return ret; } template<typename DType> MSHADOW_XINLINE void assign(DType* dst, const bool addto, const DType src) { if (addto) { *dst += src; } else { *dst = src; } } template<int ndim, typename DType, typename OP> MSHADOW_XINLINE void binary_broadcast_assign(const index_t idx, const bool addto, const DType* __restrict lhs, const DType* __restrict rhs, DType* out, const Shape<ndim>& lshape, const Shape<ndim>& rshape, const Shape<ndim>& oshape) { const Shape<ndim> coord = unravel(idx, oshape); const index_t j = ravel(coord, lshape); const index_t k = ravel(coord, rshape); assign(&out[idx], addto, OP::Map(lhs[j], rhs[k])); } template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP> MSHADOW_XINLINE void seq_reduce_assign(const index_t idx, const size_t M, const bool addto, const DType* __restrict big, OType *small, const Shape<ndim>& bshape, const Shape<ndim>& sshape, const Shape<ndim>& rshape, const Shape<ndim>& rstride) { Shape<ndim> coord = unravel(idx, sshape); index_t j = ravel(coord, bshape); AType val, residual; Reducer::SetInitValue(val, residual); for (size_t k = 0; k < M; ++k) { coord = unravel(k, rshape); Reducer::Reduce(val, AType(OP::Map(big[j + dot(coord, rstride)])), residual); } Reducer::Finalize(val, residual); assign(&small[idx], addto, OType(val)); } #ifdef __CUDACC__ #include "broadcast_reduce-inl.cuh" #else template<int ndim, typename DType, typename OP> void binary_broadcast_compute(const size_t N, const bool addto, const DType *lhs, const DType *rhs, DType *out, const Shape<ndim> lshape, const Shape<ndim> rshape, const Shape<ndim> oshape) { for (size_t idx = 0; idx < N; ++idx) { binary_broadcast_assign<ndim, DType, OP>(idx, addto, lhs, rhs, out, lshape, rshape, oshape); } } template<int ndim, typename DType, typename OP> void BinaryBroadcastComputeImpl(Stream<cpu> *s, const OpReqType req, const TBlob& lhs, const TBlob& rhs, const TBlob& out) { if (req == kNullOp) return; size_t N = out.shape_.Size(); binary_broadcast_compute<ndim, DType, OP>(N, req == kAddTo, lhs.dptr<DType>(), rhs.dptr<DType>(), out.dptr<DType>(), lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>(), out.shape_.get<ndim>()); } template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP> void seq_reduce_compute(const size_t N, const size_t M, const bool addto, const DType *big, OType *small, const Shape<ndim> bshape, const Shape<ndim> sshape, const Shape<ndim> rshape, const Shape<ndim> rstride) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) { seq_reduce_assign<Reducer, ndim, AType, DType, OType, OP>(idx, M, addto, big, small, bshape, sshape, rshape, rstride); } } template <typename Reducer, int ndim, typename DType, typename OP> void seq_reduce_compute_extra_mem(const size_t N, const size_t M, const bool addto, const DType* big, DType* small, const Shape<ndim> bshape, const Shape<ndim> sshape, const Shape<ndim> rshape, const Shape<ndim> rstride, const index_t* ws_dptr) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) { Shape<ndim> coord = unravel(idx, sshape); index_t j = ravel(coord, bshape); DType val, residual; Reducer::SetInitValue(val, residual); for (size_t k = 0; k < M; ++k) { Reducer::Reduce(val, OP::Map(big[j + ws_dptr[k]]), residual); } assign(&small[idx], addto, val); } } template <typename Reducer, int ndim, typename DType, typename OP, bool safe_acc = false> void Reduce(Stream<cpu>* s, const TBlob& small, const OpReqType req, const Tensor<cpu, 1, char>& workspace, const TBlob& big) { if (req == kNullOp) return; Shape<ndim> rshape, rstride; diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride); size_t N = small.shape_.Size(), M = rshape.Size(); if (!safe_acc) { seq_reduce_compute<Reducer, ndim, DType, DType, DType, OP>( N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride); } else { MXNET_ACC_TYPE_SWITCH(mshadow::DataType<DType>::kFlag, DataType, AType, { typedef typename std::conditional<safe_acc, AType, DataType>::type AccType; MSHADOW_TYPE_SWITCH_WITH_BOOL(small.type_flag_, OType, { typedef typename std::conditional<safe_acc, OType, DataType>::type OutType; seq_reduce_compute<Reducer, ndim, AccType, DataType, OutType, OP>( N, M, req == kAddTo, big.dptr<DataType>(), small.dptr<OutType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride); }); }); } } template <typename Reducer, int ndim, typename DType, typename OP> void ReduceWithExtraMem(Stream<cpu>* s, const TBlob& small, const OpReqType req, const Tensor<cpu, 1, char>& workspace, const TBlob& big) { using namespace mxnet_op; if (req == kNullOp) return; Shape<ndim> rshape, rstride; diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride); index_t* ws_dptr = reinterpret_cast<index_t*>(workspace.dptr_); size_t N = small.shape_.Size(), M = rshape.Size(); #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t k = 0; k < static_cast<index_t>(M); k++) { Shape<ndim> coord = unravel(k, rshape); ws_dptr[k] = dot(coord, rstride); } seq_reduce_compute_extra_mem<Reducer, ndim, DType, OP>( N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, ws_dptr); } template<int ndim, typename DType> size_t ReduceWorkspaceSize(Stream<cpu> *s, const mxnet::TShape& small, const OpReqType req, const mxnet::TShape& big) { return 0; } template<int ndim, typename DType> size_t ReduceWorkspaceSize(Stream<cpu> *s, const mxnet::TShape& small, const OpReqType req, const mxnet::TShape& big, const mxnet::TShape& lhs, const mxnet::TShape& rhs) { return 0; } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> MSHADOW_XINLINE void seq_reduce_assign(const index_t idx, const size_t M, const bool addto, const DType* __restrict big, const DType* __restrict lhs, const DType* __restrict rhs, DType *small, const Shape<ndim>& big_shape, const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0, const Shape<ndim>& small_shape, const Shape<ndim>& rshape, const Shape<ndim>& lhs_shape, const Shape<ndim>& rhs_shape, const Shape<ndim>& rstride, const Shape<ndim>& lhs_stride, const Shape<ndim>& rhs_stride) { Shape<ndim> coord = unravel(idx, small_shape); const index_t idx_big0 = ravel(coord, big_shape); const index_t idx_lhs0 = ravel(coord, lhs_shape0); const index_t idx_rhs0 = ravel(coord, rhs_shape0); DType val, residual; Reducer::SetInitValue(val, residual); for (size_t k = 0; k < M; ++k) { Shape<ndim> coord_big = unravel(k, rshape); index_t idx_big = idx_big0 + dot(coord_big, rstride); Shape<ndim> coord_lhs = unravel(k, lhs_shape); index_t idx_lhs = idx_lhs0 + dot(coord_lhs, lhs_stride); Shape<ndim> coord_rhs = unravel(k, rhs_shape); index_t idx_rhs = idx_rhs0 + dot(coord_rhs, rhs_stride); Reducer::Reduce(val, OP1::Map(big[idx_big], OP2::Map(lhs[idx_lhs], rhs[idx_rhs])), residual); } Reducer::Finalize(val, residual); assign(&small[idx], addto, val); } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> void seq_reduce_compute(const size_t N, const size_t M, const bool addto, const DType *big, const DType *lhs, const DType *rhs, DType *small, const Shape<ndim> big_shape, const Shape<ndim> small_shape, const Shape<ndim> rshape, const Shape<ndim> rstride, const Shape<ndim> lhs_shape, const Shape<ndim> lhs_stride, const Shape<ndim> rhs_shape, const Shape<ndim> rhs_stride, const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) { seq_reduce_assign<Reducer, ndim, DType, OP1, OP2>(idx, M, addto, big, lhs, rhs, small, big_shape, lhs_shape0, rhs_shape0, small_shape, rshape, lhs_shape, rhs_shape, rstride, lhs_stride, rhs_stride); } } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> void Reduce(Stream<cpu> *s, const TBlob& small, const OpReqType req, const Tensor<cpu, 1, char>& workspace, const TBlob& big, const TBlob& lhs, const TBlob& rhs) { if (req == kNullOp) return; Shape<ndim> rshape, rstride; diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride); size_t N = small.shape_.Size(); size_t M = rshape.Size(); Shape<ndim> lhs_shape, lhs_stride; diff(small.shape_.get<ndim>(), lhs.shape_.get<ndim>(), &lhs_shape, &lhs_stride); Shape<ndim> rhs_shape, rhs_stride; diff(small.shape_.get<ndim>(), rhs.shape_.get<ndim>(), &rhs_shape, &rhs_stride); seq_reduce_compute<Reducer, ndim, DType, OP1, OP2>( N, M, req == kAddTo, big.dptr<DType>(), lhs.dptr<DType>(), rhs.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, lhs_shape, lhs_stride, rhs_shape, rhs_stride, lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>()); } #endif } // namespace broadcast } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_INL_H_
test_example.valid_rose_output.c
#pragma omp greg extern int omp_get_num_threads(); extern int omp_get_thread_num(); extern void genericForHeader(); extern void foo(); extern void bar(); int a; int b; int c; int main(int argc,char **argv) { int d[10]; int e; int f; #pragma omp parallel private(a, d) firstprivate(b, c) default(shared) { foo(); foo(); #pragma omp for ordered for (int iterator = 0; iterator < 10; iterator++) { a = (b = (c = 0)); } } bar(); #pragma omp parallel private ( a, d ) firstprivate ( b, c ) default ( shared ) { { d[0] = (e = (f = 1)); } } #pragma omp critical { foo(); bar(); } #pragma omp for nowait for (int i = 0; i < 1; ++i) { bar(); } if (omp_get_thread_num() == 0) { bar(); } else { omp_get_thread_num(); } #pragma omp critical { foo(); { } } #pragma omp for for (int i = 0; i < 1; ++i) {{ d[0] = (e = (f = 1)); } } if (omp_get_thread_num() == 0) {{ d[0] = (e = (f = 1)); } } else { omp_get_thread_num(); } return 0; }
idasFoodWeb_kry_omp.c
/* * ----------------------------------------------------------------- * Programmer(s): Daniel R. Reynolds and Ting Yan @ SMU * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2021, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example program for IDAS: Food web problem, OpenMP, GMRES, * user-supplied preconditioner * * This example program uses SUNLinSol_SPGMR as the linear * solver, and IDACalcIC for initial condition calculation. * * The mathematical problem solved in this example is a DAE system * that arises from a system of partial differential equations after * spatial discretization. The PDE system is a food web population * model, with predator-prey interaction and diffusion on the unit * square in two dimensions. The dependent variable vector is: * * 1 2 ns * c = (c , c , ..., c ) , ns = 2 * np * * and the PDE's are as follows: * * i i i * dc /dt = d(i)*(c + c ) + R (x,y,c) (i = 1,...,np) * xx yy i * * i i * 0 = d(i)*(c + c ) + R (x,y,c) (i = np+1,...,ns) * xx yy i * * where the reaction terms R are: * * i ns j * R (x,y,c) = c * (b(i) + sum a(i,j)*c ) * i j=1 * * The number of species is ns = 2 * np, with the first np being * prey and the last np being predators. The coefficients a(i,j), * b(i), d(i) are: * * a(i,i) = -AA (all i) * a(i,j) = -GG (i <= np , j > np) * a(i,j) = EE (i > np, j <= np) * all other a(i,j) = 0 * b(i) = BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i <= np) * b(i) =-BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i > np) * d(i) = DPREY (i <= np) * d(i) = DPRED (i > np) * * The various scalar parameters required are set using '#define' * statements or directly in routine InitUserData. In this program, * np = 1, ns = 2. The boundary conditions are homogeneous Neumann: * normal derivative = 0. * * A polynomial in x and y is used to set the initial values of the * first np variables (the prey variables) at each x,y location, * while initial values for the remaining (predator) variables are * set to a flat value, which is corrected by IDACalcIC. * * The PDEs are discretized by central differencing on a MX by MY * mesh. * * The DAE system is solved by IDAS using the SUNLinSol_SPGMR linear solver. * Output is printed at t = 0, .001, .01, .1, .4, .7, 1. * * Optionally, we can set the number of threads from environment * variable or command line. To check the current value for number * of threads from environment: * % echo $OMP_NUM_THREADS * * Execution: * * To use the default value for the number of threads from * the OMP_NUM_THREADS environment value: * % ./idasFoodWeb_kry_omp * To specify the number of threads at the command line, use * % ./idasFoodWeb_kry_omp num_threads * where num_threads is the desired number of threads. * * ----------------------------------------------------------------- * References: * [1] Peter N. Brown and Alan C. Hindmarsh, * Reduced Storage Matrix Methods in Stiff ODE systems, Journal * of Applied Mathematics and Computation, Vol. 31 (May 1989), * pp. 40-91. * * [2] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold, * Using Krylov Methods in the Solution of Large-Scale * Differential-Algebraic Systems, SIAM J. Sci. Comput., 15 * (1994), pp. 1467-1488. * * [3] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold, * Consistent Initial Condition Calculation for Differential- * Algebraic Systems, SIAM J. Sci. Comput., 19 (1998), * pp. 1495-1512. * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <idas/idas.h> #include <sunlinsol/sunlinsol_spgmr.h> #include <nvector/nvector_openmp.h> #include <sundials/sundials_dense.h> #include <sundials/sundials_types.h> #ifdef _OPENMP #include <omp.h> #endif /* helpful macros */ #ifndef MAX #define MAX(A, B) ((A) > (B) ? (A) : (B)) #endif /* Problem Constants. */ #define NPREY 1 /* No. of prey (= no. of predators). */ #define NUM_SPECIES 2*NPREY #define PI RCONST(3.1415926535898) #define FOURPI (RCONST(4.0)*PI) #define MX 20 /* MX = number of x mesh points */ #define MY 20 /* MY = number of y mesh points */ #define NSMX (NUM_SPECIES * MX) #define NEQ (NUM_SPECIES*MX*MY) #define AA RCONST(1.0) /* Coefficient in above eqns. for a */ #define EE RCONST(10000.) /* Coefficient in above eqns. for a */ #define GG RCONST(0.5e-6) /* Coefficient in above eqns. for a */ #define BB RCONST(1.0) /* Coefficient in above eqns. for b */ #define DPREY RCONST(1.0) /* Coefficient in above eqns. for d */ #define DPRED RCONST(0.05) /* Coefficient in above eqns. for d */ #define ALPHA RCONST(50.) /* Coefficient alpha in above eqns. */ #define BETA RCONST(1000.) /* Coefficient beta in above eqns. */ #define AX RCONST(1.0) /* Total range of x variable */ #define AY RCONST(1.0) /* Total range of y variable */ #define RTOL RCONST(1.e-5) /* Relative tolerance */ #define ATOL RCONST(1.e-5) /* Absolute tolerance */ #define NOUT 6 /* Number of output times */ #define TMULT RCONST(10.0) /* Multiplier for tout values */ #define TADD RCONST(0.3) /* Increment for tout values */ #define ZERO RCONST(0.) #define ONE RCONST(1.0) /* * User-defined vector and accessor macro: IJ_Vptr. * IJ_Vptr is defined in order to express the underlying 3-D structure of * the dependent variable vector from its underlying 1-D storage (an N_Vector). * IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to * species index is = 0, x-index ix = i, and y-index jy = j. */ #define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, (i)*NUM_SPECIES + (j)*NSMX)) /* Type: UserData. Contains problem constants, etc. */ typedef struct { sunindextype Neq, ns, np, mx, my; realtype dx, dy, **acoef; realtype cox[NUM_SPECIES], coy[NUM_SPECIES], bcoef[NUM_SPECIES]; realtype **PP[MX][MY]; sunindextype *pivot[MX][MY]; N_Vector rates; N_Vector ewt; void *ida_mem; int nthreads; } *UserData; /* Prototypes for functions called by the IDA Solver. */ static int resweb(realtype time, N_Vector cc, N_Vector cp, N_Vector resval, void *user_data); static int Precond(realtype tt, N_Vector cc, N_Vector cp, N_Vector rr, realtype cj, void *user_data); static int PSolve(realtype tt, N_Vector cc, N_Vector cp, N_Vector rr, N_Vector rvec, N_Vector zvec, realtype cj, realtype delta, void *user_data); /* Prototypes for private Helper Functions. */ static void InitUserData(UserData webdata); static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id, UserData webdata); static void PrintHeader(int maxl, realtype rtol, realtype atol); static void PrintOutput(void *ida_mem, N_Vector c, realtype t); static void PrintFinalStats(void *ida_mem); static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate, UserData webdata); static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, UserData webdata); static realtype dotprod(sunindextype size, realtype *x1, realtype *x2); static int check_retval(void *returnvalue, char *funcname, int opt); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { void *ida_mem; SUNLinearSolver LS; UserData webdata; N_Vector cc, cp, id; int iout, jx, jy, retval; int maxl; realtype rtol, atol, t0, tout, tret; int num_threads; ida_mem = NULL; LS = NULL; webdata = NULL; cc = cp = id = NULL; /* Set the number of threads to use */ num_threads = 1; /* default value */ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* overwrite with OMP_NUM_THREADS */ #endif if (argc > 1) num_threads = (int) strtol(argv[1], NULL, 0); /* Allocate and initialize user data block webdata. */ webdata = (UserData) malloc(sizeof *webdata); webdata->rates = N_VNew_OpenMP(NEQ, num_threads); webdata->acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES); webdata->ewt = N_VNew_OpenMP(NEQ, num_threads); for (jx = 0; jx < MX; jx++) { for (jy = 0; jy < MY; jy++) { (webdata->pivot)[jx][jy] = newIndexArray(NUM_SPECIES); (webdata->PP)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES); } } webdata->nthreads = num_threads; InitUserData(webdata); /* Allocate N-vectors and initialize cc, cp, and id. */ cc = N_VNew_OpenMP(NEQ, num_threads); if(check_retval((void *)cc, "N_VNew_OpenMP", 0)) return(1); cp = N_VNew_OpenMP(NEQ, num_threads); if(check_retval((void *)cp, "N_VNew_OpenMP", 0)) return(1); id = N_VNew_OpenMP(NEQ, num_threads); if(check_retval((void *)id, "N_VNew_OpenMP", 0)) return(1); SetInitialProfiles(cc, cp, id, webdata); /* Set remaining inputs to IDAMalloc. */ t0 = ZERO; rtol = RTOL; atol = ATOL; /* Call IDACreate and IDAMalloc to initialize IDA. */ ida_mem = IDACreate(); if(check_retval((void *)ida_mem, "IDACreate", 0)) return(1); retval = IDASetUserData(ida_mem, webdata); if(check_retval(&retval, "IDASetUserData", 1)) return(1); retval = IDASetId(ida_mem, id); if(check_retval(&retval, "IDASetId", 1)) return(1); retval = IDAInit(ida_mem, resweb, t0, cc, cp); if(check_retval(&retval, "IDAInit", 1)) return(1); retval = IDASStolerances(ida_mem, rtol, atol); if(check_retval(&retval, "IDASStolerances", 1)) return(1); webdata->ida_mem = ida_mem; /* Create SUNLinSol_SPGMR linear solver, attach to IDA, and set preconditioning routines. */ maxl = 16; /* max dimension of the Krylov subspace */ LS = SUNLinSol_SPGMR(cc, PREC_LEFT, maxl); /* IDA only allows left preconditioning */ if(check_retval((void *)LS, "SUNLinSol_SPGMR", 0)) return(1); retval = IDASetLinearSolver(ida_mem, LS, NULL); if(check_retval(&retval, "IDASetLinearSolver", 1)) return(1); retval = IDASetPreconditioner(ida_mem, Precond, PSolve); if(check_retval(&retval, "IDASetPreconditioner", 1)) return(1); /* Call IDACalcIC (with default options) to correct the initial values. */ tout = RCONST(0.001); retval = IDACalcIC(ida_mem, IDA_YA_YDP_INIT, tout); if(check_retval(&retval, "IDACalcIC", 1)) return(1); /* Print heading, basic parameters, and initial values. */ PrintHeader(maxl, rtol, atol); PrintOutput(ida_mem, cc, ZERO); /* Loop over iout, call IDASolve (normal mode), print selected output. */ for (iout = 1; iout <= NOUT; iout++) { retval = IDASolve(ida_mem, tout, &tret, cc, cp, IDA_NORMAL); if(check_retval(&retval, "IDASolve", 1)) return(retval); PrintOutput(ida_mem, cc, tret); if (iout < 3) tout *= TMULT; else tout += TADD; } /* Print final statistics and free memory. */ PrintFinalStats(ida_mem); printf("num_threads = %i\n\n", num_threads); /* Free memory */ IDAFree(&ida_mem); SUNLinSolFree(LS); N_VDestroy(cc); N_VDestroy(cp); N_VDestroy(id); destroyMat(webdata->acoef); N_VDestroy(webdata->rates); N_VDestroy(webdata->ewt); for (jx = 0; jx < MX; jx++) { for (jy = 0; jy < MY; jy ++) { destroyArray((webdata->pivot)[jx][jy]); destroyMat((webdata->PP)[jx][jy]); } } free(webdata); return(0); } /* Define lines for readability in later routines */ #define acoef (webdata->acoef) #define bcoef (webdata->bcoef) #define cox (webdata->cox) #define coy (webdata->coy) /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY IDA *-------------------------------------------------------------------- */ /* * resweb: System residual function for predator-prey system. * This routine calls Fweb to get all the right-hand sides of the * equations, then loads the residual vector accordingly, * using cp in the case of prey species. */ static int resweb(realtype tt, N_Vector cc, N_Vector cp, N_Vector res, void *user_data) { sunindextype jx, jy, is, yloc, loc, np; realtype *resv, *cpv; UserData webdata; jx = jy = is = 0; webdata = (UserData)user_data; cpv = NV_DATA_OMP(cp); resv = NV_DATA_OMP(res); np = webdata->np; /* Call Fweb to set res to vector of right-hand sides. */ Fweb(tt, cc, res, webdata); /* Loop over all grid points, setting residual values appropriately for differential or algebraic components. */ #pragma omp parallel for default(shared) private(jy, jx, is, yloc, loc) schedule(static) num_threads(webdata->nthreads) for (jy = 0; jy < MY; jy++) { yloc = NSMX * jy; for (jx = 0; jx < MX; jx++) { loc = yloc + NUM_SPECIES * jx; for (is = 0; is < NUM_SPECIES; is++) { if (is < np) resv[loc+is] = cpv[loc+is] - resv[loc+is]; else resv[loc+is] = -resv[loc+is]; } } } return(0); } static int Precond(realtype tt, N_Vector cc, N_Vector cp, N_Vector rr, realtype cj, void *user_data) { int retval; sunindextype ret; realtype uround, xx, yy, del_x, del_y; realtype **Pxy, *ratesxy, *Pxycol, *cxy, *cpxy, *ewtxy, cctmp; realtype inc, fac, sqru, perturb_rates[NUM_SPECIES]; int is, js, jx, jy; void *ida_mem; N_Vector ewt; realtype hh; UserData webdata; webdata = (UserData) user_data; del_x = webdata->dx; del_y = webdata->dy; uround = UNIT_ROUNDOFF; sqru = sqrt(uround); ida_mem = webdata->ida_mem; ewt = webdata->ewt; retval = IDAGetErrWeights(ida_mem, ewt); if(check_retval(&retval, "IDAGetErrWeights", 1)) return(1); retval = IDAGetCurrentStep(ida_mem, &hh); if(check_retval(&retval, "IDAGetCurrentStep", 1)) return(1); for (jy = 0; jy < MY; jy++) { yy = jy * del_y; for (jx = 0; jx < MX; jx++) { xx = jx * del_x; Pxy = (webdata->PP)[jx][jy]; cxy = IJ_Vptr(cc, jx, jy); cpxy = IJ_Vptr(cp, jx, jy); ewtxy = IJ_Vptr(ewt, jx, jy); ratesxy = IJ_Vptr((webdata->rates), jx, jy); for (js = 0; js < NUM_SPECIES; js++) { inc = sqru*(MAX(fabs(cxy[js]), MAX(hh*fabs(cpxy[js]), ONE/ewtxy[js]))); cctmp = cxy[js]; cxy[js] += inc; fac = -ONE/inc; WebRates(xx, yy, cxy, perturb_rates, webdata); Pxycol = Pxy[js]; for (is = 0; is < NUM_SPECIES; is++) Pxycol[is] = (perturb_rates[is] - ratesxy[is])*fac; if (js < 1) Pxycol[js] += cj; cxy[js] = cctmp; } ret = denseGETRF(Pxy, NUM_SPECIES, NUM_SPECIES, (webdata->pivot)[jx][jy]); if (ret != 0) return(1); } } return(0); } static int PSolve(realtype tt, N_Vector cc, N_Vector cp, N_Vector rr, N_Vector rvec, N_Vector zvec, realtype cj, realtype dalta, void *user_data) { realtype **Pxy, *zxy; sunindextype *pivot; sunindextype jx, jy; UserData webdata; jx = jy = 0; webdata = (UserData) user_data; N_VScale(ONE, rvec, zvec); #pragma omp parallel for collapse(2) default(shared) private(jx, jy, zxy, Pxy, pivot) schedule(static) num_threads(webdata->nthreads) for (jx = 0; jx < MX; jx++) { for (jy = 0; jy <MY; jy++) { zxy = IJ_Vptr(zvec, jx, jy); Pxy = (webdata->PP)[jx][jy]; pivot = (webdata->pivot)[jx][jy]; denseGETRS(Pxy, NUM_SPECIES, pivot, zxy); } } return(0); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * InitUserData: Load problem constants in webdata (of type UserData). */ static void InitUserData(UserData webdata) { sunindextype i, j, np; realtype *a1,*a2, *a3, *a4, dx2, dy2; webdata->mx = MX; webdata->my = MY; webdata->ns = NUM_SPECIES; webdata->np = NPREY; webdata->dx = AX/(MX-1); webdata->dy = AY/(MY-1); webdata->Neq= NEQ; /* Set up the coefficients a and b, and others found in the equations. */ np = webdata->np; dx2 = (webdata->dx)*(webdata->dx); dy2 = (webdata->dy)*(webdata->dy); for (i = 0; i < np; i++) { a1 = &(acoef[i][np]); a2 = &(acoef[i+np][0]); a3 = &(acoef[i][0]); a4 = &(acoef[i+np][np]); /* Fill in the portion of acoef in the four quadrants, row by row. */ for (j = 0; j < np; j++) { *a1++ = -GG; *a2++ = EE; *a3++ = ZERO; *a4++ = ZERO; } /* Reset the diagonal elements of acoef to -AA. */ acoef[i][i] = -AA; acoef[i+np][i+np] = -AA; /* Set coefficients for b and diffusion terms. */ bcoef[i] = BB; bcoef[i+np] = -BB; cox[i] = DPREY/dx2; cox[i+np] = DPRED/dx2; coy[i] = DPREY/dy2; coy[i+np] = DPRED/dy2; } } /* * SetInitialProfiles: Set initial conditions in cc, cp, and id. * A polynomial profile is used for the prey cc values, and a constant * (1.0e5) is loaded as the initial guess for the predator cc values. * The id values are set to 1 for the prey and 0 for the predators. * The prey cp values are set according to the given system, and * the predator cp values are set to zero. */ static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id, UserData webdata) { sunindextype loc, yloc, is, jx, jy, np; realtype xx, yy, xyfactor; realtype *ccv, *cpv, *idv; ccv = NV_DATA_OMP(cc); cpv = NV_DATA_OMP(cp); idv = NV_DATA_OMP(id); np = webdata->np; /* Loop over grid, load cc values and id values. */ for (jy = 0; jy < MY; jy++) { yy = jy * webdata->dy; yloc = NSMX * jy; for (jx = 0; jx < MX; jx++) { xx = jx * webdata->dx; xyfactor = RCONST(16.0)*xx*(ONE-xx)*yy*(ONE-yy); xyfactor *= xyfactor; loc = yloc + NUM_SPECIES*jx; for (is = 0; is < NUM_SPECIES; is++) { if (is < np) { ccv[loc+is] = RCONST(10.0) + (realtype)(is+1) * xyfactor; idv[loc+is] = ONE; } else { ccv[loc+is] = RCONST(1.0e5); idv[loc+is] = ZERO; } } } } /* Set c' for the prey by calling the function Fweb. */ Fweb(ZERO, cc, cp, webdata); /* Set c' for predators to 0. */ for (jy = 0; jy < MY; jy++) { yloc = NSMX * jy; for (jx = 0; jx < MX; jx++) { loc = yloc + NUM_SPECIES * jx; for (is = np; is < NUM_SPECIES; is++) { cpv[loc+is] = ZERO; } } } } /* * Print first lines of output (problem description) */ static void PrintHeader(int maxl, realtype rtol, realtype atol) { printf("\nidasFoodWeb_kry_omp: Predator-prey DAE OpenMP example problem using Krylov solver for IDAS \n\n"); printf("Number of species ns: %d", NUM_SPECIES); printf(" Mesh dimensions: %d x %d", MX, MY); printf(" System size: %d\n", NEQ); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: rtol = %Lg atol = %Lg\n", rtol, atol); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol); #else printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol); #endif printf("Linear solver: SUNLinSol_SPGMR, maxl = %d\n", maxl); printf("CalcIC called to correct initial predator concentrations.\n\n"); printf("-----------------------------------------------------------\n"); printf(" t bottom-left top-right"); printf(" | nst k h\n"); printf("-----------------------------------------------------------\n\n"); } /* * PrintOutput: Print output values at output time t = tt. * Selected run statistics are printed. Then values of the concentrations * are printed for the bottom left and top right grid points only. */ static void PrintOutput(void *ida_mem, N_Vector c, realtype t) { int i, kused, retval; long int nst; realtype *c_bl, *c_tr, hused; retval = IDAGetLastOrder(ida_mem, &kused); check_retval(&retval, "IDAGetLastOrder", 1); retval = IDAGetNumSteps(ida_mem, &nst); check_retval(&retval, "IDAGetNumSteps", 1); retval = IDAGetLastStep(ida_mem, &hused); check_retval(&retval, "IDAGetLastStep", 1); c_bl = IJ_Vptr(c,0,0); c_tr = IJ_Vptr(c,MX-1,MY-1); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%8.2Le %12.4Le %12.4Le | %3ld %1d %12.4Le\n", t, c_bl[0], c_tr[0], nst, kused, hused); for (i=1;i<NUM_SPECIES;i++) printf(" %12.4Le %12.4Le |\n",c_bl[i],c_tr[i]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n", t, c_bl[0], c_tr[0], nst, kused, hused); for (i=1;i<NUM_SPECIES;i++) printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]); #else printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n", t, c_bl[0], c_tr[0], nst, kused, hused); for (i=1;i<NUM_SPECIES;i++) printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]); #endif printf("\n"); } /* * PrintFinalStats: Print final run data contained in iopt. */ static void PrintFinalStats(void *ida_mem) { long int nst, nre, sli, netf, nps, npevals, nrevalsLS; int retval; retval = IDAGetNumSteps(ida_mem, &nst); check_retval(&retval, "IDAGetNumSteps", 1); retval = IDAGetNumLinIters(ida_mem, &sli); check_retval(&retval, "IDAGetNumLinIters", 1); retval = IDAGetNumResEvals(ida_mem, &nre); check_retval(&retval, "IDAGetNumResEvals", 1); retval = IDAGetNumErrTestFails(ida_mem, &netf); check_retval(&retval, "IDAGetNumErrTestFails", 1); retval = IDAGetNumPrecSolves(ida_mem, &nps); check_retval(&retval, "IDAGetNumPrecSolves", 1); retval = IDAGetNumPrecEvals(ida_mem, &npevals); check_retval(&retval, "IDAGetNumPrecEvals", 1); retval = IDAGetNumLinResEvals(ida_mem, &nrevalsLS); check_retval(&retval, "IDAGetNumLinResEvals", 1); printf("-----------------------------------------------------------\n"); printf("Final run statistics: \n\n"); printf("Number of steps = %ld\n", nst); printf("Number of residual evaluations = %ld\n", nre); printf("Number of Preconditioner evaluations = %ld\n", npevals); printf("Number of linear iterations = %ld\n", sli); printf("Number of error test failures = %ld\n", netf); printf("Number of precond solve fun called = %ld\n", nps); } /* * Fweb: Rate function for the food-web problem. * This routine computes the right-hand sides of the system equations, * consisting of the diffusion term and interaction term. * The interaction term is computed by the function WebRates. */ static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate, UserData webdata) { sunindextype jx, jy, is, idyu, idyl, idxu, idxl; realtype xx, yy, *cxy, *ratesxy, *cratexy, dcyli, dcyui, dcxli, dcxui; /* Loop over grid points, evaluate interaction vector (length ns), form diffusion difference terms, and load crate. */ jx = jy = is = 0; for (jy = 0; jy < MY; jy++) { yy = (webdata->dy) * jy ; idyu = (jy!=MY-1) ? NSMX : -NSMX; idyl = (jy!= 0 ) ? NSMX : -NSMX; for (jx = 0; jx < MX; jx++) { xx = (webdata->dx) * jx; idxu = (jx!= MX-1) ? NUM_SPECIES : -NUM_SPECIES; idxl = (jx!= 0 ) ? NUM_SPECIES : -NUM_SPECIES; cxy = IJ_Vptr(cc,jx,jy); ratesxy = IJ_Vptr(webdata->rates,jx,jy); cratexy = IJ_Vptr(crate,jx,jy); /* Get interaction vector at this grid point. */ WebRates(xx, yy, cxy, ratesxy, webdata); /* Loop over species, do differencing, load crate segment. */ #pragma omp parallel for default(shared) private(is, dcyli, dcyui, dcxli, dcxui) schedule(static) num_threads(webdata->nthreads) for (is = 0; is < NUM_SPECIES; is++) { /* Differencing in y. */ dcyli = *(cxy+is) - *(cxy - idyl + is) ; dcyui = *(cxy + idyu + is) - *(cxy+is); /* Differencing in x. */ dcxli = *(cxy+is) - *(cxy - idxl + is); dcxui = *(cxy + idxu +is) - *(cxy+is); /* Compute the crate values at (xx,yy). */ cratexy[is] = coy[is] * (dcyui - dcyli) + cox[is] * (dcxui - dcxli) + ratesxy[is]; } /* End is loop */ } /* End of jx loop */ } /* End of jy loop */ } /* * WebRates: Evaluate reaction rates at a given spatial point. * At a given (x,y), evaluate the array of ns reaction terms R. */ static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, UserData webdata) { int is; realtype fac; for (is = 0; is < NUM_SPECIES; is++) ratesxy[is] = dotprod(NUM_SPECIES, cxy, acoef[is]); fac = ONE + ALPHA*xx*yy + BETA*sin(FOURPI*xx)*sin(FOURPI*yy); for (is = 0; is < NUM_SPECIES; is++) ratesxy[is] = cxy[is]*( bcoef[is]*fac + ratesxy[is] ); } /* * dotprod: dot product routine for realtype arrays, for use by WebRates. */ static realtype dotprod(sunindextype size, realtype *x1, realtype *x2) { sunindextype i; realtype *xx1, *xx2, temp = ZERO; xx1 = x1; xx2 = x2; for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++); return(temp); } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns an integer value so check if * retval < 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_retval(void *returnvalue, char *funcname, int opt) { int *retval; if (opt == 0 && returnvalue == NULL) { /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } else if (opt == 1) { /* Check if retval < 0 */ retval = (int *) returnvalue; if (*retval < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n", funcname, *retval); return(1); } } else if (opt == 2 && returnvalue == NULL) { /* Check if function returned NULL pointer - no memory allocated */ fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
cgk_embed.h
// // Created by xinyan on 29/12/2019. // #pragma once #include <unordered_set> #include <unordered_map> #include <random> #include <omp.h> #include <boost/progress.hpp> #include "utils.h" using std::string; using std::vector; using std::unordered_set; using std::unordered_map; using IndexType = unordered_map<string, vector<size_type > >; class CGKEmbed { public: CGKEmbed( const size_type cgk_l, const size_type num_dict, const vector<size_type >& signatures) : cgk_l_(cgk_l), signatures_(signatures), cgk_randoms(cgk_l, vector<int >(num_dict, 0)) { for (int i = 0; i < cgk_randoms.size(); ++i) { for (int j = 0; j < num_dict; ++j) { cgk_randoms[i][j] = rand() % 2; // 0 or 1 } } } string embed(const string& x) const { string out(cgk_l_, ' '); int i = 0; int j = 0; while (j < cgk_l_ && i < x.size()) { assert(j < cgk_randoms.size()); assert(signatures_[x[i]] >= 0); assert(signatures_[x[i]] < cgk_randoms[j].size()); out[j] = x[i]; i += cgk_randoms[j][signatures_[x[i]]]; j += 1; } return out; } private: const size_type cgk_l_; vector<vector<int > > cgk_randoms; const vector<size_type >& signatures_; }; class CGKRanker { public: CGKRanker( const size_type num_bits, const size_type num_cgk, const size_type cgk_l, const size_type num_dict, const vector<size_type >& signatures) : num_bits_(num_bits), num_cgk_(num_cgk), cgk_l_(cgk_l), hash_lsh_(num_cgk) { // initialize LSH for (int i = 0; i < num_cgk; ++i) { std::vector<int> indices(cgk_l); std::iota(indices.begin(), indices.end(), 0); std::random_device rd; std::mt19937 eng(rd()); std::shuffle(indices.begin(), indices.end(), eng); hash_lsh_[i] = vector<size_type >(indices.begin(), indices.begin() + num_bits); } // construction cgk_embed_.reserve(num_cgk); for (int i = 0; i < num_cgk; ++i) { cgk_embed_.emplace_back(cgk_l, num_dict, signatures); } } string embed(const string& x) const { string res; res.reserve(num_cgk_ * num_bits_); for (int i = 0; i < num_cgk_; i++) { string cgk_x = cgk_embed_[i].embed(x); for (int j = 0; j < num_bits_; ++j) { res += cgk_x[ hash_lsh_[i][j] ]; } } return res; } void add(const vector<string>& xs) { size_t max_n = xs.size(); assert(embed_string_.empty()); embed_string_ = vector<string >(max_n, ""); boost::progress_display progress_embed(max_n); #pragma omp parallel for for (int i = 0; i < max_n; ++i) { embed_string_[i] = embed(xs[i]); } } vector<int > query(const string& x) const { vector<int > dist(embed_string_.size(), 0); string cgk_x = embed(x); for (int i = 0; i < dist.size(); ++i) { dist[i] = hamming_dist(cgk_x, embed_string_[i]); } return dist; } private: const size_type num_bits_; const size_type num_cgk_; const size_type cgk_l_; vector<string > embed_string_; vector<vector<size_type > > hash_lsh_; vector<CGKEmbed > cgk_embed_; };
gimplify.c
/* Modula-3: modified */ /* Tree lowering pass. This pass converts the GENERIC functions-as-trees tree representation into the GIMPLE form. Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. Major work done by Sebastian Pop <s.pop@laposte.net>, Diego Novillo <dnovillo@redhat.com> and Jason Merrill <jason@redhat.com>. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "rtl.h" #include "varray.h" #include "gimple.h" #include "tree-iterator.h" #include "tree-inline.h" #include "diagnostic.h" #include "langhooks.h" #include "langhooks-def.h" #include "tree-flow.h" #include "cgraph.h" #include "timevar.h" #include "except.h" #include "hashtab.h" #include "flags.h" #include "real.h" #include "function.h" #include "output.h" #include "expr.h" #include "ggc.h" #include "toplev.h" #include "target.h" #include "optabs.h" #include "pointer-set.h" #include "splay-tree.h" #include "vec.h" #include "gimple.h" #include "tree-pass.h" #ifdef __cplusplus extern "C" { #endif enum gimplify_omp_var_data { GOVD_SEEN = 1, GOVD_EXPLICIT = 2, GOVD_SHARED = 4, GOVD_PRIVATE = 8, GOVD_FIRSTPRIVATE = 16, GOVD_LASTPRIVATE = 32, GOVD_REDUCTION = 64, GOVD_LOCAL = 128, GOVD_DEBUG_PRIVATE = 256, GOVD_PRIVATE_OUTER_REF = 512, GOVD_DATA_SHARE_CLASS = (GOVD_SHARED | GOVD_PRIVATE | GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE | GOVD_REDUCTION | GOVD_LOCAL) }; enum omp_region_type { ORT_WORKSHARE = 0, ORT_PARALLEL = 2, ORT_COMBINED_PARALLEL = 3, ORT_TASK = 4, ORT_UNTIED_TASK = 5 }; struct gimplify_omp_ctx { struct gimplify_omp_ctx *outer_context; splay_tree variables; struct pointer_set_t *privatized_types; location_t location; enum omp_clause_default_kind default_kind; enum omp_region_type region_type; }; static struct gimplify_ctx *gimplify_ctxp; static struct gimplify_omp_ctx *gimplify_omp_ctxp; /* Formal (expression) temporary table handling: Multiple occurrences of the same scalar expression are evaluated into the same temporary. */ typedef struct gimple_temp_hash_elt { tree val; /* Key */ tree temp; /* Value */ } elt_t; /* Forward declarations. */ static enum gimplify_status gimplify_compound_expr (tree *, gimple_seq *, bool); /* Mark X addressable. Unlike the langhook we expect X to be in gimple form and we don't do any syntax checking. */ void mark_addressable (tree x) { while (handled_component_p (x)) x = TREE_OPERAND (x, 0); if (TREE_CODE (x) != VAR_DECL && TREE_CODE (x) != PARM_DECL && TREE_CODE (x) != RESULT_DECL) return ; TREE_ADDRESSABLE (x) = 1; } /* Return a hash value for a formal temporary table entry. */ static hashval_t gimple_tree_hash (const void *p) { tree t = ((const elt_t *) p)->val; return iterative_hash_expr (t, 0); } /* Compare two formal temporary table entries. */ static int gimple_tree_eq (const void *p1, const void *p2) { tree t1 = ((const elt_t *) p1)->val; tree t2 = ((const elt_t *) p2)->val; enum tree_code code = TREE_CODE (t1); if (TREE_CODE (t2) != code || TREE_TYPE (t1) != TREE_TYPE (t2)) return 0; if (!operand_equal_p (t1, t2, 0)) return 0; /* Only allow them to compare equal if they also hash equal; otherwise results are nondeterminate, and we fail bootstrap comparison. */ gcc_assert (gimple_tree_hash (p1) == gimple_tree_hash (p2)); return 1; } /* Link gimple statement GS to the end of the sequence *SEQ_P. If *SEQ_P is NULL, a new sequence is allocated. This function is similar to gimple_seq_add_stmt, but does not scan the operands. During gimplification, we need to manipulate statement sequences before the def/use vectors have been constructed. */ void gimplify_seq_add_stmt (gimple_seq *seq_p, gimple gs) { gimple_stmt_iterator si; if (gs == NULL) return; if (*seq_p == NULL) *seq_p = gimple_seq_alloc (); si = gsi_last (*seq_p); gsi_insert_after_without_update (&si, gs, GSI_NEW_STMT); } /* Append sequence SRC to the end of sequence *DST_P. If *DST_P is NULL, a new sequence is allocated. This function is similar to gimple_seq_add_seq, but does not scan the operands. During gimplification, we need to manipulate statement sequences before the def/use vectors have been constructed. */ static void gimplify_seq_add_seq (gimple_seq *dst_p, gimple_seq src) { gimple_stmt_iterator si; if (src == NULL) return; if (*dst_p == NULL) *dst_p = gimple_seq_alloc (); si = gsi_last (*dst_p); gsi_insert_seq_after_without_update (&si, src, GSI_NEW_STMT); } /* Set up a context for the gimplifier. */ void push_gimplify_context (struct gimplify_ctx *c) { memset (c, '\0', sizeof (*c)); c->prev_context = gimplify_ctxp; gimplify_ctxp = c; } /* Tear down a context for the gimplifier. If BODY is non-null, then put the temporaries into the outer BIND_EXPR. Otherwise, put them in the local_decls. BODY is not a sequence, but the first tuple in a sequence. */ void pop_gimplify_context (gimple body) { struct gimplify_ctx *c = gimplify_ctxp; gcc_assert (c && (c->bind_expr_stack == NULL || VEC_empty (gimple, c->bind_expr_stack))); VEC_free (gimple, heap, c->bind_expr_stack); gimplify_ctxp = c->prev_context; if (body) declare_vars (c->temps, body, false); else record_vars (c->temps); if (c->temp_htab) htab_delete (c->temp_htab); } static void gimple_push_bind_expr (gimple gimple_bind) { if (gimplify_ctxp->bind_expr_stack == NULL) gimplify_ctxp->bind_expr_stack = VEC_alloc (gimple, heap, 8); VEC_safe_push (gimple, heap, gimplify_ctxp->bind_expr_stack, gimple_bind); } static void gimple_pop_bind_expr (void) { VEC_pop (gimple, gimplify_ctxp->bind_expr_stack); } gimple gimple_current_bind_expr (void) { return VEC_last (gimple, gimplify_ctxp->bind_expr_stack); } /* Return the stack GIMPLE_BINDs created during gimplification. */ VEC(gimple, heap) * gimple_bind_expr_stack (void) { return gimplify_ctxp->bind_expr_stack; } /* Returns true iff there is a COND_EXPR between us and the innermost CLEANUP_POINT_EXPR. This info is used by gimple_push_cleanup. */ static bool gimple_conditional_context (void) { return gimplify_ctxp->conditions > 0; } /* Note that we've entered a COND_EXPR. */ static void gimple_push_condition (void) { #ifdef ENABLE_GIMPLE_CHECKING if (gimplify_ctxp->conditions == 0) gcc_assert (gimple_seq_empty_p (gimplify_ctxp->conditional_cleanups)); #endif ++(gimplify_ctxp->conditions); } /* Note that we've left a COND_EXPR. If we're back at unconditional scope now, add any conditional cleanups we've seen to the prequeue. */ static void gimple_pop_condition (gimple_seq *pre_p) { int conds = --(gimplify_ctxp->conditions); gcc_assert (conds >= 0); if (conds == 0) { gimplify_seq_add_seq (pre_p, gimplify_ctxp->conditional_cleanups); gimplify_ctxp->conditional_cleanups = NULL; } } /* A stable comparison routine for use with splay trees and DECLs. */ static int splay_tree_compare_decl_uid (splay_tree_key xa, splay_tree_key xb) { tree a = (tree) xa; tree b = (tree) xb; return DECL_UID (a) - DECL_UID (b); } /* Create a new omp construct that deals with variable remapping. */ static struct gimplify_omp_ctx * new_omp_context (enum omp_region_type region_type) { struct gimplify_omp_ctx *c; c = XCNEW (struct gimplify_omp_ctx); c->outer_context = gimplify_omp_ctxp; c->variables = splay_tree_new (splay_tree_compare_decl_uid, 0, 0); c->privatized_types = pointer_set_create (); c->location = input_location; c->region_type = region_type; if ((region_type & ORT_TASK) == 0) c->default_kind = OMP_CLAUSE_DEFAULT_SHARED; else c->default_kind = OMP_CLAUSE_DEFAULT_UNSPECIFIED; return c; } /* Destroy an omp construct that deals with variable remapping. */ static void delete_omp_context (struct gimplify_omp_ctx *c) { splay_tree_delete (c->variables); pointer_set_destroy (c->privatized_types); XDELETE (c); } static void omp_add_variable (struct gimplify_omp_ctx *, tree, unsigned int); static bool omp_notice_variable (struct gimplify_omp_ctx *, tree, bool); /* A subroutine of append_to_statement_list{,_force}. T is not NULL. */ static void append_to_statement_list_1 (tree t, tree *list_p) { tree list = *list_p; tree_stmt_iterator i; if (!list) { if (t && TREE_CODE (t) == STATEMENT_LIST) { *list_p = t; return; } *list_p = list = alloc_stmt_list (); } i = tsi_last (list); tsi_link_after (&i, t, TSI_CONTINUE_LINKING); } /* Add T to the end of the list container pointed to by LIST_P. If T is an expression with no effects, it is ignored. */ void append_to_statement_list (tree t, tree *list_p) { if (t && TREE_SIDE_EFFECTS (t)) append_to_statement_list_1 (t, list_p); } /* Similar, but the statement is always added, regardless of side effects. */ void append_to_statement_list_force (tree t, tree *list_p) { if (t != NULL_TREE) append_to_statement_list_1 (t, list_p); } /* Both gimplify the statement T and append it to *SEQ_P. This function behaves exactly as gimplify_stmt, but you don't have to pass T as a reference. */ void gimplify_and_add (tree t, gimple_seq *seq_p) { gimplify_stmt (&t, seq_p); } /* Gimplify statement T into sequence *SEQ_P, and return the first tuple in the sequence of generated tuples for this statement. Return NULL if gimplifying T produced no tuples. */ static gimple gimplify_and_return_first (tree t, gimple_seq *seq_p) { gimple_stmt_iterator last = gsi_last (*seq_p); gimplify_and_add (t, seq_p); if (!gsi_end_p (last)) { gsi_next (&last); return gsi_stmt (last); } else return gimple_seq_first_stmt (*seq_p); } /* Strip off a legitimate source ending from the input string NAME of length LEN. Rather than having to know the names used by all of our front ends, we strip off an ending of a period followed by up to five characters. (Java uses ".class".) */ static inline void remove_suffix (char *name, int len) { int i; for (i = 2; i < 8 && len > i; i++) { if (name[len - i] == '.') { name[len - i] = '\0'; break; } } } /* Create a new temporary name with PREFIX. Returns an identifier. */ static GTY(()) unsigned int tmp_var_id_num; tree create_tmp_var_name (const char *prefix) { char *tmp_name; if (prefix) { char *preftmp = ASTRDUP (prefix); remove_suffix (preftmp, strlen (preftmp)); prefix = preftmp; } ASM_FORMAT_PRIVATE_NAME (tmp_name, prefix ? prefix : "T", tmp_var_id_num++); return get_identifier (tmp_name); } /* Create a new temporary variable declaration of type TYPE. Does NOT push it into the current binding. */ tree create_tmp_var_raw (tree type, const char *prefix) { tree tmp_var; tree new_type; /* Make the type of the variable writable. */ new_type = build_type_variant (type, 0, 0); TYPE_ATTRIBUTES (new_type) = TYPE_ATTRIBUTES (type); tmp_var = build_decl (input_location, VAR_DECL, prefix ? create_tmp_var_name (prefix) : NULL, type); /* The variable was declared by the compiler. */ DECL_ARTIFICIAL (tmp_var) = 1; /* And we don't want debug info for it. */ DECL_IGNORED_P (tmp_var) = 1; /* Make the variable writable. */ TREE_READONLY (tmp_var) = 0; DECL_EXTERNAL (tmp_var) = 0; TREE_STATIC (tmp_var) = 0; TREE_USED (tmp_var) = 1; return tmp_var; } /* Create a new temporary variable declaration of type TYPE. DOES push the variable into the current binding. Further, assume that this is called only from gimplification or optimization, at which point the creation of certain types are bugs. */ tree create_tmp_var (tree type, const char *prefix) { tree tmp_var; /* We don't allow types that are addressable (meaning we can't make copies), or incomplete. We also used to reject every variable size objects here, but now support those for which a constant upper bound can be obtained. The processing for variable sizes is performed in gimple_add_tmp_var, point at which it really matters and possibly reached via paths not going through this function, e.g. after direct calls to create_tmp_var_raw. */ gcc_assert (!TREE_ADDRESSABLE (type) && COMPLETE_TYPE_P (type)); tmp_var = create_tmp_var_raw (type, prefix); gimple_add_tmp_var (tmp_var); return tmp_var; } /* Create a temporary with a name derived from VAL. Subroutine of lookup_tmp_var; nobody else should call this function. */ static inline tree create_tmp_from_val (tree val) { return create_tmp_var (TREE_TYPE (val), get_name (val)); } /* Create a temporary to hold the value of VAL. If IS_FORMAL, try to reuse an existing expression temporary. */ static tree lookup_tmp_var (tree val, bool is_formal) { tree ret; /* If not optimizing, never really reuse a temporary. local-alloc won't allocate any variable that is used in more than one basic block, which means it will go into memory, causing much extra work in reload and final and poorer code generation, outweighing the extra memory allocation here. */ if (!optimize || !is_formal || TREE_SIDE_EFFECTS (val)) ret = create_tmp_from_val (val); else { elt_t elt, *elt_p; void **slot; elt.val = val; if (gimplify_ctxp->temp_htab == NULL) gimplify_ctxp->temp_htab = htab_create (1000, gimple_tree_hash, gimple_tree_eq, free); slot = htab_find_slot (gimplify_ctxp->temp_htab, (void *)&elt, INSERT); if (*slot == NULL) { elt_p = XNEW (elt_t); elt_p->val = val; elt_p->temp = ret = create_tmp_from_val (val); *slot = (void *) elt_p; } else { elt_p = (elt_t *) *slot; ret = elt_p->temp; } } return ret; } /* Return true if T is a CALL_EXPR or an expression that can be assignmed to a temporary. Note that this predicate should only be used during gimplification. See the rationale for this in gimplify_modify_expr. */ static bool is_gimple_reg_rhs_or_call (tree t) { return (get_gimple_rhs_class (TREE_CODE (t)) != GIMPLE_INVALID_RHS || TREE_CODE (t) == CALL_EXPR); } /* Return true if T is a valid memory RHS or a CALL_EXPR. Note that this predicate should only be used during gimplification. See the rationale for this in gimplify_modify_expr. */ static bool is_gimple_mem_rhs_or_call (tree t) { /* If we're dealing with a renamable type, either source or dest must be a renamed variable. */ if (is_gimple_reg_type (TREE_TYPE (t))) return is_gimple_val (t); else return (is_gimple_val (t) || is_gimple_lvalue (t) || TREE_CODE (t) == CALL_EXPR); } /* Helper for get_formal_tmp_var and get_initialized_tmp_var. */ static tree internal_get_tmp_var (tree val, gimple_seq *pre_p, gimple_seq *post_p, bool is_formal) { tree t, mod; /* Notice that we explicitly allow VAL to be a CALL_EXPR so that we can create an INIT_EXPR and convert it into a GIMPLE_CALL below. */ gimplify_expr (&val, pre_p, post_p, is_gimple_reg_rhs_or_call, fb_rvalue); t = lookup_tmp_var (val, is_formal); if (is_formal && (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)) DECL_GIMPLE_REG_P (t) = 1; mod = build2 (INIT_EXPR, TREE_TYPE (t), t, unshare_expr (val)); if (EXPR_HAS_LOCATION (val)) SET_EXPR_LOCATION (mod, EXPR_LOCATION (val)); else SET_EXPR_LOCATION (mod, input_location); /* gimplify_modify_expr might want to reduce this further. */ gimplify_and_add (mod, pre_p); ggc_free (mod); /* If we're gimplifying into ssa, gimplify_modify_expr will have given our temporary an SSA name. Find and return it. */ if (gimplify_ctxp->into_ssa) { gimple last = gimple_seq_last_stmt (*pre_p); t = gimple_get_lhs (last); } return t; } /* Returns a formal temporary variable initialized with VAL. PRE_P is as in gimplify_expr. Only use this function if: 1) The value of the unfactored expression represented by VAL will not change between the initialization and use of the temporary, and 2) The temporary will not be otherwise modified. For instance, #1 means that this is inappropriate for SAVE_EXPR temps, and #2 means it is inappropriate for && temps. For other cases, use get_initialized_tmp_var instead. */ tree get_formal_tmp_var (tree val, gimple_seq *pre_p) { return internal_get_tmp_var (val, pre_p, NULL, true); } /* Returns a temporary variable initialized with VAL. PRE_P and POST_P are as in gimplify_expr. */ tree get_initialized_tmp_var (tree val, gimple_seq *pre_p, gimple_seq *post_p) { return internal_get_tmp_var (val, pre_p, post_p, false); } /* Declares all the variables in VARS in SCOPE. If DEBUG_INFO is true, generate debug info for them; otherwise don't. */ void declare_vars (tree vars, gimple scope, bool debug_info) { tree last = vars; if (last) { tree temps, block; gcc_assert (gimple_code (scope) == GIMPLE_BIND); temps = nreverse (last); block = gimple_bind_block (scope); gcc_assert (!block || TREE_CODE (block) == BLOCK); if (!block || !debug_info) { TREE_CHAIN (last) = gimple_bind_vars (scope); gimple_bind_set_vars (scope, temps); } else { /* We need to attach the nodes both to the BIND_EXPR and to its associated BLOCK for debugging purposes. The key point here is that the BLOCK_VARS of the BIND_EXPR_BLOCK of a BIND_EXPR is a subchain of the BIND_EXPR_VARS of the BIND_EXPR. */ if (BLOCK_VARS (block)) BLOCK_VARS (block) = chainon (BLOCK_VARS (block), temps); else { gimple_bind_set_vars (scope, chainon (gimple_bind_vars (scope), temps)); BLOCK_VARS (block) = temps; } } } } /* For VAR a VAR_DECL of variable size, try to find a constant upper bound for the size and adjust DECL_SIZE/DECL_SIZE_UNIT accordingly. Abort if no such upper bound can be obtained. */ static void force_constant_size (tree var) { /* The only attempt we make is by querying the maximum size of objects of the variable's type. */ HOST_WIDE_INT max_size; gcc_assert (TREE_CODE (var) == VAR_DECL); max_size = max_int_size_in_bytes (TREE_TYPE (var)); gcc_assert (max_size >= 0); DECL_SIZE_UNIT (var) = build_int_cst (TREE_TYPE (DECL_SIZE_UNIT (var)), max_size); DECL_SIZE (var) = build_int_cst (TREE_TYPE (DECL_SIZE (var)), max_size * BITS_PER_UNIT); } void gimple_add_tmp_var (tree tmp) { gcc_assert (!TREE_CHAIN (tmp) && !DECL_SEEN_IN_BIND_EXPR_P (tmp)); /* Later processing assumes that the object size is constant, which might not be true at this point. Force the use of a constant upper bound in this case. */ if (!host_integerp (DECL_SIZE_UNIT (tmp), 1)) force_constant_size (tmp); DECL_CONTEXT (tmp) = current_function_decl; DECL_SEEN_IN_BIND_EXPR_P (tmp) = 1; if (gimplify_ctxp) { TREE_CHAIN (tmp) = gimplify_ctxp->temps; gimplify_ctxp->temps = tmp; /* Mark temporaries local within the nearest enclosing parallel. */ if (gimplify_omp_ctxp) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; while (ctx && ctx->region_type == ORT_WORKSHARE) ctx = ctx->outer_context; if (ctx) omp_add_variable (ctx, tmp, GOVD_LOCAL | GOVD_SEEN); } } else if (cfun) record_vars (tmp); else { gimple_seq body_seq; /* This case is for nested functions. We need to expose the locals they create. */ body_seq = gimple_body (current_function_decl); declare_vars (tmp, gimple_seq_first_stmt (body_seq), false); } } /* Determines whether to assign a location to the statement GS. */ static bool should_carry_location_p (gimple gs) { /* Don't emit a line note for a label. We particularly don't want to emit one for the break label, since it doesn't actually correspond to the beginning of the loop/switch. */ if (gimple_code (gs) == GIMPLE_LABEL) return false; return true; } /* Return true if a location should not be emitted for this statement by annotate_one_with_location. */ static inline bool gimple_do_not_emit_location_p (gimple g) { return gimple_plf (g, GF_PLF_1); } /* Mark statement G so a location will not be emitted by annotate_one_with_location. */ static inline void gimple_set_do_not_emit_location (gimple g) { /* The PLF flags are initialized to 0 when a new tuple is created, so no need to initialize it anywhere. */ gimple_set_plf (g, GF_PLF_1, true); } /* Set the location for gimple statement GS to LOCATION. */ static void annotate_one_with_location (gimple gs, location_t location) { if (!gimple_has_location (gs) && !gimple_do_not_emit_location_p (gs) && should_carry_location_p (gs)) gimple_set_location (gs, location); } /* Set LOCATION for all the statements after iterator GSI in sequence SEQ. If GSI is pointing to the end of the sequence, start with the first statement in SEQ. */ static void annotate_all_with_location_after (gimple_seq seq, gimple_stmt_iterator gsi, location_t location) { if (gsi_end_p (gsi)) gsi = gsi_start (seq); else gsi_next (&gsi); for (; !gsi_end_p (gsi); gsi_next (&gsi)) annotate_one_with_location (gsi_stmt (gsi), location); } /* Set the location for all the statements in a sequence STMT_P to LOCATION. */ void annotate_all_with_location (gimple_seq stmt_p, location_t location) { gimple_stmt_iterator i; if (gimple_seq_empty_p (stmt_p)) return; for (i = gsi_start (stmt_p); !gsi_end_p (i); gsi_next (&i)) { gimple gs = gsi_stmt (i); annotate_one_with_location (gs, location); } } /* Similar to copy_tree_r() but do not copy SAVE_EXPR or TARGET_EXPR nodes. These nodes model computations that should only be done once. If we were to unshare something like SAVE_EXPR(i++), the gimplification process would create wrong code. */ static tree mostly_copy_tree_r (tree *tp, int *walk_subtrees, void *data) { enum tree_code code = TREE_CODE (*tp); /* Don't unshare types, decls, constants and SAVE_EXPR nodes. */ if (TREE_CODE_CLASS (code) == tcc_type || TREE_CODE_CLASS (code) == tcc_declaration || TREE_CODE_CLASS (code) == tcc_constant || code == SAVE_EXPR || code == TARGET_EXPR /* We can't do anything sensible with a BLOCK used as an expression, but we also can't just die when we see it because of non-expression uses. So just avert our eyes and cross our fingers. Silly Java. */ || code == BLOCK) *walk_subtrees = 0; else { gcc_assert (code != BIND_EXPR); copy_tree_r (tp, walk_subtrees, data); } return NULL_TREE; } /* Callback for walk_tree to unshare most of the shared trees rooted at *TP. If *TP has been visited already (i.e., TREE_VISITED (*TP) == 1), then *TP is deep copied by calling copy_tree_r. This unshares the same trees as copy_tree_r with the exception of SAVE_EXPR nodes. These nodes model computations that should only be done once. If we were to unshare something like SAVE_EXPR(i++), the gimplification process would create wrong code. */ static tree copy_if_shared_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data ATTRIBUTE_UNUSED) { tree t = *tp; enum tree_code code = TREE_CODE (t); /* Skip types, decls, and constants. But we do want to look at their types and the bounds of types. Mark them as visited so we properly unmark their subtrees on the unmark pass. If we've already seen them, don't look down further. */ if (TREE_CODE_CLASS (code) == tcc_type || TREE_CODE_CLASS (code) == tcc_declaration || TREE_CODE_CLASS (code) == tcc_constant) { if (TREE_VISITED (t)) *walk_subtrees = 0; else TREE_VISITED (t) = 1; } /* If this node has been visited already, unshare it and don't look any deeper. */ else if (TREE_VISITED (t)) { walk_tree (tp, mostly_copy_tree_r, NULL, NULL); *walk_subtrees = 0; } /* Otherwise, mark the tree as visited and keep looking. */ else TREE_VISITED (t) = 1; return NULL_TREE; } static tree unmark_visited_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data ATTRIBUTE_UNUSED) { if (TREE_VISITED (*tp)) TREE_VISITED (*tp) = 0; else *walk_subtrees = 0; return NULL_TREE; } /* Unshare all the trees in BODY_P, a pointer into the body of FNDECL, and the bodies of any nested functions if we are unsharing the entire body of FNDECL. */ static void unshare_body (tree *body_p, tree fndecl) { struct cgraph_node *cgn = cgraph_node (fndecl); walk_tree (body_p, copy_if_shared_r, NULL, NULL); if (body_p == &DECL_SAVED_TREE (fndecl)) for (cgn = cgn->nested; cgn; cgn = cgn->next_nested) unshare_body (&DECL_SAVED_TREE (cgn->decl), cgn->decl); } /* Likewise, but mark all trees as not visited. */ static void unvisit_body (tree *body_p, tree fndecl) { struct cgraph_node *cgn = cgraph_node (fndecl); walk_tree (body_p, unmark_visited_r, NULL, NULL); if (body_p == &DECL_SAVED_TREE (fndecl)) for (cgn = cgn->nested; cgn; cgn = cgn->next_nested) unvisit_body (&DECL_SAVED_TREE (cgn->decl), cgn->decl); } /* Unconditionally make an unshared copy of EXPR. This is used when using stored expressions which span multiple functions, such as BINFO_VTABLE, as the normal unsharing process can't tell that they're shared. */ tree unshare_expr (tree expr) { walk_tree (&expr, mostly_copy_tree_r, NULL, NULL); return expr; } /* WRAPPER is a code such as BIND_EXPR or CLEANUP_POINT_EXPR which can both contain statements and have a value. Assign its value to a temporary and give it void_type_node. Returns the temporary, or NULL_TREE if WRAPPER was already void. */ tree voidify_wrapper_expr (tree wrapper, tree temp) { tree type = TREE_TYPE (wrapper); if (type && !VOID_TYPE_P (type)) { tree *p; /* Set p to point to the body of the wrapper. Loop until we find something that isn't a wrapper. */ for (p = &wrapper; p && *p; ) { switch (TREE_CODE (*p)) { case BIND_EXPR: TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; /* For a BIND_EXPR, the body is operand 1. */ p = &BIND_EXPR_BODY (*p); break; case CLEANUP_POINT_EXPR: case TRY_FINALLY_EXPR: case TRY_CATCH_EXPR: TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; p = &TREE_OPERAND (*p, 0); break; case STATEMENT_LIST: { tree_stmt_iterator i = tsi_last (*p); TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; p = tsi_end_p (i) ? NULL : tsi_stmt_ptr (i); } break; case COMPOUND_EXPR: /* Advance to the last statement. Set all container types to void. */ for (; TREE_CODE (*p) == COMPOUND_EXPR; p = &TREE_OPERAND (*p, 1)) { TREE_SIDE_EFFECTS (*p) = 1; TREE_TYPE (*p) = void_type_node; } break; default: goto out; } } out: if (p == NULL || IS_EMPTY_STMT (*p)) temp = NULL_TREE; else if (temp) { /* The wrapper is on the RHS of an assignment that we're pushing down. */ gcc_assert (TREE_CODE (temp) == INIT_EXPR || TREE_CODE (temp) == MODIFY_EXPR); TREE_OPERAND (temp, 1) = *p; *p = temp; } else { temp = create_tmp_var (type, "retval"); *p = build2 (INIT_EXPR, type, temp, *p); } return temp; } return NULL_TREE; } /* Prepare calls to builtins to SAVE and RESTORE the stack as well as a temporary through which they communicate. */ static void build_stack_save_restore (gimple *save, gimple *restore) { tree tmp_var; *save = gimple_build_call (implicit_built_in_decls[BUILT_IN_STACK_SAVE], 0); tmp_var = create_tmp_var (ptr_type_node, "saved_stack"); gimple_call_set_lhs (*save, tmp_var); *restore = gimple_build_call (implicit_built_in_decls[BUILT_IN_STACK_RESTORE], 1, tmp_var); } /* Gimplify a BIND_EXPR. Just voidify and recurse. */ static enum gimplify_status gimplify_bind_expr (tree *expr_p, gimple_seq *pre_p) { tree bind_expr = *expr_p; bool old_save_stack = gimplify_ctxp->save_stack; tree t; gimple gimple_bind; gimple_seq body; tree temp = voidify_wrapper_expr (bind_expr, NULL); /* Mark variables seen in this bind expr. */ for (t = BIND_EXPR_VARS (bind_expr); t ; t = TREE_CHAIN (t)) { if (TREE_CODE (t) == VAR_DECL) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; /* Mark variable as local. */ if (ctx && !is_global_var (t) && (! DECL_SEEN_IN_BIND_EXPR_P (t) || splay_tree_lookup (ctx->variables, (splay_tree_key) t) == NULL)) omp_add_variable (gimplify_omp_ctxp, t, GOVD_LOCAL | GOVD_SEEN); DECL_SEEN_IN_BIND_EXPR_P (t) = 1; if (DECL_HARD_REGISTER (t) && !is_global_var (t) && cfun) cfun->has_local_explicit_reg_vars = true; } /* Preliminarily mark non-addressed complex variables as eligible for promotion to gimple registers. We'll transform their uses as we find them. We exclude complex types if not optimizing because they can be subject to partial stores in GNU C by means of the __real__ and __imag__ operators and we cannot promote them to total stores (see gimplify_modify_expr_complex_part). */ if (optimize && (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE) && !TREE_THIS_VOLATILE (t) && (TREE_CODE (t) == VAR_DECL && !DECL_HARD_REGISTER (t)) && !needs_to_live_in_memory (t)) DECL_GIMPLE_REG_P (t) = 1; } gimple_bind = gimple_build_bind (BIND_EXPR_VARS (bind_expr), NULL, BIND_EXPR_BLOCK (bind_expr)); gimple_push_bind_expr (gimple_bind); gimplify_ctxp->save_stack = false; /* Gimplify the body into the GIMPLE_BIND tuple's body. */ body = NULL; gimplify_stmt (&BIND_EXPR_BODY (bind_expr), &body); gimple_bind_set_body (gimple_bind, body); if (gimplify_ctxp->save_stack) { gimple stack_save, stack_restore, gs; gimple_seq cleanup, new_body; /* Save stack on entry and restore it on exit. Add a try_finally block to achieve this. Note that mudflap depends on the format of the emitted code: see mx_register_decls(). */ build_stack_save_restore (&stack_save, &stack_restore); cleanup = new_body = NULL; gimplify_seq_add_stmt (&cleanup, stack_restore); gs = gimple_build_try (gimple_bind_body (gimple_bind), cleanup, GIMPLE_TRY_FINALLY); gimplify_seq_add_stmt (&new_body, stack_save); gimplify_seq_add_stmt (&new_body, gs); gimple_bind_set_body (gimple_bind, new_body); } gimplify_ctxp->save_stack = old_save_stack; gimple_pop_bind_expr (); gimplify_seq_add_stmt (pre_p, gimple_bind); if (temp) { *expr_p = temp; return GS_OK; } *expr_p = NULL_TREE; return GS_ALL_DONE; } /* Gimplify a RETURN_EXPR. If the expression to be returned is not a GIMPLE value, it is assigned to a new temporary and the statement is re-written to return the temporary. PRE_P points to the sequence where side effects that must happen before STMT should be stored. */ static enum gimplify_status gimplify_return_expr (tree stmt, gimple_seq *pre_p) { gimple ret; tree ret_expr = TREE_OPERAND (stmt, 0); tree result_decl, result; if (ret_expr == error_mark_node) return GS_ERROR; if (!ret_expr || TREE_CODE (ret_expr) == RESULT_DECL || ret_expr == error_mark_node) { gimple ret = gimple_build_return (ret_expr); gimple_set_no_warning (ret, TREE_NO_WARNING (stmt)); gimplify_seq_add_stmt (pre_p, ret); return GS_ALL_DONE; } if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))) result_decl = NULL_TREE; else { result_decl = TREE_OPERAND (ret_expr, 0); /* See through a return by reference. */ if (TREE_CODE (result_decl) == INDIRECT_REF) result_decl = TREE_OPERAND (result_decl, 0); gcc_assert ((TREE_CODE (ret_expr) == MODIFY_EXPR || TREE_CODE (ret_expr) == INIT_EXPR) && TREE_CODE (result_decl) == RESULT_DECL); } /* If aggregate_value_p is true, then we can return the bare RESULT_DECL. Recall that aggregate_value_p is FALSE for any aggregate type that is returned in registers. If we're returning values in registers, then we don't want to extend the lifetime of the RESULT_DECL, particularly across another call. In addition, for those aggregates for which hard_function_value generates a PARALLEL, we'll die during normal expansion of structure assignments; there's special code in expand_return to handle this case that does not exist in expand_expr. */ if (!result_decl || aggregate_value_p (result_decl, TREE_TYPE (current_function_decl))) result = result_decl; else if (gimplify_ctxp->return_temp) result = gimplify_ctxp->return_temp; else { result = create_tmp_var (TREE_TYPE (result_decl), NULL); if (TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (result)) == VECTOR_TYPE) DECL_GIMPLE_REG_P (result) = 1; /* ??? With complex control flow (usually involving abnormal edges), we can wind up warning about an uninitialized value for this. Due to how this variable is constructed and initialized, this is never true. Give up and never warn. */ TREE_NO_WARNING (result) = 1; gimplify_ctxp->return_temp = result; } /* Smash the lhs of the MODIFY_EXPR to the temporary we plan to use. Then gimplify the whole thing. */ if (result != result_decl) TREE_OPERAND (ret_expr, 0) = result; gimplify_and_add (TREE_OPERAND (stmt, 0), pre_p); ret = gimple_build_return (result); gimple_set_no_warning (ret, TREE_NO_WARNING (stmt)); gimplify_seq_add_stmt (pre_p, ret); return GS_ALL_DONE; } static void gimplify_vla_decl (tree decl, gimple_seq *seq_p) { /* This is a variable-sized decl. Simplify its size and mark it for deferred expansion. Note that mudflap depends on the format of the emitted code: see mx_register_decls(). */ tree t, addr, ptr_type; gimplify_one_sizepos (&DECL_SIZE (decl), seq_p); gimplify_one_sizepos (&DECL_SIZE_UNIT (decl), seq_p); /* All occurrences of this decl in final gimplified code will be replaced by indirection. Setting DECL_VALUE_EXPR does two things: First, it lets the rest of the gimplifier know what replacement to use. Second, it lets the debug info know where to find the value. */ ptr_type = build_pointer_type (TREE_TYPE (decl)); addr = create_tmp_var (ptr_type, get_name (decl)); DECL_IGNORED_P (addr) = 0; t = build_fold_indirect_ref (addr); SET_DECL_VALUE_EXPR (decl, t); DECL_HAS_VALUE_EXPR_P (decl) = 1; t = built_in_decls[BUILT_IN_ALLOCA]; t = build_call_expr (t, 1, DECL_SIZE_UNIT (decl)); t = fold_convert (ptr_type, t); t = build2 (MODIFY_EXPR, TREE_TYPE (addr), addr, t); gimplify_and_add (t, seq_p); /* Indicate that we need to restore the stack level when the enclosing BIND_EXPR is exited. */ gimplify_ctxp->save_stack = true; } /* Gimplifies a DECL_EXPR node *STMT_P by making any necessary allocation and initialization explicit. */ static enum gimplify_status gimplify_decl_expr (tree *stmt_p, gimple_seq *seq_p) { tree stmt = *stmt_p; tree decl = DECL_EXPR_DECL (stmt); *stmt_p = NULL_TREE; if (TREE_TYPE (decl) == error_mark_node) return GS_ERROR; if ((TREE_CODE (decl) == TYPE_DECL || TREE_CODE (decl) == VAR_DECL) && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (decl))) gimplify_type_sizes (TREE_TYPE (decl), seq_p); if (TREE_CODE (decl) == VAR_DECL && !DECL_EXTERNAL (decl)) { tree init = DECL_INITIAL (decl); if (TREE_CODE (DECL_SIZE_UNIT (decl)) != INTEGER_CST || (!TREE_STATIC (decl) && flag_stack_check == GENERIC_STACK_CHECK && compare_tree_int (DECL_SIZE_UNIT (decl), STACK_CHECK_MAX_VAR_SIZE) > 0)) gimplify_vla_decl (decl, seq_p); if (init && init != error_mark_node) { if (!TREE_STATIC (decl)) { DECL_INITIAL (decl) = NULL_TREE; init = build2 (INIT_EXPR, void_type_node, decl, init); gimplify_and_add (init, seq_p); ggc_free (init); } else /* We must still examine initializers for static variables as they may contain a label address. */ walk_tree (&init, force_labels_r, NULL, NULL); } /* Some front ends do not explicitly declare all anonymous artificial variables. We compensate here by declaring the variables, though it would be better if the front ends would explicitly declare them. */ if (!DECL_SEEN_IN_BIND_EXPR_P (decl) && DECL_ARTIFICIAL (decl) && DECL_NAME (decl) == NULL_TREE) gimple_add_tmp_var (decl); } return GS_ALL_DONE; } /* Gimplify a LOOP_EXPR. Normally this just involves gimplifying the body and replacing the LOOP_EXPR with goto, but if the loop contains an EXIT_EXPR, we need to append a label for it to jump to. */ static enum gimplify_status gimplify_loop_expr (tree *expr_p, gimple_seq *pre_p) { tree saved_label = gimplify_ctxp->exit_label; tree start_label = create_artificial_label (UNKNOWN_LOCATION); gimplify_seq_add_stmt (pre_p, gimple_build_label (start_label)); gimplify_ctxp->exit_label = NULL_TREE; gimplify_and_add (LOOP_EXPR_BODY (*expr_p), pre_p); gimplify_seq_add_stmt (pre_p, gimple_build_goto (start_label)); if (gimplify_ctxp->exit_label) gimplify_seq_add_stmt (pre_p, gimple_build_label (gimplify_ctxp->exit_label)); gimplify_ctxp->exit_label = saved_label; *expr_p = NULL; return GS_ALL_DONE; } /* Gimplifies a statement list onto a sequence. These may be created either by an enlightened front-end, or by shortcut_cond_expr. */ static enum gimplify_status gimplify_statement_list (tree *expr_p, gimple_seq *pre_p) { tree temp = voidify_wrapper_expr (*expr_p, NULL); tree_stmt_iterator i = tsi_start (*expr_p); while (!tsi_end_p (i)) { gimplify_stmt (tsi_stmt_ptr (i), pre_p); tsi_delink (&i); } if (temp) { *expr_p = temp; return GS_OK; } return GS_ALL_DONE; } /* Compare two case labels. Because the front end should already have made sure that case ranges do not overlap, it is enough to only compare the CASE_LOW values of each case label. */ static int compare_case_labels (const void *p1, const void *p2) { const_tree const case1 = *(const_tree const*)p1; const_tree const case2 = *(const_tree const*)p2; /* The 'default' case label always goes first. */ if (!CASE_LOW (case1)) return -1; else if (!CASE_LOW (case2)) return 1; else return tree_int_cst_compare (CASE_LOW (case1), CASE_LOW (case2)); } /* Sort the case labels in LABEL_VEC in place in ascending order. */ void sort_case_labels (VEC(tree,heap)* label_vec) { size_t len = VEC_length (tree, label_vec); qsort (VEC_address (tree, label_vec), len, sizeof (tree), compare_case_labels); } /* Gimplify a SWITCH_EXPR, and collect a TREE_VEC of the labels it can branch to. */ static enum gimplify_status gimplify_switch_expr (tree *expr_p, gimple_seq *pre_p) { tree switch_expr = *expr_p; gimple_seq switch_body_seq = NULL; enum gimplify_status ret; ret = gimplify_expr (&SWITCH_COND (switch_expr), pre_p, NULL, is_gimple_val, fb_rvalue); if (ret == GS_ERROR || ret == GS_UNHANDLED) return ret; if (SWITCH_BODY (switch_expr)) { VEC (tree,heap) *labels; VEC (tree,heap) *saved_labels; tree default_case = NULL_TREE; size_t i, len; gimple gimple_switch; /* If someone can be bothered to fill in the labels, they can be bothered to null out the body too. */ gcc_assert (!SWITCH_LABELS (switch_expr)); /* save old labels, get new ones from body, then restore the old labels. Save all the things from the switch body to append after. */ saved_labels = gimplify_ctxp->case_labels; gimplify_ctxp->case_labels = VEC_alloc (tree, heap, 8); gimplify_stmt (&SWITCH_BODY (switch_expr), &switch_body_seq); labels = gimplify_ctxp->case_labels; gimplify_ctxp->case_labels = saved_labels; i = 0; while (i < VEC_length (tree, labels)) { tree elt = VEC_index (tree, labels, i); tree low = CASE_LOW (elt); bool remove_element = FALSE; if (low) { /* Discard empty ranges. */ tree high = CASE_HIGH (elt); if (high && tree_int_cst_lt (high, low)) remove_element = TRUE; } else { /* The default case must be the last label in the list. */ gcc_assert (!default_case); default_case = elt; remove_element = TRUE; } if (remove_element) VEC_ordered_remove (tree, labels, i); else i++; } len = i; if (!VEC_empty (tree, labels)) sort_case_labels (labels); if (!default_case) { tree type = TREE_TYPE (switch_expr); /* If the switch has no default label, add one, so that we jump around the switch body. If the labels already cover the whole range of type, add the default label pointing to one of the existing labels. */ if (type == void_type_node) type = TREE_TYPE (SWITCH_COND (switch_expr)); if (len && INTEGRAL_TYPE_P (type) && TYPE_MIN_VALUE (type) && TYPE_MAX_VALUE (type) && tree_int_cst_equal (CASE_LOW (VEC_index (tree, labels, 0)), TYPE_MIN_VALUE (type))) { tree low, high = CASE_HIGH (VEC_index (tree, labels, len - 1)); if (!high) high = CASE_LOW (VEC_index (tree, labels, len - 1)); if (tree_int_cst_equal (high, TYPE_MAX_VALUE (type))) { for (i = 1; i < len; i++) { high = CASE_LOW (VEC_index (tree, labels, i)); low = CASE_HIGH (VEC_index (tree, labels, i - 1)); if (!low) low = CASE_LOW (VEC_index (tree, labels, i - 1)); if ((TREE_INT_CST_LOW (low) + 1 != TREE_INT_CST_LOW (high)) || (TREE_INT_CST_HIGH (low) + (TREE_INT_CST_LOW (high) == 0) != TREE_INT_CST_HIGH (high))) break; } if (i == len) default_case = build3 (CASE_LABEL_EXPR, void_type_node, NULL_TREE, NULL_TREE, CASE_LABEL (VEC_index (tree, labels, 0))); } } if (!default_case) { gimple new_default; default_case = build3 (CASE_LABEL_EXPR, void_type_node, NULL_TREE, NULL_TREE, create_artificial_label (UNKNOWN_LOCATION)); new_default = gimple_build_label (CASE_LABEL (default_case)); gimplify_seq_add_stmt (&switch_body_seq, new_default); } } gimple_switch = gimple_build_switch_vec (SWITCH_COND (switch_expr), default_case, labels); gimplify_seq_add_stmt (pre_p, gimple_switch); gimplify_seq_add_seq (pre_p, switch_body_seq); VEC_free(tree, heap, labels); } else gcc_assert (SWITCH_LABELS (switch_expr)); return GS_ALL_DONE; } static enum gimplify_status gimplify_case_label_expr (tree *expr_p, gimple_seq *pre_p) { struct gimplify_ctx *ctxp; gimple gimple_label; /* Invalid OpenMP programs can play Duff's Device type games with #pragma omp parallel. At least in the C front end, we don't detect such invalid branches until after gimplification. */ for (ctxp = gimplify_ctxp; ; ctxp = ctxp->prev_context) if (ctxp->case_labels) break; gimple_label = gimple_build_label (CASE_LABEL (*expr_p)); VEC_safe_push (tree, heap, ctxp->case_labels, *expr_p); gimplify_seq_add_stmt (pre_p, gimple_label); return GS_ALL_DONE; } /* Build a GOTO to the LABEL_DECL pointed to by LABEL_P, building it first if necessary. */ tree build_and_jump (tree *label_p) { if (label_p == NULL) /* If there's nowhere to jump, just fall through. */ return NULL_TREE; if (*label_p == NULL_TREE) { tree label = create_artificial_label (UNKNOWN_LOCATION); *label_p = label; } return build1 (GOTO_EXPR, void_type_node, *label_p); } /* Gimplify an EXIT_EXPR by converting to a GOTO_EXPR inside a COND_EXPR. This also involves building a label to jump to and communicating it to gimplify_loop_expr through gimplify_ctxp->exit_label. */ static enum gimplify_status gimplify_exit_expr (tree *expr_p) { tree cond = TREE_OPERAND (*expr_p, 0); tree expr; expr = build_and_jump (&gimplify_ctxp->exit_label); expr = build3 (COND_EXPR, void_type_node, cond, expr, NULL_TREE); *expr_p = expr; return GS_OK; } /* A helper function to be called via walk_tree. Mark all labels under *TP as being forced. To be called for DECL_INITIAL of static variables. */ tree force_labels_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED) { if (TYPE_P (*tp)) *walk_subtrees = 0; if (TREE_CODE (*tp) == LABEL_DECL) FORCED_LABEL (*tp) = 1; return NULL_TREE; } /* *EXPR_P is a COMPONENT_REF being used as an rvalue. If its type is different from its canonical type, wrap the whole thing inside a NOP_EXPR and force the type of the COMPONENT_REF to be the canonical type. The canonical type of a COMPONENT_REF is the type of the field being referenced--unless the field is a bit-field which can be read directly in a smaller mode, in which case the canonical type is the sign-appropriate type corresponding to that mode. */ static void canonicalize_component_ref (tree *expr_p) { tree expr = *expr_p; tree type; gcc_assert (TREE_CODE (expr) == COMPONENT_REF); if (INTEGRAL_TYPE_P (TREE_TYPE (expr))) type = TREE_TYPE (get_unwidened (expr, NULL_TREE)); else type = TREE_TYPE (TREE_OPERAND (expr, 1)); /* One could argue that all the stuff below is not necessary for the non-bitfield case and declare it a FE error if type adjustment would be needed. */ if (TREE_TYPE (expr) != type) { #ifdef ENABLE_TYPES_CHECKING tree old_type = TREE_TYPE (expr); #endif int type_quals; /* We need to preserve qualifiers and propagate them from operand 0. */ type_quals = TYPE_QUALS (type) | TYPE_QUALS (TREE_TYPE (TREE_OPERAND (expr, 0))); if (TYPE_QUALS (type) != type_quals) type = build_qualified_type (TYPE_MAIN_VARIANT (type), type_quals); /* Set the type of the COMPONENT_REF to the underlying type. */ TREE_TYPE (expr) = type; #ifdef ENABLE_TYPES_CHECKING /* It is now a FE error, if the conversion from the canonical type to the original expression type is not useless. */ gcc_assert (useless_type_conversion_p (old_type, type)); #endif } } /* If a NOP conversion is changing a pointer to array of foo to a pointer to foo, embed that change in the ADDR_EXPR by converting T array[U]; (T *)&array ==> &array[L] where L is the lower bound. For simplicity, only do this for constant lower bound. The constraint is that the type of &array[L] is trivially convertible to T *. */ static void canonicalize_addr_expr (tree *expr_p) { tree expr = *expr_p; tree addr_expr = TREE_OPERAND (expr, 0); tree datype, ddatype, pddatype; /* We simplify only conversions from an ADDR_EXPR to a pointer type. */ if (!POINTER_TYPE_P (TREE_TYPE (expr)) || TREE_CODE (addr_expr) != ADDR_EXPR) return; /* The addr_expr type should be a pointer to an array. */ datype = TREE_TYPE (TREE_TYPE (addr_expr)); if (TREE_CODE (datype) != ARRAY_TYPE) return; /* The pointer to element type shall be trivially convertible to the expression pointer type. */ ddatype = TREE_TYPE (datype); pddatype = build_pointer_type (ddatype); if (!useless_type_conversion_p (TYPE_MAIN_VARIANT (TREE_TYPE (expr)), pddatype)) return; /* The lower bound and element sizes must be constant. */ if (!TYPE_SIZE_UNIT (ddatype) || TREE_CODE (TYPE_SIZE_UNIT (ddatype)) != INTEGER_CST || !TYPE_DOMAIN (datype) || !TYPE_MIN_VALUE (TYPE_DOMAIN (datype)) || TREE_CODE (TYPE_MIN_VALUE (TYPE_DOMAIN (datype))) != INTEGER_CST) return; /* All checks succeeded. Build a new node to merge the cast. */ *expr_p = build4 (ARRAY_REF, ddatype, TREE_OPERAND (addr_expr, 0), TYPE_MIN_VALUE (TYPE_DOMAIN (datype)), NULL_TREE, NULL_TREE); *expr_p = build1 (ADDR_EXPR, pddatype, *expr_p); /* We can have stripped a required restrict qualifier above. */ if (!useless_type_conversion_p (TREE_TYPE (expr), TREE_TYPE (*expr_p))) *expr_p = fold_convert (TREE_TYPE (expr), *expr_p); } /* *EXPR_P is a NOP_EXPR or CONVERT_EXPR. Remove it and/or other conversions underneath as appropriate. */ static enum gimplify_status gimplify_conversion (tree *expr_p) { tree tem; location_t loc = EXPR_LOCATION (*expr_p); gcc_assert (CONVERT_EXPR_P (*expr_p)); /* Then strip away all but the outermost conversion. */ STRIP_SIGN_NOPS (TREE_OPERAND (*expr_p, 0)); /* And remove the outermost conversion if it's useless. */ if (tree_ssa_useless_type_conversion (*expr_p)) *expr_p = TREE_OPERAND (*expr_p, 0); /* Attempt to avoid NOP_EXPR by producing reference to a subtype. For example this fold (subclass *)&A into &A->subclass avoiding a need for statement. */ if (CONVERT_EXPR_P (*expr_p) && POINTER_TYPE_P (TREE_TYPE (*expr_p)) && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (*expr_p, 0))) && (tem = maybe_fold_offset_to_address (EXPR_LOCATION (*expr_p), TREE_OPERAND (*expr_p, 0), integer_zero_node, TREE_TYPE (*expr_p))) != NULL_TREE) *expr_p = tem; /* If we still have a conversion at the toplevel, then canonicalize some constructs. */ if (CONVERT_EXPR_P (*expr_p)) { tree sub = TREE_OPERAND (*expr_p, 0); /* If a NOP conversion is changing the type of a COMPONENT_REF expression, then canonicalize its type now in order to expose more redundant conversions. */ if (TREE_CODE (sub) == COMPONENT_REF) canonicalize_component_ref (&TREE_OPERAND (*expr_p, 0)); /* If a NOP conversion is changing a pointer to array of foo to a pointer to foo, embed that change in the ADDR_EXPR. */ else if (TREE_CODE (sub) == ADDR_EXPR) canonicalize_addr_expr (expr_p); } /* If we have a conversion to a non-register type force the use of a VIEW_CONVERT_EXPR instead. */ if (CONVERT_EXPR_P (*expr_p) && !is_gimple_reg_type (TREE_TYPE (*expr_p))) *expr_p = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (*expr_p), TREE_OPERAND (*expr_p, 0)); return GS_OK; } /* Nonlocal VLAs seen in the current function. */ static struct pointer_set_t *nonlocal_vlas; /* Gimplify a VAR_DECL or PARM_DECL. Returns GS_OK if we expanded a DECL_VALUE_EXPR, and it's worth re-examining things. */ static enum gimplify_status gimplify_var_or_parm_decl (tree *expr_p) { tree decl = *expr_p; /* ??? If this is a local variable, and it has not been seen in any outer BIND_EXPR, then it's probably the result of a duplicate declaration, for which we've already issued an error. It would be really nice if the front end wouldn't leak these at all. Currently the only known culprit is C++ destructors, as seen in g++.old-deja/g++.jason/binding.C. */ if (TREE_CODE (decl) == VAR_DECL && !DECL_SEEN_IN_BIND_EXPR_P (decl) && !TREE_STATIC (decl) && !DECL_EXTERNAL (decl) && decl_function_context (decl) == current_function_decl) { gcc_assert (errorcount || sorrycount); return GS_ERROR; } /* When within an OpenMP context, notice uses of variables. */ if (gimplify_omp_ctxp && omp_notice_variable (gimplify_omp_ctxp, decl, true)) return GS_ALL_DONE; /* If the decl is an alias for another expression, substitute it now. */ if (DECL_HAS_VALUE_EXPR_P (decl)) { tree value_expr = DECL_VALUE_EXPR (decl); /* For referenced nonlocal VLAs add a decl for debugging purposes to the current function. */ if (TREE_CODE (decl) == VAR_DECL && TREE_CODE (DECL_SIZE_UNIT (decl)) != INTEGER_CST && nonlocal_vlas != NULL && TREE_CODE (value_expr) == INDIRECT_REF && TREE_CODE (TREE_OPERAND (value_expr, 0)) == VAR_DECL && decl_function_context (decl) != current_function_decl) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; while (ctx && ctx->region_type == ORT_WORKSHARE) ctx = ctx->outer_context; if (!ctx && !pointer_set_insert (nonlocal_vlas, decl)) { tree copy = copy_node (decl), block; lang_hooks.dup_lang_specific_decl (copy); SET_DECL_RTL (copy, NULL_RTX); TREE_USED (copy) = 1; block = DECL_INITIAL (current_function_decl); TREE_CHAIN (copy) = BLOCK_VARS (block); BLOCK_VARS (block) = copy; SET_DECL_VALUE_EXPR (copy, unshare_expr (value_expr)); DECL_HAS_VALUE_EXPR_P (copy) = 1; } } *expr_p = unshare_expr (value_expr); return GS_OK; } return GS_ALL_DONE; } /* Gimplify the COMPONENT_REF, ARRAY_REF, REALPART_EXPR or IMAGPART_EXPR node *EXPR_P. compound_lval : min_lval '[' val ']' | min_lval '.' ID | compound_lval '[' val ']' | compound_lval '.' ID This is not part of the original SIMPLE definition, which separates array and member references, but it seems reasonable to handle them together. Also, this way we don't run into problems with union aliasing; gcc requires that for accesses through a union to alias, the union reference must be explicit, which was not always the case when we were splitting up array and member refs. PRE_P points to the sequence where side effects that must happen before *EXPR_P should be stored. POST_P points to the sequence where side effects that must happen after *EXPR_P should be stored. */ static enum gimplify_status gimplify_compound_lval (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, fallback_t fallback) { tree *p; VEC(tree,heap) *stack; enum gimplify_status ret = GS_OK, tret; int i; location_t loc = EXPR_LOCATION (*expr_p); /* Create a stack of the subexpressions so later we can walk them in order from inner to outer. */ stack = VEC_alloc (tree, heap, 10); /* We can handle anything that get_inner_reference can deal with. */ for (p = expr_p; ; p = &TREE_OPERAND (*p, 0)) { restart: /* Fold INDIRECT_REFs now to turn them into ARRAY_REFs. */ if (TREE_CODE (*p) == INDIRECT_REF) *p = fold_indirect_ref_loc (loc, *p); if (handled_component_p (*p)) ; /* Expand DECL_VALUE_EXPR now. In some cases that may expose additional COMPONENT_REFs. */ else if ((TREE_CODE (*p) == VAR_DECL || TREE_CODE (*p) == PARM_DECL) && gimplify_var_or_parm_decl (p) == GS_OK) goto restart; else break; VEC_safe_push (tree, heap, stack, *p); } gcc_assert (VEC_length (tree, stack)); /* Now STACK is a stack of pointers to all the refs we've walked through and P points to the innermost expression. Java requires that we elaborated nodes in source order. That means we must gimplify the inner expression followed by each of the indices, in order. But we can't gimplify the inner expression until we deal with any variable bounds, sizes, or positions in order to deal with PLACEHOLDER_EXPRs. So we do this in three steps. First we deal with the annotations for any variables in the components, then we gimplify the base, then we gimplify any indices, from left to right. */ for (i = VEC_length (tree, stack) - 1; i >= 0; i--) { tree t = VEC_index (tree, stack, i); if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF) { /* Gimplify the low bound and element type size and put them into the ARRAY_REF. If these values are set, they have already been gimplified. */ if (TREE_OPERAND (t, 2) == NULL_TREE) { tree low = unshare_expr (array_ref_low_bound (t)); if (!is_gimple_min_invariant (low)) { TREE_OPERAND (t, 2) = low; tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p, post_p, is_gimple_reg, fb_rvalue); ret = MIN (ret, tret); } } if (!TREE_OPERAND (t, 3)) { tree elmt_type = TREE_TYPE (TREE_TYPE (TREE_OPERAND (t, 0))); tree elmt_size = unshare_expr (array_ref_element_size (t)); tree factor = size_int (TYPE_ALIGN_UNIT (elmt_type)); /* Divide the element size by the alignment of the element type (above). */ elmt_size = size_binop_loc (loc, EXACT_DIV_EXPR, elmt_size, factor); if (!is_gimple_min_invariant (elmt_size)) { TREE_OPERAND (t, 3) = elmt_size; tret = gimplify_expr (&TREE_OPERAND (t, 3), pre_p, post_p, is_gimple_reg, fb_rvalue); ret = MIN (ret, tret); } } } else if (TREE_CODE (t) == COMPONENT_REF) { /* Set the field offset into T and gimplify it. */ if (!TREE_OPERAND (t, 2)) { tree offset = unshare_expr (component_ref_field_offset (t)); tree field = TREE_OPERAND (t, 1); tree factor = size_int (DECL_OFFSET_ALIGN (field) / BITS_PER_UNIT); /* Divide the offset by its alignment. */ offset = size_binop_loc (loc, EXACT_DIV_EXPR, offset, factor); if (!is_gimple_min_invariant (offset)) { TREE_OPERAND (t, 2) = offset; tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p, post_p, is_gimple_reg, fb_rvalue); ret = MIN (ret, tret); } } } } /* Step 2 is to gimplify the base expression. Make sure lvalue is set so as to match the min_lval predicate. Failure to do so may result in the creation of large aggregate temporaries. */ tret = gimplify_expr (p, pre_p, post_p, is_gimple_min_lval, fallback | fb_lvalue); ret = MIN (ret, tret); /* And finally, the indices and operands to BIT_FIELD_REF. During this loop we also remove any useless conversions. */ for (; VEC_length (tree, stack) > 0; ) { tree t = VEC_pop (tree, stack); if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF) { /* Gimplify the dimension. */ if (!is_gimple_min_invariant (TREE_OPERAND (t, 1))) { tret = gimplify_expr (&TREE_OPERAND (t, 1), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); } } else if (TREE_CODE (t) == BIT_FIELD_REF) { tret = gimplify_expr (&TREE_OPERAND (t, 1), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); } STRIP_USELESS_TYPE_CONVERSION (TREE_OPERAND (t, 0)); /* The innermost expression P may have originally had TREE_SIDE_EFFECTS set which would have caused all the outer expressions in *EXPR_P leading to P to also have had TREE_SIDE_EFFECTS set. */ recalculate_side_effects (t); } /* If the outermost expression is a COMPONENT_REF, canonicalize its type. */ if ((fallback & fb_rvalue) && TREE_CODE (*expr_p) == COMPONENT_REF) { canonicalize_component_ref (expr_p); ret = MIN (ret, GS_OK); } VEC_free (tree, heap, stack); return ret; } /* Gimplify the self modifying expression pointed to by EXPR_P (++, --, +=, -=). PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. POST_P points to the list where side effects that must happen after *EXPR_P should be stored. WANT_VALUE is nonzero iff we want to use the value of this expression in another expression. */ static enum gimplify_status gimplify_self_mod_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value) { enum tree_code code; tree lhs, lvalue, rhs, t1; gimple_seq post = NULL, *orig_post_p = post_p; bool postfix; enum tree_code arith_code; enum gimplify_status ret; location_t loc = EXPR_LOCATION (*expr_p); code = TREE_CODE (*expr_p); gcc_assert (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR || code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR); /* Prefix or postfix? */ if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR) /* Faster to treat as prefix if result is not used. */ postfix = want_value; else postfix = false; /* For postfix, make sure the inner expression's post side effects are executed after side effects from this expression. */ if (postfix) post_p = &post; /* Add or subtract? */ if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) arith_code = PLUS_EXPR; else arith_code = MINUS_EXPR; /* Gimplify the LHS into a GIMPLE lvalue. */ lvalue = TREE_OPERAND (*expr_p, 0); ret = gimplify_expr (&lvalue, pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret == GS_ERROR) return ret; /* Extract the operands to the arithmetic operation. */ lhs = lvalue; rhs = TREE_OPERAND (*expr_p, 1); /* For postfix operator, we evaluate the LHS to an rvalue and then use that as the result value and in the postqueue operation. We also make sure to make lvalue a minimal lval, see gcc.c-torture/execute/20040313-1.c for an example where this matters. */ if (postfix) { if (!is_gimple_min_lval (lvalue)) { mark_addressable (lvalue); lvalue = build_fold_addr_expr_loc (input_location, lvalue); gimplify_expr (&lvalue, pre_p, post_p, is_gimple_val, fb_rvalue); lvalue = build_fold_indirect_ref_loc (input_location, lvalue); } ret = gimplify_expr (&lhs, pre_p, post_p, is_gimple_val, fb_rvalue); if (ret == GS_ERROR) return ret; } /* For POINTERs increment, use POINTER_PLUS_EXPR. */ if (POINTER_TYPE_P (TREE_TYPE (lhs))) { rhs = fold_convert_loc (loc, sizetype, rhs); if (arith_code == MINUS_EXPR) rhs = fold_build1_loc (loc, NEGATE_EXPR, TREE_TYPE (rhs), rhs); arith_code = POINTER_PLUS_EXPR; } t1 = build2 (arith_code, TREE_TYPE (*expr_p), lhs, rhs); if (postfix) { gimplify_assign (lvalue, t1, orig_post_p); gimplify_seq_add_seq (orig_post_p, post); *expr_p = lhs; return GS_ALL_DONE; } else { *expr_p = build2 (MODIFY_EXPR, TREE_TYPE (lvalue), lvalue, t1); return GS_OK; } } /* If *EXPR_P has a variable sized type, wrap it in a WITH_SIZE_EXPR. */ static void maybe_with_size_expr (tree *expr_p) { tree expr = *expr_p; tree type = TREE_TYPE (expr); tree size; /* If we've already wrapped this or the type is error_mark_node, we can't do anything. */ if (TREE_CODE (expr) == WITH_SIZE_EXPR || type == error_mark_node) return; /* If the size isn't known or is a constant, we have nothing to do. */ size = TYPE_SIZE_UNIT (type); if (!size || TREE_CODE (size) == INTEGER_CST) return; /* Otherwise, make a WITH_SIZE_EXPR. */ size = unshare_expr (size); size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, expr); *expr_p = build2 (WITH_SIZE_EXPR, type, expr, size); } /* Helper for gimplify_call_expr. Gimplify a single argument *ARG_P Store any side-effects in PRE_P. CALL_LOCATION is the location of the CALL_EXPR. */ static enum gimplify_status gimplify_arg (tree *arg_p, gimple_seq *pre_p, location_t call_location) { bool (*test) (tree); fallback_t fb; /* In general, we allow lvalues for function arguments to avoid extra overhead of copying large aggregates out of even larger aggregates into temporaries only to copy the temporaries to the argument list. Make optimizers happy by pulling out to temporaries those types that fit in registers. */ if (is_gimple_reg_type (TREE_TYPE (*arg_p))) test = is_gimple_val, fb = fb_rvalue; else test = is_gimple_lvalue, fb = fb_either; /* If this is a variable sized type, we must remember the size. */ maybe_with_size_expr (arg_p); /* FIXME diagnostics: This will mess up gcc.dg/Warray-bounds.c. */ /* Make sure arguments have the same location as the function call itself. */ protected_set_expr_location (*arg_p, call_location); /* There is a sequence point before a function call. Side effects in the argument list must occur before the actual call. So, when gimplifying arguments, force gimplify_expr to use an internal post queue which is then appended to the end of PRE_P. */ return gimplify_expr (arg_p, pre_p, NULL, test, fb); } /* Gimplify the CALL_EXPR node *EXPR_P into the GIMPLE sequence PRE_P. WANT_VALUE is true if the result of the call is desired. */ static enum gimplify_status gimplify_call_expr (tree *expr_p, gimple_seq *pre_p, bool want_value) { tree fndecl, parms, p; enum gimplify_status ret; int i, nargs; gimple call; bool builtin_va_start_p = FALSE; location_t loc = EXPR_LOCATION (*expr_p); gcc_assert (TREE_CODE (*expr_p) == CALL_EXPR); /* For reliable diagnostics during inlining, it is necessary that every call_expr be annotated with file and line. */ if (! EXPR_HAS_LOCATION (*expr_p)) SET_EXPR_LOCATION (*expr_p, input_location); /* This may be a call to a builtin function. Builtin function calls may be transformed into different (and more efficient) builtin function calls under certain circumstances. Unfortunately, gimplification can muck things up enough that the builtin expanders are not aware that certain transformations are still valid. So we attempt transformation/gimplification of the call before we gimplify the CALL_EXPR. At this time we do not manage to transform all calls in the same manner as the expanders do, but we do transform most of them. */ fndecl = get_callee_fndecl (*expr_p); if (fndecl && DECL_BUILT_IN (fndecl)) { tree new_tree = fold_call_expr (input_location, *expr_p, !want_value); if (new_tree && new_tree != *expr_p) { /* There was a transformation of this call which computes the same value, but in a more efficient way. Return and try again. */ *expr_p = new_tree; return GS_OK; } if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_VA_START) { builtin_va_start_p = TRUE; if (call_expr_nargs (*expr_p) < 2) { error ("too few arguments to function %<va_start%>"); *expr_p = build_empty_stmt (EXPR_LOCATION (*expr_p)); return GS_OK; } if (fold_builtin_next_arg (*expr_p, true)) { *expr_p = build_empty_stmt (EXPR_LOCATION (*expr_p)); return GS_OK; } } } /* There is a sequence point before the call, so any side effects in the calling expression must occur before the actual call. Force gimplify_expr to use an internal post queue. */ ret = gimplify_expr (&CALL_EXPR_FN (*expr_p), pre_p, NULL, is_gimple_call_addr, fb_rvalue); nargs = call_expr_nargs (*expr_p); /* Get argument types for verification. */ fndecl = get_callee_fndecl (*expr_p); parms = NULL_TREE; if (fndecl) parms = TYPE_ARG_TYPES (TREE_TYPE (fndecl)); else if (POINTER_TYPE_P (TREE_TYPE (CALL_EXPR_FN (*expr_p)))) parms = TYPE_ARG_TYPES (TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (*expr_p)))); if (fndecl && DECL_ARGUMENTS (fndecl)) p = DECL_ARGUMENTS (fndecl); else if (parms) p = parms; else p = NULL_TREE; for (i = 0; i < nargs && p; i++, p = TREE_CHAIN (p)) ; /* If the last argument is __builtin_va_arg_pack () and it is not passed as a named argument, decrease the number of CALL_EXPR arguments and set instead the CALL_EXPR_VA_ARG_PACK flag. */ if (!p && i < nargs && TREE_CODE (CALL_EXPR_ARG (*expr_p, nargs - 1)) == CALL_EXPR) { tree last_arg = CALL_EXPR_ARG (*expr_p, nargs - 1); tree last_arg_fndecl = get_callee_fndecl (last_arg); if (last_arg_fndecl && TREE_CODE (last_arg_fndecl) == FUNCTION_DECL && DECL_BUILT_IN_CLASS (last_arg_fndecl) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (last_arg_fndecl) == BUILT_IN_VA_ARG_PACK) { tree call = *expr_p; --nargs; *expr_p = build_call_array_loc (loc, TREE_TYPE (call), CALL_EXPR_FN (call), nargs, CALL_EXPR_ARGP (call)); /* Copy all CALL_EXPR flags, location and block, except CALL_EXPR_VA_ARG_PACK flag. */ CALL_EXPR_STATIC_CHAIN (*expr_p) = CALL_EXPR_STATIC_CHAIN (call); CALL_EXPR_TAILCALL (*expr_p) = CALL_EXPR_TAILCALL (call); CALL_EXPR_RETURN_SLOT_OPT (*expr_p) = CALL_EXPR_RETURN_SLOT_OPT (call); CALL_FROM_THUNK_P (*expr_p) = CALL_FROM_THUNK_P (call); CALL_CANNOT_INLINE_P (*expr_p) = CALL_CANNOT_INLINE_P (call); SET_EXPR_LOCATION (*expr_p, EXPR_LOCATION (call)); TREE_BLOCK (*expr_p) = TREE_BLOCK (call); /* Set CALL_EXPR_VA_ARG_PACK. */ CALL_EXPR_VA_ARG_PACK (*expr_p) = 1; } } /* Finally, gimplify the function arguments. */ if (nargs > 0) { for (i = (PUSH_ARGS_REVERSED ? nargs - 1 : 0); PUSH_ARGS_REVERSED ? i >= 0 : i < nargs; PUSH_ARGS_REVERSED ? i-- : i++) { enum gimplify_status t; /* Avoid gimplifying the second argument to va_start, which needs to be the plain PARM_DECL. */ if ((i != 1) || !builtin_va_start_p) { t = gimplify_arg (&CALL_EXPR_ARG (*expr_p, i), pre_p, EXPR_LOCATION (*expr_p)); if (t == GS_ERROR) ret = GS_ERROR; } } } /* Verify the function result. */ if (want_value && fndecl && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))) { error_at (loc, "using result of function returning %<void%>"); ret = GS_ERROR; } /* Try this again in case gimplification exposed something. */ if (ret != GS_ERROR) { tree new_tree = fold_call_expr (input_location, *expr_p, !want_value); if (new_tree && new_tree != *expr_p) { /* There was a transformation of this call which computes the same value, but in a more efficient way. Return and try again. */ *expr_p = new_tree; return GS_OK; } } else { *expr_p = error_mark_node; return GS_ERROR; } /* If the function is "const" or "pure", then clear TREE_SIDE_EFFECTS on its decl. This allows us to eliminate redundant or useless calls to "const" functions. */ if (TREE_CODE (*expr_p) == CALL_EXPR) { int flags = call_expr_flags (*expr_p); if (flags & (ECF_CONST | ECF_PURE) /* An infinite loop is considered a side effect. */ && !(flags & (ECF_LOOPING_CONST_OR_PURE))) TREE_SIDE_EFFECTS (*expr_p) = 0; } /* If the value is not needed by the caller, emit a new GIMPLE_CALL and clear *EXPR_P. Otherwise, leave *EXPR_P in its gimplified form and delegate the creation of a GIMPLE_CALL to gimplify_modify_expr. This is always possible because when WANT_VALUE is true, the caller wants the result of this call into a temporary, which means that we will emit an INIT_EXPR in internal_get_tmp_var which will then be handled by gimplify_modify_expr. */ if (!want_value) { /* The CALL_EXPR in *EXPR_P is already in GIMPLE form, so all we have to do is replicate it as a GIMPLE_CALL tuple. */ call = gimple_build_call_from_tree (*expr_p); gimplify_seq_add_stmt (pre_p, call); *expr_p = NULL_TREE; } return ret; } /* Handle shortcut semantics in the predicate operand of a COND_EXPR by rewriting it into multiple COND_EXPRs, and possibly GOTO_EXPRs. TRUE_LABEL_P and FALSE_LABEL_P point to the labels to jump to if the condition is true or false, respectively. If null, we should generate our own to skip over the evaluation of this specific expression. LOCUS is the source location of the COND_EXPR. This function is the tree equivalent of do_jump. shortcut_cond_r should only be called by shortcut_cond_expr. */ static tree shortcut_cond_r (tree pred, tree *true_label_p, tree *false_label_p, location_t locus) { tree local_label = NULL_TREE; tree t, expr = NULL; /* OK, it's not a simple case; we need to pull apart the COND_EXPR to retain the shortcut semantics. Just insert the gotos here; shortcut_cond_expr will append the real blocks later. */ if (TREE_CODE (pred) == TRUTH_ANDIF_EXPR) { location_t new_locus; /* Turn if (a && b) into if (a); else goto no; if (b) goto yes; else goto no; (no:) */ if (false_label_p == NULL) false_label_p = &local_label; /* Keep the original source location on the first 'if'. */ t = shortcut_cond_r (TREE_OPERAND (pred, 0), NULL, false_label_p, locus); append_to_statement_list (t, &expr); /* Set the source location of the && on the second 'if'. */ new_locus = EXPR_HAS_LOCATION (pred) ? EXPR_LOCATION (pred) : locus; t = shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p, false_label_p, new_locus); append_to_statement_list (t, &expr); } else if (TREE_CODE (pred) == TRUTH_ORIF_EXPR) { location_t new_locus; /* Turn if (a || b) into if (a) goto yes; if (b) goto yes; else goto no; (yes:) */ if (true_label_p == NULL) true_label_p = &local_label; /* Keep the original source location on the first 'if'. */ t = shortcut_cond_r (TREE_OPERAND (pred, 0), true_label_p, NULL, locus); append_to_statement_list (t, &expr); /* Set the source location of the || on the second 'if'. */ new_locus = EXPR_HAS_LOCATION (pred) ? EXPR_LOCATION (pred) : locus; t = shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p, false_label_p, new_locus); append_to_statement_list (t, &expr); } else if (TREE_CODE (pred) == COND_EXPR) { location_t new_locus; /* As long as we're messing with gotos, turn if (a ? b : c) into if (a) if (b) goto yes; else goto no; else if (c) goto yes; else goto no; */ /* Keep the original source location on the first 'if'. Set the source location of the ? on the second 'if'. */ new_locus = EXPR_HAS_LOCATION (pred) ? EXPR_LOCATION (pred) : locus; expr = build3 (COND_EXPR, void_type_node, TREE_OPERAND (pred, 0), shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p, false_label_p, locus), shortcut_cond_r (TREE_OPERAND (pred, 2), true_label_p, false_label_p, new_locus)); } else { expr = build3 (COND_EXPR, void_type_node, pred, build_and_jump (true_label_p), build_and_jump (false_label_p)); SET_EXPR_LOCATION (expr, locus); } if (local_label) { t = build1 (LABEL_EXPR, void_type_node, local_label); append_to_statement_list (t, &expr); } return expr; } /* Given a conditional expression EXPR with short-circuit boolean predicates using TRUTH_ANDIF_EXPR or TRUTH_ORIF_EXPR, break the predicate appart into the equivalent sequence of conditionals. */ static tree shortcut_cond_expr (tree expr) { tree pred = TREE_OPERAND (expr, 0); tree then_ = TREE_OPERAND (expr, 1); tree else_ = TREE_OPERAND (expr, 2); tree true_label, false_label, end_label, t; tree *true_label_p; tree *false_label_p; bool emit_end, emit_false, jump_over_else; bool then_se = then_ && TREE_SIDE_EFFECTS (then_); bool else_se = else_ && TREE_SIDE_EFFECTS (else_); /* First do simple transformations. */ if (!else_se) { /* If there is no 'else', turn if (a && b) then c into if (a) if (b) then c. */ while (TREE_CODE (pred) == TRUTH_ANDIF_EXPR) { /* Keep the original source location on the first 'if'. */ location_t locus = EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location; TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1); /* Set the source location of the && on the second 'if'. */ if (EXPR_HAS_LOCATION (pred)) SET_EXPR_LOCATION (expr, EXPR_LOCATION (pred)); then_ = shortcut_cond_expr (expr); then_se = then_ && TREE_SIDE_EFFECTS (then_); pred = TREE_OPERAND (pred, 0); expr = build3 (COND_EXPR, void_type_node, pred, then_, NULL_TREE); SET_EXPR_LOCATION (expr, locus); } } if (!then_se) { /* If there is no 'then', turn if (a || b); else d into if (a); else if (b); else d. */ while (TREE_CODE (pred) == TRUTH_ORIF_EXPR) { /* Keep the original source location on the first 'if'. */ location_t locus = EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location; TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1); /* Set the source location of the || on the second 'if'. */ if (EXPR_HAS_LOCATION (pred)) SET_EXPR_LOCATION (expr, EXPR_LOCATION (pred)); else_ = shortcut_cond_expr (expr); else_se = else_ && TREE_SIDE_EFFECTS (else_); pred = TREE_OPERAND (pred, 0); expr = build3 (COND_EXPR, void_type_node, pred, NULL_TREE, else_); SET_EXPR_LOCATION (expr, locus); } } /* If we're done, great. */ if (TREE_CODE (pred) != TRUTH_ANDIF_EXPR && TREE_CODE (pred) != TRUTH_ORIF_EXPR) return expr; /* Otherwise we need to mess with gotos. Change if (a) c; else d; to if (a); else goto no; c; goto end; no: d; end: and recursively gimplify the condition. */ true_label = false_label = end_label = NULL_TREE; /* If our arms just jump somewhere, hijack those labels so we don't generate jumps to jumps. */ if (then_ && TREE_CODE (then_) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (then_)) == LABEL_DECL) { true_label = GOTO_DESTINATION (then_); then_ = NULL; then_se = false; } if (else_ && TREE_CODE (else_) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (else_)) == LABEL_DECL) { false_label = GOTO_DESTINATION (else_); else_ = NULL; else_se = false; } /* If we aren't hijacking a label for the 'then' branch, it falls through. */ if (true_label) true_label_p = &true_label; else true_label_p = NULL; /* The 'else' branch also needs a label if it contains interesting code. */ if (false_label || else_se) false_label_p = &false_label; else false_label_p = NULL; /* If there was nothing else in our arms, just forward the label(s). */ if (!then_se && !else_se) return shortcut_cond_r (pred, true_label_p, false_label_p, EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location); /* If our last subexpression already has a terminal label, reuse it. */ if (else_se) t = expr_last (else_); else if (then_se) t = expr_last (then_); else t = NULL; if (t && TREE_CODE (t) == LABEL_EXPR) end_label = LABEL_EXPR_LABEL (t); /* If we don't care about jumping to the 'else' branch, jump to the end if the condition is false. */ if (!false_label_p) false_label_p = &end_label; /* We only want to emit these labels if we aren't hijacking them. */ emit_end = (end_label == NULL_TREE); emit_false = (false_label == NULL_TREE); /* We only emit the jump over the else clause if we have to--if the then clause may fall through. Otherwise we can wind up with a useless jump and a useless label at the end of gimplified code, which will cause us to think that this conditional as a whole falls through even if it doesn't. If we then inline a function which ends with such a condition, that can cause us to issue an inappropriate warning about control reaching the end of a non-void function. */ jump_over_else = block_may_fallthru (then_); pred = shortcut_cond_r (pred, true_label_p, false_label_p, EXPR_HAS_LOCATION (expr) ? EXPR_LOCATION (expr) : input_location); expr = NULL; append_to_statement_list (pred, &expr); append_to_statement_list (then_, &expr); if (else_se) { if (jump_over_else) { tree last = expr_last (expr); t = build_and_jump (&end_label); if (EXPR_HAS_LOCATION (last)) SET_EXPR_LOCATION (t, EXPR_LOCATION (last)); append_to_statement_list (t, &expr); } if (emit_false) { t = build1 (LABEL_EXPR, void_type_node, false_label); append_to_statement_list (t, &expr); } append_to_statement_list (else_, &expr); } if (emit_end && end_label) { t = build1 (LABEL_EXPR, void_type_node, end_label); append_to_statement_list (t, &expr); } return expr; } /* EXPR is used in a boolean context; make sure it has BOOLEAN_TYPE. */ tree gimple_boolify (tree expr) { tree type = TREE_TYPE (expr); location_t loc = EXPR_LOCATION (expr); if (TREE_CODE (expr) == NE_EXPR && TREE_CODE (TREE_OPERAND (expr, 0)) == CALL_EXPR && integer_zerop (TREE_OPERAND (expr, 1))) { tree call = TREE_OPERAND (expr, 0); tree fn = get_callee_fndecl (call); /* For __builtin_expect ((long) (x), y) recurse into x as well if x is truth_value_p. */ if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (fn) == BUILT_IN_EXPECT && call_expr_nargs (call) == 2) { tree arg = CALL_EXPR_ARG (call, 0); if (arg) { if (TREE_CODE (arg) == NOP_EXPR && TREE_TYPE (arg) == TREE_TYPE (call)) arg = TREE_OPERAND (arg, 0); if (truth_value_p (TREE_CODE (arg))) { arg = gimple_boolify (arg); CALL_EXPR_ARG (call, 0) = fold_convert_loc (loc, TREE_TYPE (call), arg); } } } } if (TREE_CODE (type) == BOOLEAN_TYPE) return expr; switch (TREE_CODE (expr)) { case TRUTH_AND_EXPR: case TRUTH_OR_EXPR: case TRUTH_XOR_EXPR: case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: /* Also boolify the arguments of truth exprs. */ TREE_OPERAND (expr, 1) = gimple_boolify (TREE_OPERAND (expr, 1)); /* FALLTHRU */ case TRUTH_NOT_EXPR: TREE_OPERAND (expr, 0) = gimple_boolify (TREE_OPERAND (expr, 0)); /* FALLTHRU */ case EQ_EXPR: case NE_EXPR: case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR: /* These expressions always produce boolean results. */ TREE_TYPE (expr) = boolean_type_node; return expr; default: /* Other expressions that get here must have boolean values, but might need to be converted to the appropriate mode. */ return fold_convert_loc (loc, boolean_type_node, expr); } } /* Given a conditional expression *EXPR_P without side effects, gimplify its operands. New statements are inserted to PRE_P. */ static enum gimplify_status gimplify_pure_cond_expr (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p, cond; enum gimplify_status ret, tret; enum tree_code code; cond = gimple_boolify (COND_EXPR_COND (expr)); /* We need to handle && and || specially, as their gimplification creates pure cond_expr, thus leading to an infinite cycle otherwise. */ code = TREE_CODE (cond); if (code == TRUTH_ANDIF_EXPR) TREE_SET_CODE (cond, TRUTH_AND_EXPR); else if (code == TRUTH_ORIF_EXPR) TREE_SET_CODE (cond, TRUTH_OR_EXPR); ret = gimplify_expr (&cond, pre_p, NULL, is_gimple_condexpr, fb_rvalue); COND_EXPR_COND (*expr_p) = cond; tret = gimplify_expr (&COND_EXPR_THEN (expr), pre_p, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); tret = gimplify_expr (&COND_EXPR_ELSE (expr), pre_p, NULL, is_gimple_val, fb_rvalue); return MIN (ret, tret); } /* Returns true if evaluating EXPR could trap. EXPR is GENERIC, while tree_could_trap_p can be called only on GIMPLE. */ static bool generic_expr_could_trap_p (tree expr) { unsigned i, n; if (!expr || is_gimple_val (expr)) return false; if (!EXPR_P (expr) || tree_could_trap_p (expr)) return true; n = TREE_OPERAND_LENGTH (expr); for (i = 0; i < n; i++) if (generic_expr_could_trap_p (TREE_OPERAND (expr, i))) return true; return false; } /* Convert the conditional expression pointed to by EXPR_P '(p) ? a : b;' into if (p) if (p) t1 = a; a; else or else t1 = b; b; t1; The second form is used when *EXPR_P is of type void. PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. */ static enum gimplify_status gimplify_cond_expr (tree *expr_p, gimple_seq *pre_p, fallback_t fallback) { tree expr = *expr_p; tree tmp, type, arm1, arm2; enum gimplify_status ret; tree label_true, label_false, label_cont; bool have_then_clause_p, have_else_clause_p; gimple gimple_cond; enum tree_code pred_code; gimple_seq seq = NULL; location_t loc = EXPR_LOCATION (*expr_p); type = TREE_TYPE (expr); /* If this COND_EXPR has a value, copy the values into a temporary within the arms. */ if (! VOID_TYPE_P (type)) { tree result; /* If an rvalue is ok or we do not require an lvalue, avoid creating an addressable temporary. */ if (((fallback & fb_rvalue) || !(fallback & fb_lvalue)) && !TREE_ADDRESSABLE (type)) { if (gimplify_ctxp->allow_rhs_cond_expr /* If either branch has side effects or could trap, it can't be evaluated unconditionally. */ && !TREE_SIDE_EFFECTS (TREE_OPERAND (*expr_p, 1)) && !generic_expr_could_trap_p (TREE_OPERAND (*expr_p, 1)) && !TREE_SIDE_EFFECTS (TREE_OPERAND (*expr_p, 2)) && !generic_expr_could_trap_p (TREE_OPERAND (*expr_p, 2))) return gimplify_pure_cond_expr (expr_p, pre_p); result = tmp = create_tmp_var (TREE_TYPE (expr), "iftmp"); ret = GS_ALL_DONE; } else { tree type = build_pointer_type (TREE_TYPE (expr)); if (TREE_TYPE (TREE_OPERAND (expr, 1)) != void_type_node) TREE_OPERAND (expr, 1) = build_fold_addr_expr_loc (loc, TREE_OPERAND (expr, 1)); if (TREE_TYPE (TREE_OPERAND (expr, 2)) != void_type_node) TREE_OPERAND (expr, 2) = build_fold_addr_expr_loc (loc, TREE_OPERAND (expr, 2)); tmp = create_tmp_var (type, "iftmp"); expr = build3 (COND_EXPR, void_type_node, TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1), TREE_OPERAND (expr, 2)); result = build_fold_indirect_ref_loc (loc, tmp); } /* Build the then clause, 't1 = a;'. But don't build an assignment if this branch is void; in C++ it can be, if it's a throw. */ if (TREE_TYPE (TREE_OPERAND (expr, 1)) != void_type_node) TREE_OPERAND (expr, 1) = build2 (MODIFY_EXPR, TREE_TYPE (tmp), tmp, TREE_OPERAND (expr, 1)); /* Build the else clause, 't1 = b;'. */ if (TREE_TYPE (TREE_OPERAND (expr, 2)) != void_type_node) TREE_OPERAND (expr, 2) = build2 (MODIFY_EXPR, TREE_TYPE (tmp), tmp, TREE_OPERAND (expr, 2)); TREE_TYPE (expr) = void_type_node; recalculate_side_effects (expr); /* Move the COND_EXPR to the prequeue. */ gimplify_stmt (&expr, pre_p); *expr_p = result; return GS_ALL_DONE; } /* Make sure the condition has BOOLEAN_TYPE. */ TREE_OPERAND (expr, 0) = gimple_boolify (TREE_OPERAND (expr, 0)); /* Break apart && and || conditions. */ if (TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ANDIF_EXPR || TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ORIF_EXPR) { expr = shortcut_cond_expr (expr); if (expr != *expr_p) { *expr_p = expr; /* We can't rely on gimplify_expr to re-gimplify the expanded form properly, as cleanups might cause the target labels to be wrapped in a TRY_FINALLY_EXPR. To prevent that, we need to set up a conditional context. */ gimple_push_condition (); gimplify_stmt (expr_p, &seq); gimple_pop_condition (pre_p); gimple_seq_add_seq (pre_p, seq); return GS_ALL_DONE; } } /* Now do the normal gimplification. */ /* Gimplify condition. */ ret = gimplify_expr (&TREE_OPERAND (expr, 0), pre_p, NULL, is_gimple_condexpr, fb_rvalue); if (ret == GS_ERROR) return GS_ERROR; gcc_assert (TREE_OPERAND (expr, 0) != NULL_TREE); gimple_push_condition (); have_then_clause_p = have_else_clause_p = false; if (TREE_OPERAND (expr, 1) != NULL && TREE_CODE (TREE_OPERAND (expr, 1)) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (TREE_OPERAND (expr, 1))) == LABEL_DECL && (DECL_CONTEXT (GOTO_DESTINATION (TREE_OPERAND (expr, 1))) == current_function_decl) /* For -O0 avoid this optimization if the COND_EXPR and GOTO_EXPR have different locations, otherwise we end up with incorrect location information on the branches. */ && (optimize || !EXPR_HAS_LOCATION (expr) || !EXPR_HAS_LOCATION (TREE_OPERAND (expr, 1)) || EXPR_LOCATION (expr) == EXPR_LOCATION (TREE_OPERAND (expr, 1)))) { label_true = GOTO_DESTINATION (TREE_OPERAND (expr, 1)); have_then_clause_p = true; } else label_true = create_artificial_label (UNKNOWN_LOCATION); if (TREE_OPERAND (expr, 2) != NULL && TREE_CODE (TREE_OPERAND (expr, 2)) == GOTO_EXPR && TREE_CODE (GOTO_DESTINATION (TREE_OPERAND (expr, 2))) == LABEL_DECL && (DECL_CONTEXT (GOTO_DESTINATION (TREE_OPERAND (expr, 2))) == current_function_decl) /* For -O0 avoid this optimization if the COND_EXPR and GOTO_EXPR have different locations, otherwise we end up with incorrect location information on the branches. */ && (optimize || !EXPR_HAS_LOCATION (expr) || !EXPR_HAS_LOCATION (TREE_OPERAND (expr, 2)) || EXPR_LOCATION (expr) == EXPR_LOCATION (TREE_OPERAND (expr, 2)))) { label_false = GOTO_DESTINATION (TREE_OPERAND (expr, 2)); have_else_clause_p = true; } else label_false = create_artificial_label (UNKNOWN_LOCATION); gimple_cond_get_ops_from_tree (COND_EXPR_COND (expr), &pred_code, &arm1, &arm2); gimple_cond = gimple_build_cond (pred_code, arm1, arm2, label_true, label_false); gimplify_seq_add_stmt (&seq, gimple_cond); label_cont = NULL_TREE; if (!have_then_clause_p) { /* For if (...) {} else { code; } put label_true after the else block. */ if (TREE_OPERAND (expr, 1) == NULL_TREE && !have_else_clause_p && TREE_OPERAND (expr, 2) != NULL_TREE) label_cont = label_true; else { gimplify_seq_add_stmt (&seq, gimple_build_label (label_true)); have_then_clause_p = gimplify_stmt (&TREE_OPERAND (expr, 1), &seq); /* For if (...) { code; } else {} or if (...) { code; } else goto label; or if (...) { code; return; } else { ... } label_cont isn't needed. */ if (!have_else_clause_p && TREE_OPERAND (expr, 2) != NULL_TREE && gimple_seq_may_fallthru (seq)) { gimple g; label_cont = create_artificial_label (UNKNOWN_LOCATION); g = gimple_build_goto (label_cont); /* GIMPLE_COND's are very low level; they have embedded gotos. This particular embedded goto should not be marked with the location of the original COND_EXPR, as it would correspond to the COND_EXPR's condition, not the ELSE or the THEN arms. To avoid marking it with the wrong location, flag it as "no location". */ gimple_set_do_not_emit_location (g); gimplify_seq_add_stmt (&seq, g); } } } if (!have_else_clause_p) { gimplify_seq_add_stmt (&seq, gimple_build_label (label_false)); have_else_clause_p = gimplify_stmt (&TREE_OPERAND (expr, 2), &seq); } if (label_cont) gimplify_seq_add_stmt (&seq, gimple_build_label (label_cont)); gimple_pop_condition (pre_p); gimple_seq_add_seq (pre_p, seq); if (ret == GS_ERROR) ; /* Do nothing. */ else if (have_then_clause_p || have_else_clause_p) ret = GS_ALL_DONE; else { /* Both arms are empty; replace the COND_EXPR with its predicate. */ expr = TREE_OPERAND (expr, 0); gimplify_stmt (&expr, pre_p); } *expr_p = NULL; return ret; } /* Prepare the node pointed to by EXPR_P, an is_gimple_addressable expression, to be marked addressable. We cannot rely on such an expression being directly markable if a temporary has been created by the gimplification. In this case, we create another temporary and initialize it with a copy, which will become a store after we mark it addressable. This can happen if the front-end passed us something that it could not mark addressable yet, like a Fortran pass-by-reference parameter (int) floatvar. */ static void prepare_gimple_addressable (tree *expr_p, gimple_seq *seq_p) { while (handled_component_p (*expr_p)) expr_p = &TREE_OPERAND (*expr_p, 0); if (is_gimple_reg (*expr_p)) *expr_p = get_initialized_tmp_var (*expr_p, seq_p, NULL); } /* A subroutine of gimplify_modify_expr. Replace a MODIFY_EXPR with a call to __builtin_memcpy. */ static enum gimplify_status gimplify_modify_expr_to_memcpy (tree *expr_p, tree size, bool want_value, gimple_seq *seq_p) { tree t, to, to_ptr, from, from_ptr; gimple gs; location_t loc = EXPR_LOCATION (*expr_p); to = TREE_OPERAND (*expr_p, 0); from = TREE_OPERAND (*expr_p, 1); /* Mark the RHS addressable. Beware that it may not be possible to do so directly if a temporary has been created by the gimplification. */ prepare_gimple_addressable (&from, seq_p); mark_addressable (from); from_ptr = build_fold_addr_expr_loc (loc, from); gimplify_arg (&from_ptr, seq_p, loc); mark_addressable (to); to_ptr = build_fold_addr_expr_loc (loc, to); gimplify_arg (&to_ptr, seq_p, loc); t = implicit_built_in_decls[BUILT_IN_MEMCPY]; gs = gimple_build_call (t, 3, to_ptr, from_ptr, size); if (want_value) { /* tmp = memcpy() */ t = create_tmp_var (TREE_TYPE (to_ptr), NULL); gimple_call_set_lhs (gs, t); gimplify_seq_add_stmt (seq_p, gs); *expr_p = build1 (INDIRECT_REF, TREE_TYPE (to), t); return GS_ALL_DONE; } gimplify_seq_add_stmt (seq_p, gs); *expr_p = NULL; return GS_ALL_DONE; } /* A subroutine of gimplify_modify_expr. Replace a MODIFY_EXPR with a call to __builtin_memset. In this case we know that the RHS is a CONSTRUCTOR with an empty element list. */ static enum gimplify_status gimplify_modify_expr_to_memset (tree *expr_p, tree size, bool want_value, gimple_seq *seq_p) { tree t, from, to, to_ptr; gimple gs; location_t loc = EXPR_LOCATION (*expr_p); /* Assert our assumptions, to abort instead of producing wrong code silently if they are not met. Beware that the RHS CONSTRUCTOR might not be immediately exposed. */ from = TREE_OPERAND (*expr_p, 1); if (TREE_CODE (from) == WITH_SIZE_EXPR) from = TREE_OPERAND (from, 0); gcc_assert (TREE_CODE (from) == CONSTRUCTOR && VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (from))); /* Now proceed. */ to = TREE_OPERAND (*expr_p, 0); to_ptr = build_fold_addr_expr_loc (loc, to); gimplify_arg (&to_ptr, seq_p, loc); t = implicit_built_in_decls[BUILT_IN_MEMSET]; gs = gimple_build_call (t, 3, to_ptr, integer_zero_node, size); if (want_value) { /* tmp = memset() */ t = create_tmp_var (TREE_TYPE (to_ptr), NULL); gimple_call_set_lhs (gs, t); gimplify_seq_add_stmt (seq_p, gs); *expr_p = build1 (INDIRECT_REF, TREE_TYPE (to), t); return GS_ALL_DONE; } gimplify_seq_add_stmt (seq_p, gs); *expr_p = NULL; return GS_ALL_DONE; } /* A subroutine of gimplify_init_ctor_preeval. Called via walk_tree, determine, cautiously, if a CONSTRUCTOR overlaps the lhs of an assignment. Returns non-null if we detect a potential overlap. */ struct gimplify_init_ctor_preeval_data { /* The base decl of the lhs object. May be NULL, in which case we have to assume the lhs is indirect. */ tree lhs_base_decl; /* The alias set of the lhs object. */ alias_set_type lhs_alias_set; }; static tree gimplify_init_ctor_preeval_1 (tree *tp, int *walk_subtrees, void *xdata) { struct gimplify_init_ctor_preeval_data *data = (struct gimplify_init_ctor_preeval_data *) xdata; tree t = *tp; /* If we find the base object, obviously we have overlap. */ if (data->lhs_base_decl == t) return t; /* If the constructor component is indirect, determine if we have a potential overlap with the lhs. The only bits of information we have to go on at this point are addressability and alias sets. */ if (TREE_CODE (t) == INDIRECT_REF && (!data->lhs_base_decl || TREE_ADDRESSABLE (data->lhs_base_decl)) && alias_sets_conflict_p (data->lhs_alias_set, get_alias_set (t))) return t; /* If the constructor component is a call, determine if it can hide a potential overlap with the lhs through an INDIRECT_REF like above. */ if (TREE_CODE (t) == CALL_EXPR) { tree type, fntype = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (t))); for (type = TYPE_ARG_TYPES (fntype); type; type = TREE_CHAIN (type)) if (POINTER_TYPE_P (TREE_VALUE (type)) && (!data->lhs_base_decl || TREE_ADDRESSABLE (data->lhs_base_decl)) && alias_sets_conflict_p (data->lhs_alias_set, get_alias_set (TREE_TYPE (TREE_VALUE (type))))) return t; } if (IS_TYPE_OR_DECL_P (t)) *walk_subtrees = 0; return NULL; } /* A subroutine of gimplify_init_constructor. Pre-evaluate EXPR, force values that overlap with the lhs (as described by *DATA) into temporaries. */ static void gimplify_init_ctor_preeval (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, struct gimplify_init_ctor_preeval_data *data) { enum gimplify_status one; /* If the value is constant, then there's nothing to pre-evaluate. */ if (TREE_CONSTANT (*expr_p)) { /* Ensure it does not have side effects, it might contain a reference to the object we're initializing. */ gcc_assert (!TREE_SIDE_EFFECTS (*expr_p)); return; } /* If the type has non-trivial constructors, we can't pre-evaluate. */ if (TREE_ADDRESSABLE (TREE_TYPE (*expr_p))) return; /* Recurse for nested constructors. */ if (TREE_CODE (*expr_p) == CONSTRUCTOR) { unsigned HOST_WIDE_INT ix; constructor_elt *ce; VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (*expr_p); for (ix = 0; VEC_iterate (constructor_elt, v, ix, ce); ix++) gimplify_init_ctor_preeval (&ce->value, pre_p, post_p, data); return; } /* If this is a variable sized type, we must remember the size. */ maybe_with_size_expr (expr_p); /* Gimplify the constructor element to something appropriate for the rhs of a MODIFY_EXPR. Given that we know the LHS is an aggregate, we know the gimplifier will consider this a store to memory. Doing this gimplification now means that we won't have to deal with complicated language-specific trees, nor trees like SAVE_EXPR that can induce exponential search behavior. */ one = gimplify_expr (expr_p, pre_p, post_p, is_gimple_mem_rhs, fb_rvalue); if (one == GS_ERROR) { *expr_p = NULL; return; } /* If we gimplified to a bare decl, we can be sure that it doesn't overlap with the lhs, since "a = { .x=a }" doesn't make sense. This will always be true for all scalars, since is_gimple_mem_rhs insists on a temporary variable for them. */ if (DECL_P (*expr_p)) return; /* If this is of variable size, we have no choice but to assume it doesn't overlap since we can't make a temporary for it. */ if (TREE_CODE (TYPE_SIZE (TREE_TYPE (*expr_p))) != INTEGER_CST) return; /* Otherwise, we must search for overlap ... */ if (!walk_tree (expr_p, gimplify_init_ctor_preeval_1, data, NULL)) return; /* ... and if found, force the value into a temporary. */ *expr_p = get_formal_tmp_var (*expr_p, pre_p); } /* A subroutine of gimplify_init_ctor_eval. Create a loop for a RANGE_EXPR in a CONSTRUCTOR for an array. var = lower; loop_entry: object[var] = value; if (var == upper) goto loop_exit; var = var + 1; goto loop_entry; loop_exit: We increment var _after_ the loop exit check because we might otherwise fail if upper == TYPE_MAX_VALUE (type for upper). Note that we never have to deal with SAVE_EXPRs here, because this has already been taken care of for us, in gimplify_init_ctor_preeval(). */ static void gimplify_init_ctor_eval (tree, VEC(constructor_elt,gc) *, gimple_seq *, bool); static void gimplify_init_ctor_eval_range (tree object, tree lower, tree upper, tree value, tree array_elt_type, gimple_seq *pre_p, bool cleared) { tree loop_entry_label, loop_exit_label, fall_thru_label; tree var, var_type, cref, tmp; loop_entry_label = create_artificial_label (UNKNOWN_LOCATION); loop_exit_label = create_artificial_label (UNKNOWN_LOCATION); fall_thru_label = create_artificial_label (UNKNOWN_LOCATION); /* Create and initialize the index variable. */ var_type = TREE_TYPE (upper); var = create_tmp_var (var_type, NULL); gimplify_seq_add_stmt (pre_p, gimple_build_assign (var, lower)); /* Add the loop entry label. */ gimplify_seq_add_stmt (pre_p, gimple_build_label (loop_entry_label)); /* Build the reference. */ cref = build4 (ARRAY_REF, array_elt_type, unshare_expr (object), var, NULL_TREE, NULL_TREE); /* If we are a constructor, just call gimplify_init_ctor_eval to do the store. Otherwise just assign value to the reference. */ if (TREE_CODE (value) == CONSTRUCTOR) /* NB we might have to call ourself recursively through gimplify_init_ctor_eval if the value is a constructor. */ gimplify_init_ctor_eval (cref, CONSTRUCTOR_ELTS (value), pre_p, cleared); else gimplify_seq_add_stmt (pre_p, gimple_build_assign (cref, value)); /* We exit the loop when the index var is equal to the upper bound. */ gimplify_seq_add_stmt (pre_p, gimple_build_cond (EQ_EXPR, var, upper, loop_exit_label, fall_thru_label)); gimplify_seq_add_stmt (pre_p, gimple_build_label (fall_thru_label)); /* Otherwise, increment the index var... */ tmp = build2 (PLUS_EXPR, var_type, var, fold_convert (var_type, integer_one_node)); gimplify_seq_add_stmt (pre_p, gimple_build_assign (var, tmp)); /* ...and jump back to the loop entry. */ gimplify_seq_add_stmt (pre_p, gimple_build_goto (loop_entry_label)); /* Add the loop exit label. */ gimplify_seq_add_stmt (pre_p, gimple_build_label (loop_exit_label)); } /* Return true if FDECL is accessing a field that is zero sized. */ static bool zero_sized_field_decl (const_tree fdecl) { if (TREE_CODE (fdecl) == FIELD_DECL && DECL_SIZE (fdecl) && integer_zerop (DECL_SIZE (fdecl))) return true; return false; } /* Return true if TYPE is zero sized. */ static bool zero_sized_type (const_tree type) { if (AGGREGATE_TYPE_P (type) && TYPE_SIZE (type) && integer_zerop (TYPE_SIZE (type))) return true; return false; } /* A subroutine of gimplify_init_constructor. Generate individual MODIFY_EXPRs for a CONSTRUCTOR. OBJECT is the LHS against which the assignments should happen. ELTS is the CONSTRUCTOR_ELTS of the CONSTRUCTOR. CLEARED is true if the entire LHS object has been zeroed first. */ static void gimplify_init_ctor_eval (tree object, VEC(constructor_elt,gc) *elts, gimple_seq *pre_p, bool cleared) { tree array_elt_type = NULL; unsigned HOST_WIDE_INT ix; tree purpose, value; if (TREE_CODE (TREE_TYPE (object)) == ARRAY_TYPE) array_elt_type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (object))); FOR_EACH_CONSTRUCTOR_ELT (elts, ix, purpose, value) { tree cref; /* NULL values are created above for gimplification errors. */ if (value == NULL) continue; if (cleared && initializer_zerop (value)) continue; /* ??? Here's to hoping the front end fills in all of the indices, so we don't have to figure out what's missing ourselves. */ gcc_assert (purpose); /* Skip zero-sized fields, unless value has side-effects. This can happen with calls to functions returning a zero-sized type, which we shouldn't discard. As a number of downstream passes don't expect sets of zero-sized fields, we rely on the gimplification of the MODIFY_EXPR we make below to drop the assignment statement. */ if (! TREE_SIDE_EFFECTS (value) && zero_sized_field_decl (purpose)) continue; /* If we have a RANGE_EXPR, we have to build a loop to assign the whole range. */ if (TREE_CODE (purpose) == RANGE_EXPR) { tree lower = TREE_OPERAND (purpose, 0); tree upper = TREE_OPERAND (purpose, 1); /* If the lower bound is equal to upper, just treat it as if upper was the index. */ if (simple_cst_equal (lower, upper)) purpose = upper; else { gimplify_init_ctor_eval_range (object, lower, upper, value, array_elt_type, pre_p, cleared); continue; } } if (array_elt_type) { /* Do not use bitsizetype for ARRAY_REF indices. */ if (TYPE_DOMAIN (TREE_TYPE (object))) purpose = fold_convert (TREE_TYPE (TYPE_DOMAIN (TREE_TYPE (object))), purpose); cref = build4 (ARRAY_REF, array_elt_type, unshare_expr (object), purpose, NULL_TREE, NULL_TREE); } else { gcc_assert (TREE_CODE (purpose) == FIELD_DECL); cref = build3 (COMPONENT_REF, TREE_TYPE (purpose), unshare_expr (object), purpose, NULL_TREE); } if (TREE_CODE (value) == CONSTRUCTOR && TREE_CODE (TREE_TYPE (value)) != VECTOR_TYPE) gimplify_init_ctor_eval (cref, CONSTRUCTOR_ELTS (value), pre_p, cleared); else { tree init = build2 (INIT_EXPR, TREE_TYPE (cref), cref, value); gimplify_and_add (init, pre_p); ggc_free (init); } } } /* Returns the appropriate RHS predicate for this LHS. */ gimple_predicate rhs_predicate_for (tree lhs) { if (is_gimple_reg (lhs)) return is_gimple_reg_rhs_or_call; else return is_gimple_mem_rhs_or_call; } /* Gimplify a C99 compound literal expression. This just means adding the DECL_EXPR before the current statement and using its anonymous decl instead. */ static enum gimplify_status gimplify_compound_literal_expr (tree *expr_p, gimple_seq *pre_p) { tree decl_s = COMPOUND_LITERAL_EXPR_DECL_EXPR (*expr_p); tree decl = DECL_EXPR_DECL (decl_s); /* Mark the decl as addressable if the compound literal expression is addressable now, otherwise it is marked too late after we gimplify the initialization expression. */ if (TREE_ADDRESSABLE (*expr_p)) TREE_ADDRESSABLE (decl) = 1; /* Preliminarily mark non-addressed complex variables as eligible for promotion to gimple registers. We'll transform their uses as we find them. */ if ((TREE_CODE (TREE_TYPE (decl)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (decl)) == VECTOR_TYPE) && !TREE_THIS_VOLATILE (decl) && !needs_to_live_in_memory (decl)) DECL_GIMPLE_REG_P (decl) = 1; /* This decl isn't mentioned in the enclosing block, so add it to the list of temps. FIXME it seems a bit of a kludge to say that anonymous artificial vars aren't pushed, but everything else is. */ if (DECL_NAME (decl) == NULL_TREE && !DECL_SEEN_IN_BIND_EXPR_P (decl)) gimple_add_tmp_var (decl); gimplify_and_add (decl_s, pre_p); *expr_p = decl; return GS_OK; } /* Optimize embedded COMPOUND_LITERAL_EXPRs within a CONSTRUCTOR, return a new CONSTRUCTOR if something changed. */ static tree optimize_compound_literals_in_ctor (tree orig_ctor) { tree ctor = orig_ctor; VEC(constructor_elt,gc) *elts = CONSTRUCTOR_ELTS (ctor); unsigned int idx, num = VEC_length (constructor_elt, elts); for (idx = 0; idx < num; idx++) { tree value = VEC_index (constructor_elt, elts, idx)->value; tree newval = value; if (TREE_CODE (value) == CONSTRUCTOR) newval = optimize_compound_literals_in_ctor (value); else if (TREE_CODE (value) == COMPOUND_LITERAL_EXPR) { tree decl_s = COMPOUND_LITERAL_EXPR_DECL_EXPR (value); tree decl = DECL_EXPR_DECL (decl_s); tree init = DECL_INITIAL (decl); if (!TREE_ADDRESSABLE (value) && !TREE_ADDRESSABLE (decl) && init) newval = optimize_compound_literals_in_ctor (init); } if (newval == value) continue; if (ctor == orig_ctor) { ctor = copy_node (orig_ctor); CONSTRUCTOR_ELTS (ctor) = VEC_copy (constructor_elt, gc, elts); elts = CONSTRUCTOR_ELTS (ctor); } VEC_index (constructor_elt, elts, idx)->value = newval; } return ctor; } /* A subroutine of gimplify_modify_expr. Break out elements of a CONSTRUCTOR used as an initializer into separate MODIFY_EXPRs. Note that we still need to clear any elements that don't have explicit initializers, so if not all elements are initialized we keep the original MODIFY_EXPR, we just remove all of the constructor elements. If NOTIFY_TEMP_CREATION is true, do not gimplify, just return GS_ERROR if we would have to create a temporary when gimplifying this constructor. Otherwise, return GS_OK. If NOTIFY_TEMP_CREATION is false, just do the gimplification. */ static enum gimplify_status gimplify_init_constructor (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value, bool notify_temp_creation) { tree object, ctor, type; enum gimplify_status ret; VEC(constructor_elt,gc) *elts; gcc_assert (TREE_CODE (TREE_OPERAND (*expr_p, 1)) == CONSTRUCTOR); if (!notify_temp_creation) { ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret == GS_ERROR) return ret; } object = TREE_OPERAND (*expr_p, 0); ctor = TREE_OPERAND (*expr_p, 1) = optimize_compound_literals_in_ctor (TREE_OPERAND (*expr_p, 1)); type = TREE_TYPE (ctor); elts = CONSTRUCTOR_ELTS (ctor); ret = GS_ALL_DONE; switch (TREE_CODE (type)) { case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: case ARRAY_TYPE: { struct gimplify_init_ctor_preeval_data preeval_data; HOST_WIDE_INT num_type_elements, num_ctor_elements; HOST_WIDE_INT num_nonzero_elements; bool cleared, valid_const_initializer; /* Aggregate types must lower constructors to initialization of individual elements. The exception is that a CONSTRUCTOR node with no elements indicates zero-initialization of the whole. */ if (VEC_empty (constructor_elt, elts)) { if (notify_temp_creation) return GS_OK; break; } /* Fetch information about the constructor to direct later processing. We might want to make static versions of it in various cases, and can only do so if it known to be a valid constant initializer. */ valid_const_initializer = categorize_ctor_elements (ctor, &num_nonzero_elements, &num_ctor_elements, &cleared); /* If a const aggregate variable is being initialized, then it should never be a lose to promote the variable to be static. */ if (valid_const_initializer && num_nonzero_elements > 1 && TREE_READONLY (object) && TREE_CODE (object) == VAR_DECL && (flag_merge_constants >= 2 || !TREE_ADDRESSABLE (object))) { if (notify_temp_creation) return GS_ERROR; DECL_INITIAL (object) = ctor; TREE_STATIC (object) = 1; if (!DECL_NAME (object)) DECL_NAME (object) = create_tmp_var_name ("C"); walk_tree (&DECL_INITIAL (object), force_labels_r, NULL, NULL); /* ??? C++ doesn't automatically append a .<number> to the assembler name, and even when it does, it looks a FE private data structures to figure out what that number should be, which are not set for this variable. I suppose this is important for local statics for inline functions, which aren't "local" in the object file sense. So in order to get a unique TU-local symbol, we must invoke the lhd version now. */ lhd_set_decl_assembler_name (object); *expr_p = NULL_TREE; break; } /* If there are "lots" of initialized elements, even discounting those that are not address constants (and thus *must* be computed at runtime), then partition the constructor into constant and non-constant parts. Block copy the constant parts in, then generate code for the non-constant parts. */ /* TODO. There's code in cp/typeck.c to do this. */ num_type_elements = count_type_elements (type, true); /* If count_type_elements could not determine number of type elements for a constant-sized object, assume clearing is needed. Don't do this for variable-sized objects, as store_constructor will ignore the clearing of variable-sized objects. */ if (num_type_elements < 0 && int_size_in_bytes (type) >= 0) cleared = true; /* If there are "lots" of zeros, then block clear the object first. */ else if (num_type_elements - num_nonzero_elements > CLEAR_RATIO (optimize_function_for_speed_p (cfun)) && num_nonzero_elements < num_type_elements/4) cleared = true; /* ??? This bit ought not be needed. For any element not present in the initializer, we should simply set them to zero. Except we'd need to *find* the elements that are not present, and that requires trickery to avoid quadratic compile-time behavior in large cases or excessive memory use in small cases. */ else if (num_ctor_elements < num_type_elements) cleared = true; /* If there are "lots" of initialized elements, and all of them are valid address constants, then the entire initializer can be dropped to memory, and then memcpy'd out. Don't do this for sparse arrays, though, as it's more efficient to follow the standard CONSTRUCTOR behavior of memset followed by individual element initialization. Also don't do this for small all-zero initializers (which aren't big enough to merit clearing), and don't try to make bitwise copies of TREE_ADDRESSABLE types. */ if (valid_const_initializer && !(cleared || num_nonzero_elements == 0) && !TREE_ADDRESSABLE (type)) { HOST_WIDE_INT size = int_size_in_bytes (type); unsigned int align; /* ??? We can still get unbounded array types, at least from the C++ front end. This seems wrong, but attempt to work around it for now. */ if (size < 0) { size = int_size_in_bytes (TREE_TYPE (object)); if (size >= 0) TREE_TYPE (ctor) = type = TREE_TYPE (object); } /* Find the maximum alignment we can assume for the object. */ /* ??? Make use of DECL_OFFSET_ALIGN. */ if (DECL_P (object)) align = DECL_ALIGN (object); else align = TYPE_ALIGN (type); if (size > 0 && num_nonzero_elements > 1 && !can_move_by_pieces (size, align)) { tree new_tree; if (notify_temp_creation) return GS_ERROR; new_tree = create_tmp_var_raw (type, "C"); gimple_add_tmp_var (new_tree); TREE_STATIC (new_tree) = 1; TREE_READONLY (new_tree) = 1; DECL_INITIAL (new_tree) = ctor; if (align > DECL_ALIGN (new_tree)) { DECL_ALIGN (new_tree) = align; DECL_USER_ALIGN (new_tree) = 1; } walk_tree (&DECL_INITIAL (new_tree), force_labels_r, NULL, NULL); TREE_OPERAND (*expr_p, 1) = new_tree; /* This is no longer an assignment of a CONSTRUCTOR, but we still may have processing to do on the LHS. So pretend we didn't do anything here to let that happen. */ return GS_UNHANDLED; } } /* If the target is volatile, we have non-zero elements and more than one field to assign, initialize the target from a temporary. */ if (TREE_THIS_VOLATILE (object) && !TREE_ADDRESSABLE (type) && num_nonzero_elements > 0 && VEC_length (constructor_elt, elts) > 1) { tree temp = create_tmp_var (TYPE_MAIN_VARIANT (type), NULL); TREE_OPERAND (*expr_p, 0) = temp; *expr_p = build2 (COMPOUND_EXPR, TREE_TYPE (*expr_p), *expr_p, build2 (MODIFY_EXPR, void_type_node, object, temp)); return GS_OK; } if (notify_temp_creation) return GS_OK; /* If there are nonzero elements, pre-evaluate to capture elements overlapping with the lhs into temporaries. We must do this before clearing to fetch the values before they are zeroed-out. */ if (num_nonzero_elements > 0) { preeval_data.lhs_base_decl = get_base_address (object); if (!DECL_P (preeval_data.lhs_base_decl)) preeval_data.lhs_base_decl = NULL; preeval_data.lhs_alias_set = get_alias_set (object); gimplify_init_ctor_preeval (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, &preeval_data); } if (cleared) { /* Zap the CONSTRUCTOR element list, which simplifies this case. Note that we still have to gimplify, in order to handle the case of variable sized types. Avoid shared tree structures. */ CONSTRUCTOR_ELTS (ctor) = NULL; TREE_SIDE_EFFECTS (ctor) = 0; object = unshare_expr (object); gimplify_stmt (expr_p, pre_p); } /* If we have not block cleared the object, or if there are nonzero elements in the constructor, add assignments to the individual scalar fields of the object. */ if (!cleared || num_nonzero_elements > 0) gimplify_init_ctor_eval (object, elts, pre_p, cleared); *expr_p = NULL_TREE; } break; case COMPLEX_TYPE: { tree r, i; if (notify_temp_creation) return GS_OK; /* Extract the real and imaginary parts out of the ctor. */ gcc_assert (VEC_length (constructor_elt, elts) == 2); r = VEC_index (constructor_elt, elts, 0)->value; i = VEC_index (constructor_elt, elts, 1)->value; if (r == NULL || i == NULL) { tree zero = fold_convert (TREE_TYPE (type), integer_zero_node); if (r == NULL) r = zero; if (i == NULL) i = zero; } /* Complex types have either COMPLEX_CST or COMPLEX_EXPR to represent creation of a complex value. */ if (TREE_CONSTANT (r) && TREE_CONSTANT (i)) { ctor = build_complex (type, r, i); TREE_OPERAND (*expr_p, 1) = ctor; } else { ctor = build2 (COMPLEX_EXPR, type, r, i); TREE_OPERAND (*expr_p, 1) = ctor; ret = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, rhs_predicate_for (TREE_OPERAND (*expr_p, 0)), fb_rvalue); } } break; case VECTOR_TYPE: { unsigned HOST_WIDE_INT ix; constructor_elt *ce; if (notify_temp_creation) return GS_OK; /* Go ahead and simplify constant constructors to VECTOR_CST. */ if (TREE_CONSTANT (ctor)) { bool constant_p = true; tree value; /* Even when ctor is constant, it might contain non-*_CST elements, such as addresses or trapping values like 1.0/0.0 - 1.0/0.0. Such expressions don't belong in VECTOR_CST nodes. */ FOR_EACH_CONSTRUCTOR_VALUE (elts, ix, value) if (!CONSTANT_CLASS_P (value)) { constant_p = false; break; } if (constant_p) { TREE_OPERAND (*expr_p, 1) = build_vector_from_ctor (type, elts); break; } /* Don't reduce an initializer constant even if we can't make a VECTOR_CST. It won't do anything for us, and it'll prevent us from representing it as a single constant. */ if (initializer_constant_valid_p (ctor, type)) break; TREE_CONSTANT (ctor) = 0; } /* Vector types use CONSTRUCTOR all the way through gimple compilation as a general initializer. */ for (ix = 0; VEC_iterate (constructor_elt, elts, ix, ce); ix++) { enum gimplify_status tret; tret = gimplify_expr (&ce->value, pre_p, post_p, is_gimple_val, fb_rvalue); if (tret == GS_ERROR) ret = GS_ERROR; } if (!is_gimple_reg (TREE_OPERAND (*expr_p, 0))) TREE_OPERAND (*expr_p, 1) = get_formal_tmp_var (ctor, pre_p); } break; default: /* So how did we get a CONSTRUCTOR for a scalar type? */ gcc_unreachable (); } if (ret == GS_ERROR) return GS_ERROR; else if (want_value) { *expr_p = object; return GS_OK; } else { /* If we have gimplified both sides of the initializer but have not emitted an assignment, do so now. */ if (*expr_p) { tree lhs = TREE_OPERAND (*expr_p, 0); tree rhs = TREE_OPERAND (*expr_p, 1); gimple init = gimple_build_assign (lhs, rhs); gimplify_seq_add_stmt (pre_p, init); *expr_p = NULL; } return GS_ALL_DONE; } } /* Given a pointer value OP0, return a simplified version of an indirection through OP0, or NULL_TREE if no simplification is possible. Note that the resulting type may be different from the type pointed to in the sense that it is still compatible from the langhooks point of view. */ tree gimple_fold_indirect_ref (tree t) { tree type = TREE_TYPE (TREE_TYPE (t)); tree sub = t; tree subtype; STRIP_NOPS (sub); subtype = TREE_TYPE (sub); if (!POINTER_TYPE_P (subtype)) return NULL_TREE; if (TREE_CODE (sub) == ADDR_EXPR) { tree op = TREE_OPERAND (sub, 0); tree optype = TREE_TYPE (op); /* *&p => p */ if (useless_type_conversion_p (type, optype)) return op; /* *(foo *)&fooarray => fooarray[0] */ if (TREE_CODE (optype) == ARRAY_TYPE && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST && useless_type_conversion_p (type, TREE_TYPE (optype))) { tree type_domain = TYPE_DOMAIN (optype); tree min_val = size_zero_node; if (type_domain && TYPE_MIN_VALUE (type_domain)) min_val = TYPE_MIN_VALUE (type_domain); if (TREE_CODE (min_val) == INTEGER_CST) return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE); } /* *(foo *)&complexfoo => __real__ complexfoo */ else if (TREE_CODE (optype) == COMPLEX_TYPE && useless_type_conversion_p (type, TREE_TYPE (optype))) return fold_build1 (REALPART_EXPR, type, op); /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */ else if (TREE_CODE (optype) == VECTOR_TYPE && useless_type_conversion_p (type, TREE_TYPE (optype))) { tree part_width = TYPE_SIZE (type); tree index = bitsize_int (0); return fold_build3 (BIT_FIELD_REF, type, op, part_width, index); } } /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */ if (TREE_CODE (sub) == POINTER_PLUS_EXPR && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST) { tree op00 = TREE_OPERAND (sub, 0); tree op01 = TREE_OPERAND (sub, 1); tree op00type; STRIP_NOPS (op00); op00type = TREE_TYPE (op00); if (TREE_CODE (op00) == ADDR_EXPR && TREE_CODE (TREE_TYPE (op00type)) == VECTOR_TYPE && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (op00type)))) { HOST_WIDE_INT offset = tree_low_cst (op01, 0); tree part_width = TYPE_SIZE (type); unsigned HOST_WIDE_INT part_widthi = tree_low_cst (part_width, 0) / BITS_PER_UNIT; unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT; tree index = bitsize_int (indexi); if (offset / part_widthi <= TYPE_VECTOR_SUBPARTS (TREE_TYPE (op00type))) return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (op00, 0), part_width, index); } } /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */ if (TREE_CODE (sub) == POINTER_PLUS_EXPR && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST) { tree op00 = TREE_OPERAND (sub, 0); tree op01 = TREE_OPERAND (sub, 1); tree op00type; STRIP_NOPS (op00); op00type = TREE_TYPE (op00); if (TREE_CODE (op00) == ADDR_EXPR && TREE_CODE (TREE_TYPE (op00type)) == COMPLEX_TYPE && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (op00type)))) { tree size = TYPE_SIZE_UNIT (type); if (tree_int_cst_equal (size, op01)) return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (op00, 0)); } } /* *(foo *)fooarrptr => (*fooarrptr)[0] */ if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype)))) { tree type_domain; tree min_val = size_zero_node; tree osub = sub; sub = gimple_fold_indirect_ref (sub); if (! sub) sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub); type_domain = TYPE_DOMAIN (TREE_TYPE (sub)); if (type_domain && TYPE_MIN_VALUE (type_domain)) min_val = TYPE_MIN_VALUE (type_domain); if (TREE_CODE (min_val) == INTEGER_CST) return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE); } return NULL_TREE; } /* Given a pointer value OP0, return a simplified version of an indirection through OP0, or NULL_TREE if no simplification is possible. This may only be applied to a rhs of an expression. Note that the resulting type may be different from the type pointed to in the sense that it is still compatible from the langhooks point of view. */ static tree gimple_fold_indirect_ref_rhs (tree t) { return gimple_fold_indirect_ref (t); } /* Subroutine of gimplify_modify_expr to do simplifications of MODIFY_EXPRs based on the code of the RHS. We loop for as long as something changes. */ static enum gimplify_status gimplify_modify_expr_rhs (tree *expr_p, tree *from_p, tree *to_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value) { enum gimplify_status ret = GS_UNHANDLED; bool changed; do { changed = false; switch (TREE_CODE (*from_p)) { case VAR_DECL: /* If we're assigning from a read-only variable initialized with a constructor, do the direct assignment from the constructor, but only if neither source nor target are volatile since this latter assignment might end up being done on a per-field basis. */ if (DECL_INITIAL (*from_p) && TREE_READONLY (*from_p) && !TREE_THIS_VOLATILE (*from_p) && !TREE_THIS_VOLATILE (*to_p) && TREE_CODE (DECL_INITIAL (*from_p)) == CONSTRUCTOR) { tree old_from = *from_p; enum gimplify_status subret; /* Move the constructor into the RHS. */ *from_p = unshare_expr (DECL_INITIAL (*from_p)); /* Let's see if gimplify_init_constructor will need to put it in memory. */ subret = gimplify_init_constructor (expr_p, NULL, NULL, false, true); if (subret == GS_ERROR) { /* If so, revert the change. */ *from_p = old_from; } else { ret = GS_OK; changed = true; } } break; case INDIRECT_REF: { /* If we have code like *(const A*)(A*)&x where the type of "x" is a (possibly cv-qualified variant of "A"), treat the entire expression as identical to "x". This kind of code arises in C++ when an object is bound to a const reference, and if "x" is a TARGET_EXPR we want to take advantage of the optimization below. */ bool volatile_p = TREE_THIS_VOLATILE (*from_p); tree t = gimple_fold_indirect_ref_rhs (TREE_OPERAND (*from_p, 0)); if (t && (TREE_THIS_VOLATILE (t) == volatile_p || REFERENCE_CLASS_P (t))) { TREE_THIS_VOLATILE (t) = volatile_p; *from_p = t; ret = GS_OK; changed = true; } break; } case TARGET_EXPR: { /* If we are initializing something from a TARGET_EXPR, strip the TARGET_EXPR and initialize it directly, if possible. This can't be done if the initializer is void, since that implies that the temporary is set in some non-trivial way. ??? What about code that pulls out the temp and uses it elsewhere? I think that such code never uses the TARGET_EXPR as an initializer. If I'm wrong, we'll die because the temp won't have any RTL. In that case, I guess we'll need to replace references somehow. */ tree init = TARGET_EXPR_INITIAL (*from_p); if (init && !VOID_TYPE_P (TREE_TYPE (init))) { *from_p = init; ret = GS_OK; changed = true; } } break; case COMPOUND_EXPR: /* Remove any COMPOUND_EXPR in the RHS so the following cases will be caught. */ gimplify_compound_expr (from_p, pre_p, true); ret = GS_OK; changed = true; break; case CONSTRUCTOR: /* If we're initializing from a CONSTRUCTOR, break this into individual MODIFY_EXPRs. */ return gimplify_init_constructor (expr_p, pre_p, post_p, want_value, false); case COND_EXPR: /* If we're assigning to a non-register type, push the assignment down into the branches. This is mandatory for ADDRESSABLE types, since we cannot generate temporaries for such, but it saves a copy in other cases as well. */ if (!is_gimple_reg_type (TREE_TYPE (*from_p))) { /* This code should mirror the code in gimplify_cond_expr. */ enum tree_code code = TREE_CODE (*expr_p); tree cond = *from_p; tree result = *to_p; ret = gimplify_expr (&result, pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret != GS_ERROR) ret = GS_OK; if (TREE_TYPE (TREE_OPERAND (cond, 1)) != void_type_node) TREE_OPERAND (cond, 1) = build2 (code, void_type_node, result, TREE_OPERAND (cond, 1)); if (TREE_TYPE (TREE_OPERAND (cond, 2)) != void_type_node) TREE_OPERAND (cond, 2) = build2 (code, void_type_node, unshare_expr (result), TREE_OPERAND (cond, 2)); TREE_TYPE (cond) = void_type_node; recalculate_side_effects (cond); if (want_value) { gimplify_and_add (cond, pre_p); *expr_p = unshare_expr (result); } else *expr_p = cond; return ret; } break; case CALL_EXPR: /* For calls that return in memory, give *to_p as the CALL_EXPR's return slot so that we don't generate a temporary. */ if (!CALL_EXPR_RETURN_SLOT_OPT (*from_p) && aggregate_value_p (*from_p, *from_p)) { bool use_target; if (!(rhs_predicate_for (*to_p))(*from_p)) /* If we need a temporary, *to_p isn't accurate. */ use_target = false; else if (TREE_CODE (*to_p) == RESULT_DECL && DECL_NAME (*to_p) == NULL_TREE && needs_to_live_in_memory (*to_p)) /* It's OK to use the return slot directly unless it's an NRV. */ use_target = true; else if (is_gimple_reg_type (TREE_TYPE (*to_p)) || (DECL_P (*to_p) && DECL_REGISTER (*to_p))) /* Don't force regs into memory. */ use_target = false; else if (TREE_CODE (*expr_p) == INIT_EXPR) /* It's OK to use the target directly if it's being initialized. */ use_target = true; else if (!is_gimple_non_addressable (*to_p)) /* Don't use the original target if it's already addressable; if its address escapes, and the called function uses the NRV optimization, a conforming program could see *to_p change before the called function returns; see c++/19317. When optimizing, the return_slot pass marks more functions as safe after we have escape info. */ use_target = false; else use_target = true; if (use_target) { CALL_EXPR_RETURN_SLOT_OPT (*from_p) = 1; mark_addressable (*to_p); } } break; /* If we're initializing from a container, push the initialization inside it. */ case CLEANUP_POINT_EXPR: case BIND_EXPR: case STATEMENT_LIST: { tree wrap = *from_p; tree t; ret = gimplify_expr (to_p, pre_p, post_p, is_gimple_min_lval, fb_lvalue); if (ret != GS_ERROR) ret = GS_OK; t = voidify_wrapper_expr (wrap, *expr_p); gcc_assert (t == *expr_p); if (want_value) { gimplify_and_add (wrap, pre_p); *expr_p = unshare_expr (*to_p); } else *expr_p = wrap; return GS_OK; } case COMPOUND_LITERAL_EXPR: { tree complit = TREE_OPERAND (*expr_p, 1); tree decl_s = COMPOUND_LITERAL_EXPR_DECL_EXPR (complit); tree decl = DECL_EXPR_DECL (decl_s); tree init = DECL_INITIAL (decl); /* struct T x = (struct T) { 0, 1, 2 } can be optimized into struct T x = { 0, 1, 2 } if the address of the compound literal has never been taken. */ if (!TREE_ADDRESSABLE (complit) && !TREE_ADDRESSABLE (decl) && init) { *expr_p = copy_node (*expr_p); TREE_OPERAND (*expr_p, 1) = init; return GS_OK; } } default: break; } } while (changed); return ret; } /* Promote partial stores to COMPLEX variables to total stores. *EXPR_P is a MODIFY_EXPR with a lhs of a REAL/IMAGPART_EXPR of a variable with DECL_GIMPLE_REG_P set. IMPORTANT NOTE: This promotion is performed by introducing a load of the other, unmodified part of the complex object just before the total store. As a consequence, if the object is still uninitialized, an undefined value will be loaded into a register, which may result in a spurious exception if the register is floating-point and the value happens to be a signaling NaN for example. Then the fully-fledged complex operations lowering pass followed by a DCE pass are necessary in order to fix things up. */ static enum gimplify_status gimplify_modify_expr_complex_part (tree *expr_p, gimple_seq *pre_p, bool want_value) { enum tree_code code, ocode; tree lhs, rhs, new_rhs, other, realpart, imagpart; lhs = TREE_OPERAND (*expr_p, 0); rhs = TREE_OPERAND (*expr_p, 1); code = TREE_CODE (lhs); lhs = TREE_OPERAND (lhs, 0); ocode = code == REALPART_EXPR ? IMAGPART_EXPR : REALPART_EXPR; other = build1 (ocode, TREE_TYPE (rhs), lhs); other = get_formal_tmp_var (other, pre_p); realpart = code == REALPART_EXPR ? rhs : other; imagpart = code == REALPART_EXPR ? other : rhs; if (TREE_CONSTANT (realpart) && TREE_CONSTANT (imagpart)) new_rhs = build_complex (TREE_TYPE (lhs), realpart, imagpart); else new_rhs = build2 (COMPLEX_EXPR, TREE_TYPE (lhs), realpart, imagpart); gimplify_seq_add_stmt (pre_p, gimple_build_assign (lhs, new_rhs)); *expr_p = (want_value) ? rhs : NULL_TREE; return GS_ALL_DONE; } /* Gimplify the MODIFY_EXPR node pointed to by EXPR_P. modify_expr : varname '=' rhs | '*' ID '=' rhs PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. POST_P points to the list where side effects that must happen after *EXPR_P should be stored. WANT_VALUE is nonzero iff we want to use the value of this expression in another expression. */ static enum gimplify_status gimplify_modify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool want_value) { tree *from_p = &TREE_OPERAND (*expr_p, 1); tree *to_p = &TREE_OPERAND (*expr_p, 0); enum gimplify_status ret = GS_UNHANDLED; gimple assign; location_t loc = EXPR_LOCATION (*expr_p); gcc_assert (TREE_CODE (*expr_p) == MODIFY_EXPR || TREE_CODE (*expr_p) == INIT_EXPR); /* Insert pointer conversions required by the middle-end that are not required by the frontend. This fixes middle-end type checking for for example gcc.dg/redecl-6.c. */ if (POINTER_TYPE_P (TREE_TYPE (*to_p))) { STRIP_USELESS_TYPE_CONVERSION (*from_p); if (!useless_type_conversion_p (TREE_TYPE (*to_p), TREE_TYPE (*from_p))) *from_p = fold_convert_loc (loc, TREE_TYPE (*to_p), *from_p); } /* See if any simplifications can be done based on what the RHS is. */ ret = gimplify_modify_expr_rhs (expr_p, from_p, to_p, pre_p, post_p, want_value); if (ret != GS_UNHANDLED) return ret; /* For zero sized types only gimplify the left hand side and right hand side as statements and throw away the assignment. Do this after gimplify_modify_expr_rhs so we handle TARGET_EXPRs of addressable types properly. */ if (zero_sized_type (TREE_TYPE (*from_p)) && !want_value) { gimplify_stmt (from_p, pre_p); gimplify_stmt (to_p, pre_p); *expr_p = NULL_TREE; return GS_ALL_DONE; } /* If the value being copied is of variable width, compute the length of the copy into a WITH_SIZE_EXPR. Note that we need to do this before gimplifying any of the operands so that we can resolve any PLACEHOLDER_EXPRs in the size. Also note that the RTL expander uses the size of the expression to be copied, not of the destination, so that is what we must do here. */ maybe_with_size_expr (from_p); ret = gimplify_expr (to_p, pre_p, post_p, is_gimple_lvalue, fb_lvalue); if (ret == GS_ERROR) return ret; /* As a special case, we have to temporarily allow for assignments with a CALL_EXPR on the RHS. Since in GIMPLE a function call is a toplevel statement, when gimplifying the GENERIC expression MODIFY_EXPR <a, CALL_EXPR <foo>>, we cannot create the tuple GIMPLE_ASSIGN <a, GIMPLE_CALL <foo>>. Instead, we need to create the tuple GIMPLE_CALL <a, foo>. To prevent gimplify_expr from trying to create a new temporary for foo's LHS, we tell it that it should only gimplify until it reaches the CALL_EXPR. On return from gimplify_expr, the newly created GIMPLE_CALL <foo> will be the last statement in *PRE_P and all we need to do here is set 'a' to be its LHS. */ ret = gimplify_expr (from_p, pre_p, post_p, rhs_predicate_for (*to_p), fb_rvalue); if (ret == GS_ERROR) return ret; /* Now see if the above changed *from_p to something we handle specially. */ ret = gimplify_modify_expr_rhs (expr_p, from_p, to_p, pre_p, post_p, want_value); if (ret != GS_UNHANDLED) return ret; /* If we've got a variable sized assignment between two lvalues (i.e. does not involve a call), then we can make things a bit more straightforward by converting the assignment to memcpy or memset. */ if (TREE_CODE (*from_p) == WITH_SIZE_EXPR) { tree from = TREE_OPERAND (*from_p, 0); tree size = TREE_OPERAND (*from_p, 1); if (TREE_CODE (from) == CONSTRUCTOR) return gimplify_modify_expr_to_memset (expr_p, size, want_value, pre_p); if (is_gimple_addressable (from)) { *from_p = from; return gimplify_modify_expr_to_memcpy (expr_p, size, want_value, pre_p); } } /* Transform partial stores to non-addressable complex variables into total stores. This allows us to use real instead of virtual operands for these variables, which improves optimization. */ if ((TREE_CODE (*to_p) == REALPART_EXPR || TREE_CODE (*to_p) == IMAGPART_EXPR) && is_gimple_reg (TREE_OPERAND (*to_p, 0))) return gimplify_modify_expr_complex_part (expr_p, pre_p, want_value); /* Try to alleviate the effects of the gimplification creating artificial temporaries (see for example is_gimple_reg_rhs) on the debug info. */ if (!gimplify_ctxp->into_ssa && DECL_P (*from_p) && DECL_IGNORED_P (*from_p) && DECL_P (*to_p) && !DECL_IGNORED_P (*to_p)) { if (!DECL_NAME (*from_p) && DECL_NAME (*to_p)) DECL_NAME (*from_p) = create_tmp_var_name (IDENTIFIER_POINTER (DECL_NAME (*to_p))); DECL_DEBUG_EXPR_IS_FROM (*from_p) = 1; SET_DECL_DEBUG_EXPR (*from_p, *to_p); } if (TREE_CODE (*from_p) == CALL_EXPR) { /* Since the RHS is a CALL_EXPR, we need to create a GIMPLE_CALL instead of a GIMPLE_ASSIGN. */ assign = gimple_build_call_from_tree (*from_p); if (!gimple_call_noreturn_p (assign)) gimple_call_set_lhs (assign, *to_p); } else { assign = gimple_build_assign (*to_p, *from_p); gimple_set_location (assign, EXPR_LOCATION (*expr_p)); } gimplify_seq_add_stmt (pre_p, assign); if (gimplify_ctxp->into_ssa && is_gimple_reg (*to_p)) { /* If we've somehow already got an SSA_NAME on the LHS, then we've probably modified it twice. Not good. */ gcc_assert (TREE_CODE (*to_p) != SSA_NAME); *to_p = make_ssa_name (*to_p, assign); gimple_set_lhs (assign, *to_p); } if (want_value) { *expr_p = unshare_expr (*to_p); return GS_OK; } else *expr_p = NULL; return GS_ALL_DONE; } /* Gimplify a comparison between two variable-sized objects. Do this with a call to BUILT_IN_MEMCMP. */ static enum gimplify_status gimplify_variable_sized_compare (tree *expr_p) { tree op0 = TREE_OPERAND (*expr_p, 0); tree op1 = TREE_OPERAND (*expr_p, 1); tree t, arg, dest, src; location_t loc = EXPR_LOCATION (*expr_p); arg = TYPE_SIZE_UNIT (TREE_TYPE (op0)); arg = unshare_expr (arg); arg = SUBSTITUTE_PLACEHOLDER_IN_EXPR (arg, op0); src = build_fold_addr_expr_loc (loc, op1); dest = build_fold_addr_expr_loc (loc, op0); t = implicit_built_in_decls[BUILT_IN_MEMCMP]; t = build_call_expr_loc (loc, t, 3, dest, src, arg); *expr_p = build2 (TREE_CODE (*expr_p), TREE_TYPE (*expr_p), t, integer_zero_node); return GS_OK; } /* Gimplify a comparison between two aggregate objects of integral scalar mode as a comparison between the bitwise equivalent scalar values. */ static enum gimplify_status gimplify_scalar_mode_aggregate_compare (tree *expr_p) { location_t loc = EXPR_LOCATION (*expr_p); tree op0 = TREE_OPERAND (*expr_p, 0); tree op1 = TREE_OPERAND (*expr_p, 1); tree type = TREE_TYPE (op0); tree scalar_type = lang_hooks.types.type_for_mode (TYPE_MODE (type), 1); op0 = fold_build1_loc (loc, VIEW_CONVERT_EXPR, scalar_type, op0); op1 = fold_build1_loc (loc, VIEW_CONVERT_EXPR, scalar_type, op1); *expr_p = fold_build2_loc (loc, TREE_CODE (*expr_p), TREE_TYPE (*expr_p), op0, op1); return GS_OK; } /* Gimplify TRUTH_ANDIF_EXPR and TRUTH_ORIF_EXPR expressions. EXPR_P points to the expression to gimplify. Expressions of the form 'a && b' are gimplified to: a && b ? true : false LOCUS is the source location to be put on the generated COND_EXPR. gimplify_cond_expr will do the rest. */ static enum gimplify_status gimplify_boolean_expr (tree *expr_p, location_t locus) { /* Preserve the original type of the expression. */ tree type = TREE_TYPE (*expr_p); *expr_p = build3 (COND_EXPR, type, *expr_p, fold_convert_loc (locus, type, boolean_true_node), fold_convert_loc (locus, type, boolean_false_node)); SET_EXPR_LOCATION (*expr_p, locus); return GS_OK; } /* Gimplifies an expression sequence. This function gimplifies each expression and re-writes the original expression with the last expression of the sequence in GIMPLE form. PRE_P points to the list where the side effects for all the expressions in the sequence will be emitted. WANT_VALUE is true when the result of the last COMPOUND_EXPR is used. */ static enum gimplify_status gimplify_compound_expr (tree *expr_p, gimple_seq *pre_p, bool want_value) { tree t = *expr_p; do { tree *sub_p = &TREE_OPERAND (t, 0); if (TREE_CODE (*sub_p) == COMPOUND_EXPR) gimplify_compound_expr (sub_p, pre_p, false); else gimplify_stmt (sub_p, pre_p); t = TREE_OPERAND (t, 1); } while (TREE_CODE (t) == COMPOUND_EXPR); *expr_p = t; if (want_value) return GS_OK; else { gimplify_stmt (expr_p, pre_p); return GS_ALL_DONE; } } /* Gimplify a SAVE_EXPR node. EXPR_P points to the expression to gimplify. After gimplification, EXPR_P will point to a new temporary that holds the original value of the SAVE_EXPR node. PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. */ static enum gimplify_status gimplify_save_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { enum gimplify_status ret = GS_ALL_DONE; tree val; gcc_assert (TREE_CODE (*expr_p) == SAVE_EXPR); val = TREE_OPERAND (*expr_p, 0); /* If the SAVE_EXPR has not been resolved, then evaluate it once. */ if (!SAVE_EXPR_RESOLVED_P (*expr_p)) { /* The operand may be a void-valued expression such as SAVE_EXPRs generated by the Java frontend for class initialization. It is being executed only for its side-effects. */ if (TREE_TYPE (val) == void_type_node) { ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_stmt, fb_none); val = NULL; } else val = get_initialized_tmp_var (val, pre_p, post_p); TREE_OPERAND (*expr_p, 0) = val; SAVE_EXPR_RESOLVED_P (*expr_p) = 1; } *expr_p = val; return ret; } /* Re-write the ADDR_EXPR node pointed to by EXPR_P unary_expr : ... | '&' varname ... PRE_P points to the list where side effects that must happen before *EXPR_P should be stored. POST_P points to the list where side effects that must happen after *EXPR_P should be stored. */ static enum gimplify_status gimplify_addr_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { tree expr = *expr_p; tree op0 = TREE_OPERAND (expr, 0); enum gimplify_status ret; location_t loc = EXPR_LOCATION (*expr_p); switch (TREE_CODE (op0)) { case INDIRECT_REF: case MISALIGNED_INDIRECT_REF: do_indirect_ref: /* Check if we are dealing with an expression of the form '&*ptr'. While the front end folds away '&*ptr' into 'ptr', these expressions may be generated internally by the compiler (e.g., builtins like __builtin_va_end). */ /* Caution: the silent array decomposition semantics we allow for ADDR_EXPR means we can't always discard the pair. */ /* Gimplification of the ADDR_EXPR operand may drop cv-qualification conversions, so make sure we add them if needed. */ { tree op00 = TREE_OPERAND (op0, 0); tree t_expr = TREE_TYPE (expr); tree t_op00 = TREE_TYPE (op00); if (!useless_type_conversion_p (t_expr, t_op00)) op00 = fold_convert_loc (loc, TREE_TYPE (expr), op00); *expr_p = op00; ret = GS_OK; } break; case VIEW_CONVERT_EXPR: /* Take the address of our operand and then convert it to the type of this ADDR_EXPR. ??? The interactions of VIEW_CONVERT_EXPR and aliasing is not at all clear. The impact of this transformation is even less clear. */ /* If the operand is a useless conversion, look through it. Doing so guarantees that the ADDR_EXPR and its operand will remain of the same type. */ if (tree_ssa_useless_type_conversion (TREE_OPERAND (op0, 0))) op0 = TREE_OPERAND (op0, 0); *expr_p = fold_convert_loc (loc, TREE_TYPE (expr), build_fold_addr_expr_loc (loc, TREE_OPERAND (op0, 0))); ret = GS_OK; break; default: /* We use fb_either here because the C frontend sometimes takes the address of a call that returns a struct; see gcc.dg/c99-array-lval-1.c. The gimplifier will correctly make the implied temporary explicit. */ /* Make the operand addressable. */ ret = gimplify_expr (&TREE_OPERAND (expr, 0), pre_p, post_p, is_gimple_addressable, fb_either); if (ret == GS_ERROR) break; /* Then mark it. Beware that it may not be possible to do so directly if a temporary has been created by the gimplification. */ prepare_gimple_addressable (&TREE_OPERAND (expr, 0), pre_p); op0 = TREE_OPERAND (expr, 0); /* For various reasons, the gimplification of the expression may have made a new INDIRECT_REF. */ if (TREE_CODE (op0) == INDIRECT_REF) goto do_indirect_ref; mark_addressable (TREE_OPERAND (expr, 0)); /* The FEs may end up building ADDR_EXPRs early on a decl with an incomplete type. Re-build ADDR_EXPRs in canonical form here. */ if (!types_compatible_p (TREE_TYPE (op0), TREE_TYPE (TREE_TYPE (expr)))) *expr_p = build_fold_addr_expr (op0); /* Make sure TREE_CONSTANT and TREE_SIDE_EFFECTS are set properly. */ recompute_tree_invariant_for_addr_expr (*expr_p); /* If we re-built the ADDR_EXPR add a conversion to the original type if required. */ if (!useless_type_conversion_p (TREE_TYPE (expr), TREE_TYPE (*expr_p))) *expr_p = fold_convert (TREE_TYPE (expr), *expr_p); break; } return ret; } /* Gimplify the operands of an ASM_EXPR. Input operands should be a gimple value; output operands should be a gimple lvalue. */ static enum gimplify_status gimplify_asm_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { tree expr; int noutputs; const char **oconstraints; int i; tree link; const char *constraint; bool allows_mem, allows_reg, is_inout; enum gimplify_status ret, tret; gimple stmt; VEC(tree, gc) *inputs; VEC(tree, gc) *outputs; VEC(tree, gc) *clobbers; VEC(tree, gc) *labels; tree link_next; expr = *expr_p; noutputs = list_length (ASM_OUTPUTS (expr)); oconstraints = (const char **) alloca ((noutputs) * sizeof (const char *)); inputs = outputs = clobbers = labels = NULL; ret = GS_ALL_DONE; link_next = NULL_TREE; for (i = 0, link = ASM_OUTPUTS (expr); link; ++i, link = link_next) { bool ok; size_t constraint_len; link_next = TREE_CHAIN (link); oconstraints[i] = constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link))); constraint_len = strlen (constraint); if (constraint_len == 0) continue; ok = parse_output_constraint (&constraint, i, 0, 0, &allows_mem, &allows_reg, &is_inout); if (!ok) { ret = GS_ERROR; is_inout = false; } if (!allows_reg && allows_mem) mark_addressable (TREE_VALUE (link)); tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p, is_inout ? is_gimple_min_lval : is_gimple_lvalue, fb_lvalue | fb_mayfail); if (tret == GS_ERROR) { error ("invalid lvalue in asm output %d", i); ret = tret; } VEC_safe_push (tree, gc, outputs, link); TREE_CHAIN (link) = NULL_TREE; if (is_inout) { /* An input/output operand. To give the optimizers more flexibility, split it into separate input and output operands. */ tree input; char buf[10]; /* Turn the in/out constraint into an output constraint. */ char *p = xstrdup (constraint); p[0] = '='; TREE_VALUE (TREE_PURPOSE (link)) = build_string (constraint_len, p); /* And add a matching input constraint. */ if (allows_reg) { sprintf (buf, "%d", i); /* If there are multiple alternatives in the constraint, handle each of them individually. Those that allow register will be replaced with operand number, the others will stay unchanged. */ if (strchr (p, ',') != NULL) { size_t len = 0, buflen = strlen (buf); char *beg, *end, *str, *dst; for (beg = p + 1;;) { end = strchr (beg, ','); if (end == NULL) end = strchr (beg, '\0'); if ((size_t) (end - beg) < buflen) len += buflen + 1; else len += end - beg + 1; if (*end) beg = end + 1; else break; } str = (char *) alloca (len); for (beg = p + 1, dst = str;;) { const char *tem; bool mem_p, reg_p, inout_p; end = strchr (beg, ','); if (end) *end = '\0'; beg[-1] = '='; tem = beg - 1; parse_output_constraint (&tem, i, 0, 0, &mem_p, &reg_p, &inout_p); if (dst != str) *dst++ = ','; if (reg_p) { memcpy (dst, buf, buflen); dst += buflen; } else { if (end) len = end - beg; else len = strlen (beg); memcpy (dst, beg, len); dst += len; } if (end) beg = end + 1; else break; } *dst = '\0'; input = build_string (dst - str, str); } else input = build_string (strlen (buf), buf); } else input = build_string (constraint_len - 1, constraint + 1); free (p); input = build_tree_list (build_tree_list (NULL_TREE, input), unshare_expr (TREE_VALUE (link))); ASM_INPUTS (expr) = chainon (ASM_INPUTS (expr), input); } } link_next = NULL_TREE; for (link = ASM_INPUTS (expr); link; ++i, link = link_next) { link_next = TREE_CHAIN (link); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link))); parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints, &allows_mem, &allows_reg); /* If we can't make copies, we can only accept memory. */ if (TREE_ADDRESSABLE (TREE_TYPE (TREE_VALUE (link)))) { if (allows_mem) allows_reg = 0; else { error ("impossible constraint in %<asm%>"); error ("non-memory input %d must stay in memory", i); return GS_ERROR; } } /* If the operand is a memory input, it should be an lvalue. */ if (!allows_reg && allows_mem) { tree inputv = TREE_VALUE (link); STRIP_NOPS (inputv); if (TREE_CODE (inputv) == PREDECREMENT_EXPR || TREE_CODE (inputv) == PREINCREMENT_EXPR || TREE_CODE (inputv) == POSTDECREMENT_EXPR || TREE_CODE (inputv) == POSTINCREMENT_EXPR) TREE_VALUE (link) = error_mark_node; tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p, is_gimple_lvalue, fb_lvalue | fb_mayfail); mark_addressable (TREE_VALUE (link)); if (tret == GS_ERROR) { if (EXPR_HAS_LOCATION (TREE_VALUE (link))) input_location = EXPR_LOCATION (TREE_VALUE (link)); error ("memory input %d is not directly addressable", i); ret = tret; } } else { tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p, is_gimple_asm_val, fb_rvalue); if (tret == GS_ERROR) ret = tret; } TREE_CHAIN (link) = NULL_TREE; VEC_safe_push (tree, gc, inputs, link); } for (link = ASM_CLOBBERS (expr); link; ++i, link = TREE_CHAIN (link)) VEC_safe_push (tree, gc, clobbers, link); for (link = ASM_LABELS (expr); link; ++i, link = TREE_CHAIN (link)) VEC_safe_push (tree, gc, labels, link); /* Do not add ASMs with errors to the gimple IL stream. */ if (ret != GS_ERROR) { stmt = gimple_build_asm_vec (TREE_STRING_POINTER (ASM_STRING (expr)), inputs, outputs, clobbers, labels); gimple_asm_set_volatile (stmt, ASM_VOLATILE_P (expr)); gimple_asm_set_input (stmt, ASM_INPUT_P (expr)); gimplify_seq_add_stmt (pre_p, stmt); } return ret; } /* Gimplify a CLEANUP_POINT_EXPR. Currently this works by adding GIMPLE_WITH_CLEANUP_EXPRs to the prequeue as we encounter cleanups while gimplifying the body, and converting them to TRY_FINALLY_EXPRs when we return to this function. FIXME should we complexify the prequeue handling instead? Or use flags for all the cleanups and let the optimizer tighten them up? The current code seems pretty fragile; it will break on a cleanup within any non-conditional nesting. But any such nesting would be broken, anyway; we can't write a TRY_FINALLY_EXPR that starts inside a nesting construct and continues out of it. We can do that at the RTL level, though, so having an optimizer to tighten up try/finally regions would be a Good Thing. */ static enum gimplify_status gimplify_cleanup_point_expr (tree *expr_p, gimple_seq *pre_p) { gimple_stmt_iterator iter; gimple_seq body_sequence = NULL; tree temp = voidify_wrapper_expr (*expr_p, NULL); /* We only care about the number of conditions between the innermost CLEANUP_POINT_EXPR and the cleanup. So save and reset the count and any cleanups collected outside the CLEANUP_POINT_EXPR. */ int old_conds = gimplify_ctxp->conditions; gimple_seq old_cleanups = gimplify_ctxp->conditional_cleanups; gimplify_ctxp->conditions = 0; gimplify_ctxp->conditional_cleanups = NULL; gimplify_stmt (&TREE_OPERAND (*expr_p, 0), &body_sequence); gimplify_ctxp->conditions = old_conds; gimplify_ctxp->conditional_cleanups = old_cleanups; for (iter = gsi_start (body_sequence); !gsi_end_p (iter); ) { gimple wce = gsi_stmt (iter); if (gimple_code (wce) == GIMPLE_WITH_CLEANUP_EXPR) { if (gsi_one_before_end_p (iter)) { /* Note that gsi_insert_seq_before and gsi_remove do not scan operands, unlike some other sequence mutators. */ gsi_insert_seq_before_without_update (&iter, gimple_wce_cleanup (wce), GSI_SAME_STMT); gsi_remove (&iter, true); break; } else { gimple gtry; gimple_seq seq; enum gimple_try_flags kind; if (gimple_wce_cleanup_eh_only (wce)) kind = GIMPLE_TRY_CATCH; else kind = GIMPLE_TRY_FINALLY; seq = gsi_split_seq_after (iter); gtry = gimple_build_try (seq, gimple_wce_cleanup (wce), kind); /* Do not use gsi_replace here, as it may scan operands. We want to do a simple structural modification only. */ *gsi_stmt_ptr (&iter) = gtry; iter = gsi_start (seq); } } else gsi_next (&iter); } gimplify_seq_add_seq (pre_p, body_sequence); if (temp) { *expr_p = temp; return GS_OK; } else { *expr_p = NULL; return GS_ALL_DONE; } } /* Insert a cleanup marker for gimplify_cleanup_point_expr. CLEANUP is the cleanup action required. EH_ONLY is true if the cleanup should only be executed if an exception is thrown, not on normal exit. */ static void gimple_push_cleanup (tree var, tree cleanup, bool eh_only, gimple_seq *pre_p) { gimple wce; gimple_seq cleanup_stmts = NULL; /* Errors can result in improperly nested cleanups. Which results in confusion when trying to resolve the GIMPLE_WITH_CLEANUP_EXPR. */ if (errorcount || sorrycount) return; if (gimple_conditional_context ()) { /* If we're in a conditional context, this is more complex. We only want to run the cleanup if we actually ran the initialization that necessitates it, but we want to run it after the end of the conditional context. So we wrap the try/finally around the condition and use a flag to determine whether or not to actually run the destructor. Thus test ? f(A()) : 0 becomes (approximately) flag = 0; try { if (test) { A::A(temp); flag = 1; val = f(temp); } else { val = 0; } } finally { if (flag) A::~A(temp); } val */ tree flag = create_tmp_var (boolean_type_node, "cleanup"); gimple ffalse = gimple_build_assign (flag, boolean_false_node); gimple ftrue = gimple_build_assign (flag, boolean_true_node); cleanup = build3 (COND_EXPR, void_type_node, flag, cleanup, NULL); gimplify_stmt (&cleanup, &cleanup_stmts); wce = gimple_build_wce (cleanup_stmts); gimplify_seq_add_stmt (&gimplify_ctxp->conditional_cleanups, ffalse); gimplify_seq_add_stmt (&gimplify_ctxp->conditional_cleanups, wce); gimplify_seq_add_stmt (pre_p, ftrue); /* Because of this manipulation, and the EH edges that jump threading cannot redirect, the temporary (VAR) will appear to be used uninitialized. Don't warn. */ TREE_NO_WARNING (var) = 1; } else { gimplify_stmt (&cleanup, &cleanup_stmts); wce = gimple_build_wce (cleanup_stmts); gimple_wce_set_cleanup_eh_only (wce, eh_only); gimplify_seq_add_stmt (pre_p, wce); } } /* Gimplify a TARGET_EXPR which doesn't appear on the rhs of an INIT_EXPR. */ static enum gimplify_status gimplify_target_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p) { tree targ = *expr_p; tree temp = TARGET_EXPR_SLOT (targ); tree init = TARGET_EXPR_INITIAL (targ); enum gimplify_status ret; if (init) { /* TARGET_EXPR temps aren't part of the enclosing block, so add it to the temps list. Handle also variable length TARGET_EXPRs. */ if (TREE_CODE (DECL_SIZE (temp)) != INTEGER_CST) { if (!TYPE_SIZES_GIMPLIFIED (TREE_TYPE (temp))) gimplify_type_sizes (TREE_TYPE (temp), pre_p); gimplify_vla_decl (temp, pre_p); } else gimple_add_tmp_var (temp); /* If TARGET_EXPR_INITIAL is void, then the mere evaluation of the expression is supposed to initialize the slot. */ if (VOID_TYPE_P (TREE_TYPE (init))) ret = gimplify_expr (&init, pre_p, post_p, is_gimple_stmt, fb_none); else { tree init_expr = build2 (INIT_EXPR, void_type_node, temp, init); init = init_expr; ret = gimplify_expr (&init, pre_p, post_p, is_gimple_stmt, fb_none); init = NULL; ggc_free (init_expr); } if (ret == GS_ERROR) { /* PR c++/28266 Make sure this is expanded only once. */ TARGET_EXPR_INITIAL (targ) = NULL_TREE; return GS_ERROR; } if (init) gimplify_and_add (init, pre_p); /* If needed, push the cleanup for the temp. */ if (TARGET_EXPR_CLEANUP (targ)) gimple_push_cleanup (temp, TARGET_EXPR_CLEANUP (targ), CLEANUP_EH_ONLY (targ), pre_p); /* Only expand this once. */ TREE_OPERAND (targ, 3) = init; TARGET_EXPR_INITIAL (targ) = NULL_TREE; } else /* We should have expanded this before. */ gcc_assert (DECL_SEEN_IN_BIND_EXPR_P (temp)); *expr_p = temp; return GS_OK; } /* Gimplification of expression trees. */ /* Gimplify an expression which appears at statement context. The corresponding GIMPLE statements are added to *SEQ_P. If *SEQ_P is NULL, a new sequence is allocated. Return true if we actually added a statement to the queue. */ bool gimplify_stmt (tree *stmt_p, gimple_seq *seq_p) { gimple_seq_node last; if (!*seq_p) *seq_p = gimple_seq_alloc (); last = gimple_seq_last (*seq_p); gimplify_expr (stmt_p, seq_p, NULL, is_gimple_stmt, fb_none); return last != gimple_seq_last (*seq_p); } /* Add FIRSTPRIVATE entries for DECL in the OpenMP the surrounding parallels to CTX. If entries already exist, force them to be some flavor of private. If there is no enclosing parallel, do nothing. */ void omp_firstprivatize_variable (struct gimplify_omp_ctx *ctx, tree decl) { splay_tree_node n; if (decl == NULL || !DECL_P (decl)) return; do { n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n != NULL) { if (n->value & GOVD_SHARED) n->value = GOVD_FIRSTPRIVATE | (n->value & GOVD_SEEN); else return; } else if (ctx->region_type != ORT_WORKSHARE) omp_add_variable (ctx, decl, GOVD_FIRSTPRIVATE); ctx = ctx->outer_context; } while (ctx); } /* Similarly for each of the type sizes of TYPE. */ static void omp_firstprivatize_type_sizes (struct gimplify_omp_ctx *ctx, tree type) { if (type == NULL || type == error_mark_node) return; type = TYPE_MAIN_VARIANT (type); if (pointer_set_insert (ctx->privatized_types, type)) return; switch (TREE_CODE (type)) { case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE: case REAL_TYPE: case FIXED_POINT_TYPE: omp_firstprivatize_variable (ctx, TYPE_MIN_VALUE (type)); omp_firstprivatize_variable (ctx, TYPE_MAX_VALUE (type)); break; case ARRAY_TYPE: omp_firstprivatize_type_sizes (ctx, TREE_TYPE (type)); omp_firstprivatize_type_sizes (ctx, TYPE_DOMAIN (type)); break; case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: { tree field; for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field)) if (TREE_CODE (field) == FIELD_DECL) { omp_firstprivatize_variable (ctx, DECL_FIELD_OFFSET (field)); omp_firstprivatize_type_sizes (ctx, TREE_TYPE (field)); } } break; case POINTER_TYPE: case REFERENCE_TYPE: omp_firstprivatize_type_sizes (ctx, TREE_TYPE (type)); break; default: break; } omp_firstprivatize_variable (ctx, TYPE_SIZE (type)); omp_firstprivatize_variable (ctx, TYPE_SIZE_UNIT (type)); lang_hooks.types.omp_firstprivatize_type_sizes (ctx, type); } /* Add an entry for DECL in the OpenMP context CTX with FLAGS. */ static void omp_add_variable (struct gimplify_omp_ctx *ctx, tree decl, unsigned int flags) { splay_tree_node n; unsigned int nflags; tree t; if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) return; /* Never elide decls whose type has TREE_ADDRESSABLE set. This means there are constructors involved somewhere. */ if (TREE_ADDRESSABLE (TREE_TYPE (decl)) || TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl))) flags |= GOVD_SEEN; n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n != NULL) { /* We shouldn't be re-adding the decl with the same data sharing class. */ gcc_assert ((n->value & GOVD_DATA_SHARE_CLASS & flags) == 0); /* The only combination of data sharing classes we should see is FIRSTPRIVATE and LASTPRIVATE. */ nflags = n->value | flags; gcc_assert ((nflags & GOVD_DATA_SHARE_CLASS) == (GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE)); n->value = nflags; return; } /* When adding a variable-sized variable, we have to handle all sorts of additional bits of data: the pointer replacement variable, and the parameters of the type. */ if (DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { /* Add the pointer replacement variable as PRIVATE if the variable replacement is private, else FIRSTPRIVATE since we'll need the address of the original variable either for SHARED, or for the copy into or out of the context. */ if (!(flags & GOVD_LOCAL)) { nflags = flags & GOVD_PRIVATE ? GOVD_PRIVATE : GOVD_FIRSTPRIVATE; nflags |= flags & GOVD_SEEN; t = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (t) == INDIRECT_REF); t = TREE_OPERAND (t, 0); gcc_assert (DECL_P (t)); omp_add_variable (ctx, t, nflags); } /* Add all of the variable and type parameters (which should have been gimplified to a formal temporary) as FIRSTPRIVATE. */ omp_firstprivatize_variable (ctx, DECL_SIZE_UNIT (decl)); omp_firstprivatize_variable (ctx, DECL_SIZE (decl)); omp_firstprivatize_type_sizes (ctx, TREE_TYPE (decl)); /* The variable-sized variable itself is never SHARED, only some form of PRIVATE. The sharing would take place via the pointer variable which we remapped above. */ if (flags & GOVD_SHARED) flags = GOVD_PRIVATE | GOVD_DEBUG_PRIVATE | (flags & (GOVD_SEEN | GOVD_EXPLICIT)); /* We're going to make use of the TYPE_SIZE_UNIT at least in the alloca statement we generate for the variable, so make sure it is available. This isn't automatically needed for the SHARED case, since we won't be allocating local storage then. For local variables TYPE_SIZE_UNIT might not be gimplified yet, in this case omp_notice_variable will be called later on when it is gimplified. */ else if (! (flags & GOVD_LOCAL)) omp_notice_variable (ctx, TYPE_SIZE_UNIT (TREE_TYPE (decl)), true); } else if (lang_hooks.decls.omp_privatize_by_reference (decl)) { gcc_assert ((flags & GOVD_LOCAL) == 0); omp_firstprivatize_type_sizes (ctx, TREE_TYPE (decl)); /* Similar to the direct variable sized case above, we'll need the size of references being privatized. */ if ((flags & GOVD_SHARED) == 0) { t = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (decl))); if (TREE_CODE (t) != INTEGER_CST) omp_notice_variable (ctx, t, true); } } splay_tree_insert (ctx->variables, (splay_tree_key)decl, flags); } /* Notice a threadprivate variable DECL used in OpenMP context CTX. This just prints out diagnostics about threadprivate variable uses in untied tasks. If DECL2 is non-NULL, prevent this warning on that variable. */ static bool omp_notice_threadprivate_variable (struct gimplify_omp_ctx *ctx, tree decl, tree decl2) { splay_tree_node n; if (ctx->region_type != ORT_UNTIED_TASK) return false; n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n == NULL) { error ("threadprivate variable %qE used in untied task", DECL_NAME (decl)); error_at (ctx->location, "enclosing task"); splay_tree_insert (ctx->variables, (splay_tree_key)decl, 0); } if (decl2) splay_tree_insert (ctx->variables, (splay_tree_key)decl2, 0); return false; } /* Record the fact that DECL was used within the OpenMP context CTX. IN_CODE is true when real code uses DECL, and false when we should merely emit default(none) errors. Return true if DECL is going to be remapped and thus DECL shouldn't be gimplified into its DECL_VALUE_EXPR (if any). */ static bool omp_notice_variable (struct gimplify_omp_ctx *ctx, tree decl, bool in_code) { splay_tree_node n; unsigned flags = in_code ? GOVD_SEEN : 0; bool ret = false, shared; if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) return false; /* Threadprivate variables are predetermined. */ if (is_global_var (decl)) { if (DECL_THREAD_LOCAL_P (decl)) return omp_notice_threadprivate_variable (ctx, decl, NULL_TREE); if (DECL_HAS_VALUE_EXPR_P (decl)) { tree value = get_base_address (DECL_VALUE_EXPR (decl)); if (value && DECL_P (value) && DECL_THREAD_LOCAL_P (value)) return omp_notice_threadprivate_variable (ctx, decl, value); } } n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n == NULL) { enum omp_clause_default_kind default_kind, kind; struct gimplify_omp_ctx *octx; if (ctx->region_type == ORT_WORKSHARE) goto do_outer; /* ??? Some compiler-generated variables (like SAVE_EXPRs) could be remapped firstprivate instead of shared. To some extent this is addressed in omp_firstprivatize_type_sizes, but not effectively. */ default_kind = ctx->default_kind; kind = lang_hooks.decls.omp_predetermined_sharing (decl); if (kind != OMP_CLAUSE_DEFAULT_UNSPECIFIED) default_kind = kind; switch (default_kind) { case OMP_CLAUSE_DEFAULT_NONE: error ("%qE not specified in enclosing parallel", DECL_NAME (lang_hooks.decls.omp_report_decl (decl))); if ((ctx->region_type & ORT_TASK) != 0) error_at (ctx->location, "enclosing task"); else error_at (ctx->location, "enclosing parallel"); /* FALLTHRU */ case OMP_CLAUSE_DEFAULT_SHARED: flags |= GOVD_SHARED; break; case OMP_CLAUSE_DEFAULT_PRIVATE: flags |= GOVD_PRIVATE; break; case OMP_CLAUSE_DEFAULT_FIRSTPRIVATE: flags |= GOVD_FIRSTPRIVATE; break; case OMP_CLAUSE_DEFAULT_UNSPECIFIED: /* decl will be either GOVD_FIRSTPRIVATE or GOVD_SHARED. */ gcc_assert ((ctx->region_type & ORT_TASK) != 0); if (ctx->outer_context) omp_notice_variable (ctx->outer_context, decl, in_code); for (octx = ctx->outer_context; octx; octx = octx->outer_context) { splay_tree_node n2; n2 = splay_tree_lookup (octx->variables, (splay_tree_key) decl); if (n2 && (n2->value & GOVD_DATA_SHARE_CLASS) != GOVD_SHARED) { flags |= GOVD_FIRSTPRIVATE; break; } if ((octx->region_type & ORT_PARALLEL) != 0) break; } if (flags & GOVD_FIRSTPRIVATE) break; if (octx == NULL && (TREE_CODE (decl) == PARM_DECL || (!is_global_var (decl) && DECL_CONTEXT (decl) == current_function_decl))) { flags |= GOVD_FIRSTPRIVATE; break; } flags |= GOVD_SHARED; break; default: gcc_unreachable (); } if ((flags & GOVD_PRIVATE) && lang_hooks.decls.omp_private_outer_ref (decl)) flags |= GOVD_PRIVATE_OUTER_REF; omp_add_variable (ctx, decl, flags); shared = (flags & GOVD_SHARED) != 0; ret = lang_hooks.decls.omp_disregard_value_expr (decl, shared); goto do_outer; } if ((n->value & (GOVD_SEEN | GOVD_LOCAL)) == 0 && (flags & (GOVD_SEEN | GOVD_LOCAL)) == GOVD_SEEN && DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { splay_tree_node n2; tree t = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (t) == INDIRECT_REF); t = TREE_OPERAND (t, 0); gcc_assert (DECL_P (t)); n2 = splay_tree_lookup (ctx->variables, (splay_tree_key) t); n2->value |= GOVD_SEEN; } shared = ((flags | n->value) & GOVD_SHARED) != 0; ret = lang_hooks.decls.omp_disregard_value_expr (decl, shared); /* If nothing changed, there's nothing left to do. */ if ((n->value & flags) == flags) return ret; flags |= n->value; n->value = flags; do_outer: /* If the variable is private in the current context, then we don't need to propagate anything to an outer context. */ if ((flags & GOVD_PRIVATE) && !(flags & GOVD_PRIVATE_OUTER_REF)) return ret; if (ctx->outer_context && omp_notice_variable (ctx->outer_context, decl, in_code)) return true; return ret; } /* Verify that DECL is private within CTX. If there's specific information to the contrary in the innermost scope, generate an error. */ static bool omp_is_private (struct gimplify_omp_ctx *ctx, tree decl) { splay_tree_node n; n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl); if (n != NULL) { if (n->value & GOVD_SHARED) { if (ctx == gimplify_omp_ctxp) { error ("iteration variable %qE should be private", DECL_NAME (decl)); n->value = GOVD_PRIVATE; return true; } else return false; } else if ((n->value & GOVD_EXPLICIT) != 0 && (ctx == gimplify_omp_ctxp || (ctx->region_type == ORT_COMBINED_PARALLEL && gimplify_omp_ctxp->outer_context == ctx))) { if ((n->value & GOVD_FIRSTPRIVATE) != 0) error ("iteration variable %qE should not be firstprivate", DECL_NAME (decl)); else if ((n->value & GOVD_REDUCTION) != 0) error ("iteration variable %qE should not be reduction", DECL_NAME (decl)); } return (ctx == gimplify_omp_ctxp || (ctx->region_type == ORT_COMBINED_PARALLEL && gimplify_omp_ctxp->outer_context == ctx)); } if (ctx->region_type != ORT_WORKSHARE) return false; else if (ctx->outer_context) return omp_is_private (ctx->outer_context, decl); return false; } /* Return true if DECL is private within a parallel region that binds to the current construct's context or in parallel region's REDUCTION clause. */ static bool omp_check_private (struct gimplify_omp_ctx *ctx, tree decl) { splay_tree_node n; do { ctx = ctx->outer_context; if (ctx == NULL) return !(is_global_var (decl) /* References might be private, but might be shared too. */ || lang_hooks.decls.omp_privatize_by_reference (decl)); n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); if (n != NULL) return (n->value & GOVD_SHARED) == 0; } while (ctx->region_type == ORT_WORKSHARE); return false; } /* Scan the OpenMP clauses in *LIST_P, installing mappings into a new and previous omp contexts. */ static void gimplify_scan_omp_clauses (tree *list_p, gimple_seq *pre_p, enum omp_region_type region_type) { struct gimplify_omp_ctx *ctx, *outer_ctx; struct gimplify_ctx gctx; tree c; ctx = new_omp_context (region_type); outer_ctx = ctx->outer_context; while ((c = *list_p) != NULL) { bool remove = false; bool notice_outer = true; const char *check_non_private = NULL; unsigned int flags; tree decl; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: flags = GOVD_PRIVATE | GOVD_EXPLICIT; if (lang_hooks.decls.omp_private_outer_ref (OMP_CLAUSE_DECL (c))) { flags |= GOVD_PRIVATE_OUTER_REF; OMP_CLAUSE_PRIVATE_OUTER_REF (c) = 1; } else notice_outer = false; goto do_add; case OMP_CLAUSE_SHARED: flags = GOVD_SHARED | GOVD_EXPLICIT; goto do_add; case OMP_CLAUSE_FIRSTPRIVATE: flags = GOVD_FIRSTPRIVATE | GOVD_EXPLICIT; check_non_private = "firstprivate"; goto do_add; case OMP_CLAUSE_LASTPRIVATE: flags = GOVD_LASTPRIVATE | GOVD_SEEN | GOVD_EXPLICIT; check_non_private = "lastprivate"; goto do_add; case OMP_CLAUSE_REDUCTION: flags = GOVD_REDUCTION | GOVD_SEEN | GOVD_EXPLICIT; check_non_private = "reduction"; goto do_add; do_add: decl = OMP_CLAUSE_DECL (c); if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) { remove = true; break; } omp_add_variable (ctx, decl, flags); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { omp_add_variable (ctx, OMP_CLAUSE_REDUCTION_PLACEHOLDER (c), GOVD_LOCAL | GOVD_SEEN); gimplify_omp_ctxp = ctx; push_gimplify_context (&gctx); OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c) = gimple_seq_alloc (); OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = gimple_seq_alloc (); gimplify_and_add (OMP_CLAUSE_REDUCTION_INIT (c), &OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c)); pop_gimplify_context (gimple_seq_first_stmt (OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c))); push_gimplify_context (&gctx); gimplify_and_add (OMP_CLAUSE_REDUCTION_MERGE (c), &OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c)); pop_gimplify_context (gimple_seq_first_stmt (OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c))); OMP_CLAUSE_REDUCTION_INIT (c) = NULL_TREE; OMP_CLAUSE_REDUCTION_MERGE (c) = NULL_TREE; gimplify_omp_ctxp = outer_ctx; } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_STMT (c)) { gimplify_omp_ctxp = ctx; push_gimplify_context (&gctx); if (TREE_CODE (OMP_CLAUSE_LASTPRIVATE_STMT (c)) != BIND_EXPR) { tree bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (bind) = 1; BIND_EXPR_BODY (bind) = OMP_CLAUSE_LASTPRIVATE_STMT (c); OMP_CLAUSE_LASTPRIVATE_STMT (c) = bind; } gimplify_and_add (OMP_CLAUSE_LASTPRIVATE_STMT (c), &OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)); pop_gimplify_context (gimple_seq_first_stmt (OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c))); OMP_CLAUSE_LASTPRIVATE_STMT (c) = NULL_TREE; gimplify_omp_ctxp = outer_ctx; } if (notice_outer) goto do_notice; break; case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_COPYPRIVATE: decl = OMP_CLAUSE_DECL (c); if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node) { remove = true; break; } do_notice: if (outer_ctx) omp_notice_variable (outer_ctx, decl, true); if (check_non_private && region_type == ORT_WORKSHARE && omp_check_private (ctx, decl)) { error ("%s variable %qE is private in outer context", check_non_private, DECL_NAME (decl)); remove = true; } break; case OMP_CLAUSE_IF: OMP_CLAUSE_OPERAND (c, 0) = gimple_boolify (OMP_CLAUSE_OPERAND (c, 0)); /* Fall through. */ case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_NUM_THREADS: if (gimplify_expr (&OMP_CLAUSE_OPERAND (c, 0), pre_p, NULL, is_gimple_val, fb_rvalue) == GS_ERROR) remove = true; break; case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_COLLAPSE: break; case OMP_CLAUSE_DEFAULT: ctx->default_kind = OMP_CLAUSE_DEFAULT_KIND (c); break; default: gcc_unreachable (); } if (remove) *list_p = OMP_CLAUSE_CHAIN (c); else list_p = &OMP_CLAUSE_CHAIN (c); } gimplify_omp_ctxp = ctx; } /* For all variables that were not actually used within the context, remove PRIVATE, SHARED, and FIRSTPRIVATE clauses. */ static int gimplify_adjust_omp_clauses_1 (splay_tree_node n, void *data) { tree *list_p = (tree *) data; tree decl = (tree) n->key; unsigned flags = n->value; enum omp_clause_code code; tree clause; bool private_debug; if (flags & (GOVD_EXPLICIT | GOVD_LOCAL)) return 0; if ((flags & GOVD_SEEN) == 0) return 0; if (flags & GOVD_DEBUG_PRIVATE) { gcc_assert ((flags & GOVD_DATA_SHARE_CLASS) == GOVD_PRIVATE); private_debug = true; } else private_debug = lang_hooks.decls.omp_private_debug_clause (decl, !!(flags & GOVD_SHARED)); if (private_debug) code = OMP_CLAUSE_PRIVATE; else if (flags & GOVD_SHARED) { if (is_global_var (decl)) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp->outer_context; while (ctx != NULL) { splay_tree_node on = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); if (on && (on->value & (GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE | GOVD_PRIVATE | GOVD_REDUCTION)) != 0) break; ctx = ctx->outer_context; } if (ctx == NULL) return 0; } code = OMP_CLAUSE_SHARED; } else if (flags & GOVD_PRIVATE) code = OMP_CLAUSE_PRIVATE; else if (flags & GOVD_FIRSTPRIVATE) code = OMP_CLAUSE_FIRSTPRIVATE; else gcc_unreachable (); clause = build_omp_clause (input_location, code); OMP_CLAUSE_DECL (clause) = decl; OMP_CLAUSE_CHAIN (clause) = *list_p; if (private_debug) OMP_CLAUSE_PRIVATE_DEBUG (clause) = 1; else if (code == OMP_CLAUSE_PRIVATE && (flags & GOVD_PRIVATE_OUTER_REF)) OMP_CLAUSE_PRIVATE_OUTER_REF (clause) = 1; *list_p = clause; lang_hooks.decls.omp_finish_clause (clause); return 0; } static void gimplify_adjust_omp_clauses (tree *list_p) { struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp; tree c, decl; while ((c = *list_p) != NULL) { splay_tree_node n; bool remove = false; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_SHARED: case OMP_CLAUSE_FIRSTPRIVATE: decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); remove = !(n->value & GOVD_SEEN); if (! remove) { bool shared = OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED; if ((n->value & GOVD_DEBUG_PRIVATE) || lang_hooks.decls.omp_private_debug_clause (decl, shared)) { gcc_assert ((n->value & GOVD_DEBUG_PRIVATE) == 0 || ((n->value & GOVD_DATA_SHARE_CLASS) == GOVD_PRIVATE)); OMP_CLAUSE_SET_CODE (c, OMP_CLAUSE_PRIVATE); OMP_CLAUSE_PRIVATE_DEBUG (c) = 1; } } break; case OMP_CLAUSE_LASTPRIVATE: /* Make sure OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE is set to accurately reflect the presence of a FIRSTPRIVATE clause. */ decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl); OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c) = (n->value & GOVD_FIRSTPRIVATE) != 0; break; case OMP_CLAUSE_REDUCTION: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_COPYPRIVATE: case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_COLLAPSE: break; default: gcc_unreachable (); } if (remove) *list_p = OMP_CLAUSE_CHAIN (c); else list_p = &OMP_CLAUSE_CHAIN (c); } /* Add in any implicit data sharing. */ splay_tree_foreach (ctx->variables, gimplify_adjust_omp_clauses_1, list_p); gimplify_omp_ctxp = ctx->outer_context; delete_omp_context (ctx); } /* Gimplify the contents of an OMP_PARALLEL statement. This involves gimplification of the body, as well as scanning the body for used variables. We need to do this scan now, because variable-sized decls will be decomposed during gimplification. */ static void gimplify_omp_parallel (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p; gimple g; gimple_seq body = NULL; struct gimplify_ctx gctx; gimplify_scan_omp_clauses (&OMP_PARALLEL_CLAUSES (expr), pre_p, OMP_PARALLEL_COMBINED (expr) ? ORT_COMBINED_PARALLEL : ORT_PARALLEL); push_gimplify_context (&gctx); g = gimplify_and_return_first (OMP_PARALLEL_BODY (expr), &body); if (gimple_code (g) == GIMPLE_BIND) pop_gimplify_context (g); else pop_gimplify_context (NULL); gimplify_adjust_omp_clauses (&OMP_PARALLEL_CLAUSES (expr)); g = gimple_build_omp_parallel (body, OMP_PARALLEL_CLAUSES (expr), NULL_TREE, NULL_TREE); if (OMP_PARALLEL_COMBINED (expr)) gimple_omp_set_subcode (g, GF_OMP_PARALLEL_COMBINED); gimplify_seq_add_stmt (pre_p, g); *expr_p = NULL_TREE; } /* Gimplify the contents of an OMP_TASK statement. This involves gimplification of the body, as well as scanning the body for used variables. We need to do this scan now, because variable-sized decls will be decomposed during gimplification. */ static void gimplify_omp_task (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p; gimple g; gimple_seq body = NULL; struct gimplify_ctx gctx; gimplify_scan_omp_clauses (&OMP_TASK_CLAUSES (expr), pre_p, find_omp_clause (OMP_TASK_CLAUSES (expr), OMP_CLAUSE_UNTIED) ? ORT_UNTIED_TASK : ORT_TASK); push_gimplify_context (&gctx); g = gimplify_and_return_first (OMP_TASK_BODY (expr), &body); if (gimple_code (g) == GIMPLE_BIND) pop_gimplify_context (g); else pop_gimplify_context (NULL); gimplify_adjust_omp_clauses (&OMP_TASK_CLAUSES (expr)); g = gimple_build_omp_task (body, OMP_TASK_CLAUSES (expr), NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE); gimplify_seq_add_stmt (pre_p, g); *expr_p = NULL_TREE; } /* Gimplify the gross structure of an OMP_FOR statement. */ static enum gimplify_status gimplify_omp_for (tree *expr_p, gimple_seq *pre_p) { tree for_stmt, decl, var, t; enum gimplify_status ret = GS_ALL_DONE; enum gimplify_status tret; gimple gfor; gimple_seq for_body, for_pre_body; int i; for_stmt = *expr_p; gimplify_scan_omp_clauses (&OMP_FOR_CLAUSES (for_stmt), pre_p, ORT_WORKSHARE); /* Handle OMP_FOR_INIT. */ for_pre_body = NULL; gimplify_and_add (OMP_FOR_PRE_BODY (for_stmt), &for_pre_body); OMP_FOR_PRE_BODY (for_stmt) = NULL_TREE; for_body = gimple_seq_alloc (); gcc_assert (TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)) == TREE_VEC_LENGTH (OMP_FOR_COND (for_stmt))); gcc_assert (TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)) == TREE_VEC_LENGTH (OMP_FOR_INCR (for_stmt))); for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); i++) { t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); decl = TREE_OPERAND (t, 0); gcc_assert (DECL_P (decl)); gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (decl)) || POINTER_TYPE_P (TREE_TYPE (decl))); /* Make sure the iteration variable is private. */ if (omp_is_private (gimplify_omp_ctxp, decl)) omp_notice_variable (gimplify_omp_ctxp, decl, true); else omp_add_variable (gimplify_omp_ctxp, decl, GOVD_PRIVATE | GOVD_SEEN); /* If DECL is not a gimple register, create a temporary variable to act as an iteration counter. This is valid, since DECL cannot be modified in the body of the loop. */ if (!is_gimple_reg (decl)) { var = create_tmp_var (TREE_TYPE (decl), get_name (decl)); TREE_OPERAND (t, 0) = var; gimplify_seq_add_stmt (&for_body, gimple_build_assign (decl, var)); omp_add_variable (gimplify_omp_ctxp, var, GOVD_PRIVATE | GOVD_SEEN); } else var = decl; tret = gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); if (ret == GS_ERROR) return ret; /* Handle OMP_FOR_COND. */ t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i); gcc_assert (COMPARISON_CLASS_P (t)); gcc_assert (TREE_OPERAND (t, 0) == decl); tret = gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); /* Handle OMP_FOR_INCR. */ t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i); switch (TREE_CODE (t)) { case PREINCREMENT_EXPR: case POSTINCREMENT_EXPR: t = build_int_cst (TREE_TYPE (decl), 1); t = build2 (PLUS_EXPR, TREE_TYPE (decl), var, t); t = build2 (MODIFY_EXPR, TREE_TYPE (var), var, t); TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i) = t; break; case PREDECREMENT_EXPR: case POSTDECREMENT_EXPR: t = build_int_cst (TREE_TYPE (decl), -1); t = build2 (PLUS_EXPR, TREE_TYPE (decl), var, t); t = build2 (MODIFY_EXPR, TREE_TYPE (var), var, t); TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i) = t; break; case MODIFY_EXPR: gcc_assert (TREE_OPERAND (t, 0) == decl); TREE_OPERAND (t, 0) = var; t = TREE_OPERAND (t, 1); switch (TREE_CODE (t)) { case PLUS_EXPR: if (TREE_OPERAND (t, 1) == decl) { TREE_OPERAND (t, 1) = TREE_OPERAND (t, 0); TREE_OPERAND (t, 0) = var; break; } /* Fallthru. */ case MINUS_EXPR: case POINTER_PLUS_EXPR: gcc_assert (TREE_OPERAND (t, 0) == decl); TREE_OPERAND (t, 0) = var; break; default: gcc_unreachable (); } tret = gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL, is_gimple_val, fb_rvalue); ret = MIN (ret, tret); break; default: gcc_unreachable (); } if (var != decl || TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)) > 1) { tree c; for (c = OMP_FOR_CLAUSES (for_stmt); c ; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_DECL (c) == decl && OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c) == NULL) { t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); gcc_assert (TREE_OPERAND (t, 0) == var); t = TREE_OPERAND (t, 1); gcc_assert (TREE_CODE (t) == PLUS_EXPR || TREE_CODE (t) == MINUS_EXPR || TREE_CODE (t) == POINTER_PLUS_EXPR); gcc_assert (TREE_OPERAND (t, 0) == var); t = build2 (TREE_CODE (t), TREE_TYPE (decl), decl, TREE_OPERAND (t, 1)); gimplify_assign (decl, t, &OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)); } } } gimplify_and_add (OMP_FOR_BODY (for_stmt), &for_body); gimplify_adjust_omp_clauses (&OMP_FOR_CLAUSES (for_stmt)); gfor = gimple_build_omp_for (for_body, OMP_FOR_CLAUSES (for_stmt), TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)), for_pre_body); for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); i++) { t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i); gimple_omp_for_set_index (gfor, i, TREE_OPERAND (t, 0)); gimple_omp_for_set_initial (gfor, i, TREE_OPERAND (t, 1)); t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i); gimple_omp_for_set_cond (gfor, i, TREE_CODE (t)); gimple_omp_for_set_final (gfor, i, TREE_OPERAND (t, 1)); t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i); gimple_omp_for_set_incr (gfor, i, TREE_OPERAND (t, 1)); } gimplify_seq_add_stmt (pre_p, gfor); return ret == GS_ALL_DONE ? GS_ALL_DONE : GS_ERROR; } /* Gimplify the gross structure of other OpenMP worksharing constructs. In particular, OMP_SECTIONS and OMP_SINGLE. */ static void gimplify_omp_workshare (tree *expr_p, gimple_seq *pre_p) { tree expr = *expr_p; gimple stmt; gimple_seq body = NULL; gimplify_scan_omp_clauses (&OMP_CLAUSES (expr), pre_p, ORT_WORKSHARE); gimplify_and_add (OMP_BODY (expr), &body); gimplify_adjust_omp_clauses (&OMP_CLAUSES (expr)); if (TREE_CODE (expr) == OMP_SECTIONS) stmt = gimple_build_omp_sections (body, OMP_CLAUSES (expr)); else if (TREE_CODE (expr) == OMP_SINGLE) stmt = gimple_build_omp_single (body, OMP_CLAUSES (expr)); else gcc_unreachable (); gimplify_seq_add_stmt (pre_p, stmt); } /* A subroutine of gimplify_omp_atomic. The front end is supposed to have stabilized the lhs of the atomic operation as *ADDR. Return true if EXPR is this stabilized form. */ static bool goa_lhs_expr_p (tree expr, tree addr) { /* Also include casts to other type variants. The C front end is fond of adding these for e.g. volatile variables. This is like STRIP_TYPE_NOPS but includes the main variant lookup. */ STRIP_USELESS_TYPE_CONVERSION (expr); if (TREE_CODE (expr) == INDIRECT_REF) { expr = TREE_OPERAND (expr, 0); while (expr != addr && (CONVERT_EXPR_P (expr) || TREE_CODE (expr) == NON_LVALUE_EXPR) && TREE_CODE (expr) == TREE_CODE (addr) && types_compatible_p (TREE_TYPE (expr), TREE_TYPE (addr))) { expr = TREE_OPERAND (expr, 0); addr = TREE_OPERAND (addr, 0); } if (expr == addr) return true; return (TREE_CODE (addr) == ADDR_EXPR && TREE_CODE (expr) == ADDR_EXPR && TREE_OPERAND (addr, 0) == TREE_OPERAND (expr, 0)); } if (TREE_CODE (addr) == ADDR_EXPR && expr == TREE_OPERAND (addr, 0)) return true; return false; } /* Walk *EXPR_P and replace appearances of *LHS_ADDR with LHS_VAR. If an expression does not involve the lhs, evaluate it into a temporary. Return 1 if the lhs appeared as a subexpression, 0 if it did not, or -1 if an error was encountered. */ static int goa_stabilize_expr (tree *expr_p, gimple_seq *pre_p, tree lhs_addr, tree lhs_var) { tree expr = *expr_p; int saw_lhs; if (goa_lhs_expr_p (expr, lhs_addr)) { *expr_p = lhs_var; return 1; } if (is_gimple_val (expr)) return 0; saw_lhs = 0; switch (TREE_CODE_CLASS (TREE_CODE (expr))) { case tcc_binary: case tcc_comparison: saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 1), pre_p, lhs_addr, lhs_var); case tcc_unary: saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 0), pre_p, lhs_addr, lhs_var); break; case tcc_expression: switch (TREE_CODE (expr)) { case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: case TRUTH_AND_EXPR: case TRUTH_OR_EXPR: case TRUTH_XOR_EXPR: saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 1), pre_p, lhs_addr, lhs_var); case TRUTH_NOT_EXPR: saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 0), pre_p, lhs_addr, lhs_var); break; default: break; } break; default: break; } if (saw_lhs == 0) { enum gimplify_status gs; gs = gimplify_expr (expr_p, pre_p, NULL, is_gimple_val, fb_rvalue); if (gs != GS_ALL_DONE) saw_lhs = -1; } return saw_lhs; } /* Gimplify an OMP_ATOMIC statement. */ static enum gimplify_status gimplify_omp_atomic (tree *expr_p, gimple_seq *pre_p) { tree addr = TREE_OPERAND (*expr_p, 0); tree rhs = TREE_OPERAND (*expr_p, 1); tree type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (addr))); tree tmp_load; tmp_load = create_tmp_var (type, NULL); if (TREE_CODE (type) == COMPLEX_TYPE || TREE_CODE (type) == VECTOR_TYPE) DECL_GIMPLE_REG_P (tmp_load) = 1; if (goa_stabilize_expr (&rhs, pre_p, addr, tmp_load) < 0) return GS_ERROR; if (gimplify_expr (&addr, pre_p, NULL, is_gimple_val, fb_rvalue) != GS_ALL_DONE) return GS_ERROR; gimplify_seq_add_stmt (pre_p, gimple_build_omp_atomic_load (tmp_load, addr)); if (gimplify_expr (&rhs, pre_p, NULL, is_gimple_val, fb_rvalue) != GS_ALL_DONE) return GS_ERROR; gimplify_seq_add_stmt (pre_p, gimple_build_omp_atomic_store (rhs)); *expr_p = NULL; return GS_ALL_DONE; } /* Converts the GENERIC expression tree *EXPR_P to GIMPLE. If the expression produces a value to be used as an operand inside a GIMPLE statement, the value will be stored back in *EXPR_P. This value will be a tree of class tcc_declaration, tcc_constant, tcc_reference or an SSA_NAME. The corresponding sequence of GIMPLE statements is emitted in PRE_P and POST_P. Additionally, this process may overwrite parts of the input expression during gimplification. Ideally, it should be possible to do non-destructive gimplification. EXPR_P points to the GENERIC expression to convert to GIMPLE. If the expression needs to evaluate to a value to be used as an operand in a GIMPLE statement, this value will be stored in *EXPR_P on exit. This happens when the caller specifies one of fb_lvalue or fb_rvalue fallback flags. PRE_P will contain the sequence of GIMPLE statements corresponding to the evaluation of EXPR and all the side-effects that must be executed before the main expression. On exit, the last statement of PRE_P is the core statement being gimplified. For instance, when gimplifying 'if (++a)' the last statement in PRE_P will be 'if (t.1)' where t.1 is the result of pre-incrementing 'a'. POST_P will contain the sequence of GIMPLE statements corresponding to the evaluation of all the side-effects that must be executed after the main expression. If this is NULL, the post side-effects are stored at the end of PRE_P. The reason why the output is split in two is to handle post side-effects explicitly. In some cases, an expression may have inner and outer post side-effects which need to be emitted in an order different from the one given by the recursive traversal. For instance, for the expression (*p--)++ the post side-effects of '--' must actually occur *after* the post side-effects of '++'. However, gimplification will first visit the inner expression, so if a separate POST sequence was not used, the resulting sequence would be: 1 t.1 = *p 2 p = p - 1 3 t.2 = t.1 + 1 4 *p = t.2 However, the post-decrement operation in line #2 must not be evaluated until after the store to *p at line #4, so the correct sequence should be: 1 t.1 = *p 2 t.2 = t.1 + 1 3 *p = t.2 4 p = p - 1 So, by specifying a separate post queue, it is possible to emit the post side-effects in the correct order. If POST_P is NULL, an internal queue will be used. Before returning to the caller, the sequence POST_P is appended to the main output sequence PRE_P. GIMPLE_TEST_F points to a function that takes a tree T and returns nonzero if T is in the GIMPLE form requested by the caller. The GIMPLE predicates are in tree-gimple.c. FALLBACK tells the function what sort of a temporary we want if gimplification cannot produce an expression that complies with GIMPLE_TEST_F. fb_none means that no temporary should be generated fb_rvalue means that an rvalue is OK to generate fb_lvalue means that an lvalue is OK to generate fb_either means that either is OK, but an lvalue is preferable. fb_mayfail means that gimplification may fail (in which case GS_ERROR will be returned) The return value is either GS_ERROR or GS_ALL_DONE, since this function iterates until EXPR is completely gimplified or an error occurs. */ enum gimplify_status gimplify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p, bool (*gimple_test_f) (tree), fallback_t fallback) { tree tmp; gimple_seq internal_pre = NULL; gimple_seq internal_post = NULL; tree save_expr; bool is_statement; location_t saved_location; enum gimplify_status ret; gimple_stmt_iterator pre_last_gsi, post_last_gsi; save_expr = *expr_p; if (save_expr == NULL_TREE) return GS_ALL_DONE; /* If we are gimplifying a top-level statement, PRE_P must be valid. */ is_statement = gimple_test_f == is_gimple_stmt; if (is_statement) gcc_assert (pre_p); /* Consistency checks. */ if (gimple_test_f == is_gimple_reg) gcc_assert (fallback & (fb_rvalue | fb_lvalue)); else if (gimple_test_f == is_gimple_val || gimple_test_f == is_gimple_call_addr || gimple_test_f == is_gimple_condexpr || gimple_test_f == is_gimple_mem_rhs || gimple_test_f == is_gimple_mem_rhs_or_call || gimple_test_f == is_gimple_reg_rhs || gimple_test_f == is_gimple_reg_rhs_or_call || gimple_test_f == is_gimple_asm_val) gcc_assert (fallback & fb_rvalue); else if (gimple_test_f == is_gimple_min_lval || gimple_test_f == is_gimple_lvalue) gcc_assert (fallback & fb_lvalue); else if (gimple_test_f == is_gimple_addressable) gcc_assert (fallback & fb_either); else if (gimple_test_f == is_gimple_stmt) gcc_assert (fallback == fb_none); else { /* We should have recognized the GIMPLE_TEST_F predicate to know what kind of fallback to use in case a temporary is needed to hold the value or address of *EXPR_P. */ gcc_unreachable (); } /* We used to check the predicate here and return immediately if it succeeds. This is wrong; the design is for gimplification to be idempotent, and for the predicates to only test for valid forms, not whether they are fully simplified. */ if (pre_p == NULL) pre_p = &internal_pre; if (post_p == NULL) post_p = &internal_post; /* Remember the last statements added to PRE_P and POST_P. Every new statement added by the gimplification helpers needs to be annotated with location information. To centralize the responsibility, we remember the last statement that had been added to both queues before gimplifying *EXPR_P. If gimplification produces new statements in PRE_P and POST_P, those statements will be annotated with the same location information as *EXPR_P. */ pre_last_gsi = gsi_last (*pre_p); post_last_gsi = gsi_last (*post_p); saved_location = input_location; if (save_expr != error_mark_node && EXPR_HAS_LOCATION (*expr_p)) input_location = EXPR_LOCATION (*expr_p); /* Loop over the specific gimplifiers until the toplevel node remains the same. */ do { /* Strip away as many useless type conversions as possible at the toplevel. */ STRIP_USELESS_TYPE_CONVERSION (*expr_p); /* Remember the expr. */ save_expr = *expr_p; /* Die, die, die, my darling. */ if (save_expr == error_mark_node || (TREE_TYPE (save_expr) && TREE_TYPE (save_expr) == error_mark_node)) { ret = GS_ERROR; break; } /* Do any language-specific gimplification. */ ret = ((enum gimplify_status) lang_hooks.gimplify_expr (expr_p, pre_p, post_p)); if (ret == GS_OK) { if (*expr_p == NULL_TREE) break; if (*expr_p != save_expr) continue; } else if (ret != GS_UNHANDLED) break; ret = GS_OK; switch (TREE_CODE (*expr_p)) { /* First deal with the special cases. */ case POSTINCREMENT_EXPR: case POSTDECREMENT_EXPR: case PREINCREMENT_EXPR: case PREDECREMENT_EXPR: ret = gimplify_self_mod_expr (expr_p, pre_p, post_p, fallback != fb_none); break; case ARRAY_REF: case ARRAY_RANGE_REF: case REALPART_EXPR: case IMAGPART_EXPR: case COMPONENT_REF: case VIEW_CONVERT_EXPR: ret = gimplify_compound_lval (expr_p, pre_p, post_p, fallback ? fallback : fb_rvalue); break; case COND_EXPR: ret = gimplify_cond_expr (expr_p, pre_p, fallback); /* C99 code may assign to an array in a structure value of a conditional expression, and this has undefined behavior only on execution, so create a temporary if an lvalue is required. */ if (fallback == fb_lvalue) { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); mark_addressable (*expr_p); } break; case STATIC_CHAIN_EXPR: /* Modula-3: This gets converted fairly early, in tree-nested.c. */ ret = GS_ALL_DONE; break; case CALL_EXPR: ret = gimplify_call_expr (expr_p, pre_p, fallback != fb_none); /* C99 code may assign to an array in a structure returned from a function, and this has undefined behavior only on execution, so create a temporary if an lvalue is required. */ if (fallback == fb_lvalue) { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); mark_addressable (*expr_p); } break; case TREE_LIST: gcc_unreachable (); case COMPOUND_EXPR: ret = gimplify_compound_expr (expr_p, pre_p, fallback != fb_none); break; case COMPOUND_LITERAL_EXPR: ret = gimplify_compound_literal_expr (expr_p, pre_p); break; case MODIFY_EXPR: case INIT_EXPR: ret = gimplify_modify_expr (expr_p, pre_p, post_p, fallback != fb_none); /* Don't let the end of loop logic change GS_OK to GS_ALL_DONE; gimplify_modify_expr_rhs might have changed the RHS. */ if (ret == GS_OK && *expr_p) continue; break; case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: /* Pass the source location of the outer expression. */ ret = gimplify_boolean_expr (expr_p, saved_location); break; case TRUTH_NOT_EXPR: if (TREE_CODE (TREE_TYPE (*expr_p)) != BOOLEAN_TYPE) { tree type = TREE_TYPE (*expr_p); *expr_p = fold_convert (type, gimple_boolify (*expr_p)); ret = GS_OK; break; } ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); recalculate_side_effects (*expr_p); break; case ADDR_EXPR: ret = gimplify_addr_expr (expr_p, pre_p, post_p); break; case VA_ARG_EXPR: ret = gimplify_va_arg_expr (expr_p, pre_p, post_p); break; CASE_CONVERT: if (IS_EMPTY_STMT (*expr_p)) { ret = GS_ALL_DONE; break; } if (VOID_TYPE_P (TREE_TYPE (*expr_p)) || fallback == fb_none) { /* Just strip a conversion to void (or in void context) and try again. */ *expr_p = TREE_OPERAND (*expr_p, 0); break; } ret = gimplify_conversion (expr_p); if (ret == GS_ERROR) break; if (*expr_p != save_expr) break; /* FALLTHRU */ case FIX_TRUNC_EXPR: /* unary_expr: ... | '(' cast ')' val | ... */ ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); recalculate_side_effects (*expr_p); break; case INDIRECT_REF: *expr_p = fold_indirect_ref_loc (input_location, *expr_p); if (*expr_p != save_expr) break; /* else fall through. */ case ALIGN_INDIRECT_REF: case MISALIGNED_INDIRECT_REF: ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_reg, fb_rvalue); recalculate_side_effects (*expr_p); break; /* Constants need not be gimplified. */ case INTEGER_CST: case REAL_CST: case FIXED_CST: case STRING_CST: case COMPLEX_CST: case VECTOR_CST: ret = GS_ALL_DONE; break; case CONST_DECL: /* If we require an lvalue, such as for ADDR_EXPR, retain the CONST_DECL node. Otherwise the decl is replaceable by its value. */ /* ??? Should be == fb_lvalue, but ADDR_EXPR passes fb_either. */ if (fallback & fb_lvalue) ret = GS_ALL_DONE; else *expr_p = DECL_INITIAL (*expr_p); break; case DECL_EXPR: ret = gimplify_decl_expr (expr_p, pre_p); break; case BIND_EXPR: ret = gimplify_bind_expr (expr_p, pre_p); break; case LOOP_EXPR: ret = gimplify_loop_expr (expr_p, pre_p); break; case SWITCH_EXPR: ret = gimplify_switch_expr (expr_p, pre_p); break; case EXIT_EXPR: ret = gimplify_exit_expr (expr_p); break; case GOTO_EXPR: /* If the target is not LABEL, then it is a computed jump and the target needs to be gimplified. */ if (TREE_CODE (GOTO_DESTINATION (*expr_p)) != LABEL_DECL) { ret = gimplify_expr (&GOTO_DESTINATION (*expr_p), pre_p, NULL, is_gimple_val, fb_rvalue); if (ret == GS_ERROR) break; } gimplify_seq_add_stmt (pre_p, gimple_build_goto (GOTO_DESTINATION (*expr_p))); break; case PREDICT_EXPR: gimplify_seq_add_stmt (pre_p, gimple_build_predict (PREDICT_EXPR_PREDICTOR (*expr_p), PREDICT_EXPR_OUTCOME (*expr_p))); ret = GS_ALL_DONE; break; case LABEL_EXPR: ret = GS_ALL_DONE; gcc_assert (decl_function_context (LABEL_EXPR_LABEL (*expr_p)) == current_function_decl); gimplify_seq_add_stmt (pre_p, gimple_build_label (LABEL_EXPR_LABEL (*expr_p))); break; case CASE_LABEL_EXPR: ret = gimplify_case_label_expr (expr_p, pre_p); break; case RETURN_EXPR: ret = gimplify_return_expr (*expr_p, pre_p); break; case CONSTRUCTOR: /* Don't reduce this in place; let gimplify_init_constructor work its magic. Buf if we're just elaborating this for side effects, just gimplify any element that has side-effects. */ if (fallback == fb_none) { unsigned HOST_WIDE_INT ix; constructor_elt *ce; tree temp = NULL_TREE; for (ix = 0; VEC_iterate (constructor_elt, CONSTRUCTOR_ELTS (*expr_p), ix, ce); ix++) if (TREE_SIDE_EFFECTS (ce->value)) append_to_statement_list (ce->value, &temp); *expr_p = temp; ret = GS_OK; } /* C99 code may assign to an array in a constructed structure or union, and this has undefined behavior only on execution, so create a temporary if an lvalue is required. */ else if (fallback == fb_lvalue) { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); mark_addressable (*expr_p); } else ret = GS_ALL_DONE; break; /* The following are special cases that are not handled by the original GIMPLE grammar. */ /* SAVE_EXPR nodes are converted into a GIMPLE identifier and eliminated. */ case SAVE_EXPR: ret = gimplify_save_expr (expr_p, pre_p, post_p); break; case BIT_FIELD_REF: { enum gimplify_status r0, r1, r2; r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_lvalue, fb_either); r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, is_gimple_val, fb_rvalue); r2 = gimplify_expr (&TREE_OPERAND (*expr_p, 2), pre_p, post_p, is_gimple_val, fb_rvalue); recalculate_side_effects (*expr_p); ret = MIN (r0, MIN (r1, r2)); } break; case TARGET_MEM_REF: { enum gimplify_status r0 = GS_ALL_DONE, r1 = GS_ALL_DONE; if (TMR_SYMBOL (*expr_p)) r0 = gimplify_expr (&TMR_SYMBOL (*expr_p), pre_p, post_p, is_gimple_lvalue, fb_either); else if (TMR_BASE (*expr_p)) r0 = gimplify_expr (&TMR_BASE (*expr_p), pre_p, post_p, is_gimple_val, fb_either); if (TMR_INDEX (*expr_p)) r1 = gimplify_expr (&TMR_INDEX (*expr_p), pre_p, post_p, is_gimple_val, fb_rvalue); /* TMR_STEP and TMR_OFFSET are always integer constants. */ ret = MIN (r0, r1); } break; case NON_LVALUE_EXPR: /* This should have been stripped above. */ gcc_unreachable (); case ASM_EXPR: ret = gimplify_asm_expr (expr_p, pre_p, post_p); break; case TRY_FINALLY_EXPR: case TRY_CATCH_EXPR: { gimple_seq eval, cleanup; gimple try_; eval = cleanup = NULL; gimplify_and_add (TREE_OPERAND (*expr_p, 0), &eval); gimplify_and_add (TREE_OPERAND (*expr_p, 1), &cleanup); /* Don't create bogus GIMPLE_TRY with empty cleanup. */ if (gimple_seq_empty_p (cleanup)) { gimple_seq_add_seq (pre_p, eval); ret = GS_ALL_DONE; break; } try_ = gimple_build_try (eval, cleanup, TREE_CODE (*expr_p) == TRY_FINALLY_EXPR ? GIMPLE_TRY_FINALLY : GIMPLE_TRY_CATCH); if (TREE_CODE (*expr_p) == TRY_CATCH_EXPR) gimple_try_set_catch_is_cleanup (try_, TRY_CATCH_IS_CLEANUP (*expr_p)); gimplify_seq_add_stmt (pre_p, try_); ret = GS_ALL_DONE; break; } case CLEANUP_POINT_EXPR: ret = gimplify_cleanup_point_expr (expr_p, pre_p); break; case TARGET_EXPR: ret = gimplify_target_expr (expr_p, pre_p, post_p); break; case CATCH_EXPR: { gimple c; gimple_seq handler = NULL; gimplify_and_add (CATCH_BODY (*expr_p), &handler); c = gimple_build_catch (CATCH_TYPES (*expr_p), handler); gimplify_seq_add_stmt (pre_p, c); ret = GS_ALL_DONE; break; } case EH_FILTER_EXPR: { gimple ehf; gimple_seq failure = NULL; gimplify_and_add (EH_FILTER_FAILURE (*expr_p), &failure); ehf = gimple_build_eh_filter (EH_FILTER_TYPES (*expr_p), failure); gimple_set_no_warning (ehf, TREE_NO_WARNING (*expr_p)); gimplify_seq_add_stmt (pre_p, ehf); ret = GS_ALL_DONE; break; } case OBJ_TYPE_REF: { enum gimplify_status r0, r1; r0 = gimplify_expr (&OBJ_TYPE_REF_OBJECT (*expr_p), pre_p, post_p, is_gimple_val, fb_rvalue); r1 = gimplify_expr (&OBJ_TYPE_REF_EXPR (*expr_p), pre_p, post_p, is_gimple_val, fb_rvalue); TREE_SIDE_EFFECTS (*expr_p) = 0; ret = MIN (r0, r1); } break; case LABEL_DECL: /* We get here when taking the address of a label. We mark the label as "forced"; meaning it can never be removed and it is a potential target for any computed goto. */ FORCED_LABEL (*expr_p) = 1; ret = GS_ALL_DONE; break; case STATEMENT_LIST: ret = gimplify_statement_list (expr_p, pre_p); break; case WITH_SIZE_EXPR: { gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p == &internal_post ? NULL : post_p, gimple_test_f, fallback); gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, is_gimple_val, fb_rvalue); } break; case VAR_DECL: case PARM_DECL: ret = gimplify_var_or_parm_decl (expr_p); break; case RESULT_DECL: /* When within an OpenMP context, notice uses of variables. */ if (gimplify_omp_ctxp) omp_notice_variable (gimplify_omp_ctxp, *expr_p, true); ret = GS_ALL_DONE; break; case SSA_NAME: /* Allow callbacks into the gimplifier during optimization. */ ret = GS_ALL_DONE; break; case OMP_PARALLEL: gimplify_omp_parallel (expr_p, pre_p); ret = GS_ALL_DONE; break; case OMP_TASK: gimplify_omp_task (expr_p, pre_p); ret = GS_ALL_DONE; break; case OMP_FOR: ret = gimplify_omp_for (expr_p, pre_p); break; case OMP_SECTIONS: case OMP_SINGLE: gimplify_omp_workshare (expr_p, pre_p); ret = GS_ALL_DONE; break; case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: { gimple_seq body = NULL; gimple g; gimplify_and_add (OMP_BODY (*expr_p), &body); switch (TREE_CODE (*expr_p)) { case OMP_SECTION: g = gimple_build_omp_section (body); break; case OMP_MASTER: g = gimple_build_omp_master (body); break; case OMP_ORDERED: g = gimple_build_omp_ordered (body); break; case OMP_CRITICAL: g = gimple_build_omp_critical (body, OMP_CRITICAL_NAME (*expr_p)); break; default: gcc_unreachable (); } gimplify_seq_add_stmt (pre_p, g); ret = GS_ALL_DONE; break; } case OMP_ATOMIC: ret = gimplify_omp_atomic (expr_p, pre_p); break; case POINTER_PLUS_EXPR: /* Convert ((type *)A)+offset into &A->field_of_type_and_offset. The second is gimple immediate saving a need for extra statement. */ if (TREE_CODE (TREE_OPERAND (*expr_p, 1)) == INTEGER_CST && (tmp = maybe_fold_offset_to_address (EXPR_LOCATION (*expr_p), TREE_OPERAND (*expr_p, 0), TREE_OPERAND (*expr_p, 1), TREE_TYPE (*expr_p)))) { *expr_p = tmp; break; } /* Convert (void *)&a + 4 into (void *)&a[1]. */ if (TREE_CODE (TREE_OPERAND (*expr_p, 0)) == NOP_EXPR && TREE_CODE (TREE_OPERAND (*expr_p, 1)) == INTEGER_CST && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*expr_p, 0),0))) && (tmp = maybe_fold_offset_to_address (EXPR_LOCATION (*expr_p), TREE_OPERAND (TREE_OPERAND (*expr_p, 0), 0), TREE_OPERAND (*expr_p, 1), TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*expr_p, 0), 0))))) { *expr_p = fold_convert (TREE_TYPE (*expr_p), tmp); break; } /* FALLTHRU */ default: switch (TREE_CODE_CLASS (TREE_CODE (*expr_p))) { case tcc_comparison: /* Handle comparison of objects of non scalar mode aggregates with a call to memcmp. It would be nice to only have to do this for variable-sized objects, but then we'd have to allow the same nest of reference nodes we allow for MODIFY_EXPR and that's too complex. Compare scalar mode aggregates as scalar mode values. Using memcmp for them would be very inefficient at best, and is plain wrong if bitfields are involved. */ { tree type = TREE_TYPE (TREE_OPERAND (*expr_p, 1)); if (!AGGREGATE_TYPE_P (type)) goto expr_2; else if (TYPE_MODE (type) != BLKmode) ret = gimplify_scalar_mode_aggregate_compare (expr_p); else ret = gimplify_variable_sized_compare (expr_p); break; } /* If *EXPR_P does not need to be special-cased, handle it according to its class. */ case tcc_unary: ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); break; case tcc_binary: expr_2: { enum gimplify_status r0, r1; r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, is_gimple_val, fb_rvalue); r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, is_gimple_val, fb_rvalue); ret = MIN (r0, r1); break; } case tcc_declaration: case tcc_constant: ret = GS_ALL_DONE; goto dont_recalculate; default: gcc_assert (TREE_CODE (*expr_p) == TRUTH_AND_EXPR || TREE_CODE (*expr_p) == TRUTH_OR_EXPR || TREE_CODE (*expr_p) == TRUTH_XOR_EXPR); goto expr_2; } recalculate_side_effects (*expr_p); dont_recalculate: break; } /* If we replaced *expr_p, gimplify again. */ if (ret == GS_OK && (*expr_p == NULL || *expr_p == save_expr)) ret = GS_ALL_DONE; } while (ret == GS_OK); /* If we encountered an error_mark somewhere nested inside, either stub out the statement or propagate the error back out. */ if (ret == GS_ERROR) { if (is_statement) *expr_p = NULL; goto out; } /* This was only valid as a return value from the langhook, which we handled. Make sure it doesn't escape from any other context. */ gcc_assert (ret != GS_UNHANDLED); if (fallback == fb_none && *expr_p && !is_gimple_stmt (*expr_p)) { /* We aren't looking for a value, and we don't have a valid statement. If it doesn't have side-effects, throw it away. */ if (!TREE_SIDE_EFFECTS (*expr_p)) *expr_p = NULL; else if (!TREE_THIS_VOLATILE (*expr_p)) { /* This is probably a _REF that contains something nested that has side effects. Recurse through the operands to find it. */ enum tree_code code = TREE_CODE (*expr_p); switch (code) { case COMPONENT_REF: case REALPART_EXPR: case IMAGPART_EXPR: case VIEW_CONVERT_EXPR: gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, gimple_test_f, fallback); break; case ARRAY_REF: case ARRAY_RANGE_REF: gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p, gimple_test_f, fallback); gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p, gimple_test_f, fallback); break; default: /* Anything else with side-effects must be converted to a valid statement before we get here. */ gcc_unreachable (); } *expr_p = NULL; } else if (COMPLETE_TYPE_P (TREE_TYPE (*expr_p)) && TYPE_MODE (TREE_TYPE (*expr_p)) != BLKmode) { /* Historically, the compiler has treated a bare reference to a non-BLKmode volatile lvalue as forcing a load. */ tree type = TYPE_MAIN_VARIANT (TREE_TYPE (*expr_p)); /* Normally, we do not want to create a temporary for a TREE_ADDRESSABLE type because such a type should not be copied by bitwise-assignment. However, we make an exception here, as all we are doing here is ensuring that we read the bytes that make up the type. We use create_tmp_var_raw because create_tmp_var will abort when given a TREE_ADDRESSABLE type. */ tree tmp = create_tmp_var_raw (type, "vol"); gimple_add_tmp_var (tmp); gimplify_assign (tmp, *expr_p, pre_p); *expr_p = NULL; } else /* We can't do anything useful with a volatile reference to an incomplete type, so just throw it away. Likewise for a BLKmode type, since any implicit inner load should already have been turned into an explicit one by the gimplification process. */ *expr_p = NULL; } /* If we are gimplifying at the statement level, we're done. Tack everything together and return. */ if (fallback == fb_none || is_statement) { /* Since *EXPR_P has been converted into a GIMPLE tuple, clear it out for GC to reclaim it. */ *expr_p = NULL_TREE; if (!gimple_seq_empty_p (internal_pre) || !gimple_seq_empty_p (internal_post)) { gimplify_seq_add_seq (&internal_pre, internal_post); gimplify_seq_add_seq (pre_p, internal_pre); } /* The result of gimplifying *EXPR_P is going to be the last few statements in *PRE_P and *POST_P. Add location information to all the statements that were added by the gimplification helpers. */ if (!gimple_seq_empty_p (*pre_p)) annotate_all_with_location_after (*pre_p, pre_last_gsi, input_location); if (!gimple_seq_empty_p (*post_p)) annotate_all_with_location_after (*post_p, post_last_gsi, input_location); goto out; } #ifdef ENABLE_GIMPLE_CHECKING if (*expr_p) { enum tree_code code = TREE_CODE (*expr_p); /* These expressions should already be in gimple IR form. */ gcc_assert (code != MODIFY_EXPR && code != ASM_EXPR && code != BIND_EXPR && code != CATCH_EXPR && (code != COND_EXPR || gimplify_ctxp->allow_rhs_cond_expr) && code != EH_FILTER_EXPR && code != GOTO_EXPR && code != LABEL_EXPR && code != LOOP_EXPR && code != SWITCH_EXPR && code != TRY_FINALLY_EXPR && code != OMP_CRITICAL && code != OMP_FOR && code != OMP_MASTER && code != OMP_ORDERED && code != OMP_PARALLEL && code != OMP_SECTIONS && code != OMP_SECTION && code != OMP_SINGLE); } #endif /* Otherwise we're gimplifying a subexpression, so the resulting value is interesting. If it's a valid operand that matches GIMPLE_TEST_F, we're done. Unless we are handling some post-effects internally; if that's the case, we need to copy into a temporary before adding the post-effects to POST_P. */ if (gimple_seq_empty_p (internal_post) && (*gimple_test_f) (*expr_p)) goto out; /* Otherwise, we need to create a new temporary for the gimplified expression. */ /* We can't return an lvalue if we have an internal postqueue. The object the lvalue refers to would (probably) be modified by the postqueue; we need to copy the value out first, which means an rvalue. */ if ((fallback & fb_lvalue) && gimple_seq_empty_p (internal_post) && is_gimple_addressable (*expr_p)) { /* An lvalue will do. Take the address of the expression, store it in a temporary, and replace the expression with an INDIRECT_REF of that temporary. */ tmp = build_fold_addr_expr_loc (input_location, *expr_p); gimplify_expr (&tmp, pre_p, post_p, is_gimple_reg, fb_rvalue); *expr_p = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (tmp)), tmp); } else if ((fallback & fb_rvalue) && is_gimple_reg_rhs_or_call (*expr_p)) { /* An rvalue will do. Assign the gimplified expression into a new temporary TMP and replace the original expression with TMP. First, make sure that the expression has a type so that it can be assigned into a temporary. */ gcc_assert (!VOID_TYPE_P (TREE_TYPE (*expr_p))); if (!gimple_seq_empty_p (internal_post) || (fallback & fb_lvalue)) /* The postqueue might change the value of the expression between the initialization and use of the temporary, so we can't use a formal temp. FIXME do we care? */ { *expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p); if (TREE_CODE (TREE_TYPE (*expr_p)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (*expr_p)) == VECTOR_TYPE) DECL_GIMPLE_REG_P (*expr_p) = 1; } else *expr_p = get_formal_tmp_var (*expr_p, pre_p); } else { #ifdef ENABLE_GIMPLE_CHECKING if (!(fallback & fb_mayfail)) { fprintf (stderr, "gimplification failed:\n"); print_generic_expr (stderr, *expr_p, 0); debug_tree (*expr_p); internal_error ("gimplification failed"); } #endif gcc_assert (fallback & fb_mayfail); /* If this is an asm statement, and the user asked for the impossible, don't die. Fail and let gimplify_asm_expr issue an error. */ ret = GS_ERROR; goto out; } /* Make sure the temporary matches our predicate. */ gcc_assert ((*gimple_test_f) (*expr_p)); if (!gimple_seq_empty_p (internal_post)) { annotate_all_with_location (internal_post, input_location); gimplify_seq_add_seq (pre_p, internal_post); } out: input_location = saved_location; return ret; } /* Look through TYPE for variable-sized objects and gimplify each such size that we find. Add to LIST_P any statements generated. */ void gimplify_type_sizes (tree type, gimple_seq *list_p) { tree field, t; if (type == NULL || type == error_mark_node) return; /* We first do the main variant, then copy into any other variants. */ type = TYPE_MAIN_VARIANT (type); /* Avoid infinite recursion. */ if (TYPE_SIZES_GIMPLIFIED (type)) return; TYPE_SIZES_GIMPLIFIED (type) = 1; switch (TREE_CODE (type)) { case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE: case REAL_TYPE: case FIXED_POINT_TYPE: gimplify_one_sizepos (&TYPE_MIN_VALUE (type), list_p); gimplify_one_sizepos (&TYPE_MAX_VALUE (type), list_p); for (t = TYPE_NEXT_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t)) { TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (type); TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (type); } break; case ARRAY_TYPE: /* These types may not have declarations, so handle them here. */ gimplify_type_sizes (TREE_TYPE (type), list_p); gimplify_type_sizes (TYPE_DOMAIN (type), list_p); /* Ensure VLA bounds aren't removed, for -O0 they should be variables with assigned stack slots, for -O1+ -g they should be tracked by VTA. */ if (!(TYPE_NAME (type) && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL && DECL_IGNORED_P (TYPE_NAME (type))) && TYPE_DOMAIN (type) && INTEGRAL_TYPE_P (TYPE_DOMAIN (type))) { t = TYPE_MIN_VALUE (TYPE_DOMAIN (type)); if (t && TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t)) DECL_IGNORED_P (t) = 0; t = TYPE_MAX_VALUE (TYPE_DOMAIN (type)); if (t && TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t)) DECL_IGNORED_P (t) = 0; } break; case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field)) if (TREE_CODE (field) == FIELD_DECL) { gimplify_one_sizepos (&DECL_FIELD_OFFSET (field), list_p); gimplify_one_sizepos (&DECL_SIZE (field), list_p); gimplify_one_sizepos (&DECL_SIZE_UNIT (field), list_p); gimplify_type_sizes (TREE_TYPE (field), list_p); } break; case POINTER_TYPE: case REFERENCE_TYPE: /* We used to recurse on the pointed-to type here, which turned out to be incorrect because its definition might refer to variables not yet initialized at this point if a forward declaration is involved. It was actually useful for anonymous pointed-to types to ensure that the sizes evaluation dominates every possible later use of the values. Restricting to such types here would be safe since there is no possible forward declaration around, but would introduce an undesirable middle-end semantic to anonymity. We then defer to front-ends the responsibility of ensuring that the sizes are evaluated both early and late enough, e.g. by attaching artificial type declarations to the tree. */ break; default: break; } gimplify_one_sizepos (&TYPE_SIZE (type), list_p); gimplify_one_sizepos (&TYPE_SIZE_UNIT (type), list_p); for (t = TYPE_NEXT_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t)) { TYPE_SIZE (t) = TYPE_SIZE (type); TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (type); TYPE_SIZES_GIMPLIFIED (t) = 1; } } /* A subroutine of gimplify_type_sizes to make sure that *EXPR_P, a size or position, has had all of its SAVE_EXPRs evaluated. We add any required statements to *STMT_P. */ void gimplify_one_sizepos (tree *expr_p, gimple_seq *stmt_p) { tree type, expr = *expr_p; /* We don't do anything if the value isn't there, is constant, or contains A PLACEHOLDER_EXPR. We also don't want to do anything if it's already a VAR_DECL. If it's a VAR_DECL from another function, the gimplifier will want to replace it with a new variable, but that will cause problems if this type is from outside the function. It's OK to have that here. */ if (expr == NULL_TREE || TREE_CONSTANT (expr) || TREE_CODE (expr) == VAR_DECL || CONTAINS_PLACEHOLDER_P (expr)) return; type = TREE_TYPE (expr); *expr_p = unshare_expr (expr); gimplify_expr (expr_p, stmt_p, NULL, is_gimple_val, fb_rvalue); expr = *expr_p; /* Verify that we've an exact type match with the original expression. In particular, we do not wish to drop a "sizetype" in favour of a type of similar dimensions. We don't want to pollute the generic type-stripping code with this knowledge because it doesn't matter for the bulk of GENERIC/GIMPLE. It only matters that TYPE_SIZE_UNIT and friends retain their "sizetype-ness". */ if (TREE_TYPE (expr) != type && TREE_CODE (type) == INTEGER_TYPE && TYPE_IS_SIZETYPE (type)) { tree tmp; gimple stmt; *expr_p = create_tmp_var (type, NULL); tmp = build1 (NOP_EXPR, type, expr); stmt = gimplify_assign (*expr_p, tmp, stmt_p); if (EXPR_HAS_LOCATION (expr)) gimple_set_location (stmt, EXPR_LOCATION (expr)); else gimple_set_location (stmt, input_location); } } /* Gimplify the body of statements pointed to by BODY_P and return a GIMPLE_BIND containing the sequence of GIMPLE statements corresponding to BODY_P. FNDECL is the function decl containing *BODY_P. */ gimple gimplify_body (tree *body_p, tree fndecl, bool do_parms) { location_t saved_location = input_location; gimple_seq parm_stmts, seq; gimple outer_bind; struct gimplify_ctx gctx; timevar_push (TV_TREE_GIMPLIFY); /* Initialize for optimize_insn_for_s{ize,peed}_p possibly called during gimplification. */ default_rtl_profile (); gcc_assert (gimplify_ctxp == NULL); push_gimplify_context (&gctx); /* Unshare most shared trees in the body and in that of any nested functions. It would seem we don't have to do this for nested functions because they are supposed to be output and then the outer function gimplified first, but the g++ front end doesn't always do it that way. */ unshare_body (body_p, fndecl); unvisit_body (body_p, fndecl); if (cgraph_node (fndecl)->origin) nonlocal_vlas = pointer_set_create (); /* Make sure input_location isn't set to something weird. */ input_location = DECL_SOURCE_LOCATION (fndecl); /* Resolve callee-copies. This has to be done before processing the body so that DECL_VALUE_EXPR gets processed correctly. */ parm_stmts = (do_parms) ? gimplify_parameters () : NULL; /* Gimplify the function's body. */ seq = NULL; gimplify_stmt (body_p, &seq); outer_bind = gimple_seq_first_stmt (seq); if (!outer_bind) { outer_bind = gimple_build_nop (); gimplify_seq_add_stmt (&seq, outer_bind); } /* The body must contain exactly one statement, a GIMPLE_BIND. If this is not the case, wrap everything in a GIMPLE_BIND to make it so. */ if (gimple_code (outer_bind) == GIMPLE_BIND && gimple_seq_first (seq) == gimple_seq_last (seq)) ; else outer_bind = gimple_build_bind (NULL_TREE, seq, NULL); *body_p = NULL_TREE; /* If we had callee-copies statements, insert them at the beginning of the function and clear DECL_VALUE_EXPR_P on the parameters. */ if (!gimple_seq_empty_p (parm_stmts)) { tree parm; gimplify_seq_add_seq (&parm_stmts, gimple_bind_body (outer_bind)); gimple_bind_set_body (outer_bind, parm_stmts); for (parm = DECL_ARGUMENTS (current_function_decl); parm; parm = TREE_CHAIN (parm)) if (DECL_HAS_VALUE_EXPR_P (parm)) { DECL_HAS_VALUE_EXPR_P (parm) = 0; DECL_IGNORED_P (parm) = 0; } } if (nonlocal_vlas) { pointer_set_destroy (nonlocal_vlas); nonlocal_vlas = NULL; } pop_gimplify_context (outer_bind); gcc_assert (gimplify_ctxp == NULL); #ifdef ENABLE_TYPES_CHECKING if (!errorcount && !sorrycount) verify_types_in_gimple_seq (gimple_bind_body (outer_bind)); #endif timevar_pop (TV_TREE_GIMPLIFY); input_location = saved_location; return outer_bind; } /* Entry point to the gimplification pass. FNDECL is the FUNCTION_DECL node for the function we want to gimplify. Returns the sequence of GIMPLE statements corresponding to the body of FNDECL. */ void gimplify_function_tree (tree fndecl) { tree oldfn, parm, ret; gimple_seq seq; gimple bind; gcc_assert (!gimple_body (fndecl)); oldfn = current_function_decl; current_function_decl = fndecl; if (DECL_STRUCT_FUNCTION (fndecl)) push_cfun (DECL_STRUCT_FUNCTION (fndecl)); else push_struct_function (fndecl); for (parm = DECL_ARGUMENTS (fndecl); parm ; parm = TREE_CHAIN (parm)) { /* Preliminarily mark non-addressed complex variables as eligible for promotion to gimple registers. We'll transform their uses as we find them. */ if ((TREE_CODE (TREE_TYPE (parm)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (parm)) == VECTOR_TYPE) && !TREE_THIS_VOLATILE (parm) && !needs_to_live_in_memory (parm)) DECL_GIMPLE_REG_P (parm) = 1; } ret = DECL_RESULT (fndecl); if ((TREE_CODE (TREE_TYPE (ret)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (ret)) == VECTOR_TYPE) && !needs_to_live_in_memory (ret)) DECL_GIMPLE_REG_P (ret) = 1; bind = gimplify_body (&DECL_SAVED_TREE (fndecl), fndecl, true); /* The tree body of the function is no longer needed, replace it with the new GIMPLE body. */ seq = gimple_seq_alloc (); gimple_seq_add_stmt (&seq, bind); gimple_set_body (fndecl, seq); /* If we're instrumenting function entry/exit, then prepend the call to the entry hook and wrap the whole function in a TRY_FINALLY_EXPR to catch the exit hook. */ /* ??? Add some way to ignore exceptions for this TFE. */ if (flag_instrument_function_entry_exit && !DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (fndecl) && !flag_instrument_functions_exclude_p (fndecl)) { tree x; gimple new_bind; gimple tf; gimple_seq cleanup = NULL, body = NULL; x = implicit_built_in_decls[BUILT_IN_PROFILE_FUNC_EXIT]; gimplify_seq_add_stmt (&cleanup, gimple_build_call (x, 0)); tf = gimple_build_try (seq, cleanup, GIMPLE_TRY_FINALLY); x = implicit_built_in_decls[BUILT_IN_PROFILE_FUNC_ENTER]; gimplify_seq_add_stmt (&body, gimple_build_call (x, 0)); gimplify_seq_add_stmt (&body, tf); new_bind = gimple_build_bind (NULL, body, gimple_bind_block (bind)); /* Clear the block for BIND, since it is no longer directly inside the function, but within a try block. */ gimple_bind_set_block (bind, NULL); /* Replace the current function body with the body wrapped in the try/finally TF. */ seq = gimple_seq_alloc (); gimple_seq_add_stmt (&seq, new_bind); gimple_set_body (fndecl, seq); } DECL_SAVED_TREE (fndecl) = NULL_TREE; cfun->curr_properties = PROP_gimple_any; current_function_decl = oldfn; pop_cfun (); } /* Some transformations like inlining may invalidate the GIMPLE form for operands. This function traverses all the operands in STMT and gimplifies anything that is not a valid gimple operand. Any new GIMPLE statements are inserted before *GSI_P. */ void gimple_regimplify_operands (gimple stmt, gimple_stmt_iterator *gsi_p) { size_t i, num_ops; tree orig_lhs = NULL_TREE, lhs, t; gimple_seq pre = NULL; gimple post_stmt = NULL; struct gimplify_ctx gctx; push_gimplify_context (&gctx); gimplify_ctxp->into_ssa = gimple_in_ssa_p (cfun); switch (gimple_code (stmt)) { case GIMPLE_COND: gimplify_expr (gimple_cond_lhs_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); gimplify_expr (gimple_cond_rhs_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); break; case GIMPLE_SWITCH: gimplify_expr (gimple_switch_index_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); break; case GIMPLE_OMP_ATOMIC_LOAD: gimplify_expr (gimple_omp_atomic_load_rhs_ptr (stmt), &pre, NULL, is_gimple_val, fb_rvalue); break; case GIMPLE_ASM: { size_t i, noutputs = gimple_asm_noutputs (stmt); const char *constraint, **oconstraints; bool allows_mem, allows_reg, is_inout; oconstraints = (const char **) alloca ((noutputs) * sizeof (const char *)); for (i = 0; i < noutputs; i++) { tree op = gimple_asm_output_op (stmt, i); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (op))); oconstraints[i] = constraint; parse_output_constraint (&constraint, i, 0, 0, &allows_mem, &allows_reg, &is_inout); gimplify_expr (&TREE_VALUE (op), &pre, NULL, is_inout ? is_gimple_min_lval : is_gimple_lvalue, fb_lvalue | fb_mayfail); } for (i = 0; i < gimple_asm_ninputs (stmt); i++) { tree op = gimple_asm_input_op (stmt, i); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (op))); parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints, &allows_mem, &allows_reg); if (TREE_ADDRESSABLE (TREE_TYPE (TREE_VALUE (op))) && allows_mem) allows_reg = 0; if (!allows_reg && allows_mem) gimplify_expr (&TREE_VALUE (op), &pre, NULL, is_gimple_lvalue, fb_lvalue | fb_mayfail); else gimplify_expr (&TREE_VALUE (op), &pre, NULL, is_gimple_asm_val, fb_rvalue); } } break; default: /* NOTE: We start gimplifying operands from last to first to make sure that side-effects on the RHS of calls, assignments and ASMs are executed before the LHS. The ordering is not important for other statements. */ num_ops = gimple_num_ops (stmt); orig_lhs = gimple_get_lhs (stmt); for (i = num_ops; i > 0; i--) { tree op = gimple_op (stmt, i - 1); if (op == NULL_TREE) continue; if (i == 1 && (is_gimple_call (stmt) || is_gimple_assign (stmt))) gimplify_expr (&op, &pre, NULL, is_gimple_lvalue, fb_lvalue); else if (i == 2 && is_gimple_assign (stmt) && num_ops == 2 && get_gimple_rhs_class (gimple_expr_code (stmt)) == GIMPLE_SINGLE_RHS) gimplify_expr (&op, &pre, NULL, rhs_predicate_for (gimple_assign_lhs (stmt)), fb_rvalue); else if (i == 2 && is_gimple_call (stmt)) { if (TREE_CODE (op) == FUNCTION_DECL) continue; gimplify_expr (&op, &pre, NULL, is_gimple_call_addr, fb_rvalue); } else gimplify_expr (&op, &pre, NULL, is_gimple_val, fb_rvalue); gimple_set_op (stmt, i - 1, op); } lhs = gimple_get_lhs (stmt); /* If the LHS changed it in a way that requires a simple RHS, create temporary. */ if (lhs && !is_gimple_reg (lhs)) { bool need_temp = false; if (is_gimple_assign (stmt) && num_ops == 2 && get_gimple_rhs_class (gimple_expr_code (stmt)) == GIMPLE_SINGLE_RHS) gimplify_expr (gimple_assign_rhs1_ptr (stmt), &pre, NULL, rhs_predicate_for (gimple_assign_lhs (stmt)), fb_rvalue); else if (is_gimple_reg (lhs)) { if (is_gimple_reg_type (TREE_TYPE (lhs))) { if (is_gimple_call (stmt)) { i = gimple_call_flags (stmt); if ((i & ECF_LOOPING_CONST_OR_PURE) || !(i & (ECF_CONST | ECF_PURE))) need_temp = true; } if (stmt_can_throw_internal (stmt)) need_temp = true; } } else { if (is_gimple_reg_type (TREE_TYPE (lhs))) need_temp = true; else if (TYPE_MODE (TREE_TYPE (lhs)) != BLKmode) { if (is_gimple_call (stmt)) { tree fndecl = gimple_call_fndecl (stmt); if (!aggregate_value_p (TREE_TYPE (lhs), fndecl) && !(fndecl && DECL_RESULT (fndecl) && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))) need_temp = true; } else need_temp = true; } } if (need_temp) { tree temp = create_tmp_var (TREE_TYPE (lhs), NULL); if (TREE_CODE (TREE_TYPE (lhs)) == COMPLEX_TYPE || TREE_CODE (TREE_TYPE (lhs)) == VECTOR_TYPE) DECL_GIMPLE_REG_P (temp) = 1; if (TREE_CODE (orig_lhs) == SSA_NAME) orig_lhs = SSA_NAME_VAR (orig_lhs); if (gimple_in_ssa_p (cfun)) temp = make_ssa_name (temp, NULL); gimple_set_lhs (stmt, temp); post_stmt = gimple_build_assign (lhs, temp); if (TREE_CODE (lhs) == SSA_NAME) SSA_NAME_DEF_STMT (lhs) = post_stmt; } } break; } if (gimple_referenced_vars (cfun)) for (t = gimplify_ctxp->temps; t ; t = TREE_CHAIN (t)) add_referenced_var (t); if (!gimple_seq_empty_p (pre)) { if (gimple_in_ssa_p (cfun)) { gimple_stmt_iterator i; for (i = gsi_start (pre); !gsi_end_p (i); gsi_next (&i)) mark_symbols_for_renaming (gsi_stmt (i)); } gsi_insert_seq_before (gsi_p, pre, GSI_SAME_STMT); } if (post_stmt) gsi_insert_after (gsi_p, post_stmt, GSI_NEW_STMT); pop_gimplify_context (NULL); } /* Expands EXPR to list of gimple statements STMTS. If SIMPLE is true, force the result to be either ssa_name or an invariant, otherwise just force it to be a rhs expression. If VAR is not NULL, make the base variable of the final destination be VAR if suitable. */ tree force_gimple_operand (tree expr, gimple_seq *stmts, bool simple, tree var) { tree t; enum gimplify_status ret; gimple_predicate gimple_test_f; struct gimplify_ctx gctx; *stmts = NULL; if (is_gimple_val (expr)) return expr; gimple_test_f = simple ? is_gimple_val : is_gimple_reg_rhs; push_gimplify_context (&gctx); gimplify_ctxp->into_ssa = gimple_in_ssa_p (cfun); gimplify_ctxp->allow_rhs_cond_expr = true; if (var) expr = build2 (MODIFY_EXPR, TREE_TYPE (var), var, expr); if (TREE_CODE (expr) != MODIFY_EXPR && TREE_TYPE (expr) == void_type_node) { gimplify_and_add (expr, stmts); expr = NULL_TREE; } else { ret = gimplify_expr (&expr, stmts, NULL, gimple_test_f, fb_rvalue); gcc_assert (ret != GS_ERROR); } if (gimple_referenced_vars (cfun)) for (t = gimplify_ctxp->temps; t ; t = TREE_CHAIN (t)) add_referenced_var (t); pop_gimplify_context (NULL); return expr; } /* Invokes force_gimple_operand for EXPR with parameters SIMPLE_P and VAR. If some statements are produced, emits them at GSI. If BEFORE is true. the statements are appended before GSI, otherwise they are appended after it. M specifies the way GSI moves after insertion (GSI_SAME_STMT or GSI_CONTINUE_LINKING are the usual values). */ tree force_gimple_operand_gsi (gimple_stmt_iterator *gsi, tree expr, bool simple_p, tree var, bool before, enum gsi_iterator_update m) { gimple_seq stmts; expr = force_gimple_operand (expr, &stmts, simple_p, var); if (!gimple_seq_empty_p (stmts)) { if (gimple_in_ssa_p (cfun)) { gimple_stmt_iterator i; for (i = gsi_start (stmts); !gsi_end_p (i); gsi_next (&i)) mark_symbols_for_renaming (gsi_stmt (i)); } if (before) gsi_insert_seq_before (gsi, stmts, m); else gsi_insert_seq_after (gsi, stmts, m); } return expr; } #include "gt-gimplify.h" #ifdef __cplusplus } /* extern "C" */ #endif
common.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_UTILS_COMMON_FUN_H_ #define LIGHTGBM_UTILS_COMMON_FUN_H_ #include <LightGBM/utils/log.h> #include <LightGBM/utils/openmp_wrapper.h> #include <limits> #include <string> #include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <cstdio> #include <functional> #include <iomanip> #include <iterator> #include <map> #include <memory> #include <sstream> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> #ifdef _MSC_VER #include <intrin.h> #pragma intrinsic(_BitScanReverse) #endif #if defined(_MSC_VER) #include <malloc.h> #elif MM_MALLOC #include <mm_malloc.h> #elif defined(__GNUC__) #include <malloc.h> #define _mm_malloc(a, b) memalign(b, a) #define _mm_free(a) free(a) #else #include <stdlib.h> #define _mm_malloc(a, b) malloc(a) #define _mm_free(a) free(a) #endif namespace LightGBM { namespace Common { inline static char tolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } inline static std::string Trim(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of(" \f\n\r\t\v") + 1); str.erase(0, str.find_first_not_of(" \f\n\r\t\v")); return str; } inline static std::string RemoveQuotationSymbol(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of("'\"") + 1); str.erase(0, str.find_first_not_of("'\"")); return str; } inline static bool StartsWith(const std::string& str, const std::string prefix) { if (str.substr(0, prefix.size()) == prefix) { return true; } else { return false; } } inline static std::vector<std::string> Split(const char* c_str, char delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == delimiter) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> SplitBrackets(const char* c_str, char left_delimiter, char right_delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; bool open = false; while (pos < str.length()) { if (str[pos] == left_delimiter) { open = true; ++pos; i = pos; } else if (str[pos] == right_delimiter && open) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } open = false; ++pos; } else { ++pos; } } return ret; } inline static std::vector<std::string> SplitLines(const char* c_str) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == '\n' || str[pos] == '\r') { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } // skip the line endings while (str[pos] == '\n' || str[pos] == '\r') ++pos; // new begin i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> Split(const char* c_str, const char* delimiters) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { bool met_delimiters = false; for (int j = 0; delimiters[j] != '\0'; ++j) { if (str[pos] == delimiters[j]) { met_delimiters = true; break; } } if (met_delimiters) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } template<typename T> inline static const char* Atoi(const char* p, T* out) { int sign; T value; while (*p == ' ') { ++p; } sign = 1; if (*p == '-') { sign = -1; ++p; } else if (*p == '+') { ++p; } for (value = 0; *p >= '0' && *p <= '9'; ++p) { value = value * 10 + (*p - '0'); } *out = static_cast<T>(sign * value); while (*p == ' ') { ++p; } return p; } template<typename T> inline static double Pow(T base, int power) { if (power < 0) { return 1.0 / Pow(base, -power); } else if (power == 0) { return 1; } else if (power % 2 == 0) { return Pow(base*base, power / 2); } else if (power % 3 == 0) { return Pow(base*base*base, power / 3); } else { return base * Pow(base, power - 1); } } inline static const char* Atof(const char* p, double* out) { int frac; double sign, value, scale; *out = NAN; // Skip leading white space, if any. while (*p == ' ') { ++p; } // Get sign, if any. sign = 1.0; if (*p == '-') { sign = -1.0; ++p; } else if (*p == '+') { ++p; } // is a number if ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E') { // Get digits before decimal point or exponent, if any. for (value = 0.0; *p >= '0' && *p <= '9'; ++p) { value = value * 10.0 + (*p - '0'); } // Get digits after decimal point, if any. if (*p == '.') { double right = 0.0; int nn = 0; ++p; while (*p >= '0' && *p <= '9') { right = (*p - '0') + right * 10.0; ++nn; ++p; } value += right / Pow(10.0, nn); } // Handle exponent, if any. frac = 0; scale = 1.0; if ((*p == 'e') || (*p == 'E')) { uint32_t expon; // Get sign of exponent, if any. ++p; if (*p == '-') { frac = 1; ++p; } else if (*p == '+') { ++p; } // Get digits of exponent, if any. for (expon = 0; *p >= '0' && *p <= '9'; ++p) { expon = expon * 10 + (*p - '0'); } if (expon > 308) expon = 308; // Calculate scaling factor. while (expon >= 50) { scale *= 1E50; expon -= 50; } while (expon >= 8) { scale *= 1E8; expon -= 8; } while (expon > 0) { scale *= 10.0; expon -= 1; } } // Return signed and scaled floating point result. *out = sign * (frac ? (value / scale) : (value * scale)); } else { size_t cnt = 0; while (*(p + cnt) != '\0' && *(p + cnt) != ' ' && *(p + cnt) != '\t' && *(p + cnt) != ',' && *(p + cnt) != '\n' && *(p + cnt) != '\r' && *(p + cnt) != ':') { ++cnt; } if (cnt > 0) { std::string tmp_str(p, cnt); std::transform(tmp_str.begin(), tmp_str.end(), tmp_str.begin(), Common::tolower); if (tmp_str == std::string("na") || tmp_str == std::string("nan") || tmp_str == std::string("null")) { *out = NAN; } else if (tmp_str == std::string("inf") || tmp_str == std::string("infinity")) { *out = sign * 1e308; } else { Log::Fatal("Unknown token %s in data file", tmp_str.c_str()); } p += cnt; } } while (*p == ' ') { ++p; } return p; } inline static bool AtoiAndCheck(const char* p, int* out) { const char* after = Atoi(p, out); if (*after != '\0') { return false; } return true; } inline static bool AtofAndCheck(const char* p, double* out) { const char* after = Atof(p, out); if (*after != '\0') { return false; } return true; } inline static unsigned CountDecimalDigit32(uint32_t n) { #if defined(_MSC_VER) || defined(__GNUC__) static const uint32_t powers_of_10[] = { 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; #ifdef _MSC_VER // NOLINTNEXTLINE unsigned long i = 0; _BitScanReverse(&i, n | 1); uint32_t t = (i + 1) * 1233 >> 12; #elif __GNUC__ uint32_t t = (32 - __builtin_clz(n | 1)) * 1233 >> 12; #endif return t - (n < powers_of_10[t]) + 1; #else if (n < 10) return 1; if (n < 100) return 2; if (n < 1000) return 3; if (n < 10000) return 4; if (n < 100000) return 5; if (n < 1000000) return 6; if (n < 10000000) return 7; if (n < 100000000) return 8; if (n < 1000000000) return 9; return 10; #endif } inline static void Uint32ToStr(uint32_t value, char* buffer) { const char kDigitsLut[200] = { '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', '3', '0', '3', '1', '3', '2', '3', '3', '3', '4', '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', '4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8', '4', '9', '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5', '7', '5', '8', '5', '9', '6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9', '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7', '7', '8', '7', '9', '8', '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', '9', '0', '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7', '9', '8', '9', '9' }; unsigned digit = CountDecimalDigit32(value); buffer += digit; *buffer = '\0'; while (value >= 100) { const unsigned i = (value % 100) << 1; value /= 100; *--buffer = kDigitsLut[i + 1]; *--buffer = kDigitsLut[i]; } if (value < 10) { *--buffer = static_cast<char>(value) + '0'; } else { const unsigned i = value << 1; *--buffer = kDigitsLut[i + 1]; *--buffer = kDigitsLut[i]; } } inline static void Int32ToStr(int32_t value, char* buffer) { uint32_t u = static_cast<uint32_t>(value); if (value < 0) { *buffer++ = '-'; u = ~u + 1; } Uint32ToStr(u, buffer); } inline static void DoubleToStr(double value, char* buffer, size_t buffer_len) { #ifdef _MSC_VER int num_chars = sprintf_s(buffer, buffer_len, "%.17g", value); #else int num_chars = snprintf(buffer, buffer_len, "%.17g", value); #endif CHECK_GE(num_chars, 0); } inline static const char* SkipSpaceAndTab(const char* p) { while (*p == ' ' || *p == '\t') { ++p; } return p; } inline static const char* SkipReturn(const char* p) { while (*p == '\n' || *p == '\r' || *p == ' ') { ++p; } return p; } template<typename T, typename T2> inline static std::vector<T2> ArrayCast(const std::vector<T>& arr) { std::vector<T2> ret(arr.size()); for (size_t i = 0; i < arr.size(); ++i) { ret[i] = static_cast<T2>(arr[i]); } return ret; } template<typename T, bool is_float, bool is_unsign> struct __TToStringHelperFast { void operator()(T value, char* buffer, size_t) const { Int32ToStr(value, buffer); } }; template<typename T> struct __TToStringHelperFast<T, true, false> { void operator()(T value, char* buffer, size_t buf_len) const { #ifdef _MSC_VER int num_chars = sprintf_s(buffer, buf_len, "%g", value); #else int num_chars = snprintf(buffer, buf_len, "%g", value); #endif CHECK_GE(num_chars, 0); } }; template<typename T> struct __TToStringHelperFast<T, false, true> { void operator()(T value, char* buffer, size_t) const { Uint32ToStr(value, buffer); } }; template<typename T> inline static std::string ArrayToStringFast(const std::vector<T>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } __TToStringHelperFast<T, std::is_floating_point<T>::value, std::is_unsigned<T>::value> helper; const size_t buf_len = 16; std::vector<char> buffer(buf_len); std::stringstream str_buf; helper(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { helper(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } inline static std::string ArrayToString(const std::vector<double>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } const size_t buf_len = 32; std::vector<char> buffer(buf_len); std::stringstream str_buf; DoubleToStr(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { DoubleToStr(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } template<typename T, bool is_float> struct __StringToTHelper { T operator()(const std::string& str) const { T ret = 0; Atoi(str.c_str(), &ret); return ret; } }; template<typename T> struct __StringToTHelper<T, true> { T operator()(const std::string& str) const { return static_cast<T>(std::stod(str)); } }; template<typename T> inline static std::vector<T> StringToArray(const std::string& str, char delimiter) { std::vector<std::string> strs = Split(str.c_str(), delimiter); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T> inline static std::vector<std::vector<T>> StringToArrayofArrays( const std::string& str, char left_bracket, char right_bracket, char delimiter) { std::vector<std::string> strs = SplitBrackets(str.c_str(), left_bracket, right_bracket); std::vector<std::vector<T>> ret; for (const auto& s : strs) { ret.push_back(StringToArray<T>(s, delimiter)); } return ret; } template<typename T> inline static std::vector<T> StringToArray(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } std::vector<std::string> strs = Split(str.c_str(), ' '); CHECK_EQ(strs.size(), static_cast<size_t>(n)); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T, bool is_float> struct __StringToTHelperFast { const char* operator()(const char*p, T* out) const { return Atoi(p, out); } }; template<typename T> struct __StringToTHelperFast<T, true> { const char* operator()(const char*p, T* out) const { double tmp = 0.0f; auto ret = Atof(p, &tmp); *out = static_cast<T>(tmp); return ret; } }; template<typename T> inline static std::vector<T> StringToArrayFast(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } auto p_str = str.c_str(); __StringToTHelperFast<T, std::is_floating_point<T>::value> helper; std::vector<T> ret(n); for (int i = 0; i < n; ++i) { p_str = helper(p_str, &ret[i]); } return ret; } template<typename T> inline static std::string Join(const std::vector<T>& strs, const char* delimiter) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[0]; for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } template<> inline std::string Join<int8_t>(const std::vector<int8_t>& strs, const char* delimiter) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << static_cast<int16_t>(strs[0]); for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << static_cast<int16_t>(strs[i]); } return str_buf.str(); } template<typename T> inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter) { if (end - start <= 0) { return std::string(""); } start = std::min(start, static_cast<size_t>(strs.size()) - 1); end = std::min(end, static_cast<size_t>(strs.size())); std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[start]; for (size_t i = start + 1; i < end; ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } inline static int64_t Pow2RoundUp(int64_t x) { int64_t t = 1; for (int i = 0; i < 64; ++i) { if (t >= x) { return t; } t <<= 1; } return 0; } /*! * \brief Do inplace softmax transformation on p_rec * \param p_rec The input/output vector of the values. */ inline static void Softmax(std::vector<double>* p_rec) { std::vector<double> &rec = *p_rec; double wmax = rec[0]; for (size_t i = 1; i < rec.size(); ++i) { wmax = std::max(rec[i], wmax); } double wsum = 0.0f; for (size_t i = 0; i < rec.size(); ++i) { rec[i] = std::exp(rec[i] - wmax); wsum += rec[i]; } for (size_t i = 0; i < rec.size(); ++i) { rec[i] /= static_cast<double>(wsum); } } inline static void Softmax(const double* input, double* output, int len) { double wmax = input[0]; for (int i = 1; i < len; ++i) { wmax = std::max(input[i], wmax); } double wsum = 0.0f; for (int i = 0; i < len; ++i) { output[i] = std::exp(input[i] - wmax); wsum += output[i]; } for (int i = 0; i < len; ++i) { output[i] /= static_cast<double>(wsum); } } template<typename T> std::vector<const T*> ConstPtrInVectorWrapper(const std::vector<std::unique_ptr<T>>& input) { std::vector<const T*> ret; for (auto t = input.begin(); t !=input.end(); ++t) { ret.push_back(t->get()); } return ret; } template<typename T1, typename T2> inline static void SortForPair(std::vector<T1>* keys, std::vector<T2>* values, size_t start, bool is_reverse = false) { std::vector<std::pair<T1, T2>> arr; auto& ref_key = *keys; auto& ref_value = *values; for (size_t i = start; i < keys->size(); ++i) { arr.emplace_back(ref_key[i], ref_value[i]); } if (!is_reverse) { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first < b.first; }); } else { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first > b.first; }); } for (size_t i = start; i < arr.size(); ++i) { ref_key[i] = arr[i].first; ref_value[i] = arr[i].second; } } template <typename T> inline static std::vector<T*> Vector2Ptr(std::vector<std::vector<T>>* data) { std::vector<T*> ptr(data->size()); auto& ref_data = *data; for (size_t i = 0; i < data->size(); ++i) { ptr[i] = ref_data[i].data(); } return ptr; } template <typename T> inline static std::vector<int> VectorSize(const std::vector<std::vector<T>>& data) { std::vector<int> ret(data.size()); for (size_t i = 0; i < data.size(); ++i) { ret[i] = static_cast<int>(data[i].size()); } return ret; } inline static double AvoidInf(double x) { if (std::isnan(x)) { return 0.0; } else if (x >= 1e300) { return 1e300; } else if (x <= -1e300) { return -1e300; } else { return x; } } inline static float AvoidInf(float x) { if (std::isnan(x)) { return 0.0f; } else if (x >= 1e38) { return 1e38f; } else if (x <= -1e38) { return -1e38f; } else { return x; } } template<typename _Iter> inline static typename std::iterator_traits<_Iter>::value_type* IteratorValType(_Iter) { return (0); } template<typename _RanIt, typename _Pr, typename _VTRanIt> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred, _VTRanIt*) { size_t len = _Last - _First; const size_t kMinInnerLen = 1024; int num_threads = OMP_NUM_THREADS(); if (len <= kMinInnerLen || num_threads <= 1) { std::sort(_First, _Last, _Pred); return; } size_t inner_size = (len + num_threads - 1) / num_threads; inner_size = std::max(inner_size, kMinInnerLen); num_threads = static_cast<int>((len + inner_size - 1) / inner_size); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < num_threads; ++i) { size_t left = inner_size*i; size_t right = left + inner_size; right = std::min(right, len); if (right > left) { std::sort(_First + left, _First + right, _Pred); } } // Buffer for merge. std::vector<_VTRanIt> temp_buf(len); _RanIt buf = temp_buf.begin(); size_t s = inner_size; // Recursive merge while (s < len) { int loop_size = static_cast<int>((len + s * 2 - 1) / (s * 2)); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < loop_size; ++i) { size_t left = i * 2 * s; size_t mid = left + s; size_t right = mid + s; right = std::min(len, right); if (mid >= right) { continue; } std::copy(_First + left, _First + mid, buf + left); std::merge(buf + left, buf + mid, _First + mid, _First + right, _First + left, _Pred); } s *= 2; } } template<typename _RanIt, typename _Pr> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred) { return ParallelSort(_First, _Last, _Pred, IteratorValType(_First)); } // Check that all y[] are in interval [ymin, ymax] (end points included); throws error if not template <typename T> inline static void CheckElementsIntervalClosed(const T *y, T ymin, T ymax, int ny, const char *callername) { auto fatal_msg = [&y, &ymin, &ymax, &callername](int i) { std::ostringstream os; os << "[%s]: does not tolerate element [#%i = " << y[i] << "] outside [" << ymin << ", " << ymax << "]"; Log::Fatal(os.str().c_str(), callername, i); }; for (int i = 1; i < ny; i += 2) { if (y[i - 1] < y[i]) { if (y[i - 1] < ymin) { fatal_msg(i - 1); } else if (y[i] > ymax) { fatal_msg(i); } } else { if (y[i - 1] > ymax) { fatal_msg(i - 1); } else if (y[i] < ymin) { fatal_msg(i); } } } if (ny & 1) { // odd if (y[ny - 1] < ymin || y[ny - 1] > ymax) { fatal_msg(ny - 1); } } } // One-pass scan over array w with nw elements: find min, max and sum of elements; // this is useful for checking weight requirements. template <typename T1, typename T2> inline static void ObtainMinMaxSum(const T1 *w, int nw, T1 *mi, T1 *ma, T2 *su) { T1 minw; T1 maxw; T1 sumw; int i; if (nw & 1) { // odd minw = w[0]; maxw = w[0]; sumw = w[0]; i = 2; } else { // even if (w[0] < w[1]) { minw = w[0]; maxw = w[1]; } else { minw = w[1]; maxw = w[0]; } sumw = w[0] + w[1]; i = 3; } for (; i < nw; i += 2) { if (w[i - 1] < w[i]) { minw = std::min(minw, w[i - 1]); maxw = std::max(maxw, w[i]); } else { minw = std::min(minw, w[i]); maxw = std::max(maxw, w[i - 1]); } sumw += w[i - 1] + w[i]; } if (mi != nullptr) { *mi = minw; } if (ma != nullptr) { *ma = maxw; } if (su != nullptr) { *su = static_cast<T2>(sumw); } } inline static std::vector<uint32_t> EmptyBitset(int n) { int size = n / 32; if (n % 32 != 0) ++size; return std::vector<uint32_t>(size); } template<typename T> inline static void InsertBitset(std::vector<uint32_t>* vec, const T val) { auto& ref_v = *vec; int i1 = val / 32; int i2 = val % 32; if (static_cast<int>(vec->size()) < i1 + 1) { vec->resize(i1 + 1, 0); } ref_v[i1] |= (1 << i2); } template<typename T> inline static std::vector<uint32_t> ConstructBitset(const T* vals, int n) { std::vector<uint32_t> ret; for (int i = 0; i < n; ++i) { int i1 = vals[i] / 32; int i2 = vals[i] % 32; if (static_cast<int>(ret.size()) < i1 + 1) { ret.resize(i1 + 1, 0); } ret[i1] |= (1 << i2); } return ret; } template<typename T> inline static bool FindInBitset(const uint32_t* bits, int n, T pos) { int i1 = pos / 32; if (i1 >= n) { return false; } int i2 = pos % 32; return (bits[i1] >> i2) & 1; } inline static bool CheckDoubleEqualOrdered(double a, double b) { double upper = std::nextafter(a, INFINITY); return b <= upper; } inline static double GetDoubleUpperBound(double a) { return std::nextafter(a, INFINITY); } inline static size_t GetLine(const char* str) { auto start = str; while (*str != '\0' && *str != '\n' && *str != '\r') { ++str; } return str - start; } inline static const char* SkipNewLine(const char* str) { if (*str == '\r') { ++str; } if (*str == '\n') { ++str; } return str; } template <typename T> static int Sign(T x) { return (x > T(0)) - (x < T(0)); } template <typename T> static T SafeLog(T x) { if (x > 0) { return std::log(x); } else { return -INFINITY; } } inline bool CheckAllowedJSON(const std::string& s) { unsigned char char_code; for (auto c : s) { char_code = static_cast<unsigned char>(c); if (char_code == 34 // " || char_code == 44 // , || char_code == 58 // : || char_code == 91 // [ || char_code == 93 // ] || char_code == 123 // { || char_code == 125 // } ) { return false; } } return true; } inline int RoundInt(double x) { return static_cast<int>(x + 0.5f); } template <typename T, std::size_t N = 32> class AlignmentAllocator { public: typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; inline AlignmentAllocator() throw() {} template <typename T2> inline AlignmentAllocator(const AlignmentAllocator<T2, N>&) throw() {} inline ~AlignmentAllocator() throw() {} inline pointer adress(reference r) { return &r; } inline const_pointer adress(const_reference r) const { return &r; } inline pointer allocate(size_type n) { return (pointer)_mm_malloc(n * sizeof(value_type), N); } inline void deallocate(pointer p, size_type) { _mm_free(p); } inline void construct(pointer p, const value_type& wert) { new (p) value_type(wert); } inline void destroy(pointer p) { p->~value_type(); } inline size_type max_size() const throw() { return size_type(-1) / sizeof(value_type); } template <typename T2> struct rebind { typedef AlignmentAllocator<T2, N> other; }; bool operator!=(const AlignmentAllocator<T, N>& other) const { return !(*this == other); } // Returns true if and only if storage allocated from *this // can be deallocated from other, and vice versa. // Always returns true for stateless allocators. bool operator==(const AlignmentAllocator<T, N>&) const { return true; } }; class Timer { public: Timer() { #ifdef TIMETAG int num_threads = OMP_NUM_THREADS(); start_time_.resize(num_threads); stats_.resize(num_threads); #endif // TIMETAG } ~Timer() { Print(); } #ifdef TIMETAG void Start(const std::string& name) { auto tid = omp_get_thread_num(); start_time_[tid][name] = std::chrono::steady_clock::now(); } void Stop(const std::string& name) { auto cur_time = std::chrono::steady_clock::now(); auto tid = omp_get_thread_num(); if (stats_[tid].find(name) == stats_[tid].end()) { stats_[tid][name] = std::chrono::duration<double, std::milli>(0); } stats_[tid][name] += cur_time - start_time_[tid][name]; } #else void Start(const std::string&) {} void Stop(const std::string&) {} #endif // TIMETAG void Print() const { #ifdef TIMETAG std::unordered_map<std::string, std::chrono::duration<double, std::milli>> stats(stats_[0].begin(), stats_[0].end()); for (size_t i = 1; i < stats_.size(); ++i) { for (auto it = stats_[i].begin(); it != stats_[i].end(); ++it) { if (stats.find(it->first) == stats.end()) { stats[it->first] = it->second; } else { stats[it->first] += it->second; } } } std::map<std::string, std::chrono::duration<double, std::milli>> ordered( stats.begin(), stats.end()); for (auto it = ordered.begin(); it != ordered.end(); ++it) { Log::Info("%s costs:\t %f", it->first.c_str(), it->second * 1e-3); } #endif // TIMETAG } #ifdef TIMETAG std::vector< std::unordered_map<std::string, std::chrono::steady_clock::time_point>> start_time_; std::vector<std::unordered_map<std::string, std::chrono::duration<double, std::milli>>> stats_; #endif // TIMETAG }; // Note: this class is not thread-safe, don't use it inside omp blocks class FunctionTimer { public: #ifdef TIMETAG FunctionTimer(const std::string& name, Timer& timer) : timer_(timer) { timer.Start(name); name_ = name; } ~FunctionTimer() { timer_.Stop(name_); } private: std::string name_; Timer& timer_; #else FunctionTimer(const std::string&, Timer&) {} #endif // TIMETAG }; } // namespace Common extern Common::Timer global_timer; } // namespace LightGBM #endif // LightGBM_UTILS_COMMON_FUN_H_
GB_subassign_17.c
//------------------------------------------------------------------------------ // GB_subassign_17: C(I,J)<!M,repl> = scalar ; using S //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Method 17: C(I,J)<!M,repl> = scalar ; using S // M: present // Mask_comp: true // C_replace: true // accum: NULL // A: scalar // S: constructed // C: not bitmap // M: not bitmap #include "GB_subassign_methods.h" GrB_Info GB_subassign_17 ( GrB_Matrix C, // input: const GrB_Index *I, const int64_t ni, const int64_t nI, const int Ikind, const int64_t Icolon [3], const GrB_Index *J, const int64_t nj, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], const GrB_Matrix M, const bool Mask_struct, const void *scalar, const GrB_Type atype, GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (!GB_IS_FULL (C)) ; ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M //-------------------------------------------------------------------------- // S = C(I,J) //-------------------------------------------------------------------------- GB_EMPTY_TASKLIST ; GB_OK (GB_subassign_symbolic (S, C, I, ni, J, nj, true, Context)) ; //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GB_MATRIX_WAIT_IF_JUMBLED (M) ; GB_GET_C ; // C must not be bitmap const int64_t Cnvec = C->nvec ; const int64_t *restrict Ch = C->h ; const int64_t *restrict Cp = C->p ; const bool C_is_hyper = (Ch != NULL) ; GB_GET_MASK ; GB_GET_SCALAR ; GB_GET_S ; GrB_BinaryOp accum = NULL ; //-------------------------------------------------------------------------- // Method 17: C(I,J)<!M,repl> = scalar ; using S //-------------------------------------------------------------------------- // Time: Close to optimal; must visit all IxJ, so Omega(|I|*|J|) is // required. The sparsity of !M cannot be exploited. // Methods 13, 15, 17, and 19 are very similar. //-------------------------------------------------------------------------- // Parallel: all IxJ (Methods 01, 03, 13, 15, 17, 19) //-------------------------------------------------------------------------- GB_SUBASSIGN_IXJ_SLICE ; //-------------------------------------------------------------------------- // phase 1: create zombies, update entries, and count pending tuples //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iA_start, iA_end) ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t j = kfirst ; j <= klast ; j++) { //------------------------------------------------------------------ // get jC, the corresponding vector of C //------------------------------------------------------------------ int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; //------------------------------------------------------------------ // get S(iA_start:end,j) and M(iA_start:end,j) //------------------------------------------------------------------ GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; GB_GET_VECTOR_FOR_IXJ (M, iA_start) ; //------------------------------------------------------------------ // C(I(iA_start,iA_end-1),jC)<!M,repl> = scalar //------------------------------------------------------------------ for (int64_t iA = iA_start ; iA < iA_end ; iA++) { //-------------------------------------------------------------- // Get the indices at the top of each list. //-------------------------------------------------------------- int64_t iS = (pS < pS_end) ? GBI (Si, pS, Svlen) : INT64_MAX ; int64_t iM = (pM < pM_end) ? GBI (Mi, pM, Mvlen) : INT64_MAX ; //-------------------------------------------------------------- // find the smallest index of [iS iA iM] (always iA) //-------------------------------------------------------------- int64_t i = iA ; //-------------------------------------------------------------- // get M(i,j) //-------------------------------------------------------------- bool mij ; if (i == iM) { // mij = (bool) M [pM] mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ; GB_NEXT (M) ; } else { // mij not present, implicitly false ASSERT (i < iM) ; mij = false ; } // complement the mask entry mij since Mask_comp is true mij = !mij ; //-------------------------------------------------------------- // assign the entry //-------------------------------------------------------------- if (i == iS) { ASSERT (i == iA) ; { // both S (i,j) and A (i,j) present GB_C_S_LOOKUP ; if (mij) { // ----[C A 1] or [X A 1]--------------------------- // [C A 1]: action: ( =A ): copy A, no accum // [X A 1]: action: ( undelete ): zombie lives GB_noaccum_C_A_1_scalar ; } else { // ----[C A 0] or [X A 0]--------------------------- // [X A 0]: action: ( X ): still a zombie // [C A 0]: C_repl: action: ( delete ): zombie GB_DELETE_ENTRY ; } GB_NEXT (S) ; } } else { ASSERT (i == iA) ; { // S (i,j) is not present, A (i,j) is present if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) task_pending++ ; } } } } } GB_PHASE1_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // phase 2: insert pending tuples //-------------------------------------------------------------------------- GB_PENDING_CUMSUM ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iA_start, iA_end) ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t j = kfirst ; j <= klast ; j++) { //------------------------------------------------------------------ // get jC, the corresponding vector of C //------------------------------------------------------------------ int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; //------------------------------------------------------------------ // get S(iA_start:end,j) and M(iA_start:end,j) //------------------------------------------------------------------ GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; GB_GET_VECTOR_FOR_IXJ (M, iA_start) ; //------------------------------------------------------------------ // C(I(iA_start,iA_end-1),jC)<!M,repl> = scalar //------------------------------------------------------------------ for (int64_t iA = iA_start ; iA < iA_end ; iA++) { //-------------------------------------------------------------- // Get the indices at the top of each list. //-------------------------------------------------------------- int64_t iS = (pS < pS_end) ? GBI (Si, pS, Svlen) : INT64_MAX ; int64_t iM = (pM < pM_end) ? GBI (Mi, pM, Mvlen) : INT64_MAX ; //-------------------------------------------------------------- // find the smallest index of [iS iA iM] (always iA) //-------------------------------------------------------------- int64_t i = iA ; //-------------------------------------------------------------- // get M(i,j) //-------------------------------------------------------------- bool mij ; if (i == iM) { // mij = (bool) M [pM] mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ; GB_NEXT (M) ; } else { // mij not present, implicitly false ASSERT (i < iM) ; mij = false ; } // complement the mask entry mij since Mask_comp is true mij = !mij ; //-------------------------------------------------------------- // assign the entry //-------------------------------------------------------------- if (i == iS) { ASSERT (i == iA) ; { GB_NEXT (S) ; } } else { ASSERT (i == iA) ; { // S (i,j) is not present, A (i,j) is present if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (scalar) ; } } } } } GB_PHASE2_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // finalize the matrix and return result //-------------------------------------------------------------------------- GB_SUBASSIGN_WRAPUP ; }
GB_unop__cos_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__cos_fp32_fp32) // op(A') function: GB (_unop_tran__cos_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = cosf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cosf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = cosf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_COS || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__cos_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = cosf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = cosf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__cos_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convolution_3x3_pack4_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_winograd64_transform_kernel_pack4_fp16sa_neon(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch) { // winograd63 transform kernel Mat kernel_tm; kernel_tm.create(8 * 8, inch, outch); const float ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i = 0; i < 8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j = 0; j < 8; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 64-inch-outch // dst = 4b-4a-inch/4a-64-outch/4b; kernel_tm_pack4.create(2 * inch / 4, 64, (outch / 4) / 2 + (outch / 4) % 2, (size_t)2u * 16, 16); int q = 0; for (; q + 7 < outch; q += 8) { const Mat k0 = kernel_tm.channel(q); const Mat k1 = kernel_tm.channel(q + 1); const Mat k2 = kernel_tm.channel(q + 2); const Mat k3 = kernel_tm.channel(q + 3); const Mat k4 = kernel_tm.channel(q + 4); const Mat k5 = kernel_tm.channel(q + 5); const Mat k6 = kernel_tm.channel(q + 6); const Mat k7 = kernel_tm.channel(q + 7); Mat g0 = kernel_tm_pack4.channel(q / 8); for (int k = 0; k < 64; k++) { __fp16* g00 = g0.row<__fp16>(k); for (int p = 0; p + 3 < inch; p += 4) { const float* k00 = k0.row(p); const float* k01 = k0.row(p + 1); const float* k02 = k0.row(p + 2); const float* k03 = k0.row(p + 3); const float* k10 = k1.row(p); const float* k11 = k1.row(p + 1); const float* k12 = k1.row(p + 2); const float* k13 = k1.row(p + 3); const float* k20 = k2.row(p); const float* k21 = k2.row(p + 1); const float* k22 = k2.row(p + 2); const float* k23 = k2.row(p + 3); const float* k30 = k3.row(p); const float* k31 = k3.row(p + 1); const float* k32 = k3.row(p + 2); const float* k33 = k3.row(p + 3); const float* k40 = k4.row(p); const float* k41 = k4.row(p + 1); const float* k42 = k4.row(p + 2); const float* k43 = k4.row(p + 3); const float* k50 = k5.row(p); const float* k51 = k5.row(p + 1); const float* k52 = k5.row(p + 2); const float* k53 = k5.row(p + 3); const float* k60 = k6.row(p); const float* k61 = k6.row(p + 1); const float* k62 = k6.row(p + 2); const float* k63 = k6.row(p + 3); const float* k70 = k7.row(p); const float* k71 = k7.row(p + 1); const float* k72 = k7.row(p + 2); const float* k73 = k7.row(p + 3); g00[0] = (__fp16)k00[k]; g00[1] = (__fp16)k10[k]; g00[2] = (__fp16)k20[k]; g00[3] = (__fp16)k30[k]; g00[4] = (__fp16)k40[k]; g00[5] = (__fp16)k50[k]; g00[6] = (__fp16)k60[k]; g00[7] = (__fp16)k70[k]; g00[8] = (__fp16)k01[k]; g00[9] = (__fp16)k11[k]; g00[10] = (__fp16)k21[k]; g00[11] = (__fp16)k31[k]; g00[12] = (__fp16)k41[k]; g00[13] = (__fp16)k51[k]; g00[14] = (__fp16)k61[k]; g00[15] = (__fp16)k71[k]; g00[16] = (__fp16)k02[k]; g00[17] = (__fp16)k12[k]; g00[18] = (__fp16)k22[k]; g00[19] = (__fp16)k32[k]; g00[20] = (__fp16)k42[k]; g00[21] = (__fp16)k52[k]; g00[22] = (__fp16)k62[k]; g00[23] = (__fp16)k72[k]; g00[24] = (__fp16)k03[k]; g00[25] = (__fp16)k13[k]; g00[26] = (__fp16)k23[k]; g00[27] = (__fp16)k33[k]; g00[28] = (__fp16)k43[k]; g00[29] = (__fp16)k53[k]; g00[30] = (__fp16)k63[k]; g00[31] = (__fp16)k73[k]; g00 += 32; } } } for (; q + 3 < outch; q += 4) { const Mat k0 = kernel_tm.channel(q); const Mat k1 = kernel_tm.channel(q + 1); const Mat k2 = kernel_tm.channel(q + 2); const Mat k3 = kernel_tm.channel(q + 3); Mat g0 = kernel_tm_pack4.channel(q / 8 + (q % 8) / 4); for (int k = 0; k < 64; k++) { __fp16* g00 = g0.row<__fp16>(k); for (int p = 0; p + 3 < inch; p += 4) { const float* k00 = k0.row(p); const float* k01 = k0.row(p + 1); const float* k02 = k0.row(p + 2); const float* k03 = k0.row(p + 3); const float* k10 = k1.row(p); const float* k11 = k1.row(p + 1); const float* k12 = k1.row(p + 2); const float* k13 = k1.row(p + 3); const float* k20 = k2.row(p); const float* k21 = k2.row(p + 1); const float* k22 = k2.row(p + 2); const float* k23 = k2.row(p + 3); const float* k30 = k3.row(p); const float* k31 = k3.row(p + 1); const float* k32 = k3.row(p + 2); const float* k33 = k3.row(p + 3); g00[0] = (__fp16)k00[k]; g00[1] = (__fp16)k10[k]; g00[2] = (__fp16)k20[k]; g00[3] = (__fp16)k30[k]; g00[4] = (__fp16)k01[k]; g00[5] = (__fp16)k11[k]; g00[6] = (__fp16)k21[k]; g00[7] = (__fp16)k31[k]; g00[8] = (__fp16)k02[k]; g00[9] = (__fp16)k12[k]; g00[10] = (__fp16)k22[k]; g00[11] = (__fp16)k32[k]; g00[12] = (__fp16)k03[k]; g00[13] = (__fp16)k13[k]; g00[14] = (__fp16)k23[k]; g00[15] = (__fp16)k33[k]; g00 += 16; } } } } static void conv3x3s1_winograd64_pack4_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; //size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); bottom_blob_tm.create(tiles, 64, inch, 2u * elempack, elempack, opt.workspace_allocator); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); __fp16 tmp[8][8][4]; // tile for (int i = 0; i < h_tm / 8; i++) { for (int j = 0; j < w_tm / 8; j++) { const __fp16* r0 = img0.row<const __fp16>(i * 6) + (j * 6) * 4; for (int m = 0; m < 8; m++) { float16x4_t _r00 = vld1_f16(r0); float16x4_t _r01 = vld1_f16(r0 + 4); float16x4_t _r02 = vld1_f16(r0 + 8); float16x4_t _r03 = vld1_f16(r0 + 12); float16x4_t _r04 = vld1_f16(r0 + 16); float16x4_t _r05 = vld1_f16(r0 + 20); float16x4_t _r06 = vld1_f16(r0 + 24); float16x4_t _r07 = vld1_f16(r0 + 28); float16x4_t _tmp0m = vfma_n_f16(vsub_f16(_r00, _r06), vsub_f16(_r04, _r02), 5.25f); float16x4_t _tmp7m = vfma_n_f16(vsub_f16(_r07, _r01), vsub_f16(_r03, _r05), 5.25f); vst1_f16(tmp[0][m], _tmp0m); vst1_f16(tmp[7][m], _tmp7m); // tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; // tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float16x4_t _tmp12a = vfms_n_f16(vadd_f16(_r02, _r06), _r04, 4.25f); float16x4_t _tmp12b = vfms_n_f16(vadd_f16(_r01, _r05), _r03, 4.25f); // float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); // float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); float16x4_t _tmp1m = vadd_f16(_tmp12a, _tmp12b); float16x4_t _tmp2m = vsub_f16(_tmp12a, _tmp12b); vst1_f16(tmp[1][m], _tmp1m); vst1_f16(tmp[2][m], _tmp2m); // tmp[1][m] = tmp12a + tmp12b; // tmp[2][m] = tmp12a - tmp12b; float16x4_t _tmp34a = vfms_n_f16(vfma_n_f16(_r06, _r02, 0.25f), _r04, 1.25f); float16x4_t _tmp34b = vfma_n_f16(vfms_n_f16(vmul_n_f16(_r01, 0.5f), _r03, 2.5f), _r05, 2.f); // float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); // float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); float16x4_t _tmp3m = vadd_f16(_tmp34a, _tmp34b); float16x4_t _tmp4m = vsub_f16(_tmp34a, _tmp34b); vst1_f16(tmp[3][m], _tmp3m); vst1_f16(tmp[4][m], _tmp4m); // tmp[3][m] = tmp34a + tmp34b; // tmp[4][m] = tmp34a - tmp34b; float16x4_t _tmp56a = vfma_n_f16(_r06, vfms_n_f16(_r02, _r04, 1.25f), 4.f); float16x4_t _tmp56b = vfma_n_f16(vfms_n_f16(vmul_n_f16(_r01, 2.f), _r03, 2.5f), _r05, 0.5f); // float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); // float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); float16x4_t _tmp5m = vadd_f16(_tmp56a, _tmp56b); float16x4_t _tmp6m = vsub_f16(_tmp56a, _tmp56b); vst1_f16(tmp[5][m], _tmp5m); vst1_f16(tmp[6][m], _tmp6m); // tmp[5][m] = tmp56a + tmp56b; // tmp[6][m] = tmp56a - tmp56b; r0 += w * 4; } __fp16* r0_tm_0 = (__fp16*)img0_tm + (i * w_tm / 8 + j) * 4; __fp16* r0_tm_1 = r0_tm_0 + tiles * 4; __fp16* r0_tm_2 = r0_tm_0 + tiles * 8; __fp16* r0_tm_3 = r0_tm_0 + tiles * 12; __fp16* r0_tm_4 = r0_tm_0 + tiles * 16; __fp16* r0_tm_5 = r0_tm_0 + tiles * 20; __fp16* r0_tm_6 = r0_tm_0 + tiles * 24; __fp16* r0_tm_7 = r0_tm_0 + tiles * 28; for (int m = 0; m < 8; m++) { float16x4_t _tmp00 = vld1_f16(tmp[m][0]); float16x4_t _tmp01 = vld1_f16(tmp[m][1]); float16x4_t _tmp02 = vld1_f16(tmp[m][2]); float16x4_t _tmp03 = vld1_f16(tmp[m][3]); float16x4_t _tmp04 = vld1_f16(tmp[m][4]); float16x4_t _tmp05 = vld1_f16(tmp[m][5]); float16x4_t _tmp06 = vld1_f16(tmp[m][6]); float16x4_t _tmp07 = vld1_f16(tmp[m][7]); float16x4_t _r0tm0 = vfma_n_f16(vsub_f16(_tmp00, _tmp06), vsub_f16(_tmp04, _tmp02), 5.25f); float16x4_t _r0tm7 = vfma_n_f16(vsub_f16(_tmp07, _tmp01), vsub_f16(_tmp03, _tmp05), 5.25f); // r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; // r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float16x4_t _tmp12a = vfms_n_f16(vadd_f16(_tmp02, _tmp06), _tmp04, 4.25f); float16x4_t _tmp12b = vfms_n_f16(vadd_f16(_tmp01, _tmp05), _tmp03, 4.25f); // float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); // float tmp12b = (tmp0[1] + tmp0[5] - tmp0[3] * 4.25); float16x4_t _r0tm1 = vadd_f16(_tmp12a, _tmp12b); float16x4_t _r0tm2 = vsub_f16(_tmp12a, _tmp12b); // r0_tm[1] = tmp12a + tmp12b; // r0_tm[2] = tmp12a - tmp12b; float16x4_t _tmp34a = vfms_n_f16(vfma_n_f16(_tmp06, _tmp02, 0.25f), _tmp04, 1.25f); float16x4_t _tmp34b = vfma_n_f16(vfms_n_f16(vmul_n_f16(_tmp01, 0.5f), _tmp03, 2.5f), _tmp05, 2.f); // float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); // float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); float16x4_t _r0tm3 = vadd_f16(_tmp34a, _tmp34b); float16x4_t _r0tm4 = vsub_f16(_tmp34a, _tmp34b); // r0_tm[3] = tmp34a + tmp34b; // r0_tm[4] = tmp34a - tmp34b; float16x4_t _tmp56a = vfma_n_f16(_tmp06, vfms_n_f16(_tmp02, _tmp04, 1.25f), 4.f); float16x4_t _tmp56b = vfma_n_f16(vfms_n_f16(vmul_n_f16(_tmp01, 2.f), _tmp03, 2.5f), _tmp05, 0.5f); // float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); // float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); float16x4_t _r0tm5 = vadd_f16(_tmp56a, _tmp56b); float16x4_t _r0tm6 = vsub_f16(_tmp56a, _tmp56b); // r0_tm[5] = tmp56a + tmp56b; // r0_tm[6] = tmp56a - tmp56b; vst1_f16(r0_tm_0, _r0tm0); vst1_f16(r0_tm_1, _r0tm1); vst1_f16(r0_tm_2, _r0tm2); vst1_f16(r0_tm_3, _r0tm3); vst1_f16(r0_tm_4, _r0tm4); vst1_f16(r0_tm_5, _r0tm5); vst1_f16(r0_tm_6, _r0tm6); vst1_f16(r0_tm_7, _r0tm7); r0_tm_0 += tiles * 32; r0_tm_1 += tiles * 32; r0_tm_2 += tiles * 32; r0_tm_3 += tiles * 32; r0_tm_4 += tiles * 32; r0_tm_5 += tiles * 32; r0_tm_6 += tiles * 32; r0_tm_7 += tiles * 32; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = h_tm / 8 * w_tm / 8; // permute // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 64, 2u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 64, 2u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, 2u * elempack, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 64; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 7 < tiles; i += 8) { __fp16* tm2p = tm2.row<__fp16>(i / 8); const __fp16* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x8 asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n" "st1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3"); r0 += bottom_blob_tm.cstep * 4; } } for (; i + 3 < tiles; i += 4) { __fp16* tm2p = tm2.row<__fp16>(i / 8 + (i % 8) / 4); const __fp16* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x4 asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld4 {v0.4h, v1.4h, v2.4h, v3.4h}, [%0] \n" "st1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%1], #32 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3"); r0 += bottom_blob_tm.cstep * 4; } } for (; i < tiles; i++) { __fp16* tm2p = tm2.row<__fp16>(i / 8 + (i % 8) / 4 + i % 4); const __fp16* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { asm volatile( "prfm pldl1keep, [%0, #64] \n" "ld1 {v0.4h}, [%0] \n" "st1 {v0.4h}, [%1], #8 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0"); r0 += bottom_blob_tm.cstep * 4; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 64, outch, 2u * elempack, elempack, opt.workspace_allocator); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 1; remain_outch_start = nn_outch << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 2; __fp16* output0_tm = top_blob_tm.channel(p); __fp16* output1_tm = top_blob_tm.channel(p + 1); const Mat kernel01_tm = kernel_tm.channel(pp); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 7 < tiles; i += 8) { const __fp16* r0 = bb2.row<const __fp16>(i / 8); const __fp16* kptr = kernel01_tm.row<const __fp16>(r); int nn = inch; // inch always > 0 asm volatile( "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%3], #64 \n" // r01 r23 r45 r67 "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%4], #64 \n" // k0123 "fmla v24.8h, v4.8h, v0.h[0] \n" "fmla v25.8h, v4.8h, v0.h[1] \n" "fmla v26.8h, v4.8h, v0.h[2] \n" "fmla v27.8h, v4.8h, v0.h[3] \n" "fmla v28.8h, v4.8h, v0.h[4] \n" "fmla v29.8h, v4.8h, v0.h[5] \n" "fmla v30.8h, v4.8h, v0.h[6] \n" "fmla v31.8h, v4.8h, v0.h[7] \n" "fmla v24.8h, v5.8h, v1.h[0] \n" "fmla v25.8h, v5.8h, v1.h[1] \n" "fmla v26.8h, v5.8h, v1.h[2] \n" "fmla v27.8h, v5.8h, v1.h[3] \n" "fmla v28.8h, v5.8h, v1.h[4] \n" "fmla v29.8h, v5.8h, v1.h[5] \n" "fmla v30.8h, v5.8h, v1.h[6] \n" "fmla v31.8h, v5.8h, v1.h[7] \n" "fmla v24.8h, v6.8h, v2.h[0] \n" "fmla v25.8h, v6.8h, v2.h[1] \n" "fmla v26.8h, v6.8h, v2.h[2] \n" "fmla v27.8h, v6.8h, v2.h[3] \n" "fmla v28.8h, v6.8h, v2.h[4] \n" "fmla v29.8h, v6.8h, v2.h[5] \n" "fmla v30.8h, v6.8h, v2.h[6] \n" "fmla v31.8h, v6.8h, v2.h[7] \n" "subs %w0, %w0, #1 \n" "fmla v24.8h, v7.8h, v3.h[0] \n" "fmla v25.8h, v7.8h, v3.h[1] \n" "fmla v26.8h, v7.8h, v3.h[2] \n" "fmla v27.8h, v7.8h, v3.h[3] \n" "fmla v28.8h, v7.8h, v3.h[4] \n" "fmla v29.8h, v7.8h, v3.h[5] \n" "fmla v30.8h, v7.8h, v3.h[6] \n" "fmla v31.8h, v7.8h, v3.h[7] \n" "bne 0b \n" "st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n" "st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%1], #32 \n" "ext v24.16b, v24.16b, v24.16b, #8 \n" "ext v25.16b, v25.16b, v25.16b, #8 \n" "ext v26.16b, v26.16b, v26.16b, #8 \n" "ext v27.16b, v27.16b, v27.16b, #8 \n" "ext v28.16b, v28.16b, v28.16b, #8 \n" "ext v29.16b, v29.16b, v29.16b, #8 \n" "ext v30.16b, v30.16b, v30.16b, #8 \n" "ext v31.16b, v31.16b, v31.16b, #8 \n" "st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%2], #32 \n" "st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%2], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(kptr) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 3 < tiles; i += 4) { const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4); const __fp16* kptr = kernel01_tm.row<const __fp16>(r); int nn = inch; // inch always > 0 asm volatile( "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "0: \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%3], #32 \n" // r01 r23 r45 r67 "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%4], #64 \n" // k0123 "fmla v24.8h, v4.8h, v0.h[0] \n" "fmla v25.8h, v4.8h, v0.h[1] \n" "fmla v26.8h, v4.8h, v0.h[2] \n" "fmla v27.8h, v4.8h, v0.h[3] \n" "fmla v24.8h, v5.8h, v1.h[0] \n" "fmla v25.8h, v5.8h, v1.h[1] \n" "fmla v26.8h, v5.8h, v1.h[2] \n" "fmla v27.8h, v5.8h, v1.h[3] \n" "fmla v24.8h, v6.8h, v2.h[0] \n" "fmla v25.8h, v6.8h, v2.h[1] \n" "fmla v26.8h, v6.8h, v2.h[2] \n" "fmla v27.8h, v6.8h, v2.h[3] \n" "subs %w0, %w0, #1 \n" "fmla v24.8h, v7.8h, v3.h[0] \n" "fmla v25.8h, v7.8h, v3.h[1] \n" "fmla v26.8h, v7.8h, v3.h[2] \n" "fmla v27.8h, v7.8h, v3.h[3] \n" "bne 0b \n" "st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n" "ext v24.16b, v24.16b, v24.16b, #8 \n" "ext v25.16b, v25.16b, v25.16b, #8 \n" "ext v26.16b, v26.16b, v26.16b, #8 \n" "ext v27.16b, v27.16b, v27.16b, #8 \n" "st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%2], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(kptr) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v24", "v25", "v26", "v27"); } for (; i < tiles; i++) { const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4 + i % 4); const __fp16* kptr = kernel01_tm.row<const __fp16>(r); float16x8_t _sum0 = vdupq_n_f16(0.f); for (int q = 0; q < inch; q++) { float16x4_t _r0 = vld1_f16(r0); float16x8_t _k0 = vld1q_f16(kptr); float16x8_t _k1 = vld1q_f16(kptr + 8); float16x8_t _k2 = vld1q_f16(kptr + 16); float16x8_t _k3 = vld1q_f16(kptr + 24); _sum0 = vfmaq_lane_f16(_sum0, _k0, _r0, 0); _sum0 = vfmaq_lane_f16(_sum0, _k1, _r0, 1); _sum0 = vfmaq_lane_f16(_sum0, _k2, _r0, 2); _sum0 = vfmaq_lane_f16(_sum0, _k3, _r0, 3); kptr += 32; r0 += 4; } vst1_f16(output0_tm, vget_low_f16(_sum0)); vst1_f16(output1_tm, vget_high_f16(_sum0)); output0_tm += 4; output1_tm += 4; } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { __fp16* output0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p / 2 + p % 2); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 7 < tiles; i += 8) { const __fp16* r0 = bb2.row<const __fp16>(i / 8); const __fp16* kptr = kernel0_tm.row<const __fp16>(r); int nn = inch; // inch always > 0 asm volatile( "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%2], #64 \n" // r01 r23 r45 r67 "prfm pldl1keep, [%3, #256] \n" "ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%3], #32 \n" // k0123 "fmla v24.4h, v4.4h, v0.h[0] \n" "fmla v25.4h, v4.4h, v0.h[1] \n" "fmla v26.4h, v4.4h, v0.h[2] \n" "fmla v27.4h, v4.4h, v0.h[3] \n" "fmla v28.4h, v4.4h, v0.h[4] \n" "fmla v29.4h, v4.4h, v0.h[5] \n" "fmla v30.4h, v4.4h, v0.h[6] \n" "fmla v31.4h, v4.4h, v0.h[7] \n" "fmla v24.4h, v5.4h, v1.h[0] \n" "fmla v25.4h, v5.4h, v1.h[1] \n" "fmla v26.4h, v5.4h, v1.h[2] \n" "fmla v27.4h, v5.4h, v1.h[3] \n" "fmla v28.4h, v5.4h, v1.h[4] \n" "fmla v29.4h, v5.4h, v1.h[5] \n" "fmla v30.4h, v5.4h, v1.h[6] \n" "fmla v31.4h, v5.4h, v1.h[7] \n" "fmla v24.4h, v6.4h, v2.h[0] \n" "fmla v25.4h, v6.4h, v2.h[1] \n" "fmla v26.4h, v6.4h, v2.h[2] \n" "fmla v27.4h, v6.4h, v2.h[3] \n" "fmla v28.4h, v6.4h, v2.h[4] \n" "fmla v29.4h, v6.4h, v2.h[5] \n" "fmla v30.4h, v6.4h, v2.h[6] \n" "fmla v31.4h, v6.4h, v2.h[7] \n" "subs %w0, %w0, #1 \n" "fmla v24.4h, v7.4h, v3.h[0] \n" "fmla v25.4h, v7.4h, v3.h[1] \n" "fmla v26.4h, v7.4h, v3.h[2] \n" "fmla v27.4h, v7.4h, v3.h[3] \n" "fmla v28.4h, v7.4h, v3.h[4] \n" "fmla v29.4h, v7.4h, v3.h[5] \n" "fmla v30.4h, v7.4h, v3.h[6] \n" "fmla v31.4h, v7.4h, v3.h[7] \n" "bne 0b \n" "st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n" "st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%1], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 3 < tiles; i += 4) { const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4); const __fp16* kptr = kernel0_tm.row<const __fp16>(r); int nn = inch; // inch always > 0 asm volatile( "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "0: \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%2], #32 \n" // r01 r23 r45 r67 "prfm pldl1keep, [%3, #256] \n" "ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%3], #32 \n" // k0123 "fmla v24.4h, v4.4h, v0.h[0] \n" "fmla v25.4h, v4.4h, v0.h[1] \n" "fmla v26.4h, v4.4h, v0.h[2] \n" "fmla v27.4h, v4.4h, v0.h[3] \n" "fmla v24.4h, v5.4h, v1.h[0] \n" "fmla v25.4h, v5.4h, v1.h[1] \n" "fmla v26.4h, v5.4h, v1.h[2] \n" "fmla v27.4h, v5.4h, v1.h[3] \n" "fmla v24.4h, v6.4h, v2.h[0] \n" "fmla v25.4h, v6.4h, v2.h[1] \n" "fmla v26.4h, v6.4h, v2.h[2] \n" "fmla v27.4h, v6.4h, v2.h[3] \n" "subs %w0, %w0, #1 \n" "fmla v24.4h, v7.4h, v3.h[0] \n" "fmla v25.4h, v7.4h, v3.h[1] \n" "fmla v26.4h, v7.4h, v3.h[2] \n" "fmla v27.4h, v7.4h, v3.h[3] \n" "bne 0b \n" "st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v24", "v25", "v26", "v27"); } for (; i < tiles; i++) { const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4 + i % 4); const __fp16* kptr = kernel0_tm.row<const __fp16>(r); float16x4_t _sum0 = vdup_n_f16(0.f); for (int q = 0; q < inch; q++) { float16x4_t _r0 = vld1_f16(r0); float16x4_t _k0 = vld1_f16(kptr); float16x4_t _k1 = vld1_f16(kptr + 4); float16x4_t _k2 = vld1_f16(kptr + 8); float16x4_t _k3 = vld1_f16(kptr + 12); _sum0 = vfma_lane_f16(_sum0, _k0, _r0, 0); _sum0 = vfma_lane_f16(_sum0, _k1, _r0, 1); _sum0 = vfma_lane_f16(_sum0, _k2, _r0, 2); _sum0 = vfma_lane_f16(_sum0, _k3, _r0, 3); kptr += 16; r0 += 4; } vst1_f16(output0_tm, _sum0); output0_tm += 4; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 2u * 4, 4, opt.workspace_allocator); } { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); // const float bias0 = bias ? bias[p] : 0.f; float16x4_t _bias0 = bias ? vld1_f16((const __fp16*)bias + p * 4) : vdup_n_f16(0.f); __fp16 tmp[6][8][4]; // tile for (int i = 0; i < outh / 6; i++) { for (int j = 0; j < outw / 6; j++) { // top_blob_tm.create(tiles, 64, outch, elemsize, elempack); const __fp16* output0_tm_0 = (const __fp16*)out0_tm + (i * w_tm / 8 + j) * 4; const __fp16* output0_tm_1 = output0_tm_0 + tiles * 4; const __fp16* output0_tm_2 = output0_tm_0 + tiles * 8; const __fp16* output0_tm_3 = output0_tm_0 + tiles * 12; const __fp16* output0_tm_4 = output0_tm_0 + tiles * 16; const __fp16* output0_tm_5 = output0_tm_0 + tiles * 20; const __fp16* output0_tm_6 = output0_tm_0 + tiles * 24; const __fp16* output0_tm_7 = output0_tm_0 + tiles * 28; __fp16* output0 = out0.row<__fp16>(i * 6) + (j * 6) * 4; // TODO neon optimize for (int m = 0; m < 8; m++) { float16x4_t _out0tm0 = vld1_f16(output0_tm_0); float16x4_t _out0tm1 = vld1_f16(output0_tm_1); float16x4_t _out0tm2 = vld1_f16(output0_tm_2); float16x4_t _out0tm3 = vld1_f16(output0_tm_3); float16x4_t _out0tm4 = vld1_f16(output0_tm_4); float16x4_t _out0tm5 = vld1_f16(output0_tm_5); float16x4_t _out0tm6 = vld1_f16(output0_tm_6); float16x4_t _out0tm7 = vld1_f16(output0_tm_7); float16x4_t _tmp024a = vadd_f16(_out0tm1, _out0tm2); float16x4_t _tmp135a = vsub_f16(_out0tm1, _out0tm2); // float tmp024a = output0_tm[1] + output0_tm[2]; // float tmp135a = output0_tm[1] - output0_tm[2]; float16x4_t _tmp024b = vadd_f16(_out0tm3, _out0tm4); float16x4_t _tmp135b = vsub_f16(_out0tm3, _out0tm4); // float tmp024b = output0_tm[3] + output0_tm[4]; // float tmp135b = output0_tm[3] - output0_tm[4]; float16x4_t _tmp024c = vadd_f16(_out0tm5, _out0tm6); float16x4_t _tmp135c = vsub_f16(_out0tm5, _out0tm6); // float tmp024c = output0_tm[5] + output0_tm[6]; // float tmp135c = output0_tm[5] - output0_tm[6]; float16x4_t _tmp0m = vadd_f16(vadd_f16(_out0tm0, _tmp024a), vfma_n_f16(_tmp024b, _tmp024c, 32.f)); float16x4_t _tmp2m = vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 4.f), _tmp024c, 8.f); float16x4_t _tmp4m = vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 16.f), _tmp024c, 2.f); vst1_f16(tmp[0][m], _tmp0m); vst1_f16(tmp[2][m], _tmp2m); vst1_f16(tmp[4][m], _tmp4m); // tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; // tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; // tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; float16x4_t _tmp1m = vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 2.f), _tmp135c, 16.f); float16x4_t _tmp3m = vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 8.f), _tmp135c, 4.f); float16x4_t _tmp5m = vadd_f16(vadd_f16(_out0tm7, _tmp135a), vfma_n_f16(_tmp135c, _tmp135b, 32.f)); vst1_f16(tmp[1][m], _tmp1m); vst1_f16(tmp[3][m], _tmp3m); vst1_f16(tmp[5][m], _tmp5m); // tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; // tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; // tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; output0_tm_0 += tiles * 32; output0_tm_1 += tiles * 32; output0_tm_2 += tiles * 32; output0_tm_3 += tiles * 32; output0_tm_4 += tiles * 32; output0_tm_5 += tiles * 32; output0_tm_6 += tiles * 32; output0_tm_7 += tiles * 32; } for (int m = 0; m < 6; m++) { float16x4_t _tmp00 = vld1_f16(tmp[m][0]); float16x4_t _tmp01 = vld1_f16(tmp[m][1]); float16x4_t _tmp02 = vld1_f16(tmp[m][2]); float16x4_t _tmp03 = vld1_f16(tmp[m][3]); float16x4_t _tmp04 = vld1_f16(tmp[m][4]); float16x4_t _tmp05 = vld1_f16(tmp[m][5]); float16x4_t _tmp06 = vld1_f16(tmp[m][6]); float16x4_t _tmp07 = vld1_f16(tmp[m][7]); float16x4_t _tmp024a = vadd_f16(_tmp01, _tmp02); float16x4_t _tmp135a = vsub_f16(_tmp01, _tmp02); // float tmp024a = tmp0[1] + tmp0[2]; // float tmp135a = tmp0[1] - tmp0[2]; float16x4_t _tmp024b = vadd_f16(_tmp03, _tmp04); float16x4_t _tmp135b = vsub_f16(_tmp03, _tmp04); // float tmp024b = tmp0[3] + tmp0[4]; // float tmp135b = tmp0[3] - tmp0[4]; float16x4_t _tmp024c = vadd_f16(_tmp05, _tmp06); float16x4_t _tmp135c = vsub_f16(_tmp05, _tmp06); // float tmp024c = tmp0[5] + tmp0[6]; // float tmp135c = tmp0[5] - tmp0[6]; float16x4_t _out00 = vadd_f16(_bias0, vadd_f16(vadd_f16(_tmp00, _tmp024a), vfma_n_f16(_tmp024b, _tmp024c, 32.f))); float16x4_t _out02 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 4.f), _tmp024c, 8.f)); float16x4_t _out04 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 16.f), _tmp024c, 2.f)); vst1_f16(output0, _out00); vst1_f16(output0 + 8, _out02); vst1_f16(output0 + 16, _out04); // output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; // output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; // output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; float16x4_t _out01 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 2.f), _tmp135c, 16.f)); float16x4_t _out03 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 8.f), _tmp135c, 4.f)); float16x4_t _out05 = vadd_f16(_bias0, vadd_f16(vadd_f16(_tmp07, _tmp135a), vfma_n_f16(_tmp135c, _tmp135b, 32.f))); vst1_f16(output0 + 4, _out01); vst1_f16(output0 + 12, _out03); vst1_f16(output0 + 20, _out05); // output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; // output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; // output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw * 4; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s1_pack4_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const __fp16* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); float16x4_t _bias0 = bias ? vld1_f16(bias + p * 4) : vdup_n_f16((__fp16)0.f); out0.fill(_bias0); int q = 0; for (; q < inch; q++) { __fp16* outptr0 = out0.row<__fp16>(0); const Mat img0 = bottom_blob.channel(q); const __fp16* r0 = img0.row<const __fp16>(0); const __fp16* r1 = img0.row<const __fp16>(1); const __fp16* r2 = img0.row<const __fp16>(2); const __fp16* kptr = kernel.channel(p).row<const __fp16>(q); // 16 * 9 float16x8_t _k00_01 = vld1q_f16(kptr); float16x8_t _k00_23 = vld1q_f16(kptr + 8); float16x8_t _k01_01 = vld1q_f16(kptr + 16); float16x8_t _k01_23 = vld1q_f16(kptr + 24); float16x8_t _k02_01 = vld1q_f16(kptr + 32); float16x8_t _k02_23 = vld1q_f16(kptr + 40); float16x8_t _k10_01 = vld1q_f16(kptr + 48); float16x8_t _k10_23 = vld1q_f16(kptr + 56); float16x8_t _k11_01 = vld1q_f16(kptr + 64); float16x8_t _k11_23 = vld1q_f16(kptr + 72); float16x8_t _k12_01 = vld1q_f16(kptr + 80); float16x8_t _k12_23 = vld1q_f16(kptr + 88); float16x8_t _k20_01 = vld1q_f16(kptr + 96); float16x8_t _k20_23 = vld1q_f16(kptr + 104); float16x8_t _k21_01 = vld1q_f16(kptr + 112); float16x8_t _k21_23 = vld1q_f16(kptr + 120); float16x8_t _k22_01 = vld1q_f16(kptr + 128); float16x8_t _k22_23 = vld1q_f16(kptr + 136); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v10.4h, v11.4h, v12.4h, v13.4h}, [%0] \n" // sum0 sum1 sum2 sum3 "prfm pldl1keep, [%1, #384] \n" "ld1 {v0.8h, v1.8h, v2.8h}, [%1] \n" // r00 r01 r02 r03 r04 r05 "ext v6.16b, %8.16b, %8.16b, #8 \n" "fmla v10.4h, %8.4h, v0.h[0] \n" "fmla v11.4h, %8.4h, v0.h[4] \n" "fmla v12.4h, %8.4h, v1.h[0] \n" "fmla v13.4h, %8.4h, v1.h[4] \n" "fmla v10.4h, v6.4h, v0.h[1] \n" "fmla v11.4h, v6.4h, v0.h[5] \n" "fmla v12.4h, v6.4h, v1.h[1] \n" "fmla v13.4h, v6.4h, v1.h[5] \n" "ext v7.16b, %9.16b, %9.16b, #8 \n" "fmla v10.4h, %9.4h, v0.h[2] \n" "fmla v11.4h, %9.4h, v0.h[6] \n" "fmla v12.4h, %9.4h, v1.h[2] \n" "fmla v13.4h, %9.4h, v1.h[6] \n" "fmla v10.4h, v7.4h, v0.h[3] \n" "fmla v11.4h, v7.4h, v0.h[7] \n" "fmla v12.4h, v7.4h, v1.h[3] \n" "fmla v13.4h, v7.4h, v1.h[7] \n" "ext v8.16b, %10.16b, %10.16b, #8 \n" "fmla v10.4h, %10.4h, v0.h[4] \n" "fmla v11.4h, %10.4h, v1.h[0] \n" "fmla v12.4h, %10.4h, v1.h[4] \n" "fmla v13.4h, %10.4h, v2.h[0] \n" "fmla v10.4h, v8.4h, v0.h[5] \n" "fmla v11.4h, v8.4h, v1.h[1] \n" "fmla v12.4h, v8.4h, v1.h[5] \n" "fmla v13.4h, v8.4h, v2.h[1] \n" "ext v9.16b, %11.16b, %11.16b, #8 \n" "fmla v10.4h, %11.4h, v0.h[6] \n" "fmla v11.4h, %11.4h, v1.h[2] \n" "fmla v12.4h, %11.4h, v1.h[6] \n" "fmla v13.4h, %11.4h, v2.h[2] \n" "fmla v10.4h, v9.4h, v0.h[7] \n" "fmla v11.4h, v9.4h, v1.h[3] \n" "fmla v12.4h, v9.4h, v1.h[7] \n" "fmla v13.4h, v9.4h, v2.h[3] \n" "prfm pldl1keep, [%2, #384] \n" "ld1 {v3.8h, v4.8h, v5.8h}, [%2] \n" // r10 r11 r12 r13 r14 r15 "ext v6.16b, %12.16b, %12.16b, #8 \n" "fmla v10.4h, %12.4h, v1.h[0] \n" "fmla v11.4h, %12.4h, v1.h[4] \n" "fmla v12.4h, %12.4h, v2.h[0] \n" "fmla v13.4h, %12.4h, v2.h[4] \n" "fmla v10.4h, v6.4h, v1.h[1] \n" "fmla v11.4h, v6.4h, v1.h[5] \n" "fmla v12.4h, v6.4h, v2.h[1] \n" "fmla v13.4h, v6.4h, v2.h[5] \n" "ext v7.16b, %13.16b, %13.16b, #8 \n" "fmla v10.4h, %13.4h, v1.h[2] \n" "fmla v11.4h, %13.4h, v1.h[6] \n" "fmla v12.4h, %13.4h, v2.h[2] \n" "fmla v13.4h, %13.4h, v2.h[6] \n" "fmla v10.4h, v7.4h, v1.h[3] \n" "fmla v11.4h, v7.4h, v1.h[7] \n" "fmla v12.4h, v7.4h, v2.h[3] \n" "fmla v13.4h, v7.4h, v2.h[7] \n" "ext v8.16b, %14.16b, %14.16b, #8 \n" "fmla v10.4h, %14.4h, v3.h[0] \n" "fmla v11.4h, %14.4h, v3.h[4] \n" "fmla v12.4h, %14.4h, v4.h[0] \n" "fmla v13.4h, %14.4h, v4.h[4] \n" "fmla v10.4h, v8.4h, v3.h[1] \n" "fmla v11.4h, v8.4h, v3.h[5] \n" "fmla v12.4h, v8.4h, v4.h[1] \n" "fmla v13.4h, v8.4h, v4.h[5] \n" "ext v9.16b, %15.16b, %15.16b, #8 \n" "fmla v10.4h, %15.4h, v3.h[2] \n" "fmla v11.4h, %15.4h, v3.h[6] \n" "fmla v12.4h, %15.4h, v4.h[2] \n" "fmla v13.4h, %15.4h, v4.h[6] \n" "fmla v10.4h, v9.4h, v3.h[3] \n" "fmla v11.4h, v9.4h, v3.h[7] \n" "fmla v12.4h, v9.4h, v4.h[3] \n" "fmla v13.4h, v9.4h, v4.h[7] \n" "ext v6.16b, %16.16b, %16.16b, #8 \n" "fmla v10.4h, %16.4h, v3.h[4] \n" "fmla v11.4h, %16.4h, v4.h[0] \n" "fmla v12.4h, %16.4h, v4.h[4] \n" "fmla v13.4h, %16.4h, v5.h[0] \n" "fmla v10.4h, v6.4h, v3.h[5] \n" "fmla v11.4h, v6.4h, v4.h[1] \n" "fmla v12.4h, v6.4h, v4.h[5] \n" "fmla v13.4h, v6.4h, v5.h[1] \n" "ext v7.16b, %17.16b, %17.16b, #8 \n" "fmla v10.4h, %17.4h, v3.h[6] \n" "fmla v11.4h, %17.4h, v4.h[2] \n" "fmla v12.4h, %17.4h, v4.h[6] \n" "fmla v13.4h, %17.4h, v5.h[2] \n" "fmla v10.4h, v7.4h, v3.h[7] \n" "fmla v11.4h, v7.4h, v4.h[3] \n" "fmla v12.4h, v7.4h, v4.h[7] \n" "fmla v13.4h, v7.4h, v5.h[3] \n" "prfm pldl1keep, [%3, #384] \n" "ld1 {v0.8h, v1.8h, v2.8h}, [%3] \n" // r20 r21 r22 r23 r24 r25 "ext v8.16b, %18.16b, %18.16b, #8 \n" "fmla v10.4h, %18.4h, v4.h[0] \n" "fmla v11.4h, %18.4h, v4.h[4] \n" "fmla v12.4h, %18.4h, v5.h[0] \n" "fmla v13.4h, %18.4h, v5.h[4] \n" "fmla v10.4h, v8.4h, v4.h[1] \n" "fmla v11.4h, v8.4h, v4.h[5] \n" "fmla v12.4h, v8.4h, v5.h[1] \n" "fmla v13.4h, v8.4h, v5.h[5] \n" "ext v9.16b, %19.16b, %19.16b, #8 \n" "fmla v10.4h, %19.4h, v4.h[2] \n" "fmla v11.4h, %19.4h, v4.h[6] \n" "fmla v12.4h, %19.4h, v5.h[2] \n" "fmla v13.4h, %19.4h, v5.h[6] \n" "fmla v10.4h, v9.4h, v4.h[3] \n" "fmla v11.4h, v9.4h, v4.h[7] \n" "fmla v12.4h, v9.4h, v5.h[3] \n" "fmla v13.4h, v9.4h, v5.h[7] \n" "ext v6.16b, %20.16b, %20.16b, #8 \n" "fmla v10.4h, %20.4h, v0.h[0] \n" "fmla v11.4h, %20.4h, v0.h[4] \n" "fmla v12.4h, %20.4h, v1.h[0] \n" "fmla v13.4h, %20.4h, v1.h[4] \n" "fmla v10.4h, v6.4h, v0.h[1] \n" "fmla v11.4h, v6.4h, v0.h[5] \n" "fmla v12.4h, v6.4h, v1.h[1] \n" "fmla v13.4h, v6.4h, v1.h[5] \n" "ext v7.16b, %21.16b, %21.16b, #8 \n" "fmla v10.4h, %21.4h, v0.h[2] \n" "fmla v11.4h, %21.4h, v0.h[6] \n" "fmla v12.4h, %21.4h, v1.h[2] \n" "fmla v13.4h, %21.4h, v1.h[6] \n" "fmla v10.4h, v7.4h, v0.h[3] \n" "fmla v11.4h, v7.4h, v0.h[7] \n" "fmla v12.4h, v7.4h, v1.h[3] \n" "fmla v13.4h, v7.4h, v1.h[7] \n" "ext v8.16b, %22.16b, %22.16b, #8 \n" "fmla v10.4h, %22.4h, v0.h[4] \n" "fmla v11.4h, %22.4h, v1.h[0] \n" "fmla v12.4h, %22.4h, v1.h[4] \n" "fmla v13.4h, %22.4h, v2.h[0] \n" "fmla v10.4h, v8.4h, v0.h[5] \n" "fmla v11.4h, v8.4h, v1.h[1] \n" "fmla v12.4h, v8.4h, v1.h[5] \n" "fmla v13.4h, v8.4h, v2.h[1] \n" "ext v9.16b, %23.16b, %23.16b, #8 \n" "fmla v10.4h, %23.4h, v0.h[6] \n" "fmla v11.4h, %23.4h, v1.h[2] \n" "fmla v12.4h, %23.4h, v1.h[6] \n" "fmla v13.4h, %23.4h, v2.h[2] \n" "fmla v10.4h, v9.4h, v0.h[7] \n" "fmla v11.4h, v9.4h, v1.h[3] \n" "fmla v12.4h, v9.4h, v1.h[7] \n" "fmla v13.4h, v9.4h, v2.h[3] \n" "ext v6.16b, %24.16b, %24.16b, #8 \n" "fmla v10.4h, %24.4h, v1.h[0] \n" "fmla v11.4h, %24.4h, v1.h[4] \n" "fmla v12.4h, %24.4h, v2.h[0] \n" "fmla v13.4h, %24.4h, v2.h[4] \n" "add %1, %1, #32 \n" "fmla v10.4h, v6.4h, v1.h[1] \n" "fmla v11.4h, v6.4h, v1.h[5] \n" "fmla v12.4h, v6.4h, v2.h[1] \n" "fmla v13.4h, v6.4h, v2.h[5] \n" "ext v7.16b, %25.16b, %25.16b, #8 \n" "fmla v10.4h, %25.4h, v1.h[2] \n" "fmla v11.4h, %25.4h, v1.h[6] \n" "fmla v12.4h, %25.4h, v2.h[2] \n" "fmla v13.4h, %25.4h, v2.h[6] \n" "add %2, %2, #32 \n" "fmla v10.4h, v7.4h, v1.h[3] \n" "fmla v11.4h, v7.4h, v1.h[7] \n" "fmla v12.4h, v7.4h, v2.h[3] \n" "fmla v13.4h, v7.4h, v2.h[7] \n" "add %3, %3, #32 \n" "st1 {v10.4h, v11.4h, v12.4h, v13.4h}, [%0], #32 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00_01), // %8 "w"(_k00_23), // %9 "w"(_k01_01), // %10 "w"(_k01_23), // %11 "w"(_k02_01), // %12 "w"(_k02_23), // %13 "w"(_k10_01), // %14 "w"(_k10_23), // %15 "w"(_k11_01), // %16 "w"(_k11_23), // %17 "w"(_k12_01), // %18 "w"(_k12_23), // %19 "w"(_k20_01), // %20 "w"(_k20_23), // %21 "w"(_k21_01), // %22 "w"(_k21_23), // %23 "w"(_k22_01), // %24 "w"(_k22_23) // %25 : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13"); } for (; j + 1 < outw; j += 2) { asm volatile( "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.8h, v1.8h}, [%1] \n" // r00 r01 r02 r03 "prfm pldl1keep, [%0, #128] \n" "ld1 {v12.4h, v13.4h}, [%0] \n" // sum0 sum1 "ext v4.16b, %8.16b, %8.16b, #8 \n" "fmul v10.4h, %8.4h, v0.h[0] \n" "fmul v11.4h, %8.4h, v0.h[4] \n" "fmla v12.4h, v4.4h, v0.h[1] \n" "fmla v13.4h, v4.4h, v0.h[5] \n" "ext v5.16b, %9.16b, %9.16b, #8 \n" "fmla v10.4h, %9.4h, v0.h[2] \n" "fmla v11.4h, %9.4h, v0.h[6] \n" "fmla v12.4h, v5.4h, v0.h[3] \n" "fmla v13.4h, v5.4h, v0.h[7] \n" "ext v6.16b, %10.16b, %10.16b, #8 \n" "fmla v10.4h, %10.4h, v0.h[4] \n" "fmla v11.4h, %10.4h, v1.h[0] \n" "fmla v12.4h, v6.4h, v0.h[5] \n" "fmla v13.4h, v6.4h, v1.h[1] \n" "ext v7.16b, %11.16b, %11.16b, #8 \n" "fmla v10.4h, %11.4h, v0.h[6] \n" "fmla v11.4h, %11.4h, v1.h[2] \n" "fmla v12.4h, v7.4h, v0.h[7] \n" "fmla v13.4h, v7.4h, v1.h[3] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.8h, v3.8h}, [%2] \n" // r10 r11 r12 r13 "ext v8.16b, %12.16b, %12.16b, #8 \n" "fmla v10.4h, %12.4h, v1.h[0] \n" "fmla v11.4h, %12.4h, v1.h[4] \n" "fmla v12.4h, v8.4h, v1.h[1] \n" "fmla v13.4h, v8.4h, v1.h[5] \n" "ext v9.16b, %13.16b, %13.16b, #8 \n" "fmla v10.4h, %13.4h, v1.h[2] \n" "fmla v11.4h, %13.4h, v1.h[6] \n" "fmla v12.4h, v9.4h, v1.h[3] \n" "fmla v13.4h, v9.4h, v1.h[7] \n" "ext v4.16b, %14.16b, %14.16b, #8 \n" "fmla v10.4h, %14.4h, v2.h[0] \n" "fmla v11.4h, %14.4h, v2.h[4] \n" "fmla v12.4h, v4.4h, v2.h[1] \n" "fmla v13.4h, v4.4h, v2.h[5] \n" "ext v5.16b, %15.16b, %15.16b, #8 \n" "fmla v10.4h, %15.4h, v2.h[2] \n" "fmla v11.4h, %15.4h, v2.h[6] \n" "fmla v12.4h, v5.4h, v2.h[3] \n" "fmla v13.4h, v5.4h, v2.h[7] \n" "ext v6.16b, %16.16b, %16.16b, #8 \n" "fmla v10.4h, %16.4h, v2.h[4] \n" "fmla v11.4h, %16.4h, v3.h[0] \n" "fmla v12.4h, v6.4h, v2.h[5] \n" "fmla v13.4h, v6.4h, v3.h[1] \n" "ext v7.16b, %17.16b, %17.16b, #8 \n" "fmla v10.4h, %17.4h, v2.h[6] \n" "fmla v11.4h, %17.4h, v3.h[2] \n" "fmla v12.4h, v7.4h, v2.h[7] \n" "fmla v13.4h, v7.4h, v3.h[3] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v0.8h, v1.8h}, [%3] \n" // r20 r21 r22 r23 "ext v8.16b, %18.16b, %18.16b, #8 \n" "fmla v10.4h, %18.4h, v3.h[0] \n" "fmla v11.4h, %18.4h, v3.h[4] \n" "fmla v12.4h, v8.4h, v3.h[1] \n" "fmla v13.4h, v8.4h, v3.h[5] \n" "ext v9.16b, %19.16b, %19.16b, #8 \n" "fmla v10.4h, %19.4h, v3.h[2] \n" "fmla v11.4h, %19.4h, v3.h[6] \n" "fmla v12.4h, v9.4h, v3.h[3] \n" "fmla v13.4h, v9.4h, v3.h[7] \n" "ext v4.16b, %20.16b, %20.16b, #8 \n" "fmla v10.4h, %20.4h, v0.h[0] \n" "fmla v11.4h, %20.4h, v0.h[4] \n" "fmla v12.4h, v4.4h, v0.h[1] \n" "fmla v13.4h, v4.4h, v0.h[5] \n" "ext v5.16b, %21.16b, %21.16b, #8 \n" "fmla v10.4h, %21.4h, v0.h[2] \n" "fmla v11.4h, %21.4h, v0.h[6] \n" "fmla v12.4h, v5.4h, v0.h[3] \n" "fmla v13.4h, v5.4h, v0.h[7] \n" "ext v6.16b, %22.16b, %22.16b, #8 \n" "fmla v10.4h, %22.4h, v0.h[4] \n" "fmla v11.4h, %22.4h, v1.h[0] \n" "fmla v12.4h, v6.4h, v0.h[5] \n" "fmla v13.4h, v6.4h, v1.h[1] \n" "ext v7.16b, %23.16b, %23.16b, #8 \n" "fmla v10.4h, %23.4h, v0.h[6] \n" "fmla v11.4h, %23.4h, v1.h[2] \n" "fmla v12.4h, v7.4h, v0.h[7] \n" "fmla v13.4h, v7.4h, v1.h[3] \n" "ext v8.16b, %24.16b, %24.16b, #8 \n" "fmla v10.4h, %24.4h, v1.h[0] \n" "fmla v11.4h, %24.4h, v1.h[4] \n" "fmla v12.4h, v8.4h, v1.h[1] \n" "fmla v13.4h, v8.4h, v1.h[5] \n" "ext v9.16b, %25.16b, %25.16b, #8 \n" "fmla v10.4h, %25.4h, v1.h[2] \n" "fmla v11.4h, %25.4h, v1.h[6] \n" "fmla v12.4h, v9.4h, v1.h[3] \n" "fmla v13.4h, v9.4h, v1.h[7] \n" "add %1, %1, #16 \n" "fadd v10.4h, v10.4h, v12.4h \n" "add %2, %2, #16 \n" "fadd v11.4h, v11.4h, v13.4h \n" "add %3, %3, #16 \n" "st1 {v10.4h, v11.4h}, [%0], #16 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00_01), // %8 "w"(_k00_23), // %9 "w"(_k01_01), // %10 "w"(_k01_23), // %11 "w"(_k02_01), // %12 "w"(_k02_23), // %13 "w"(_k10_01), // %14 "w"(_k10_23), // %15 "w"(_k11_01), // %16 "w"(_k11_23), // %17 "w"(_k12_01), // %18 "w"(_k12_23), // %19 "w"(_k20_01), // %20 "w"(_k20_23), // %21 "w"(_k21_01), // %22 "w"(_k21_23), // %23 "w"(_k22_01), // %24 "w"(_k22_23) // %25 : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13"); } for (; j < outw; j++) { asm volatile( "prfm pldl1keep, [%1, #192] \n" "ld1 {v0.4h, v1.4h, v2.4h}, [%1] \n" // r00 r01 r02 "prfm pldl1keep, [%0, #64] \n" "ld1 {v13.4h}, [%0] \n" // sum0 "ext v6.16b, %8.16b, %8.16b, #8 \n" "fmul v10.4h, %8.4h, v0.h[0] \n" "fmul v11.4h, v6.4h, v0.h[1] \n" "ext v7.16b, %9.16b, %9.16b, #8 \n" "fmul v12.4h, %9.4h, v0.h[2] \n" "fmla v13.4h, v7.4h, v0.h[3] \n" "ext v8.16b, %10.16b, %10.16b, #8 \n" "fmla v10.4h, %10.4h, v1.h[0] \n" "fmla v11.4h, v8.4h, v1.h[1] \n" "ext v9.16b, %11.16b, %11.16b, #8 \n" "fmla v12.4h, %11.4h, v1.h[2] \n" "fmla v13.4h, v9.4h, v1.h[3] \n" "prfm pldl1keep, [%2, #192] \n" "ld1 {v3.4h, v4.4h, v5.4h}, [%2] \n" // r10 r11 r12 "ext v6.16b, %12.16b, %12.16b, #8 \n" "fmla v10.4h, %12.4h, v2.h[0] \n" "fmla v11.4h, v6.4h, v2.h[1] \n" "ext v7.16b, %13.16b, %13.16b, #8 \n" "fmla v12.4h, %13.4h, v2.h[2] \n" "fmla v13.4h, v7.4h, v2.h[3] \n" "ext v8.16b, %14.16b, %14.16b, #8 \n" "fmla v10.4h, %14.4h, v3.h[0] \n" "fmla v11.4h, v8.4h, v3.h[1] \n" "ext v9.16b, %15.16b, %15.16b, #8 \n" "fmla v12.4h, %15.4h, v3.h[2] \n" "fmla v13.4h, v9.4h, v3.h[3] \n" "ext v6.16b, %16.16b, %16.16b, #8 \n" "fmla v10.4h, %16.4h, v4.h[0] \n" "fmla v11.4h, v6.4h, v4.h[1] \n" "ext v7.16b, %17.16b, %17.16b, #8 \n" "fmla v12.4h, %17.4h, v4.h[2] \n" "fmla v13.4h, v7.4h, v4.h[3] \n" "prfm pldl1keep, [%3, #192] \n" "ld1 {v0.4h, v1.4h, v2.4h}, [%3] \n" // r20 r21 r22 "ext v8.16b, %18.16b, %18.16b, #8 \n" "fmla v10.4h, %18.4h, v5.h[0] \n" "fmla v11.4h, v8.4h, v5.h[1] \n" "ext v9.16b, %19.16b, %19.16b, #8 \n" "fmla v12.4h, %19.4h, v5.h[2] \n" "fmla v13.4h, v9.4h, v5.h[3] \n" "ext v6.16b, %20.16b, %20.16b, #8 \n" "fmla v10.4h, %20.4h, v0.h[0] \n" "fmla v11.4h, v6.4h, v0.h[1] \n" "ext v7.16b, %21.16b, %21.16b, #8 \n" "fmla v12.4h, %21.4h, v0.h[2] \n" "fmla v13.4h, v7.4h, v0.h[3] \n" "ext v8.16b, %22.16b, %22.16b, #8 \n" "fmla v10.4h, %22.4h, v1.h[0] \n" "fmla v11.4h, v8.4h, v1.h[1] \n" "ext v9.16b, %23.16b, %23.16b, #8 \n" "fmla v12.4h, %23.4h, v1.h[2] \n" "fmla v13.4h, v9.4h, v1.h[3] \n" "ext v6.16b, %24.16b, %24.16b, #8 \n" "fmla v10.4h, %24.4h, v2.h[0] \n" "fmla v11.4h, v6.4h, v2.h[1] \n" "ext v7.16b, %25.16b, %25.16b, #8 \n" "fmla v12.4h, %25.4h, v2.h[2] \n" "fmla v13.4h, v7.4h, v2.h[3] \n" "fadd v10.4h, v10.4h, v11.4h \n" "add %1, %1, #8 \n" "fadd v12.4h, v12.4h, v13.4h \n" "add %2, %2, #8 \n" "fadd v10.4h, v10.4h, v12.4h \n" "add %3, %3, #8 \n" "st1 {v10.4h}, [%0], #8 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00_01), // %8 "w"(_k00_23), // %9 "w"(_k01_01), // %10 "w"(_k01_23), // %11 "w"(_k02_01), // %12 "w"(_k02_23), // %13 "w"(_k10_01), // %14 "w"(_k10_23), // %15 "w"(_k11_01), // %16 "w"(_k11_23), // %17 "w"(_k12_01), // %18 "w"(_k12_23), // %19 "w"(_k20_01), // %20 "w"(_k20_23), // %21 "w"(_k21_01), // %22 "w"(_k21_23), // %23 "w"(_k22_01), // %24 "w"(_k22_23) // %25 : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13"); } r0 += 8; r1 += 8; r2 += 8; } } } }
9.race2.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 100 int main() { int A[N]; #pragma omp for simd for (int i = 3; i < N; i++) { A[i] = A[i - 3] + 2; } return 0; } // CHECK: Data Race detected // END
ParallelOpenMP.h
#pragma once #include <cstddef> #include <exception> #include <c10/util/SmallVector.h> #ifdef _OPENMP #define INTRA_OP_PARALLEL #include <omp.h> #endif namespace at { #ifdef _OPENMP namespace internal { template <typename F> inline void invoke_parallel(int64_t begin, int64_t end, int64_t grain_size, const F& f) { std::atomic_flag err_flag = ATOMIC_FLAG_INIT; std::exception_ptr eptr; #pragma omp parallel { // choose number of tasks based on grain size and number of threads // can't use num_threads clause due to bugs in GOMP's thread pool (See #32008) int64_t num_threads = omp_get_num_threads(); if (grain_size > 0) { num_threads = std::min(num_threads, divup((end - begin), grain_size)); } int64_t tid = omp_get_thread_num(); int64_t chunk_size = divup((end - begin), num_threads); int64_t begin_tid = begin + tid * chunk_size; if (begin_tid < end) { try { internal::ThreadIdGuard tid_guard(tid); f(begin_tid, std::min(end, chunk_size + begin_tid)); } catch (...) { if (!err_flag.test_and_set()) { eptr = std::current_exception(); } } } } if (eptr) { std::rethrow_exception(eptr); } } } // namespace internal #endif // _OPENMP template <class F> inline void parallel_for( const int64_t begin, const int64_t end, const int64_t grain_size, const F& f) { TORCH_INTERNAL_ASSERT_DEBUG_ONLY(grain_size >= 0); if (begin >= end) { return; } #ifdef _OPENMP at::internal::lazy_init_num_threads(); const auto numiter = end - begin; const bool use_parallel = ( numiter > grain_size && numiter > 1 && omp_get_max_threads() > 1 && !omp_in_parallel()); if (!use_parallel) { internal::ThreadIdGuard tid_guard(0); f(begin, end); return; } internal::invoke_parallel(begin, end, grain_size, f); #else internal::ThreadIdGuard tid_guard(0); f(begin, end); #endif } template <class scalar_t, class F, class SF> inline scalar_t parallel_reduce( const int64_t begin, const int64_t end, const int64_t grain_size, const scalar_t ident, const F& f, const SF& sf) { TORCH_CHECK(grain_size >= 0); if (begin >= end) { return ident; } #ifdef _OPENMP at::internal::lazy_init_num_threads(); const bool use_parallel = ( (end - begin) <= grain_size || in_parallel_region() || get_num_threads() == 1); if (!use_parallel) { internal::ThreadIdGuard tid_guard(0); return f(begin, end, ident); } c10::SmallVector<scalar_t, 64> results(at::get_num_threads(), ident); internal::invoke_parallel(begin, end, grain_size, [&](int64_t begin, int64_t end) { auto tid = at::get_thread_num(); results[tid] = f(begin, end, ident); }); scalar_t result = ident; for (auto partial_result : results) { result = sf(result, partial_result); } return result; #else internal::ThreadIdGuard tid_guard(0); return f(begin, end, ident); #endif } } // namespace at
compute.c
#include <omp.h> #include "../omp_mm.h" void compute() { #pragma omp parallel for shared( a, b, c) private(i, j, k) for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { for (k = 0; k < SIZE; k++) { c[i][j] += (a[i][k] * b[k][j]); } } } }
rawSHA1_ng_fmt_plug.c
// // Alternative SSE2 optimised raw SHA-1 implementation for John The Ripper. // // This plugin requires -msse4 in CFLAGS. // // Copyright (C) 2012 Tavis Ormandy <taviso@cmpxchg8b.com> // Copyright (c) 2015 magnum (AVX2/AVX512 support) // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, // Boston, MA 02110-1301, USA. // #include "arch.h" #if defined(SIMD_COEF_32) && (SIMD_COEF_32 < 16 || ARCH_BITS >= 64) && !_MSC_VER && !__ARM_NEON #if FMT_EXTERNS_H extern struct fmt_main fmt_sha1_ng; #elif FMT_REGISTERS_H john_register_one(&fmt_sha1_ng); #else #include "misc.h" #if !defined(DEBUG) && !defined(WITH_ASAN) // These compilers claim to be __GNUC__ but warn on gcc pragmas. #if __GNUC__ && !__INTEL_COMPILER && !__clang__ && !__llvm__ && !_MSC_VER #pragma GCC optimize 3 #pragma GCC optimize "-fprefetch-loop-arrays" #endif #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #include <string.h> #include <stdint.h> #if !FAST_FORMATS_OMP #undef _OPENMP #elif _OPENMP #include <omp.h> #endif #include "stdbool.h" #if SIMD_COEF_32 > 8 #include "int128.h" #endif #include "pseudo_intrinsics.h" #include "params.h" #include "formats.h" #include "memory.h" #include "sha.h" #include "johnswap.h" #include "aligned.h" #include "rawSHA1_common.h" #include "memdbg.h" #define VWIDTH SIMD_COEF_32 #define SHA1_BLOCK_WORDS 16 #define SHA1_DIGEST_WORDS 5 #define SHA1_PARALLEL_HASH 512 // This must be a multiple of max VWIDTH. #ifdef __MIC__ #ifndef OMP_SCALE #define OMP_SCALE 128 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 // Multiplier to hide OMP overhead #endif #endif #define X(X0, X2, X8, X13) do { \ X0 = vxor(X0, X8); \ X0 = vxor(X0, X13); \ X0 = vxor(X0, X2); \ X0 = vroti_epi32(X0, 1); \ } while (false) #define R1(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vcmov(C, D, B)); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #define R2(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vxor(vxor(B, C), D)); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #define R4(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vxor(vxor(B, C), D)); \ E = vadd_epi32(E, W); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #if !VCMOV_EMULATED #define R3(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vcmov(D, B, vxor(C, B))); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #else #define R3(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vor(vand(D, B), vand(vor(D, B), C))); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #endif #if SIMD_COEF_32 == 4 // Not used for AVX2 and better, which has gather instructions. #define _MM_TRANSPOSE4_EPI32(R0, R1, R2, R3) do {\ vtype T0, T1, T2, T3; \ T0 = vunpacklo_epi32(R0, R1); \ T1 = vunpacklo_epi32(R2, R3); \ T2 = vunpackhi_epi32(R0, R1); \ T3 = vunpackhi_epi32(R2, R3); \ R0 = vunpacklo_epi64(T0, T1); \ R1 = vunpackhi_epi64(T0, T1); \ R2 = vunpacklo_epi64(T2, T3); \ R3 = vunpackhi_epi64(T2, T3); \ } while (false) #endif // M and N contain the first and last 128bits of a 512bit SHA-1 message block // respectively. The remaining 256bits are always zero, and so are not stored // here to avoid the load overhead. // For AVX2, we have half a block and for AVX512/MIC we actually have a full // block. static uint32_t (*M)[VWIDTH]; static uint32_t *N; // MD contains the state of the SHA-1 A register at R75 for each of the input // messages. static uint32_t *MD; /* unused inline static uint32_t __attribute__((const)) rotateright(uint32_t value, uint8_t count) { register uint32_t result; asm("ror %%cl, %0" : "=r" (result) : "0" (value), "c" (count)); return result; } */ inline static uint32_t __attribute__((const)) rotateleft(uint32_t value, uint8_t count) { register uint32_t result; #if (__MINGW32__ || __MINGW64__) && __STRICT_ANSI__ result = _rotl(value, count); //((value<<count)|((uint32_t)value>>(32-count))); #elif __i386__ || __x86_64__ asm("rol %%cl, %0" : "=r" (result) : "0" (value), "c" (count)); #else // assume count <= 32 result = (value << count) | (value >> (32 - count)); #endif return result; } // GCC < 4.3 does not have __builtin_bswap32(), provide an alternative. #if !__INTEL_COMPILER && GCC_VERSION < 40300 #define __builtin_bswap32 bswap32 inline static uint32_t __attribute__((const)) bswap32(uint32_t value) { register uint32_t result; #if (__MINGW32__ || __MINGW64__) && __STRICT_ANSI__ result = _byteswap_ulong(value); #elif __i386 || __x86_64__ asm("bswap %0" : "=r" (result) : "0" (value)); #else result = (value << 24) | ((value << 8) & 0xFF0000) | (value >> 24) | ((value >> 8) & 0xFF00); #endif return result; } #endif static void sha1_fmt_init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif M = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*M), MEM_ALIGN_CACHE); N = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*N), MEM_ALIGN_CACHE); MD = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*MD), MEM_ALIGN_CACHE); } static void done(void) { MEM_FREE(MD); MEM_FREE(N); MEM_FREE(M); } static void *sha1_fmt_binary(char *ciphertext) { // Static buffer storing the binary representation of ciphertext. static union { uint32_t w[SHA1_DIGEST_WORDS]; vtype v; } result; uint32_t a75; // Convert ascii representation into binary. memcpy(result.w, rawsha1_common_get_binary(ciphertext), 20); // One preprocessing step, if we calculate E80 rol 2 here, we // can compare it against A75 and save 5 rounds in crypt_all(). a75 = rotateleft(__builtin_bswap32(result.w[4]) - 0xC3D2E1F0, 2); // Fill the vector with it, so we can do a vectorized compare result.v = vset1_epi32(a75); return result.w; } // This function is called when John wants us to buffer a crypt() operation // on the specified key. We also preprocess it for SHA-1 as we load it. // // This implementation is hardcoded to only accept passwords under 15 // characters. This is because we can create a new message block in just two // MOVDQA instructions (we need 15 instead of 16 because we must append a bit // to the message). For AVX2 it's 31 characters and for AVX-512+ it's 125. // // This routine assumes that key is not on an unmapped page boundary, but // doesn't require it to be 16 byte aligned (although that would be nice). static void sha1_fmt_set_key(char *key, int index) { vtype Z = vsetzero(); vtype X = vloadu(key); vtype B; // First, find the length of the key by scanning for a zero byte. #if (__AVX512F__ && !__AVX512BW__) || __MIC__ || __ALTIVEC__ || __ARM_NEON uint32_t len = strlen(key); #else // FIXME: even uint64_t won't be long enough for AVX-1024 uint64_t mask = vcmpeq_epi8_mask(X, Z); uint32_t len = __builtin_ctzl(mask); #endif // Create a lookup tables to find correct masks for each supported input // length. It would be nice if we could use bit shifts to produce these // dynamically, but they require an immediate operand. #if VWIDTH > 8 // FIXME: a problem with using int128 here is it won't work at // all for 32-bit builds - but that may be academic. #define XX ((((uint128_t)0xFFFFFFFFFFFFFFFFULL)<<64) + 0xFFFFFFFFFFFFFFFFULL) #define YY ((uint128_t)0x80) #define ZZ ((uint128_t)0x0) static const JTR_ALIGN(MEM_ALIGN_SIMD) uint128_t kTrailingBitTable[][4] = { {YY<< 0, ZZ, ZZ, ZZ}, {YY<< 8, ZZ, ZZ, ZZ}, {YY<< 16, ZZ, ZZ, ZZ}, {YY<< 24, ZZ, ZZ, ZZ}, {YY<< 32, ZZ, ZZ, ZZ}, {YY<< 40, ZZ, ZZ, ZZ}, {YY<< 48, ZZ, ZZ, ZZ}, {YY<< 56, ZZ, ZZ, ZZ}, {YY<< 64, ZZ, ZZ, ZZ}, {YY<< 72, ZZ, ZZ, ZZ}, {YY<< 80, ZZ, ZZ, ZZ}, {YY<< 88, ZZ, ZZ, ZZ}, {YY<< 96, ZZ, ZZ, ZZ}, {YY<<104, ZZ, ZZ, ZZ}, {YY<<112, ZZ, ZZ, ZZ}, {YY<<120, ZZ, ZZ, ZZ}, {ZZ, YY<< 0, ZZ, ZZ}, {ZZ, YY<< 8, ZZ, ZZ}, {ZZ, YY<< 16, ZZ, ZZ}, {ZZ, YY<< 24, ZZ, ZZ}, {ZZ, YY<< 32, ZZ, ZZ}, {ZZ, YY<< 40, ZZ, ZZ}, {ZZ, YY<< 48, ZZ, ZZ}, {ZZ, YY<< 56, ZZ, ZZ}, {ZZ, YY<< 64, ZZ, ZZ}, {ZZ, YY<< 72, ZZ, ZZ}, {ZZ, YY<< 80, ZZ, ZZ}, {ZZ, YY<< 88, ZZ, ZZ}, {ZZ, YY<< 96, ZZ, ZZ}, {ZZ, YY<<104, ZZ, ZZ}, {ZZ, YY<<112, ZZ, ZZ}, {ZZ, YY<<120, ZZ, ZZ}, {ZZ, ZZ, YY<< 0, ZZ}, {ZZ, ZZ, YY<< 8, ZZ}, {ZZ, ZZ, YY<< 16, ZZ}, {ZZ, ZZ, YY<< 24, ZZ}, {ZZ, ZZ, YY<< 32, ZZ}, {ZZ, ZZ, YY<< 40, ZZ}, {ZZ, ZZ, YY<< 48, ZZ}, {ZZ, ZZ, YY<< 56, ZZ}, {ZZ, ZZ, YY<< 64, ZZ}, {ZZ, ZZ, YY<< 72, ZZ}, {ZZ, ZZ, YY<< 80, ZZ}, {ZZ, ZZ, YY<< 88, ZZ}, {ZZ, ZZ, YY<< 96, ZZ}, {ZZ, ZZ, YY<<104, ZZ}, {ZZ, ZZ, YY<<112, ZZ}, {ZZ, ZZ, YY<<120, ZZ}, {ZZ, ZZ, ZZ, YY<< 0}, {ZZ, ZZ, ZZ, YY<< 8}, {ZZ, ZZ, ZZ, YY<< 16}, {ZZ, ZZ, ZZ, YY<< 24}, {ZZ, ZZ, ZZ, YY<< 32}, {ZZ, ZZ, ZZ, YY<< 40}, {ZZ, ZZ, ZZ, YY<< 48}, {ZZ, ZZ, ZZ, YY<< 56}, {ZZ, ZZ, ZZ, YY<< 64}, {ZZ, ZZ, ZZ, YY<< 72}, {ZZ, ZZ, ZZ, YY<< 80}, {ZZ, ZZ, ZZ, YY<< 88}, {ZZ, ZZ, ZZ, YY<< 96}, {ZZ, ZZ, ZZ, YY<<104}, {ZZ, ZZ, ZZ, YY<<112}, {ZZ, ZZ, ZZ, YY<<120} }; static const JTR_ALIGN(MEM_ALIGN_SIMD) uint128_t kUsedBytesTable[][4] = { {XX<< 0, XX, XX, XX}, {XX<< 8, XX, XX, XX}, {XX<< 16, XX, XX, XX}, {XX<< 24, XX, XX, XX}, {XX<< 32, XX, XX, XX}, {XX<< 40, XX, XX, XX}, {XX<< 48, XX, XX, XX}, {XX<< 56, XX, XX, XX}, {XX<< 64, XX, XX, XX}, {XX<< 72, XX, XX, XX}, {XX<< 80, XX, XX, XX}, {XX<< 88, XX, XX, XX}, {XX<< 96, XX, XX, XX}, {XX<<104, XX, XX, XX}, {XX<<112, XX, XX, XX}, {XX<<120, XX, XX, XX}, {ZZ, XX<< 0, XX, XX}, {ZZ, XX<< 8, XX, XX}, {ZZ, XX<< 16, XX, XX}, {ZZ, XX<< 24, XX, XX}, {ZZ, XX<< 32, XX, XX}, {ZZ, XX<< 40, XX, XX}, {ZZ, XX<< 48, XX, XX}, {ZZ, XX<< 56, XX, XX}, {ZZ, XX<< 64, XX, XX}, {ZZ, XX<< 72, XX, XX}, {ZZ, XX<< 80, XX, XX}, {ZZ, XX<< 88, XX, XX}, {ZZ, XX<< 96, XX, XX}, {ZZ, XX<<104, XX, XX}, {ZZ, XX<<112, XX, XX}, {ZZ, XX<<120, XX, XX}, {ZZ, ZZ, XX<< 0, XX}, {ZZ, ZZ, XX<< 8, XX}, {ZZ, ZZ, XX<< 16, XX}, {ZZ, ZZ, XX<< 24, XX}, {ZZ, ZZ, XX<< 32, XX}, {ZZ, ZZ, XX<< 40, XX}, {ZZ, ZZ, XX<< 48, XX}, {ZZ, ZZ, XX<< 56, XX}, {ZZ, ZZ, XX<< 64, XX}, {ZZ, ZZ, XX<< 72, XX}, {ZZ, ZZ, XX<< 80, XX}, {ZZ, ZZ, XX<< 88, XX}, {ZZ, ZZ, XX<< 96, XX}, {ZZ, ZZ, XX<<104, XX}, {ZZ, ZZ, XX<<112, XX}, {ZZ, ZZ, XX<<120, XX}, {ZZ, ZZ, ZZ, XX<< 0}, {ZZ, ZZ, ZZ, XX<< 8}, {ZZ, ZZ, ZZ, XX<< 16}, {ZZ, ZZ, ZZ, XX<< 24}, {ZZ, ZZ, ZZ, XX<< 32}, {ZZ, ZZ, ZZ, XX<< 40}, {ZZ, ZZ, ZZ, XX<< 48}, {ZZ, ZZ, ZZ, XX<< 56}, {ZZ, ZZ, ZZ, XX<< 64}, {ZZ, ZZ, ZZ, XX<< 72}, {ZZ, ZZ, ZZ, XX<< 80}, {ZZ, ZZ, ZZ, XX<< 88}, {ZZ, ZZ, ZZ, XX<< 96}, {ZZ, ZZ, ZZ, XX<<104}, {ZZ, ZZ, ZZ, XX<<112}, {ZZ, ZZ, ZZ, XX<<120} }; #elif VWIDTH > 4 static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kTrailingBitTable[][8] = { { 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000 }, }; static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kUsedBytesTable[][8] = { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000 }, }; #else static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kTrailingBitTable[][4] = { { 0x00000080, 0x00000000, 0x00000000, 0x00000000 }, { 0x00008000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00800000, 0x00000000, 0x00000000, 0x00000000 }, { 0x80000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000080, 0x00000000, 0x00000000 }, { 0x00000000, 0x00008000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00800000, 0x00000000, 0x00000000 }, { 0x00000000, 0x80000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000080, 0x00000000 }, { 0x00000000, 0x00000000, 0x00008000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00800000, 0x00000000 }, { 0x00000000, 0x00000000, 0x80000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000080 }, { 0x00000000, 0x00000000, 0x00000000, 0x00008000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00800000 }, { 0x00000000, 0x00000000, 0x00000000, 0x80000000 }, }; static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kUsedBytesTable[][4] = { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00 }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000 }, { 0x00000000, 0x00000000, 0x00000000, 0xFF000000 }, }; #endif N[index] = len; // Zero out the rest of the DQWORD in X by making a suitable mask. Z = vload(kUsedBytesTable[len]); // Find the correct position for the trailing bit required by SHA-1. B = vload(kTrailingBitTable[len]); // Now we have this: // B = 00 00 00 00 00 80 00 00 00 00 00 00 00 00 00 // Z = 00 00 00 00 00 ff ff ff ff ff ff ff ff ff ff // X = 41 41 41 41 41 00 12 34 56 78 12 34 56 78 9A // <---------------> <------------------------> // key bytes w/nul junk from stack. // Use PANDN to apply the mask, then POR to append the trailing bit // required by SHA-1, which leaves us with this: // X = 41 41 41 41 41 80 00 00 00 00 00 00 00 00 00 X = vor(vandnot(Z, X), B); // SHA-1 requires us to byte swap all the 32bit words in the message, which // we do here. // X = 40 41 42 44 45 80 00 00 00 00 00 00 00 00 00 // What we have. // X = 44 42 41 40 00 00 80 45 00 00 00 00 00 00 00 // What we want. vswap32(X); // Store the result into the message buffer. vstore(&M[index], X); return; } static char *sha1_fmt_get_key(int index) { static uint32_t key[VWIDTH + 1]; int i; // This function is not hot, we can do this slowly. First, restore // endianness. for (i = 0; i < SIMD_COEF_32; i++) key[i] = __builtin_bswap32(M[index][i]); // Skip backwards until we hit the trailing bit, then remove it. memset(strrchr((char*)(key), 0x80), 0x00, 1); return (char*) key; } static int sha1_fmt_crypt_all(int *pcount, struct db_salt *salt) { uint32_t i; // Fetch crypt count from john. const int32_t count = *pcount; // To reduce the overhead of multiple function calls, we buffer lots of // passwords, and then hash them in multiples of VWIDTH all at once. #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < count; i += VWIDTH) { vtype W[SHA1_BLOCK_WORDS]; vtype A, B, C, D, E; vtype K; #if __AVX512F__ || __MIC__ const vtype indices = vset_epi32(15<<4,14<<4,13<<4,12<<4, 11<<4,10<<4, 9<<4, 8<<4, 7<<4, 6<<4, 5<<4, 4<<4, 3<<4, 2<<4, 1<<4, 0<<4); #elif __AVX2__ const vtype indices = vset_epi32( 7<<3, 6<<3, 5<<3, 4<<3, 3<<3, 2<<3, 1<<3, 0<<3); #endif #if __AVX2__ || __MIC__ // Gather the message right into place. uint32_t j; for (j = 0; j < VWIDTH; ++j) W[j] = vgather_epi32(&M[i][j], indices, sizeof(uint32_t)); #else // AVX has no gather instructions, so load and transpose. W[0] = vload(&M[i + 0]); W[1] = vload(&M[i + 1]); W[2] = vload(&M[i + 2]); W[3] = vload(&M[i + 3]); _MM_TRANSPOSE4_EPI32(W[0], W[1], W[2], W[3]); #endif A = vset1_epi32(0x67452301); B = vset1_epi32(0xEFCDAB89); C = vset1_epi32(0x98BADCFE); D = vset1_epi32(0x10325476); E = vset1_epi32(0xC3D2E1F0); K = vset1_epi32(0x5A827999); R1(W[0], A, B, C, D, E); R1(W[1], E, A, B, C, D); R1(W[2], D, E, A, B, C); #if VWIDTH > 4 R1(W[3], C, D, E, A, B); R1(W[4], B, C, D, E, A); R1(W[5], A, B, C, D, E); // 5 R1(W[6], E, A, B, C, D); #else R1(W[3], C, D, E, A, B); W[4] = vsetzero(); R1(W[4], B, C, D, E, A); W[5] = vsetzero(); R1(W[5], A, B, C, D, E); W[6] = vsetzero(); // 5 R1(W[6], E, A, B, C, D); W[7] = vsetzero(); #endif #if VWIDTH > 8 R1(W[7], D, E, A, B, C); R1(W[8], C, D, E, A, B); R1(W[9], B, C, D, E, A); R1(W[10], A, B, C, D, E); // 10 R1(W[11], E, A, B, C, D); R1(W[12], D, E, A, B, C); R1(W[13], C, D, E, A, B); R1(W[14], B, C, D, E, A); #else R1(W[7], D, E, A, B, C); W[8] = vsetzero(); R1(W[8], C, D, E, A, B); W[9] = vsetzero(); R1(W[9], B, C, D, E, A); W[10] = vsetzero(); R1(W[10], A, B, C, D, E); W[11] = vsetzero(); // 10 R1(W[11], E, A, B, C, D); W[12] = vsetzero(); R1(W[12], D, E, A, B, C); W[13] = vsetzero(); R1(W[13], C, D, E, A, B); W[14] = vsetzero(); R1(W[14], B, C, D, E, A); #endif // Fetch the message lengths, multiply 8 (to get the length in bits). W[15] = vslli_epi32(vload(&N[i]), 3); R1(W[15], A, B, C, D, E); // 15 X(W[0], W[2], W[8], W[13]); R1(W[0], E, A, B, C, D); X(W[1], W[3], W[9], W[14]); R1(W[1], D, E, A, B, C); X(W[2], W[4], W[10], W[15]); R1(W[2], C, D, E, A, B); X(W[3], W[5], W[11], W[0]); R1(W[3], B, C, D, E, A); K = vset1_epi32(0x6ED9EBA1); X(W[4], W[6], W[12], W[1]); R2(W[4], A, B, C, D, E); // 20 X(W[5], W[7], W[13], W[2]); R2(W[5], E, A, B, C, D); X(W[6], W[8], W[14], W[3]); R2(W[6], D, E, A, B, C); X(W[7], W[9], W[15], W[4]); R2(W[7], C, D, E, A, B); X(W[8], W[10], W[0], W[5]); R2(W[8], B, C, D, E, A); X(W[9], W[11], W[1], W[6]); R2(W[9], A, B, C, D, E); // 25 X(W[10], W[12], W[2], W[7]); R2(W[10], E, A, B, C, D); X(W[11], W[13], W[3], W[8]); R2(W[11], D, E, A, B, C); X(W[12], W[14], W[4], W[9]); R2(W[12], C, D, E, A, B); X(W[13], W[15], W[5], W[10]); R2(W[13], B, C, D, E, A); X(W[14], W[0], W[6], W[11]); R2(W[14], A, B, C, D, E); // 30 X(W[15], W[1], W[7], W[12]); R2(W[15], E, A, B, C, D); X(W[0], W[2], W[8], W[13]); R2(W[0], D, E, A, B, C); X(W[1], W[3], W[9], W[14]); R2(W[1], C, D, E, A, B); X(W[2], W[4], W[10], W[15]); R2(W[2], B, C, D, E, A); X(W[3], W[5], W[11], W[0]); R2(W[3], A, B, C, D, E); // 35 X(W[4], W[6], W[12], W[1]); R2(W[4], E, A, B, C, D); X(W[5], W[7], W[13], W[2]); R2(W[5], D, E, A, B, C); X(W[6], W[8], W[14], W[3]); R2(W[6], C, D, E, A, B); X(W[7], W[9], W[15], W[4]); R2(W[7], B, C, D, E, A); K = vset1_epi32(0x8F1BBCDC); X(W[8], W[10], W[0], W[5]); R3(W[8], A, B, C, D, E); // 40 X(W[9], W[11], W[1], W[6]); R3(W[9], E, A, B, C, D); X(W[10], W[12], W[2], W[7]); R3(W[10], D, E, A, B, C); X(W[11], W[13], W[3], W[8]); R3(W[11], C, D, E, A, B); X(W[12], W[14], W[4], W[9]); R3(W[12], B, C, D, E, A); X(W[13], W[15], W[5], W[10]); R3(W[13], A, B, C, D, E); // 45 X(W[14], W[0], W[6], W[11]); R3(W[14], E, A, B, C, D); X(W[15], W[1], W[7], W[12]); R3(W[15], D, E, A, B, C); X(W[0], W[2], W[8], W[13]); R3(W[0], C, D, E, A, B); X(W[1], W[3], W[9], W[14]); R3(W[1], B, C, D, E, A); X(W[2], W[4], W[10], W[15]); R3(W[2], A, B, C, D, E); // 50 X(W[3], W[5], W[11], W[0]); R3(W[3], E, A, B, C, D); X(W[4], W[6], W[12], W[1]); R3(W[4], D, E, A, B, C); X(W[5], W[7], W[13], W[2]); R3(W[5], C, D, E, A, B); X(W[6], W[8], W[14], W[3]); R3(W[6], B, C, D, E, A); X(W[7], W[9], W[15], W[4]); R3(W[7], A, B, C, D, E); // 55 X(W[8], W[10], W[0], W[5]); R3(W[8], E, A, B, C, D); X(W[9], W[11], W[1], W[6]); R3(W[9], D, E, A, B, C); X(W[10], W[12], W[2], W[7]); R3(W[10], C, D, E, A, B); X(W[11], W[13], W[3], W[8]); R3(W[11], B, C, D, E, A); K = vset1_epi32(0xCA62C1D6); X(W[12], W[14], W[4], W[9]); R2(W[12], A, B, C, D, E); // 60 X(W[13], W[15], W[5], W[10]); R2(W[13], E, A, B, C, D); X(W[14], W[0], W[6], W[11]); R2(W[14], D, E, A, B, C); X(W[15], W[1], W[7], W[12]); R2(W[15], C, D, E, A, B); X(W[0], W[2], W[8], W[13]); R2(W[0], B, C, D, E, A); X(W[1], W[3], W[9], W[14]); R2(W[1], A, B, C, D, E); // 65 X(W[2], W[4], W[10], W[15]); R2(W[2], E, A, B, C, D); X(W[3], W[5], W[11], W[0]); R2(W[3], D, E, A, B, C); X(W[4], W[6], W[12], W[1]); R2(W[4], C, D, E, A, B); X(W[5], W[7], W[13], W[2]); R2(W[5], B, C, D, E, A); X(W[6], W[8], W[14], W[3]); R2(W[6], A, B, C, D, E); // 70 X(W[7], W[9], W[15], W[4]); R2(W[7], E, A, B, C, D); X(W[8], W[10], W[0], W[5]); R2(W[8], D, E, A, B, C); X(W[9], W[11], W[1], W[6]); R2(W[9], C, D, E, A, B); X(W[10], W[12], W[2], W[7]); R2(W[10], B, C, D, E, A); X(W[11], W[13], W[3], W[8]); R4(W[11], A, B, C, D, E); // 75 // A75 has an interesting property, it is the first word that's (almost) // part of the final MD (E79 ror 2). The common case will be that this // doesn't match, so we stop here and save 5 rounds. // // Note that I'm using E due to displacement caused by vectorization, // this is A in standard SHA-1. vstore(&MD[i], E); } return count; } static int sha1_fmt_cmp_all(void *binary, int count) { uint32_t M; uint32_t i; vtype B; // This function is hot, we need to do this quickly. We use PCMP to find // out if any of the dwords in A75 matched E in the input hash. // First, Load the target hash into an XMM register B = vloadu(binary); M = 0; #ifdef _OPENMP #pragma omp parallel for reduction(|:M) #endif // We can test for matches 4/8 at a time. As the common case will be that // there is no match, we can avoid testing it after every compare, reducing // the number of branches. // // It's hard to convince GCC that it's safe to unroll this loop, so I've // manually unrolled it a little bit. for (i = 0; i < count; i += 64) { uint32_t R = 0; #if __AVX512F__ || __MIC__ R |= vanyeq_epi32(B, vload(&MD[i + 0])); R |= vanyeq_epi32(B, vload(&MD[i + 16])); R |= vanyeq_epi32(B, vload(&MD[i + 32])); R |= vanyeq_epi32(B, vload(&MD[i + 48])); #elif __AVX2__ R |= vanyeq_epi32(B, vload(&MD[i + 0])); R |= vanyeq_epi32(B, vload(&MD[i + 8])); R |= vanyeq_epi32(B, vload(&MD[i + 16])); R |= vanyeq_epi32(B, vload(&MD[i + 24])); R |= vanyeq_epi32(B, vload(&MD[i + 32])); R |= vanyeq_epi32(B, vload(&MD[i + 40])); R |= vanyeq_epi32(B, vload(&MD[i + 48])); R |= vanyeq_epi32(B, vload(&MD[i + 56])); #else R |= vanyeq_epi32(B, vload(&MD[i + 0])); R |= vanyeq_epi32(B, vload(&MD[i + 4])); R |= vanyeq_epi32(B, vload(&MD[i + 8])); R |= vanyeq_epi32(B, vload(&MD[i + 12])); R |= vanyeq_epi32(B, vload(&MD[i + 16])); R |= vanyeq_epi32(B, vload(&MD[i + 20])); R |= vanyeq_epi32(B, vload(&MD[i + 24])); R |= vanyeq_epi32(B, vload(&MD[i + 28])); R |= vanyeq_epi32(B, vload(&MD[i + 32])); R |= vanyeq_epi32(B, vload(&MD[i + 36])); R |= vanyeq_epi32(B, vload(&MD[i + 40])); R |= vanyeq_epi32(B, vload(&MD[i + 44])); R |= vanyeq_epi32(B, vload(&MD[i + 48])); R |= vanyeq_epi32(B, vload(&MD[i + 52])); R |= vanyeq_epi32(B, vload(&MD[i + 56])); R |= vanyeq_epi32(B, vload(&MD[i + 60])); #endif M |= R; } return M; } inline static int sha1_fmt_get_hash(int index) { return MD[index]; } static int sha1_fmt_get_hash0(int index) { return sha1_fmt_get_hash(index) & PH_MASK_0; } static int sha1_fmt_get_hash1(int index) { return sha1_fmt_get_hash(index) & PH_MASK_1; } static int sha1_fmt_get_hash2(int index) { return sha1_fmt_get_hash(index) & PH_MASK_2; } static int sha1_fmt_get_hash3(int index) { return sha1_fmt_get_hash(index) & PH_MASK_3; } static int sha1_fmt_get_hash4(int index) { return sha1_fmt_get_hash(index) & PH_MASK_4; } static int sha1_fmt_get_hash5(int index) { return sha1_fmt_get_hash(index) & PH_MASK_5; } static int sha1_fmt_get_hash6(int index) { return sha1_fmt_get_hash(index) & PH_MASK_6; } inline static int sha1_fmt_get_binary(void *binary) { return *(uint32_t*)(binary); } static int sha1_fmt_binary0(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_0; } static int sha1_fmt_binary1(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_1; } static int sha1_fmt_binary2(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_2; } static int sha1_fmt_binary3(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_3; } static int sha1_fmt_binary4(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_4; } static int sha1_fmt_binary5(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_5; } static int sha1_fmt_binary6(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_6; } static int sha1_fmt_cmp_one(void *binary, int index) { // We can quickly check if it will be worth doing a full comparison here, // this lets us turn up SHA1_PARALLEL_HASH without too much overhead when a // partial match occurs. return sha1_fmt_get_binary(binary) == sha1_fmt_get_hash(index); } // This function is not hot, and will only be called for around 1:2^32 random // crypts. Use a real SHA-1 implementation to verify the result exactly. This // routine is only called by John when cmp_one succeeds. static int sha1_fmt_cmp_exact(char *source, int index) { uint32_t full_sha1_digest[SHA1_DIGEST_WORDS]; SHA_CTX ctx; char *key; // Fetch the original input to hash. key = sha1_fmt_get_key(index); SHA1_Init(&ctx); SHA1_Update(&ctx, key, strlen(key)); SHA1_Final((unsigned char*)(full_sha1_digest), &ctx); // Compare result. return !memcmp(rawsha1_common_get_binary(source), full_sha1_digest, sizeof(full_sha1_digest)); } struct fmt_main fmt_sha1_ng = { .params = { .label = "Raw-SHA1-ng", #if VWIDTH == 16 .format_name = "(pwlen <= 55)", #if __MIC__ .algorithm_name = "SHA1 512/512 MIC 16x", #else .algorithm_name = "SHA1 512/512 AVX512 16x", #endif #elif VWIDTH == 8 .format_name = "(pwlen <= 31)", .algorithm_name = "SHA1 256/256 AVX2 8x", #else .format_name = "(pwlen <= 15)", .algorithm_name = "SHA1 128/128 " #if __ALTIVEC__ "AltiVec" #elif __ARM_NEON "NEON" #elif __XOP__ "XOP" #elif __AVX__ "AVX" #elif __SSE4_1__ "SSE4.1" #else "SSE2" #endif " 4x", #endif .benchmark_comment = "", .benchmark_length = -1, #if VWIDTH * 4 - 1 > 55 .plaintext_length = 55, #else .plaintext_length = sizeof(vtype) - 1, #endif .binary_size = sizeof(vtype), .binary_align = VWIDTH * 4, .salt_size = 0, .salt_align = 1, .min_keys_per_crypt = VWIDTH, .max_keys_per_crypt = SHA1_PARALLEL_HASH, .flags = #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE, .tunable_cost_name = { NULL }, .signature = { FORMAT_TAG, FORMAT_TAG_OLD }, .tests = rawsha1_common_tests, }, .methods = { .init = sha1_fmt_init, .done = done, .reset = fmt_default_reset, .prepare = rawsha1_common_prepare, .valid = rawsha1_common_valid, .split = rawsha1_common_split, .binary = sha1_fmt_binary, .salt = fmt_default_salt, .tunable_cost_value = { NULL }, .source = fmt_default_source, .salt_hash = fmt_default_salt_hash, .set_salt = fmt_default_set_salt, .set_key = sha1_fmt_set_key, .get_key = sha1_fmt_get_key, .clear_keys = fmt_default_clear_keys, .crypt_all = sha1_fmt_crypt_all, .get_hash = { [0] = sha1_fmt_get_hash0, [1] = sha1_fmt_get_hash1, [2] = sha1_fmt_get_hash2, [3] = sha1_fmt_get_hash3, [4] = sha1_fmt_get_hash4, [5] = sha1_fmt_get_hash5, [6] = sha1_fmt_get_hash6, }, .binary_hash = { [0] = sha1_fmt_binary0, [1] = sha1_fmt_binary1, [2] = sha1_fmt_binary2, [3] = sha1_fmt_binary3, [4] = sha1_fmt_binary4, [5] = sha1_fmt_binary5, [6] = sha1_fmt_binary6, }, .cmp_all = sha1_fmt_cmp_all, .cmp_one = sha1_fmt_cmp_one, .cmp_exact = sha1_fmt_cmp_exact }, }; #endif /* plugin stanza */ #endif /* defined(SIMD_COEF_32) && (SIMD_COEF_32 < 16 || ARCH_BITS >= 64) && !_MSC_VER */
syncs.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB LU code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include "applu.incl" //--------------------------------------------------------------------- // Thread synchronization for pipeline operation //--------------------------------------------------------------------- void sync_left(int ldmx, int ldmy, int ldmz, double v[ldmz][ldmy/2*2+1][ldmx/2*2+1][5]) { int neigh; if (iam > 0 && iam <= mthreadnum) { neigh = iam - 1; while (isync[neigh] == 0) { #pragma omp flush(isync) } isync[neigh] = 0; #pragma omp flush(isync,v) } } //--------------------------------------------------------------------- // Thread synchronization for pipeline operation //--------------------------------------------------------------------- void sync_right(int ldmx, int ldmy, int ldmz, double v[ldmz][ldmy/2*2+1][ldmx/2*2+1][5]) { if (iam < mthreadnum) { #pragma omp flush(isync,v) while (isync[iam] == 1) { #pragma omp flush(isync) } isync[iam] = 1; #pragma omp flush(isync) } }
snoop.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/utils/strings.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/snofold.h" #include "ViennaRNA/pair_mat.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/snoop.h" #include "ViennaRNA/plotting/probabilities.h" #include "ViennaRNA/plotting/structures.h" /* #include "ViennaRNA/fold.h" */ #include "ViennaRNA/duplex.h" #include "ViennaRNA/loops/all.h" #define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */ #define NEW_NINIO 1 /* new asymetry penalty */ PRIVATE void encode_seqs(const char *s1, const char *s2); PRIVATE short * encode_seq(const char *seq); PRIVATE void find_max_snoop(const char *s1, const char *s2, const int max, const int alignment_length, const int *position, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char *name, const int fullStemEnergy); PRIVATE void find_max_snoop_XS(const char *s1, const char *s2, const int **access_s1, const int max, const int alignment_length, const int *position, const int *position_j, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char *name, const int fullStemEnergy); PRIVATE char * alisnoop_backtrack(int i, int j, const char **s2, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, int *pscd, int *psct, int *pscg, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const short **S1, const short **S2); PRIVATE char * snoop_backtrack(int i, int j, const char *s2, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2); PRIVATE char * snoop_backtrack_XS(int i, int j, const char *s2, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2); PRIVATE int compare(const void *sub1, const void *sub2); PRIVATE int covscore(const int *types, int n_seq); PRIVATE short * aliencode_seq(const char *sequence); PUBLIC int snoop_subopt_sorted = 0; /* from subopt.c, default 0 */ /*@unused@*/ #define MAXLOOP_L 3 #define MIN2(A, B) ((A) < (B) ? (A) : (B)) #define MAX2(A, B) ((A) > (B) ? (A) : (B)) #define ASS 1 PRIVATE vrna_param_t *P = NULL; PRIVATE int **c = NULL; /* energy array, given that i-j pair */ PRIVATE int **r = NULL; PRIVATE int **lc = NULL; /* energy array, given that i-j pair */ PRIVATE int **lr = NULL; PRIVATE int **c_fill = NULL; PRIVATE int **r_fill = NULL; PRIVATE int **lpair = NULL; PRIVATE short *S1 = NULL, *SS1 = NULL, *S2 = NULL, *SS2 = NULL; PRIVATE short *S1_fill = NULL, *SS1_fill = NULL, *S2_fill = NULL, *SS2_fill = NULL; PRIVATE int n1, n2; /* sequence lengths */ extern int cut_point; PRIVATE int delay_free = 0; /*--------------------------------------------------------------------------*/ snoopT alisnoopfold(const char **s1, const char **s2, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { int s, n_seq; int i, j, E, l1, Emin = INF, i_min = 0, j_min = 0; char *struc; snoopT mfe; int *indx; int *mLoop; int *cLoop; folden **foldlist; folden **foldlist_XS; int Duplex_El, Duplex_Er, pscd, psct, pscg; int Loop_D; int u; int Loop_E; short **Sali1, **Sali2; int *type, *type2, *type3; vrna_md_t md; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0; Loop_D = 0; pscd = 0; psct = 0; pscg = 0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); 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)) { snoupdate_fold_params(); if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } c = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); r = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); for (i = 0; i <= n1; i++) { c[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); r[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); for (j = n2; j > -1; j--) { c[i][j] = INF; r[i][j] = INF; } } Sali1 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); Sali2 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); for (s = 0; s < n_seq; s++) { if ((int)strlen(s1[s]) != n1) vrna_message_error("uneqal seqence lengths"); if ((int)strlen(s2[s]) != n2) vrna_message_error("uneqal seqence lengths"); Sali1[s] = aliencode_seq(s1[s]); Sali2[s] = aliencode_seq(s2[s]); } type = (int *)vrna_alloc(n_seq * sizeof(int)); type2 = (int *)vrna_alloc(n_seq * sizeof(int)); type3 = (int *)vrna_alloc(n_seq * sizeof(int)); /* encode_seqs(s1, s2); */ for (i = 6; i <= n1 - 5; i++) { int U; U = 0; for (s = 0; s < n_seq; s++) U += Sali1[s][i - 2]; U = (U == (n_seq) * 4 ? 1 : 0); for (j = n2 - min_d2; j > min_d1; j--) { int type4, k, l, psc, psc2, psc3; for (s = 0; s < n_seq; s++) type[s] = pair[Sali1[s][i]][Sali2[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; if (/* pair[Sali1[i+1]][Sali2[j-1]] && */ U && j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem) { /*constraint on s2 and i*/ folden *temp; temp = foldlist[j + 1]; while (temp->next) { int k = temp->k; for (s = 0; s < n_seq; s++) { type2[s] = pair[Sali1[s][i - 3]][Sali2[s][k + 1]]; type3[s] = pair[Sali1[s][i - 4]][Sali2[s][k + 1]]; } psc2 = covscore(type2, n_seq); psc3 = covscore(type3, n_seq); if (psc2 > MINPSCORE) r[i][j] = MIN2(r[i][j], c[i - 3][k + 1] + temp->energy); if (psc3 > MINPSCORE) r[i][j] = MIN2(r[i][j], c[i - 4][k + 1] + temp->energy); temp = temp->next; } } /* dangle 5'SIDE relative to the mRNA */ for (s = 0; s < n_seq; s++) c[i][j] += E_ExtLoop(type[s], Sali1[s][i - 1], Sali2[s][j + 1], P); for (k = i - 1; k > 0 && (i - k) < MAXLOOP_L; k--) { for (l = j + 1; l <= n2; l++) { if (i - k + l - j > 2 * MAXLOOP_L - 2) break; if (abs(i - k - l + j) >= ASS) continue; for (E = s = 0; s < n_seq; s++) { type4 = pair[Sali1[s][k]][Sali2[s][l]]; if (type4 == 0) type4 = 7; E += E_IntLoop(i - k - 1, l - j - 1, type4, rtype[type[s]], Sali1[s][k + 1], Sali2[s][l - 1], Sali1[s][i - 1], Sali2[s][j + 1], P); } c[i][j] = MIN2(c[i][j], c[k][l] + E); r[i][j] = MIN2(r[i][j], r[k][l] + E); } } c[i][j] -= psc; r[i][j] -= psc; E = r[i][j]; for (s = 0; s < n_seq; s++) E += E_ExtLoop(rtype[type[s]], Sali2[s][j - 1], Sali1[s][i + 1], P); /** *** if (i<n1) E += P->dangle3[rtype[type[s]]][Sali1[s][i+1]]; *** if (j>1) E += P->dangle5[rtype[type[s]]][Sali2[s][j-1]]; *** if (type[s]>2) E += P->TerminalAU; **/ if (E < Emin) { Emin = E; i_min = i; j_min = j; } } } if (Emin > 0) { printf("no target found under the constraints chosen\n"); for (i = 0; i <= n1; i++) { free(r[i]); free(c[i]); } free(c); free(r); for (s = 0; s < n_seq; s++) { free(Sali1[s]); free(Sali2[s]); } free(Sali1); free(Sali2); free(S2); free(SS1); free(SS2); free(type); free(type2); free(type3); mfe.energy = INF; mfe.structure = NULL; return mfe; } struc = alisnoop_backtrack(i_min, j_min, (const char **)s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, &pscd, &psct, &pscg, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, (const short **)Sali1, (const short **)Sali2); /* if (i_min<n1-5) i_min++; */ /* if (j_min>6 ) j_min--; */ l1 = strchr(struc, '&') - struc; mfe.i = i_min - 5; mfe.j = j_min - 5; mfe.u = u - 5; mfe.Duplex_Er = (float)Duplex_Er / 100; mfe.Duplex_El = (float)Duplex_El / 100; mfe.Loop_D = (float)Loop_D / 100; mfe.Loop_E = (float)Loop_E / 100; mfe.energy = (float)Emin / 100; /* mfe.fullStemEnergy = (float) fullStemEnergy/100; */ mfe.pscd = pscd; mfe.psct = psct; mfe.structure = struc; for (s = 0; s < n_seq; s++) { free(Sali1[s]); free(Sali2[s]); } free(Sali1); free(Sali2); free(type); free(type2); free(type3); if (!delay_free) { for (i = 0; i <= n1; i++) { free(r[i]); free(c[i]); } free(c); free(r); free(S2); free(SS1); free(SS2); } return mfe; } PUBLIC snoopT * alisnoop_subopt(const char **s1, const char **s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { short **Sali1, **Sali2; /* printf("%d %d\n", min_s2, max_s2); */ int i, j, s, n_seq, n1, n2, E, n_subopt = 0, n_max; char *struc; snoopT mfe; snoopT *subopt; int thresh; int *type; int Duplex_El, Duplex_Er, Loop_E, pscd, psct, pscg; int Loop_D; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0; Loop_D = 0; pscd = 0; psct = 0; pscg = 0; int u; u = 0; n_max = 16; subopt = (snoopT *)vrna_alloc(n_max * sizeof(snoopT)); delay_free = 1; mfe = alisnoopfold(s1, s2, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); if (mfe.energy > 0) { free(subopt); delay_free = 0; return NULL; } thresh = MIN2((int)((mfe.Duplex_Er + mfe.Duplex_El + mfe.Loop_E) * 100 + 0.1 + 410) + delta, threshTE); /* subopt[n_subopt++]=mfe; */ free(mfe.structure); n1 = (int)strlen(s1[0]); n2 = (int)strlen(s2[0]); for (s = 0; s1[s] != NULL; s++) ; n_seq = s; Sali1 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); Sali2 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *)); for (s = 0; s < n_seq; s++) { if ((int)strlen(s1[s]) != n1) vrna_message_error("uneqal seqence lengths"); if ((int)strlen(s2[s]) != n2) vrna_message_error("uneqal seqence lengths"); Sali1[s] = aliencode_seq(s1[s]); Sali2[s] = aliencode_seq(s2[s]); } Sali1[n_seq] = NULL; Sali2[n_seq] = NULL; type = (int *)vrna_alloc(n_seq * sizeof(int)); for (i = n1; i > 1; i--) { for (j = 1; j <= n2; j++) { int ii, jj, Ed, psc, skip; for (s = 0; s < n_seq; s++) type[s] = pair[Sali2[s][j]][Sali1[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 = r[i][j]; for (s = 0; s < n_seq; s++) { /* if (i<n1-5) Ed += P->dangle3[type[s]][Sali1[s][i+1]]; */ /* if (j>6) Ed += P->dangle5[type[s]][Sali2[s][j-1]]; */ if (type[s] > 2) Ed += P->TerminalAU; } 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. */ w = 1; 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 (r[ii][jj] < E) { skip = 1; break; } } if (skip) continue; psct = 0; pscg = 0; struc = alisnoop_backtrack(i, j, s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, &pscd, &psct, &pscg, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, (const short int **)Sali1, (const int short **)Sali2); if (Duplex_Er > threshRE || Duplex_El > threshLE || Loop_D > threshD || (Duplex_Er + Duplex_El) > threshDE || (Duplex_Er + Duplex_El + Loop_E) > threshTE || (Duplex_Er + Duplex_El + Loop_E + Loop_D + 410) > threshSE) { /* printf(" Duplex_Er %d threshRE %d Duplex_El %d threshLE %d \n" */ /* " Duplex_Er + Duplex_El %d threshDE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E %d threshTE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E + Loop_D %d threshSE %d \n", */ /* Duplex_Er , threshRE , Duplex_El ,threshLE, */ /* Duplex_Er + Duplex_El, threshDE, */ /* Duplex_Er + Duplex_El+ Loop_E , threshTE, */ /* Duplex_Er + Duplex_El+ Loop_E + Loop_D, threshSE); */ Duplex_Er = 0; Duplex_El = 0; Loop_E = 0; Loop_D = 0; u = 0, free(struc); continue; } if (n_subopt + 1 >= n_max) { n_max *= 2; subopt = (snoopT *)vrna_realloc(subopt, n_max * sizeof(snoopT)); } subopt[n_subopt].i = i - 5; subopt[n_subopt].j = j - 5; subopt[n_subopt].u = u - 5; subopt[n_subopt].Duplex_Er = Duplex_Er * 0.01; subopt[n_subopt].Duplex_El = Duplex_El * 0.01; subopt[n_subopt].Loop_E = Loop_E * 0.01; subopt[n_subopt].Loop_D = Loop_D * 0.01; subopt[n_subopt].energy = (Duplex_Er + Duplex_El + Loop_E + Loop_D + 410) * 0.01; subopt[n_subopt].pscd = pscd * 0.01; subopt[n_subopt].psct = -psct * 0.01; subopt[n_subopt++].structure = struc; /* i=u; */ Duplex_Er = 0; Duplex_El = 0; Loop_E = 0; Loop_D = 0; u = 0; pscd = 0; psct = 0; } } for (i = 0; i <= n1; i++) { free(c[i]); free(r[i]); } free(c); free(r); for (s = 0; s < n_seq; s++) { free(Sali1[s]); free(Sali2[s]); } free(Sali1); free(Sali2); free(type); if (snoop_subopt_sorted) qsort(subopt, n_subopt, sizeof(snoopT), compare); subopt[n_subopt].i = 0; subopt[n_subopt].j = 0; subopt[n_subopt].structure = NULL; return subopt; } PRIVATE char * alisnoop_backtrack(int i, int j, const char **snoseq, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, int *pscd, int *psct, int *pscg, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const short **Sali1, const short **Sali2) { /* backtrack structure going backwards from i, and forwards from j * return structure in bracket notation with & as separator */ int k, l, *type, *type2, *type3, type4, E, traced, i0, j0, s, n_seq, psc; int traced_r = 0; /* flag for following backtrack in c or r */ char *st1, *st2, *struc; char *struc_loop; n1 = (int)Sali1[0][0]; n2 = (int)Sali2[0][0]; for (s = 0; Sali1[s] != NULL; s++) ; n_seq = s; for (s = 0; Sali2[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)); type2 = (int *)vrna_alloc(n_seq * sizeof(int)); type3 = (int *)vrna_alloc(n_seq * sizeof(int)); int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); i0 = i; j0 = j; /* MIN2(i+1,n1); j0=MAX2(j-1,1);!modified */ for (s = 0; s < n_seq; s++) { type[s] = pair[Sali1[s][i]][Sali2[s][j]]; if (type[s] == 0) type[s] = 7; *Duplex_Er += E_ExtLoop(rtype[type[s]], (j > 1) ? Sali2[s][j - 1] : -1, (i < n1) ? Sali1[s][i + 1] : -1, P); /** *** if (i<n1) *Duplex_Er += P->dangle3[rtype[type[s]]][Sali1[s][i+1]]; *** if (j>1) *Duplex_Er += P->dangle5[rtype[type[s]]][Sali2[s][j-1]]; *** if (type[s]>2) *Duplex_Er += P->TerminalAU; **/ } while (i > 0 && j <= n2 - min_d2) { if (!traced_r) { E = r[i][j]; traced = 0; st1[i - 1] = '<'; st2[j - 1] = '>'; for (s = 0; s < n_seq; s++) type[s] = pair[Sali1[s][i]][Sali2[s][j]]; psc = covscore(type, n_seq); for (s = 0; s < n_seq; s++) if (type[s] == 0) type[s] = 7; E += psc; *pscd += psc; for (k = i - 1; k > 0 && (i - k) < MAXLOOP_L; k--) { for (l = j + 1; l <= n2; l++) { int LE; if (i - k + l - j > 2 * MAXLOOP_L - 2) break; if (abs(i - k - l + j) >= ASS) continue; for (s = LE = 0; s < n_seq; s++) { type4 = pair[Sali1[s][k]][Sali2[s][l]]; if (type4 == 0) type4 = 7; LE += E_IntLoop(i - k - 1, l - j - 1, type4, rtype[type[s]], Sali1[s][k + 1], Sali2[s][l - 1], Sali1[s][i - 1], Sali2[s][j + 1], P); } if (E == r[k][l] + LE) { traced = 1; i = k; j = l; *Duplex_Er += LE; break; } } if (traced) break; } if (!traced) { int U = 0; for (s = 0; s < n_seq; s++) U += Sali1[s][i - 2]; U = (U == (n_seq) * 4 ? 1 : 0); if (/* pair[Sali1[i+1]][Sali2[j-1]] && */ /* only U's are allowed */ U && j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem) { int min_k, max_k; max_k = MIN2(n2 - min_s2, j + max_half_stem + 1); min_k = MAX2(j + half_stem + 1, n2 - max_s2); folden *temp; temp = foldlist[j + 1]; while (temp->next) { int psc2, psc3; int k = temp->k; for (s = 0; s < n_seq; s++) { type2[s] = pair[Sali1[s][i - 3]][Sali2[s][k + 1]]; type3[s] = pair[Sali1[s][i - 4]][Sali2[s][k + 1]]; } psc2 = covscore(type2, n_seq); psc3 = covscore(type3, n_seq); if (psc2 > MINPSCORE /*&& pair[Sali1[i-4]][Sali2[k+2]]*/) { /* introduce structure from RNAfold */ if (E == c[i - 3][k + 1] + temp->energy) { *Loop_E = temp->energy; st1[i - 3] = '|'; *u = i - 2; int a, b; /* int fix_ij=indx[k-1+1]+j+1; */ for (a = 0; a < MISMATCH; a++) { for (b = 0; b < MISMATCH; b++) { int ij = indx[k - 1 - a + 1] + j + 1 + b; if (cLoop[ij] == temp->energy) { /* int bla; */ struc_loop = alisnobacktrack_fold_from_pair(snoseq, j + 1 + b, k - a - 1 + 1, psct); a = INF; b = INF; } } } traced = 1; traced_r = 1; i = i - 3; j = k + 1; break; } } if (psc3 > MINPSCORE /*&& pair[Sali1[i-5]][Sali2[k+2]]*/) { /* introduce structure from RNAfold */ if (E == c[i - 4][k + 1] + temp->energy) { *Loop_E = temp->energy; st1[i - 3] = '|'; *u = i - 2; int a, b; /* int fix_ij=indx[k-1+1]+j+1; */ for (a = 0; a < MISMATCH; a++) { for (b = 0; b < MISMATCH; b++) { int ij = indx[k - 1 - a + 1] + j + 1 + b; if (cLoop[ij] == temp->energy) { /* int bla; */ struc_loop = alisnobacktrack_fold_from_pair(snoseq, j + 1 + b, k - a - 1 + 1, psct); a = INF; b = INF; } } } traced = 1; traced_r = 1; i = i - 4; j = k + 1; break; } } /* else if */ temp = temp->next; } /* while temp-> next */ } /* test on j */ } /* traced? */ } /* traced_r? */ else { E = c[i][j]; traced = 0; st1[i - 1] = '<'; st2[j - 1] = '>'; for (s = 0; s < n_seq; s++) type[s] = pair[Sali1[s][i]][Sali2[s][j]]; psc = covscore(type, n_seq); for (s = 0; s < n_seq; s++) if (type[s] == 0) type[s] = 7; E += psc; *pscd += psc; if (!type) vrna_message_error("backtrack failed in fold duplex c"); for (k = i - 1; (i - k) < MAXLOOP_L; k--) { for (l = j + 1; l <= n2; l++) { int LE; if (i - k + l - j > 2 * MAXLOOP_L - 2) break; if (abs(i - k - l + j) >= ASS) continue; for (s = LE = 0; s < n_seq; s++) { type4 = pair[Sali1[s][k]][Sali2[s][l]]; if (type4 == 0) type4 = 7; LE += E_IntLoop(i - k - 1, l - j - 1, type4, rtype[type[s]], Sali1[s][k + 1], Sali2[s][l - 1], Sali1[s][i - 1], Sali2[s][j + 1], P); } if (E == c[k][l] + LE) { traced = 1; i = k; j = l; *Duplex_El += LE; break; } } if (traced) break; } } if (!traced) { for (s = 0; s < n_seq; s++) { int correction; correction = E_ExtLoop(type[s], (i > 1) ? Sali1[s][i - 1] : -1, (j < n2) ? Sali2[s][j + 1] : -1, P); *Duplex_El += correction; E -= correction; /** *** if (i>1) {E -= P->dangle5[type[s]][Sali1[s][i-1]]; *Duplex_El +=P->dangle5[type[s]][Sali1[s][i-1]];} *** if (j<n2) {E -= P->dangle3[type[s]][Sali2[s][j+1]]; *Duplex_El +=P->dangle3[type[s]][Sali2[s][j+1]];} *** if (type[s]>2) {E -= P->TerminalAU; *Duplex_El +=P->TerminalAU;} **/ } if (E != n_seq * P->DuplexInit) vrna_message_error("backtrack failed in fold duplex end"); else break; } } /* if (i>1) i--; */ /* if (j<n2) j++; */ /* struc = (char *) vrna_alloc(i0-i+1+j-j0+1+2); */ /* declare final duplex structure */ struc = (char *)vrna_alloc(i0 - i + 1 + n2 - 1 + 1 + 2); /* declare final duplex structure */ char *struc2; struc2 = (char *)vrna_alloc(n2 + 1); /* char * struct_const; */ 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] = struc_loop[k-1];*/ /* '.'; normal */ /* char * struct_const; */ /* struct_const = (char *) vrna_alloc(sizeof(char)*(n2+1)); */ for (k = 1; k <= n2; k++) { if (!st2[k - 1]) st2[k - 1] = struc_loop[k - 1]; /* '.'; */ struc2[k - 1] = st2[k - 1]; /* '.'; */ /* if (k>=j0 && k<=j){ */ /* struct_const[k-1]='x'; */ /* } */ /* else{ */ /* if(k<j0) {struct_const[k-1]='<';} */ /* if(k>j) {struct_const[k-1]='>';} */ /* } */ } /* char duplexseq_1[j0+1]; */ /* char duplexseq_2[n2-j+3]; */ if (j < n2) { char **duplexseq_1, **duplexseq_2; duplexseq_1 = (char **)vrna_alloc((n_seq + 1) * sizeof(char *)); duplexseq_2 = (char **)vrna_alloc((n_seq + 1) * sizeof(char *)); for (s = 0; s < n_seq; s++) { duplexseq_1[s] = (char *)vrna_alloc((j0) * sizeof(char)); /* modfied j0+1 */ duplexseq_2[s] = (char *)vrna_alloc((n2 - j + 2) * sizeof(char)); /* modified j+3 */ strncpy(duplexseq_1[s], snoseq[s], j0 - 1); /* modified j0 */ strcpy(duplexseq_2[s], snoseq[s] + j); /* modified j-1 */ duplexseq_1[s][j0 - 1] = '\0'; /* modified j0 */ duplexseq_2[s][n2 - j + 1] = '\0'; /* modified j+2 */ } duplexseq_1[n_seq] = NULL; duplexseq_2[n_seq] = NULL; duplexT temp; temp = aliduplexfold((const char **)duplexseq_1, (const char **)duplexseq_2); *Loop_D = MIN2(0, -410 + (int)100 * temp.energy * n_seq); if (*Loop_D) { int l1, ibegin, iend, jbegin, jend; l1 = strchr(temp.structure, '&') - temp.structure; ibegin = temp.i - l1; iend = temp.i - 1; jbegin = temp.j; jend = temp.j + (int)strlen(temp.structure) - l1 - 2 - 1; for (k = ibegin + 1; k <= iend + 1; k++) struc2[k - 1] = temp.structure[k - ibegin - 1]; for (k = jbegin + j; k <= jend + j; k++) struc2[k - 1] = temp.structure[l1 + k - j - jbegin + 1]; } for (s = 0; s < n_seq; s++) { free(duplexseq_1[s]); free(duplexseq_2[s]); } free(duplexseq_1); free(duplexseq_2); free(temp.structure); } strcpy(struc, st1 + MAX2(i - 1, 0)); strcat(struc, "&"); /* strcat(struc, st2); */ strncat(struc, struc2 + 5, (int)strlen(struc2) - 10); free(struc2); free(struc_loop); free(st1); free(st2); free(type); free(type2); free(type3); /* free_arrays(); */ return struc; } void Lsnoop_subopt(const char *s1, const char *s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length, const char *name, const int fullStemEnergy) { int min_colonne = INF; int max_pos; int max; max = INF; /* int temp; */ /* int nsubopt=10; */ n1 = (int)strlen(s1); n2 = (int)strlen(s2); int *position; position = (int *)vrna_alloc((n1 + 3) * sizeof(int)); /* int Eminj, Emin_l; */ int i, j; /* l1, Emin=INF, i_min=0, j_min=0; */ /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; vrna_md_t md; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0, Loop_D = 0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { snoupdate_fold_params(); if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } lc = (int **)vrna_alloc(sizeof(int *) * (5)); lr = (int **)vrna_alloc(sizeof(int *) * (5)); for (i = 0; i < 5; i++) { lc[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); lr[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); for (j = n2; j > -1; j--) { lc[i][j] = INF; lr[i][j] = INF; } } encode_seqs(s1, s2); for (i = 1; i <= n1; i++) { int idx = i % 5; int idx_1 = (i - 1) % 5; int idx_2 = (i - 2) % 5; int idx_3 = (i - 3) % 5; int idx_4 = (i - 4) % 5; for (j = n2 - min_d2; j > min_d1; j--) { int type, type2, k; type = pair[S1[i]][S2[j]]; lc[idx][j] = (type) ? P->DuplexInit + 2 * penalty : INF; lr[idx][j] = INF; if (!type) continue; if ( /*pair[S1[i+1]][S2[j-1]] && check that we have a solid base stack after the mLoop */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem && S1[i - 2] == 4) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2 - min_s2, j + max_half_stem + 1); min_k = MAX2(j + half_stem + 1, n2 - max_s2); for (k = min_k; k <= max_k; k++) { if (mLoop[indx[k - 1] + j + 1] < 0) { } if (pair[S1[i - 3]][S2[k]] /*genau zwei ungepaarte nucleotiden --NU--*/ && mLoop[indx[k - 1] + j + 1] < threshloop) lr[idx][j] = MIN2(lr[idx][j], lc[idx_3][k] + mLoop[indx[k - 1] + j + 1]); else if (pair[S1[i - 4]][S2[k]] && mLoop[indx[k - 1] + j + 1] < threshloop) /*--NUN--*/ lr[idx][j] = MIN2(lr[idx][j], lc[idx_4][k] + mLoop[indx[k - 1] + j + 1]); } } /* dangle 5'SIDE relative to the mRNA */ lc[idx][j] += E_ExtLoop(type, (i > 1) ? SS1[i - 1] : -1, (j < n2) ? SS2[j + 1] : -1, P); /** *** if (i>1) lc[idx][j] += P->dangle5[type][SS1[i-1]]; *** if (j<n2) lc[idx][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) lc[idx][j] += P->TerminalAU; **/ if (j < n2 && i > 1) { type2 = pair[S1[i - 1]][S2[j + 1]]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_1][j + 1] + E_IntLoop(0, 0, type2, rtype[type], SS1[i], SS2[j], SS1[i - 1], SS2[j + 1], P) + 2 * penalty, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_1][j + 1] + E_IntLoop(0, 0, type2, rtype[type], SS1[i], SS2[j], SS1[i - 1], SS2[j + 1], P) + 2 * penalty, lr[idx][j]); } } if (j < n2 - 1 && i > 2) { type2 = pair[S1[i - 2]][S2[j + 2]]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_2][j + 2] + E_IntLoop(1, 1, type2, rtype[type], SS1[i - 1], SS2[j + 1], SS1[i - 1], SS2[j + 1], P) + 4 * penalty, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_2][j + 2] + E_IntLoop(1, 1, type2, rtype[type], SS1[i - 1], SS2[j + 1], SS1[i - 1], SS2[j + 1], P) + 4 * penalty, lr[idx][j]); } } if (j < n2 - 2 && i > 3) { type2 = pair[S1[i - 3]][S2[j + 3]]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_3][j + 3] + E_IntLoop(2, 2, type2, rtype[type], SS1[i - 2], SS2[j + 2], SS1[i - 1], SS2[j + 1], P) + 6 * penalty, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_3][j + 3] + E_IntLoop(2, 2, type2, rtype[type], SS1[i - 2], SS2[j + 2], SS1[i - 1], SS2[j + 1], P) + 6 * penalty, lr[idx][j]); } } /** *** (type>2?P->TerminalAU:0)+(i<(n1)?P->dangle3[rtype[type]][SS1[i+1]]+penalty:0)+(j>1?P->dangle5[rtype[type]][SS2[j-1]]+penalty:0) **/ min_colonne = MIN2(lr[idx][j] + E_ExtLoop(rtype[type], (j > 1) ? SS2[j - 1] : -1, (i < n1) ? SS1[i + 1] : -1, P), min_colonne); } position[i] = min_colonne; if (max >= min_colonne) { max = min_colonne; max_pos = i; } min_colonne = INF; } free(S1); free(S2); free(SS1); free(SS2); if (max < threshTE) { find_max_snoop(s1, s2, max, alignment_length, position, delta, distance, penalty, threshloop, threshLE, threshRE, threshDE, threshTE, threshSE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, name, fullStemEnergy); } for (i = 1; i < 5; i++) { free(lc[i]); free(lr[i]); } free(lc[0]); free(lr[0]); free(lc); free(lr); free(position); } void Lsnoop_subopt_list(const char *s1, const char *s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length, const char *name, const int fullStemEnergy) { int min_colonne = INF; int max_pos; int max; max = INF; /* int temp; */ /* int nsubopt=10; */ n1 = (int)strlen(s1); n2 = (int)strlen(s2); int *position; position = (int *)vrna_alloc((n1 + 3) * sizeof(int)); /* int Eminj, Emin_l; */ int i, j;/* l1, Emin=INF, i_min=0, j_min=0; */ /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; vrna_md_t md; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0, Loop_D = 0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { snoupdate_fold_params(); if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } lpair = (int **)vrna_alloc(sizeof(int *) * (6)); lc = (int **)vrna_alloc(sizeof(int *) * (6)); lr = (int **)vrna_alloc(sizeof(int *) * (6)); for (i = 0; i < 6; i++) { lc[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); lr[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); lpair[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); for (j = n2; j > -1; j--) { lc[i][j] = INF; lr[i][j] = INF; lpair[i][j] = 0; } } encode_seqs(s1, s2); int lim_maxj = n2 - min_d2; int lim_minj = min_d1; int lim_maxi = n1; for (i = 5; i <= lim_maxi; i++) { int idx = i % 5; int idx_1 = (i - 1) % 5; int idx_2 = (i - 2) % 5; int idx_3 = (i - 3) % 5; int idx_4 = (i - 4) % 5; for (j = lim_maxj; j > lim_minj; j--) { int type, type2;/* E, k,l; */ type = pair[S1[i]][S2[j]]; lpair[idx][j] = type; lc[idx][j] = (type) ? P->DuplexInit + 2 * penalty : INF; lr[idx][j] = INF; if (!type) continue; if ( /*pair[S1[i+1]][S2[j-1]] && Be sure it binds*/ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem && S1[i - 2] == 4) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2 - min_s2, j + max_half_stem + 1); min_k = MAX2(j + half_stem + 1, n2 - max_s2); folden *temp; temp = foldlist[j + 1]; while (temp->next) { int k = temp->k; /* if(k >= min_k-1 && k < max_k){ comment to recover normal behaviour */ if (lpair[idx_3][k + 1] /*&& lpair[idx_4][k+2]*/) lr[idx][j] = MIN2(lr[idx][j], lc[idx_3][k + 1] + temp->energy); /*--NU--*/ /*else*/ if (lpair[idx_4][k + 1]) /*--NUN--*/ lr[idx][j] = MIN2(lr[idx][j], lc[idx_4][k + 1] + temp->energy); /* } */ temp = temp->next; } } /* dangle 5'SIDE relative to the mRNA */ lc[idx][j] += E_ExtLoop(type, SS1[i - 1], SS2[j + 1], P); /** *** lc[idx][j] += P->dangle5[type][SS1[i-1]]; *** lc[idx][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) lc[idx][j] += P->TerminalAU; **/ /* if(j<n2 && i>1){ */ /* type2=pair[S1[i-1]][S2[j+1]]; */ type2 = lpair[idx_1][j + 1]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_1][j + 1] + E_IntLoop(0, 0, type2, rtype[type], SS1[i], SS2[j], SS1[i - 1], SS2[j + 1], P) + 2 * penalty, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_1][j + 1] + E_IntLoop(0, 0, type2, rtype[type], SS1[i], SS2[j], SS1[i - 1], SS2[j + 1], P) + 2 * penalty, lr[idx][j]); } /* } */ /* if(j<n2-1 && i>2){ */ /* type2=pair[S1[i-2]][S2[j+2]]; */ type2 = lpair[idx_2][j + 2]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_2][j + 2] + E_IntLoop(1, 1, type2, rtype[type], SS1[i - 1], SS2[j + 1], SS1[i - 1], SS2[j + 1], P), lc[idx][j]); lr[idx][j] = MIN2(lr[idx_2][j + 2] + E_IntLoop(1, 1, type2, rtype[type], SS1[i - 1], SS2[j + 1], SS1[i - 1], SS2[j + 1], P), lr[idx][j]); /* } */ } /* if(j<n2-2 && i>3){ */ /* type2 = pair[S1[i-3]][S2[j+3]]; */ type2 = lpair[idx_3][j + 3]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_3][j + 3] + E_IntLoop(2, 2, type2, rtype[type], SS1[i - 2], SS2[j + 2], SS1[i - 1], SS2[j + 1], P) + 6 * penalty, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_3][j + 3] + E_IntLoop(2, 2, type2, rtype[type], SS1[i - 2], SS2[j + 2], SS1[i - 1], SS2[j + 1], P) + 6 * penalty, lr[idx][j]); /* } */ } /* min_colonne=MIN2(lr[idx][j]+(type>2?P->TerminalAU:0)+P->dangle3[rtype[type]][SS1[i+1]]+P->dangle5[rtype[type]][SS2[j-1]], min_colonne); */ int bla; bla = lr[idx][j] + E_ExtLoop(rtype[type], SS2[j - 1], SS1[i + 1], P) + 2 * penalty; min_colonne = MIN2(bla, min_colonne); } position[i] = min_colonne; if (max >= min_colonne) { max = min_colonne; max_pos = i; } min_colonne = INF; } free(S1); free(S2); free(SS1); free(SS2); if (max < threshTE) { find_max_snoop(s1, s2, max, alignment_length, position, delta, distance, penalty, threshloop, threshLE, threshRE, threshDE, threshTE, threshSE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, name, fullStemEnergy); } for (i = 1; i < 6; i++) { free(lc[i]); free(lr[i]); free(lpair[i]); } free(lc[0]); free(lr[0]); free(lpair[0]); free(lc); free(lr); free(lpair); free(position); } PRIVATE void find_max_snoop(const char *s1, const char *s2, const int max, const int alignment_length, const int *position, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char *name, const int fullStemEnergy) { int count = 0; int pos = n1 + 1; int threshold = MIN2(threshTE, max + delta); /* printf("threshTE %d max %d\n", threshTE, max); */ /* #pragma omp parallel for */ /* for(pos=n1+1;pos>distance;pos--){ */ while (pos-- > 5) { int temp_min = 0; if (position[pos] < (threshold)) { int search_range; search_range = distance + 1; while (--search_range) if (position[pos - search_range] <= position[pos - temp_min]) temp_min = search_range; pos -= temp_min; int begin = MAX2(6, pos - alignment_length + 1); char *s3 = (char *)vrna_alloc(sizeof(char) * (pos - begin + 3 + 12)); strcpy(s3, "NNNNN"); strncat(s3, (s1 + begin - 1), pos - begin + 2); strcat(s3, "NNNNN\0"); /* printf("%s s3\n", s3); */ snoopT test; test = snoopfold(s3, s2, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, fullStemEnergy); if (test.energy == INF) { free(s3); continue; } if (test.Duplex_El > threshLE * 0.01 || test.Duplex_Er > threshRE * 0.01 || test.Loop_D > threshD * 0.01 || (test.Duplex_Er + test.Duplex_El) > threshDE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E + test.Loop_D + 410) > threshSE * 0.01) { free(test.structure); free(s3); continue; } int l1; l1 = strchr(test.structure, '&') - test.structure; int shift = 0; if (test.i > (int)strlen(s3) - 10) { test.i--; l1--; } if (test.i - l1 < 0) { l1--; shift++; } char *target_struct = (char *)vrna_alloc(sizeof(char) * (strlen(test.structure) + 1)); strncpy(target_struct, test.structure + shift, l1); strncat(target_struct, test.structure + (strchr(test.structure, '&') - test.structure), (int)strlen(test.structure) - (strchr(test.structure, '&') - test. structure)); strcat(target_struct, "\0"); char *target; target = (char *)vrna_alloc(l1 + 1); strncpy(target, (s3 + test.i + 5 - l1), l1); target[l1] = '\0'; char *s4; s4 = (char *)vrna_alloc(sizeof(char) * (strlen(s2) - 9)); strncpy(s4, s2 + 5, (int)strlen(s2) - 10); s4[(int)strlen(s2) - 10] = '\0'; printf( "%s %3d,%-3d;%3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f + %5.2f + 4.1 ) (%5.2f) \n%s&%s\n", target_struct, begin + test.i - 5 - l1, begin + test.i - 6, begin + test.u - 6, test.j + 1, test.j + (int)(strrchr(test.structure, '>') - strchr(test.structure, '>')) + 1, test.Loop_D + test.Duplex_El + test.Duplex_Er + test.Loop_E + 4.10, test.Duplex_El, test.Duplex_Er, test.Loop_E, test.Loop_D, test.fullStemEnergy, target, s4); if (name) { char *temp_seq; char *temp_struc; char *psoutput; temp_seq = (char *)vrna_alloc(sizeof(char) * (l1 + n2 - 9)); temp_struc = (char *)vrna_alloc(sizeof(char) * (l1 + n2 - 9)); strcpy(temp_seq, target); strcat(temp_seq, s4); strncpy(temp_struc, target_struct, l1); strcat(temp_struc, target_struct + l1 + 1); temp_seq[n2 + l1 - 10] = '\0'; temp_struc[n2 + l1 - 10] = '\0'; cut_point = l1 + 1; psoutput = vrna_strdup_printf("sno_%d_u_%d_%s.ps", count, begin + test.u - 6, name); PS_rna_plot_snoop_a(temp_seq, temp_struc, psoutput, NULL, NULL); cut_point = -1; free(temp_seq); free(temp_struc); free(psoutput); count++; /* free(psoutput); */ } free(s4); free(test.structure); free(target_struct); free(target); free(s3); } } } snoopT snoopfold(const char *s1, const char *s2, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int fullStemEnergy) { /* int Eminj, Emin_l; */ int i, j, l1, Emin = INF, i_min = 0, j_min = 0; char *struc; snoopT mfe; int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; int u; int Loop_E; vrna_md_t md; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0, Loop_D = 0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); n1 = (int)strlen(s1); n2 = (int)strlen(s2); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { snoupdate_fold_params(); if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } c = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); r = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); for (i = 0; i <= n1; i++) { c[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); r[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); for (j = n2; j > -1; j--) { c[i][j] = INF; r[i][j] = INF; } } encode_seqs(s1, s2); for (i = 6; i <= n1 - 5; i++) { for (j = n2 - min_d2; j > min_d1; j--) { int type, type2, E, k, l; type = pair[S1[i]][S2[j]]; c[i][j] = (type) ? P->DuplexInit : INF; if (!type) continue; if (/* pair[S1[i+1]][S2[j-1]] && */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem && S1[i - 2] == 4) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2 - min_s2, j + max_half_stem); min_k = MAX2(j + half_stem, n2 - max_s2); folden *temp; temp = foldlist[j + 1]; while (temp->next) { int k = temp->k; /* if(k >= min_k-1 && k < max_k){ uncomment to recovernormal behaviour */ if (pair[S1[i - 3]][S2[k + 1]] /*&& pair[S1[i-4]][S2[k+2]]*/) r[i][j] = MIN2(r[i][j], c[i - 3][k + 1] + temp->energy); /*else*/ if (pair[S1[i - 4]][S2[k + 1]] /*&& pair[S1[i-5]][S2[k+2]]*/) r[i][j] = MIN2(r[i][j], c[i - 4][k + 1] + temp->energy); /* } */ temp = temp->next; } } /* dangle 5'SIDE relative to the mRNA */ /** *** c[i][j] += P->dangle5[type][SS1[i-1]]; *** c[i][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) c[i][j] += P->TerminalAU; **/ c[i][j] += E_ExtLoop(type, SS1[i - 1], SS2[j + 1], P); for (k = i - 1; k > 0 && (i - k) < MAXLOOP_L; k--) { for (l = j + 1; l <= n2; l++) { if (i - k + l - j > 2 * MAXLOOP_L - 2) break; if (abs(i - k - l + j) >= ASS) continue; 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 + (i - k + l - j) * penalty); r[i][j] = MIN2(r[i][j], r[k][l] + E + (i - k + l - j) * penalty); } } E = r[i][j]; /** *** if (i<n1) E += P->dangle3[rtype[type]][SS1[i+1]]; *** if (j>1) E += P->dangle5[rtype[type]][SS2[j-1]]; *** f (type>2) E += P->TerminalAU; **/ 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; } } } if (Emin > 0) { printf("no target found under the constraints chosen\n"); for (i = 0; i <= n1; i++) { free(r[i]); free(c[i]); } free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); mfe.energy = INF; return mfe; } struc = snoop_backtrack(i_min, j_min, s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); /* if (i_min<n1-5) i_min++; */ /* if (j_min>1 ) j_min--; */ l1 = strchr(struc, '&') - struc; mfe.i = i_min - 5; mfe.j = j_min - 5; mfe.u = u - 5; mfe.Duplex_Er = (float)Duplex_Er / 100; mfe.Duplex_El = (float)Duplex_El / 100; mfe.Loop_D = (float)Loop_D / 100; mfe.Loop_E = (float)Loop_E / 100; mfe.energy = (float)Emin / 100; mfe.fullStemEnergy = (float)fullStemEnergy / 100; mfe.structure = struc; if (!delay_free) { for (i = 0; i <= n1; i++) { free(r[i]); free(c[i]); } free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); } return mfe; } PRIVATE int snoopfold_XS_fill(const char *s1, const char *s2, const int **access_s1, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { /* int Eminj, Emin_l; */ int i, j, Emin = INF, i_min = 0, j_min = 0; /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; vrna_md_t md; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0, Loop_D = 0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); n1 = (int)strlen(s1); n2 = (int)strlen(s2); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { snoupdate_fold_params(); if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } c_fill = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); r_fill = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); for (i = 0; i <= n1; i++) { c_fill[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); r_fill[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); for (j = n2; j > -1; j--) { c_fill[i][j] = INF; r_fill[i][j] = INF; } } encode_seqs(s1, s2); int di[5]; di[0] = 0; for (i = 6; i <= n1 - 5; i++) { di[1] = access_s1[5][i] - access_s1[4][i - 1]; di[2] = access_s1[5][i - 1] - access_s1[4][i - 2] + di[1]; di[3] = access_s1[5][i - 2] - access_s1[4][i - 3] + di[2]; di[4] = access_s1[5][i - 3] - access_s1[4][i - 4] + di[3]; di[1] = MIN2(di[1], 165); di[2] = MIN2(di[2], 330); di[3] = MIN2(di[3], 495); di[4] = MIN2(di[4], 660); for (j = n2 - min_d2; j > min_d1; j--) { int type, type2, E, k, l; type = pair[S1[i]][S2[j]]; c_fill[i][j] = (type) ? P->DuplexInit : INF; if (!type) continue; if (/* pair[S1[i+1]][S2[j-1]] && */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem && S1[i - 2] == 4) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2 - min_s2, j + max_half_stem); min_k = MAX2(j + half_stem, n2 - max_s2); folden *temp; temp = foldlist[j + 1]; while (temp->next) { int k = temp->k; /* if(k >= min_k-1 && k < max_k){ uncomment to recovernormal behaviour */ if (pair[S1[i - 3]][S2[k + 1]] /*&& pair[S1[i-4]][S2[k+2]]*/) r_fill[i][j] = MIN2(r_fill[i][j], c_fill[i - 3][k + 1] + temp->energy + di[3]); /*else*/ if (pair[S1[i - 4]][S2[k + 1]] /*&& pair[S1[i-5]][S2[k+2]]*/) r_fill[i][j] = MIN2(r_fill[i][j], c_fill[i - 4][k + 1] + temp->energy + di[4]); /* } */ temp = temp->next; } } /* dangle 5'SIDE relative to the mRNA */ /** *** c_fill[i][j] += P->dangle5[type][SS1[i-1]]; *** c_fill[i][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) c_fill[i][j] += P->TerminalAU; **/ c_fill[i][j] += E_ExtLoop(type, SS1[i - 1], SS2[j + 1], P); for (k = i - 1; k > 0 && (i - k) < MAXLOOP_L; k--) { for (l = j + 1; l <= n2; l++) { if (i - k + l - j > 2 * MAXLOOP_L - 2) break; if (abs(i - k - l + j) >= ASS) continue; 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_fill[i][j] = MIN2(c_fill[i][j], c_fill[k][l] + E + di[i - k]); r_fill[i][j] = MIN2(r_fill[i][j], r_fill[k][l] + E + di[i - k]); } } E = r_fill[i][j]; /** *** if (i<n1) E += P->dangle3[rtype[type]][SS1[i+1]]; *** if (j>1) E += P->dangle5[rtype[type]][SS2[j-1]]; *** if (type>2) E += P->TerminalAU; **/ 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; } } } return Emin; } PUBLIC snoopT * snoop_subopt(const char *s1, const char *s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int fullStemEnergy) { /* printf("%d %d\n", min_s2, max_s2); */ int i, j, n1, n2, E, n_subopt = 0, n_max; char *struc; snoopT mfe; snoopT *subopt; int thresh; int Duplex_El, Duplex_Er, Loop_E; int Loop_D; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0; Loop_D = 0; int u; u = 0; n_max = 16; subopt = (snoopT *)vrna_alloc(n_max * sizeof(snoopT)); delay_free = 1; mfe = snoopfold(s1, s2, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, fullStemEnergy); if (mfe.energy > 0) { free(subopt); delay_free = 0; return NULL; } thresh = MIN2((int)((mfe.Duplex_Er + mfe.Duplex_El + mfe.Loop_E) * 100 + 0.1 + 410) + delta, threshTE); /* subopt[n_subopt++]=mfe; */ free(mfe.structure); n1 = (int)strlen(s1); n2 = (int)strlen(s2); for (i = n1; i > 0; i--) { for (j = 1; j <= n2; j++) { int type, Ed; type = pair[S2[j]][S1[i]]; if (!type) continue; E = Ed = r[i][j]; /** *** if (i<n1) Ed += P->dangle3[type][SS1[i+1]]; *** if (j>1) Ed += P->dangle5[type][SS2[j-1]]; *** if (type>2) Ed += P->TerminalAU; **/ 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. */ /* w=1; */ /* 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 (r[ii][jj]<E) {type=0; break;} */ /* } */ if (!type) continue; struc = snoop_backtrack(i, j, s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); if (Duplex_Er > threshRE || Duplex_El > threshLE || Loop_D > threshD || (Duplex_Er + Duplex_El) > threshDE || (Duplex_Er + Duplex_El + Loop_E) > threshTE || (Duplex_Er + Duplex_El + Loop_E + Loop_D + 410) > threshSE) { /* printf(" Duplex_Er %d threshRE %d Duplex_El %d threshLE %d \n" */ /* " Duplex_Er + Duplex_El %d threshDE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E %d threshTE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E + Loop_D %d threshSE %d \n", */ /* Duplex_Er , threshRE , Duplex_El ,threshLE, */ /* Duplex_Er + Duplex_El, threshDE, */ /* Duplex_Er + Duplex_El+ Loop_E , threshTE, */ /* Duplex_Er + Duplex_El+ Loop_E + Loop_D, threshSE); */ Duplex_Er = 0; Duplex_El = 0; Loop_E = 0; Loop_D = 0; u = 0, free(struc); continue; } if (n_subopt + 1 >= n_max) { n_max *= 2; subopt = (snoopT *)vrna_realloc(subopt, n_max * sizeof(snoopT)); } subopt[n_subopt].i = i - 5; subopt[n_subopt].j = j - 5; subopt[n_subopt].u = u - 5; subopt[n_subopt].Duplex_Er = Duplex_Er * 0.01; subopt[n_subopt].Duplex_El = Duplex_El * 0.01; subopt[n_subopt].Loop_E = Loop_E * 0.01; subopt[n_subopt].Loop_D = Loop_D * 0.01; subopt[n_subopt].energy = (Duplex_Er + Duplex_El + Loop_E + Loop_D + 410) * 0.01; subopt[n_subopt].fullStemEnergy = (float)fullStemEnergy * 0.01; subopt[n_subopt++].structure = struc; Duplex_Er = 0; Duplex_El = 0; Loop_E = 0; Loop_D = 0; u = 0; } } for (i = 0; i <= n1; i++) { free(c[i]); free(r[i]); } free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); delay_free = 0; if (snoop_subopt_sorted) qsort(subopt, n_subopt, sizeof(snoopT), compare); subopt[n_subopt].i = 0; subopt[n_subopt].j = 0; subopt[n_subopt].structure = NULL; return subopt; } PUBLIC void snoop_subopt_XS(const char *s1, const char *s2, const int **access_s1, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length, const char *name, const int fullStemEnergy) { /* printf("%d %d\n", min_s2, max_s2); */ int i, j, E, n_max; /* char *struc; */ /* snoopT mfe; */ int thresh; int Duplex_El, Duplex_Er, Loop_E; int Loop_D; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0; Loop_D = 0; int u; u = 0; n_max = 16; delay_free = 1; int Emin = snoopfold_XS_fill(s1, s2, access_s1, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); if (Emin > 0) delay_free = 0; thresh = MIN2(-100, threshTE + alignment_length * 30); /* n1=(int)strlen(s1); */ /* n2=(int)strlen(s2); */ int n3 = (int)strlen(s1); int n4 = (int)strlen(s2); S1_fill = (short *)vrna_alloc(sizeof(short) * (n3 + 2)); S2_fill = (short *)vrna_alloc(sizeof(short) * (n4 + 2)); SS1_fill = (short *)vrna_alloc(sizeof(short) * (n3 + 1)); SS2_fill = (short *)vrna_alloc(sizeof(short) * (n4 + 1)); memcpy(S1_fill, S1, sizeof(short) * n3 + 2); memcpy(S2_fill, S2, sizeof(short) * n4 + 2); memcpy(SS1_fill, SS1, sizeof(short) * n3 + 1); memcpy(SS2_fill, SS2, sizeof(short) * n4 + 1); free(S1); free(S2); free(SS1); free(SS2); int count = 0; for (i = n3 - 5; i > 0; i--) { for (j = 1; j <= n4; j++) { int type, Ed; type = pair[S2_fill[j]][S1_fill[i]]; if (!type) continue; E = Ed = r_fill[i][j]; /** ***if (i<n3) Ed += P->dangle3[type][SS1_fill[i+1]]; ***if (j>1) Ed += P->dangle5[type][SS2_fill[j-1]]; ***if (type>2) Ed += P->TerminalAU; **/ Ed += E_ExtLoop(type, (j > 1) ? SS2[j - 1] : -1, (i < n3) ? SS1[i + 1] : -1, P); if (Ed > thresh) continue; /* to 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. */ /* w=10; */ /* for (ii=MAX2(i-w,1); (ii<=MIN2(i+w,n3-5)) && type; ii++) { */ /* for (jj=MAX2(j-w,1); jj<=MIN2(j+w,n4-5); jj++) */ /* if (r_fill[ii][jj]<E) {type=0; break;} */ /* } */ /* i=ii;j=jj; */ if (!type) continue; int begin = MAX2(5, i - alignment_length); int end = MIN2(n3 - 5, i - 1); char *s3 = (char *)vrna_alloc(sizeof(char) * (end - begin + 2) + 5); strncpy(s3, (s1 + begin), end - begin + 1); strcat(s3, "NNNNN\0"); int n5 = (int)strlen(s3); snoopT test = snoopfold_XS(s3, s2, access_s1, i, j, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, fullStemEnergy); if (test.energy == INF) { free(s3); continue; } if (test.Duplex_El > threshLE * 0.01 || test.Duplex_Er > threshRE * 0.01 || test.Loop_D > threshD * 0.01 || (test.Duplex_Er + test.Duplex_El) > threshDE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E) > threshTE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E + test.Loop_D + 410) > threshSE * 0.01) { free(test.structure); free(s3); continue; } char *s4; s4 = (char *)vrna_alloc(sizeof(char) * (n4 - 9)); strncpy(s4, s2 + 5, n4 - 10); s4[n4 - 10] = '\0'; char *s5 = vrna_alloc(sizeof(char) * n5 - test.i + 2 - 5); strncpy(s5, s3 + test.i - 1, n5 - test.i + 1 - 5); s5[n5 - test.i + 1 - 5] = '\0'; float dE = ((float)(access_s1[n5 - test.i + 1 - 5][i])) * 0.01; printf( "%s %3d,%-3d;%3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f + %5.2f + %5.2f + 4.10) (%5.2f)\n%s&%s\n", test.structure, i - (n5 - test.i), i - 5, i - (n5 - test.u), j - 5, j - 5 + (int)(strrchr(test.structure, '>') - strchr(test.structure, '>')), test.Loop_D + test.Duplex_El + test.Duplex_Er + test.Loop_E + 4.10 + dE, test.Duplex_El, test.Duplex_Er, test.Loop_E, test.Loop_D, dE, test.fullStemEnergy, s5, s4); if (name) { int begin_t, end_t, begin_q, end_q, and, pipe, k; char *psoutput; begin_q = 0; end_q = n4 - 10; begin_t = 0; end_t = n5 - test.i + 1 - 5; and = end_t + 1; pipe = test.u - test.i + 1; cut_point = end_t + 1; char *catseq, *catstruct;/* *fname; */ catseq = (char *)vrna_alloc(n5 + end_q - begin_q + 2); catstruct = (char *)vrna_alloc(n5 + end_q - begin_q + 2); strcpy(catseq, s5); strncpy(catstruct, test.structure, end_t); strcat(catseq, s4); strncat(catstruct, test.structure + end_t + 1, end_q - begin_q + 1); catstruct[end_t - begin_t + end_q - begin_q + 2] = '\0'; catseq[end_t - begin_t + end_q - begin_q + 2] = '\0'; int *relative_access; relative_access = vrna_alloc(sizeof(int) * strlen(s5)); relative_access[0] = access_s1[1][i - (n5 - test.i) + 5]; for (k = 1; k < (int)strlen(s5); k++) relative_access[k] = access_s1[k + 1][i - (n5 - test.i) + k + 5] - access_s1[k][i - (n5 - test.i) + k + 4]; psoutput = vrna_strdup_printf("sno_XS_%d_u_%d_%s.ps", count, i - (n5 - test.u), name); PS_rna_plot_snoop_a(catseq, catstruct, psoutput, relative_access, NULL); free(catseq); free(catstruct); free(relative_access); free(psoutput); count++; } free(s3); free(s4); free(s5); free(test.structure); } } for (i = 0; i <= n3; i++) { free(c_fill[i]); free(r_fill[i]); } free(c_fill); free(r_fill); free(S1_fill); free(S2_fill); free(SS1_fill); free(SS2_fill); delay_free = 0; } PRIVATE char * snoop_backtrack(int i, int j, const char *snoseq, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { /* 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; int traced_r = 0; /* flag for following backtrack in c or r */ char *st1, *st2, *struc; char *struc_loop; st1 = (char *)vrna_alloc(sizeof(char) * (n1 + 1)); st2 = (char *)vrna_alloc(sizeof(char) * (n2 + 1)); int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; type = pair[S1[i]][S2[j]]; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); i0 = i; j0 = j; /** *** if (i<n1) *Duplex_Er += P->dangle3[rtype[type]][SS1[i+1]]; *** if (j>1) *Duplex_Er += P->dangle5[rtype[type]][SS2[j-1]]; *** if (type>2) *Duplex_Er += P->TerminalAU; **/ *Duplex_Er += E_ExtLoop(rtype[type], (j > 1) ? SS2[j - 1] : -1, (i < n1) ? SS1[i + 1] : -1, P); while (i > 0 && j <= n2 - min_d2) { if (!traced_r) { E = r[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 r"); for (k = i - 1; k > 0 && (i - k) < MAXLOOP_L; k--) { for (l = j + 1; l <= n2; l++) { int LE; if (i - k + l - j > 2 * MAXLOOP_L - 2) break; if (abs(i - k - l + j) >= ASS) continue; 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 == r[k][l] + LE + (i - k + l - j) * penalty) { traced = 1; i = k; j = l; *Duplex_Er += LE; break; } } if (traced) break; } if (!traced) { if (/* pair[S1[i+1]][S2[j-1]] && */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem && S1[i - 2] == 4) { int min_k, max_k; max_k = MIN2(n2 - min_s2, j + max_half_stem + 1); min_k = MAX2(j + half_stem + 1, n2 - max_s2); folden *temp; temp = foldlist[j + 1]; while (temp->next) { int k = temp->k; if (pair[S1[i - 3]][S2[k + 1]] /*&& pair[S1[i-4]][S2[k+2]]*/) { /* introduce structure from RNAfold */ if (E == c[i - 3][k + 1] + temp->energy) { *Loop_E = temp->energy; st1[i - 3] = '|'; *u = i - 2; int a, b; /* int fix_ij=indx[k-1+1]+j+1; */ for (a = 0; a < MISMATCH; a++) { for (b = 0; b < MISMATCH; b++) { int ij = indx[k - 1 - a + 1] + j + 1 + b; if (cLoop[ij] == temp->energy) { struc_loop = snobacktrack_fold_from_pair(snoseq, j + 1 + b, k - a - 1 + 1); a = INF; b = INF; } } } traced = 1; traced_r = 1; i = i - 3; j = k + 1; break; } } /*else*/ if (pair[S1[i - 4]][S2[k + 1]] /*&& pair[S1[i-5]][S2[k+2]]*/) { /* introduce structure from RNAfold */ if (E == c[i - 4][k + 1] + temp->energy) { *Loop_E = temp->energy; st1[i - 3] = '|'; *u = i - 2; int a, b; /* int fix_ij=indx[k-1+1]+j+1; */ for (a = 0; a < MISMATCH; a++) { for (b = 0; b < MISMATCH; b++) { int ij = indx[k - 1 - a + 1] + j + 1 + b; if (cLoop[ij] == temp->energy) { struc_loop = snobacktrack_fold_from_pair(snoseq, j + 1 + b, k - a - 1 + 1); a = INF; b = INF; } } } traced = 1; traced_r = 1; i = i - 4; j = k + 1; break; } } /* else if */ temp = temp->next; } /* while temp-> next */ } /* test on j */ } /* traced? */ } /* traced_r? */ else { 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 c"); for (k = i - 1; (i - k) < MAXLOOP_L; k--) { for (l = j + 1; l <= n2; l++) { int LE; if (i - k + l - j > 2 * MAXLOOP_L - 2) break; if (abs(i - k - l + j) >= ASS) continue; 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 + (i - k + l - j) * penalty) { traced = 1; i = k; j = l; *Duplex_El += LE; break; } } if (traced) break; } } if (!traced) { int correction; correction = E_ExtLoop(type, (i > 1) ? SS1[i - 1] : -1, (j < n2) ? SS2[j + 1] : -1, P); E -= correction; *Duplex_El += correction; /** *** if (i>1) {E -= P->dangle5[type][SS1[i-1]]; *Duplex_El +=P->dangle5[type][SS1[i-1]];} *** if (j<n2) {E -= P->dangle3[type][SS2[j+1]]; *Duplex_El +=P->dangle3[type][SS2[j+1]];} *** if (type>2) {E -= P->TerminalAU; *Duplex_El +=P->TerminalAU;} **/ if (E != P->DuplexInit) vrna_message_error("backtrack failed in fold duplex end"); else break; } } /* if (i>1) i--; */ /* if (j<n2) j++; */ /* struc = (char *) vrna_alloc(i0-i+1+j-j0+1+2); */ /* declare final duplex structure */ struc = (char *)vrna_alloc(i0 - i + 1 + n2 - 1 + 1 + 2); /* declare final duplex structure */ char *struc2; struc2 = (char *)vrna_alloc(n2 + 1); /* char * struct_const; */ 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] = struc_loop[k-1];*/ /* '.'; normal */ /* char * struct_const; */ /* struct_const = (char *) vrna_alloc(sizeof(char)*(n2+1)); */ for (k = 1; k <= n2; k++) { if (!st2[k - 1]) st2[k - 1] = struc_loop[k - 1]; /* '.'; */ struc2[k - 1] = st2[k - 1]; /* '.'; */ /* if (k>=j0 && k<=j){ */ /* struct_const[k-1]='x'; */ /* } */ /* else{ */ /* if(k<j0) {struct_const[k-1]='<';} */ /* if(k>j) {struct_const[k-1]='>';} */ /* } */ } char duplexseq_1[j0]; char duplexseq_2[n2 - j + 2]; if (j < n2) { strncpy(duplexseq_1, snoseq, j0 - 1); strcpy(duplexseq_2, snoseq + j); duplexseq_1[j0 - 1] = '\0'; duplexseq_2[n2 - j + 1] = '\0'; duplexT temp; temp = duplexfold(duplexseq_1, duplexseq_2); *Loop_D = MIN2(0, -410 + (int)100 * temp.energy); if (*Loop_D) { int l1, ibegin, iend, jbegin, jend; l1 = strchr(temp.structure, '&') - temp.structure; ibegin = temp.i - l1; iend = temp.i - 1; jbegin = temp.j; jend = temp.j + (int)strlen(temp.structure) - l1 - 2 - 1; for (k = ibegin + 1; k <= iend + 1; k++) struc2[k - 1] = temp.structure[k - ibegin - 1]; for (k = jbegin + j; k <= jend + j; k++) struc2[k - 1] = temp.structure[l1 + k - j - jbegin + 1]; } free(temp.structure); } strcpy(struc, st1 + MAX2(i - 1, 0)); strcat(struc, "&"); /* strcat(struc, st2); */ strncat(struc, struc2 + 5, (int)strlen(struc2) - 10); free(struc2); free(struc_loop); free(st1); free(st2); /* free_arrays(); */ return struc; } void Lsnoop_subopt_list_XS(const char *s1, const char *s2, const int **access_s1, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length, const char *name, const int fullStemEnergy) { int min_colonne = INF; int max_pos; int max; max = INF; /* int temp; */ /* int nsubopt=10; */ n1 = (int)strlen(s1); n2 = (int)strlen(s2); int *position; int *position_j; int min_j_colonne; int max_pos_j = INF; position = (int *)vrna_alloc((n1 + 3) * sizeof(int)); position_j = (int *)vrna_alloc((n1 + 3) * sizeof(int)); /* int Eminj, Emin_l; */ int i, j;/* l1, Emin=INF, i_min=0, j_min=0; */ /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; vrna_md_t md; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0, Loop_D = 0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { snoupdate_fold_params(); if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } lpair = (int **)vrna_alloc(sizeof(int *) * (6)); lc = (int **)vrna_alloc(sizeof(int *) * (6)); lr = (int **)vrna_alloc(sizeof(int *) * (6)); for (i = 0; i < 6; i++) { lc[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); lr[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); lpair[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); for (j = n2; j > -1; j--) { lc[i][j] = INF; lr[i][j] = INF; lpair[i][j] = 0; } } encode_seqs(s1, s2); int lim_maxj = n2 - min_d2; int lim_minj = min_d1; int lim_maxi = n1 - 5; for (i = 5; i <= lim_maxi; i++) { int idx = i % 5; int idx_1 = (i - 1) % 5; int idx_2 = (i - 2) % 5; int idx_3 = (i - 3) % 5; int idx_4 = (i - 4) % 5; int di1, di2, di3, di4; di1 = access_s1[5][i] - access_s1[4][i - 1]; di2 = access_s1[5][i - 1] - access_s1[4][i - 2] + di1; di3 = access_s1[5][i - 2] - access_s1[4][i - 3] + di2; di4 = access_s1[5][i - 3] - access_s1[4][i - 4] + di3; di1 = MIN2(di1, 165); di2 = MIN2(di2, 330); di3 = MIN2(di3, 495); di4 = MIN2(di4, 660); for (j = lim_maxj; j > lim_minj; j--) { int type, type2;/* E, k,l; */ type = pair[S1[i]][S2[j]]; lpair[idx][j] = type; lc[idx][j] = (type) ? P->DuplexInit + access_s1[1][i] : INF; lr[idx][j] = INF; if (!type) continue; if ( /*pair[S1[i+1]][S2[j-1]] && Be sure it binds*/ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 - min_s2 - half_stem && S1[i - 2] == 4) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2 - min_s2, j + max_half_stem + 1); min_k = MAX2(j + half_stem + 1, n2 - max_s2); folden *temp; temp = foldlist[j + 1]; while (temp->next) { int k = temp->k; /* if(k >= min_k-1 && k < max_k){ comment to recover normal behaviour */ if (lpair[idx_3][k + 1] && lc[idx_3][k + 1] /*+di3*/ < 411 /*&& lpair[idx_4][k+2]*/) /* remove second condition */ lr[idx][j] = MIN2(lr[idx][j], di3 + lc[idx_3][k + 1] + temp->energy); /*--NU--*/ /*else*/ if (lpair[idx_4][k + 1] && /*di4 +*/ lc[idx_4][k + 1] < 411) /*--NUN--*/ /* remove second condition */ lr[idx][j] = MIN2(lr[idx][j], di4 + lc[idx_4][k + 1] + temp->energy); /* } */ temp = temp->next; } } /* dangle 5'SIDE relative to the mRNA */ /** *** lc[idx][j] += P->dangle5[type][SS1[i-1]]; *** lc[idx][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) lc[idx][j] += P->TerminalAU; **/ lc[idx][j] += E_ExtLoop(type, SS1[i - 1], SS2[j + 1], P); /* if(j<n2 && i>1){ */ /* type2=pair[S1[i-1]][S2[j+1]]; */ type2 = lpair[idx_1][j + 1]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_1][j + 1] + E_IntLoop(0, 0, type2, rtype[type], SS1[i], SS2[j], SS1[i - 1], SS2[j + 1], P) + di1, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_1][j + 1] + E_IntLoop(0, 0, type2, rtype[type], SS1[i], SS2[j], SS1[i - 1], SS2[j + 1], P) + di1, lr[idx][j]); } type2 = lpair[idx_2][j + 2]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_2][j + 2] + E_IntLoop(1, 1, type2, rtype[type], SS1[i - 1], SS2[j + 1], SS1[i - 1], SS2[j + 1], P) + di2, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_2][j + 2] + E_IntLoop(1, 1, type2, rtype[type], SS1[i - 1], SS2[j + 1], SS1[i - 1], SS2[j + 1], P) + di2, lr[idx][j]); } type2 = lpair[idx_3][j + 3]; if (type2 > 0) { lc[idx][j] = MIN2(lc[idx_3][j + 3] + E_IntLoop(2, 2, type2, rtype[type], SS1[i - 2], SS2[j + 2], SS1[i - 1], SS2[j + 1], P) + di3, lc[idx][j]); lr[idx][j] = MIN2(lr[idx_3][j + 3] + E_IntLoop(2, 2, type2, rtype[type], SS1[i - 2], SS2[j + 2], SS1[i - 1], SS2[j + 1], P) + di3, lr[idx][j]); } int bla; int temp2; temp2 = min_colonne; bla = lr[idx][j] + E_ExtLoop(rtype[type], SS2[j - 1], SS1[i + 1], P); /** *** (type>2?P->TerminalAU:0)+P->dangle3[rtype[type]][SS1[i+1]]+P->dangle5[rtype[type]][SS2[j-1]]; **/ min_colonne = MIN2(bla, min_colonne); if (temp2 > min_colonne) min_j_colonne = j; } position[i] = min_colonne; if (max >= min_colonne) { max = min_colonne; max_pos = i; max_pos_j = min_j_colonne; } position_j[i] = min_j_colonne; min_colonne = INF; } free(S1); free(S2); free(SS1); free(SS2); if (max < threshTE + 30 * alignment_length) { find_max_snoop_XS(s1, s2, access_s1, max, alignment_length, position, position_j, delta, distance, penalty, threshloop, threshLE, threshRE, threshDE, threshTE, threshSE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, name, fullStemEnergy); } for (i = 1; i < 6; i++) { free(lc[i]); free(lr[i]); free(lpair[i]); } free(lc[0]); free(lr[0]); free(lpair[0]); free(lc); free(lr); free(lpair); free(position); free(position_j); } PRIVATE void find_max_snoop_XS(const char *s1, const char *s2, const int **access_s1, const int max, const int alignment_length, const int *position, const int *position_j, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char *name, const int fullStemEnergy) { int count = 0; int n3 = (int)strlen(s1); int n4 = (int)strlen(s2); int pos = n1 - 4; int max_pos_j; int threshold = MIN2(threshTE + alignment_length * 30, -100); /* printf("threshTE %d max %d\n", threshTE, max); */ /* #pragma omp parallel for */ /* for(pos=n1+1;pos>distance;pos--){ */ while (pos-- > 5) { int temp_min = 0; if (position[pos] < (threshold)) { int search_range; search_range = distance + 1; while (--search_range) if (position[pos - search_range] <= position[pos - temp_min]) temp_min = search_range; pos -= temp_min; max_pos_j = position_j[pos]; int begin = MAX2(5, pos - alignment_length); int end = MIN2(n3 - 5, pos - 1); char *s3 = (char *)vrna_alloc(sizeof(char) * (end - begin + 2) + 5); strncpy(s3, (s1 + begin), end - begin + 1); strcat(s3, "NNNNN\0"); int n5 = (int)strlen(s3); snoopT test; test = snoopfold_XS(s3, s2, access_s1, pos, max_pos_j, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, fullStemEnergy); if (test.energy == INF) { free(s3); continue; } if (test.Duplex_El > threshLE * 0.01 || test.Duplex_Er > threshRE * 0.01 || test.Loop_D > threshD * 0.01 || (test.Duplex_Er + test.Duplex_El) > threshDE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E) > threshTE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E + test.Loop_D + 410) > threshSE * 0.01) { free(test.structure); free(s3); continue; } char *s4; s4 = (char *)vrna_alloc(sizeof(char) * (n4 - 9)); strncpy(s4, s2 + 5, n4 - 10); s4[n4 - 10] = '\0'; char *s5 = vrna_alloc(sizeof(char) * n5 - test.i + 2 - 5); strncpy(s5, s3 + test.i - 1, n5 - test.i + 1 - 5); s5[n5 - test.i + 1 - 5] = '\0'; float dE = ((float)(access_s1[n5 - test.i + 1 - 5][pos])) * 0.01; printf( "%s %3d,%-3d;%3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f + %5.2f + %5.2f + 4.10) (%5.2f)\n%s&%s\n", test.structure, pos - (n5 - test.i), pos - 5, pos - (n5 - test.u), max_pos_j - 5, max_pos_j - 5 + (int)(strrchr(test.structure, '>') - strchr(test.structure, '>')), test.Loop_D + test.Duplex_El + test.Duplex_Er + test.Loop_E + 4.10 + dE, test.Duplex_El, test.Duplex_Er, test.Loop_E, test.Loop_D, dE, test.fullStemEnergy, s5, s4); if (name) { int begin_t, end_t, begin_q, end_q, and, pipe, i; char *psoutput; begin_q = 0; end_q = n4 - 10; begin_t = 0; end_t = n5 - test.i + 1 - 5; and = end_t + 1; pipe = test.u - test.i + 1; cut_point = end_t + 1; char *catseq, *catstruct;/* *fname; */ catseq = (char *)vrna_alloc(n5 + end_q - begin_q + 2); catstruct = (char *)vrna_alloc(n5 + end_q - begin_q + 2); strcpy(catseq, s5); strncpy(catstruct, test.structure, end_t); strcat(catseq, s4); strncat(catstruct, test.structure + end_t + 1, end_q - begin_q + 1); catstruct[end_t - begin_t + end_q - begin_q + 2] = '\0'; catseq[end_t - begin_t + end_q - begin_q + 2] = '\0'; int *relative_access; relative_access = vrna_alloc(sizeof(int) * strlen(s5)); relative_access[0] = access_s1[1][pos - (n5 - test.i) + 5]; for (i = 1; i < (int)strlen(s5); i++) relative_access[i] = access_s1[i + 1][pos - (n5 - test.i) + i + 5] - access_s1[i][pos - (n5 - test.i) + i + 4]; psoutput = vrna_strdup_printf("sno_XS_%d_u_%d_%s.ps", count, pos - (n5 - test.u), name); PS_rna_plot_snoop_a(catseq, catstruct, psoutput, relative_access, NULL); free(catseq); free(catstruct); free(relative_access); free(psoutput); count++; } free(s3); free(s4); free(s5); free(test.structure); } } } snoopT snoopfold_XS(const char *s1, const char *s2, const int **access_s1, const int pos_i, const int pos_j, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int fullStemEnergy) { /* int Eminj, Emin_l; */ int a, b, i, j, Emin = INF, a_min = 0, b_min = 0; char *struc; snoopT mfe; int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; int u; int Loop_E; vrna_md_t md; Duplex_El = 0; Duplex_Er = 0; Loop_E = 0, Loop_D = 0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); n1 = (int)strlen(s1); n2 = (int)strlen(s2); set_model_details(&md); if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) { snoupdate_fold_params(); if (P) free(P); P = vrna_params(&md); make_pair_matrix(); } c = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); r = (int **)vrna_alloc(sizeof(int *) * (n1 + 1)); for (i = 0; i <= n1; i++) { c[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); r[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1)); for (j = n2; j > -1; j--) { c[i][j] = INF; r[i][j] = INF; } } encode_seqs(s1, s2); i = n1 - 5; j = pos_j; /* printf("tar: %s\nsno: %s\n ", s1, s2); */ /* printf("pos_i %d pos_j %d\n", pos_i, pos_j); */ /* printf("type %d n1 %d n2 %d S1[n1] %d S2[n2] %d", pair[S1[i]][S2[j]], n1, n2, S1[n1], S2[n2]); */ int type, type2, E, p, q; r[i][j] = P->DuplexInit; /* r[i][j] += P->dangle3[rtype[type]][SS1[i+1]] + P->dangle5[rtype[type]][SS2[j-1]]; */ if (pair[S1[i]][S2[j]] > 2) r[i][j] += P->TerminalAU; for (a = i - 1; a > 0; a--) { /* i-1 */ r[a + 1][0] = INF; for (b = j + 1; b <= n2 - min_d2; b++) { /* j+1 */ r[a][b] = INF; type = pair[S1[a]][S2[b]]; if (!type) continue; if (S1[a + 1] == 4) { folden *temp; temp = foldlist_XS[b - 1]; while (temp->next) { int k = temp->k; if (pair[S1[a + 3]][S2[k - 1]] && k < max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 - min_s2 - half_stem /*&& r[a+3][k-1] + access_s1[i-(a+3)+1][pos_i] < 411*/) /* remove last condition last condition is to check if the interaction is stable enough */ c[a][b] = MIN2(c[a][b], r[a + 3][k - 1] + temp->energy); temp = temp->next; } } if (S1[a + 2] == 4) { folden *temp; temp = foldlist_XS[b - 1]; while (temp->next) { int k = temp->k; if (pair[S1[a + 4]][S2[k - 1]] && k < max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 - min_s2 - half_stem /*&& r[a+4][k-1] + access_s1[i-(a+4)+1][pos_i] < 411 */) /* remove last condition */ c[a][b] = MIN2(c[a][b], r[a + 4][k - 1] + temp->energy); temp = temp->next; } } for (p = a + 1; p < n1 && (p - a) < MAXLOOP_L; p++) { /* p < n1 */ for (q = b - 1; q > 1; q--) { /* q > 1 */ if (p - a + b - q > 2 * MAXLOOP_L - 2) break; if (abs((p - a) - (b - q)) >= ASS) continue; type2 = pair[S1[p]][S2[q]]; if (!type2) continue; E = E_IntLoop(p - a - 1, b - q - 1, type2, rtype[type], SS1[a + 1], SS2[b - 1], SS1[p - 1], SS2[q + 1], P); c[a][b] = MIN2(c[a][b], c[p][q] + E); r[a][b] = MIN2(r[a][b], r[p][q] + E); } } E = c[a][b]; if (type > 2) E += P->TerminalAU; /* E +=P->dangle5[rtype[type]][SS1[i+1]]; */ /* E +=P->dangle5[rtype[type]][SS2[j-1]]; */ E += access_s1[i - a + 1][pos_i]; if (E < Emin) { Emin = E; a_min = a; b_min = b; } } } if (Emin > 0) { printf("no target found under the constraints chosen\n"); for (i = 0; i <= n1; i++) { free(r[i]); free(c[i]); } free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); mfe.energy = INF; return mfe; } type2 = pair[S1[a_min]][S2[b_min]]; if (type2 > 2) Emin += P->TerminalAU; mfe.energy = ((float)(Emin)) / 100; struc = snoop_backtrack_XS(a_min, b_min, s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); mfe.i = a_min; mfe.j = b_min; mfe.u = u; mfe.Duplex_Er = (float)Duplex_Er / 100; mfe.Duplex_El = (float)Duplex_El / 100; mfe.Loop_D = (float)Loop_D / 100; mfe.Loop_E = (float)Loop_E / 100; mfe.energy = (float)Emin / 100; mfe.fullStemEnergy = (float)fullStemEnergy / 100; mfe.structure = struc; return mfe; } PRIVATE char * snoop_backtrack_XS(int i, int j, const char *snoseq, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { /* 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; int traced_c = 0; /* flag for following backtrack in c or r */ char *st1, *st2, *struc; char *struc_loop; st1 = (char *)vrna_alloc(sizeof(char) * (n1 + 1)); st2 = (char *)vrna_alloc(sizeof(char) * (n2 + 1)); int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; type = pair[S1[i]][S2[j]]; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); i0 = i; j0 = j; /* i0=MAX2(i,1); j0=MIN2(j+1,n2); */ while (i <= n1 && j >= 1) { if (!traced_c) { E = c[i][j]; traced = 0; st1[i] = '<'; st2[j - 1] = '>'; type = pair[S1[i]][S2[j]]; if (!type) vrna_message_error("backtrack failed in fold duplex c"); for (k = i + 1; k > 0 && (k - i) < MAXLOOP_L; k++) { for (l = j - 1; l >= 1; l--) { int LE; if (k - i + j - l > 2 * MAXLOOP_L - 2) break; if (abs(k - i - j + l) >= ASS) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; LE = E_IntLoop(k - i - 1, j - l - 1, type2, rtype[type], SS1[i + 1], SS2[j - 1], SS1[k - 1], SS2[l + 1], P); if (E == c[k][l] + LE) { traced = 1; i = k; j = l; *Duplex_El += LE; break; } } if (traced) break; } if (!traced) { if (S1[i + 1] == 4) { folden *temp; temp = foldlist_XS[j - 1]; while (temp->next) { int k = temp->k; if (pair[S1[i + 3]][S2[k - 1]] && k < max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 - min_s2 - half_stem) { if (E == r[i + 3][k - 1] + temp->energy) { *Loop_E = temp->energy; st1[i + 1] = '|'; st1[i + 2] = '.'; *u = i + 1; int a, b; for (a = 0; a < MISMATCH; a++) { for (b = 0; b < MISMATCH; b++) { int ij = indx[j - 1 - a] + k + b; if (cLoop[ij] == temp->energy) { struc_loop = snobacktrack_fold_from_pair(snoseq, k + b, j - 1 - a); a = INF; b = INF; } } } traced = 1; traced_c = 1; i = i + 3; j = k - 1; break; } } temp = temp->next; } } if (S1[i + 2] == 4) { /* introduce structure from RNAfold */ folden *temp; temp = foldlist_XS[j - 1]; while (temp->next) { int k = temp->k; if (pair[S1[i + 4]][S2[k - 1]] && k < max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 - min_s2 - half_stem) { if (E == r[i + 4][k - 1] + temp->energy) { *Loop_E = temp->energy; st1[i + 2] = '|'; st1[i + 1] = st1[i + 3] = '.'; *u = i + 2; int a, b; for (a = 0; a < MISMATCH; a++) { for (b = 0; b < MISMATCH; b++) { int ij = indx[j - 1 - a] + k + b; if (cLoop[ij] == temp->energy) { struc_loop = snobacktrack_fold_from_pair(snoseq, k + b, j - a - 1); a = INF; b = INF; } } } traced = 1; traced_c = 1; i = i + 4; j = k - 1; break; } } temp = temp->next; } } } /* traced? */ } /* traced_r? */ else { E = r[i][j]; traced = 0; st1[i] = '<'; st2[j - 1] = '>'; type = pair[S1[i]][S2[j]]; if (!type) vrna_message_error("backtrack failed in fold duplex r"); for (k = i + 1; k > 0 && (k - i) < MAXLOOP_L; k++) { for (l = j - 1; l >= 1; l--) { int LE; if (k - i + j - l > 2 * MAXLOOP_L - 2) break; if (abs(k - i - j + l) >= ASS) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; LE = E_IntLoop(k - i - 1, j - l - 1, type2, rtype[type], SS1[i + 1], SS2[j - 1], SS1[k - 1], SS2[l + 1], P); if (E == r[k][l] + LE) { traced = 1; i = k; j = l; *Duplex_Er += LE; break; } } if (traced) break; } } if (!traced) { /* if (i>1) {E -= P->dangle5[type][SS1[i-1]]; *Duplex_El +=P->dangle5[type][SS1[i-1]];} */ /* if (j<n2) {E -= P->dangle3[type][SS2[j+1]]; *Duplex_El +=P->dangle3[type][SS2[j+1]];} */ if (type > 2) { E -= P->TerminalAU; *Duplex_Er += P->TerminalAU; } if (E != P->DuplexInit) vrna_message_error("backtrack failed in fold duplex end"); else break; } } /* struc = (char *) vrna_alloc(i0-i+1+j-j0+1+2); */ /* declare final duplex structure */ struc = (char *)vrna_alloc(i - i0 + 1 + n2); /* declare final duplex structure */ char *struc2; struc2 = (char *)vrna_alloc(n2 + 1); /* char * struct_const; */ for (k = MIN2(i0, 1); k <= i; k++) if (!st1[k - 1]) st1[k - 1] = '.'; /* for (k=j0; k<=j; k++) if (!st2[k-1]) st2[k-1] = struc_loop[k-1];*/ /* '.'; normal */ /* char * struct_const; */ /* struct_const = (char *) vrna_alloc(sizeof(char)*(n2+1)); */ for (k = 1; k <= n2; k++) { if (!st2[k - 1]) st2[k - 1] = struc_loop[k - 1]; /* '.'; */ struc2[k - 1] = st2[k - 1]; /* '.'; */ /* if (k>=j0 && k<=j){ */ /* struct_const[k-1]='x'; */ /* } */ /* else{ */ /* if(k<j0) {struct_const[k-1]='<';} */ /* if(k>j) {struct_const[k-1]='>';} */ /* } */ } char duplexseq_1[j]; char duplexseq_2[n2 - j0 + 2]; if (j0 < n2) { strncpy(duplexseq_1, snoseq, j - 1); strcpy(duplexseq_2, snoseq + j0); duplexseq_1[j - 1] = '\0'; duplexseq_2[n2 - j0 + 1] = '\0'; duplexT temp; temp = duplexfold(duplexseq_1, duplexseq_2); *Loop_D = MIN2(0, -410 + (int)100 * temp.energy); if (*Loop_D) { int l1, ibegin, iend, jbegin, jend; l1 = strchr(temp.structure, '&') - temp.structure; ibegin = temp.i - l1; iend = temp.i - 1; jbegin = temp.j; jend = temp.j + (int)strlen(temp.structure) - l1 - 2 - 1; for (k = ibegin + 1; k <= iend + 1; k++) struc2[k - 1] = temp.structure[k - ibegin - 1]; for (k = jbegin + j0; k <= jend + j0; k++) struc2[k - 1] = temp.structure[l1 + k - j0 - jbegin + 1]; } free(temp.structure); } strcpy(struc, st1 + MAX2(i0, 1)); strcat(struc, "&"); /* strcat(struc, st2); */ strncat(struc, struc2 + 5, (int)strlen(struc2) - 10); free(struc2); free(struc_loop); free(st1); free(st2); for (i = 0; i <= n1; i++) { free(r[i]); free(c[i]); } free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); /* free_arrays(); */ 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 */ #define NONE -10000 /* score for forbidden 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; } /*---------------------------------------------------------------------------*/ PRIVATE short * aliencode_seq(const char *sequence) { unsigned int i, l; short *Stemp; l = strlen(sequence); Stemp = (short *)vrna_alloc(sizeof(short) * (l + 2)); Stemp[0] = (short)l; /* make numerical encoding of sequence */ for (i = 1; i <= l; i++) Stemp[i] = (short)encode_char(toupper(sequence[i - 1])); /* for circular folding add first base at position n+1 */ /* Stemp[l+1] = Stemp[1]; */ return Stemp; } PRIVATE short * encode_seq(const char *sequence) { unsigned int i, l; short *S; l = strlen(sequence); extern double nc_fact; S = (short *)vrna_alloc(sizeof(short) * (l + 2)); S[0] = (short)l; /* make numerical encoding of sequence */ for (i = 1; i <= l; i++) S[i] = (short)encode_char(toupper(sequence[i - 1])); /* for circular folding add first base at position n+1 */ S[l + 1] = S[1]; return S; } PRIVATE void encode_seqs(const char *s1, const char *s2) { unsigned int i, l; l = strlen(s1); S1 = encode_seq(s1); SS1 = (short *)vrna_alloc(sizeof(short) * (l + 1)); /* SS1 exists only for the special X K and I bases and energy_set!=0 */ for (i = 1; i <= l; i++) /* make numerical encoding of sequence */ SS1[i] = alias[S1[i]]; /* for mismatches of nostandard bases */ l = strlen(s2); S2 = encode_seq(s2); SS2 = (short *)vrna_alloc(sizeof(short) * (l + 1)); /* SS2 exists only for the special X K and I bases and energy_set!=0 */ for (i = 1; i <= l; i++) /* make numerical encoding of sequence */ SS2[i] = alias[S2[i]]; /* for mismatches of nostandard bases */ } PRIVATE int compare(const void *sub1, const void *sub2) { int d; if (((snoopT *)sub1)->energy > ((snoopT *)sub2)->energy) return 1; if (((snoopT *)sub1)->energy < ((snoopT *)sub2)->energy) return -1; d = ((snoopT *)sub1)->i - ((snoopT *)sub2)->i; if (d != 0) return d; return ((snoopT *)sub1)->j - ((snoopT *)sub2)->j; }
DRB070-simd1-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* One dimension array computation with a vetorization directive */ int a[100], b[100], c[100]; int main() { int i; #pragma omp parallel for private(i ) for (i=0;i<100;i++) { a[i]= i * 40; b[i] = i - 1; c[i] = i; } #pragma omp parallel for private(i ) for (i=0;i<100;i++) a[i]=b[i]*c[i]; for (i=0;i<100;i++) { printf("%d %d %d\n", a[i], b[i], c[i]); } return 0; }
blake2bp.c
/* BLAKE2 reference source code package - optimized C implementations Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at your option. The terms of these licenses can be found at: - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 - OpenSSL license : https://www.openssl.org/source/license.html - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 More information about the BLAKE2 hash function can be found at https://blake2.net. */ #include "cryptoTools/Common/config.h" #ifdef ENABLE_BLAKE2_SSE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #if defined(_OPENMP) #include <omp.h> #endif #include "blake2.h" #include "blake2-impl.h" #define PARALLELISM_DEGREE 4 /* blake2b_init_param defaults to setting the expecting output length from the digest_length parameter block field. In some cases, however, we do not want this, as the output length of these instances is given by inner_length instead. */ static int blake2bp_init_leaf_param( blake2b_state *S, const blake2b_param *P ) { int err = blake2b_init_param(S, P); S->outlen = P->inner_length; return err; } static int blake2bp_init_leaf( blake2b_state *S, size_t outlen, size_t keylen, uint64_t offset ) { blake2b_param P[1]; P->digest_length = (uint8_t)outlen; P->key_length = (uint8_t)keylen; P->fanout = PARALLELISM_DEGREE; P->depth = 2; P->leaf_length = 0; P->node_offset = (uint32_t)offset; P->xof_length = 0; P->node_depth = 0; P->inner_length = BLAKE2B_OUTBYTES; memset( P->reserved, 0, sizeof( P->reserved ) ); memset( P->salt, 0, sizeof( P->salt ) ); memset( P->personal, 0, sizeof( P->personal ) ); return blake2bp_init_leaf_param( S, P ); } static int blake2bp_init_root( blake2b_state *S, size_t outlen, size_t keylen ) { blake2b_param P[1]; P->digest_length = (uint8_t)outlen; P->key_length = (uint8_t)keylen; P->fanout = PARALLELISM_DEGREE; P->depth = 2; P->leaf_length = 0; P->node_offset = 0; P->xof_length = 0; P->node_depth = 1; P->inner_length = BLAKE2B_OUTBYTES; memset( P->reserved, 0, sizeof( P->reserved ) ); memset( P->salt, 0, sizeof( P->salt ) ); memset( P->personal, 0, sizeof( P->personal ) ); return blake2b_init_param( S, P ); } int blake2bp_init( blake2bp_state *S, size_t outlen ) { size_t i; if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1; memset( S->buf, 0, sizeof( S->buf ) ); S->buflen = 0; S->outlen = outlen; if( blake2bp_init_root( S->R, outlen, 0 ) < 0 ) return -1; for( i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2bp_init_leaf( S->S[i], outlen, 0, i ) < 0 ) return -1; S->R->last_node = 1; S->S[PARALLELISM_DEGREE - 1]->last_node = 1; return 0; } int blake2bp_init_key( blake2bp_state *S, size_t outlen, const void *key, size_t keylen ) { size_t i; if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1; if( !key || !keylen || keylen > BLAKE2B_KEYBYTES ) return -1; memset( S->buf, 0, sizeof( S->buf ) ); S->buflen = 0; S->outlen = outlen; if( blake2bp_init_root( S->R, outlen, keylen ) < 0 ) return -1; for( i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2bp_init_leaf( S->S[i], outlen, keylen, i ) < 0 ) return -1; S->R->last_node = 1; S->S[PARALLELISM_DEGREE - 1]->last_node = 1; { uint8_t block[BLAKE2B_BLOCKBYTES]; memset( block, 0, BLAKE2B_BLOCKBYTES ); memcpy( block, key, keylen ); for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S->S[i], block, BLAKE2B_BLOCKBYTES ); secure_zero_memory( block, BLAKE2B_BLOCKBYTES ); /* Burn the key from stack */ } return 0; } int blake2bp_update( blake2bp_state *S, const void *pin, size_t inlen ) { const unsigned char * in = (const unsigned char *)pin; size_t left = S->buflen; size_t fill = sizeof( S->buf ) - left; size_t i; if( left && inlen >= fill ) { memcpy( S->buf + left, in, fill ); for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S->S[i], S->buf + i * BLAKE2B_BLOCKBYTES, BLAKE2B_BLOCKBYTES ); in += fill; inlen -= fill; left = 0; } #if defined(_OPENMP) #pragma omp parallel shared(S), num_threads(PARALLELISM_DEGREE) #else for( i = 0; i < PARALLELISM_DEGREE; ++i ) #endif { #if defined(_OPENMP) size_t i = omp_get_thread_num(); #endif size_t inlen__ = inlen; const unsigned char *in__ = ( const unsigned char * )in; in__ += i * BLAKE2B_BLOCKBYTES; while( inlen__ >= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES ) { blake2b_update( S->S[i], in__, BLAKE2B_BLOCKBYTES ); in__ += PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; inlen__ -= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; } } in += inlen - inlen % ( PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES ); inlen %= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; if( inlen > 0 ) memcpy( S->buf + left, in, inlen ); S->buflen = left + inlen; return 0; } int blake2bp_final( blake2bp_state *S, void *out, size_t outlen ) { uint8_t hash[PARALLELISM_DEGREE][BLAKE2B_OUTBYTES]; size_t i; if(out == NULL || outlen < S->outlen) { return -1; } for( i = 0; i < PARALLELISM_DEGREE; ++i ) { if( S->buflen > i * BLAKE2B_BLOCKBYTES ) { size_t left = S->buflen - i * BLAKE2B_BLOCKBYTES; if( left > BLAKE2B_BLOCKBYTES ) left = BLAKE2B_BLOCKBYTES; blake2b_update( S->S[i], S->buf + i * BLAKE2B_BLOCKBYTES, left ); } blake2b_final( S->S[i], hash[i], BLAKE2B_OUTBYTES ); } for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S->R, hash[i], BLAKE2B_OUTBYTES ); return blake2b_final( S->R, out, S->outlen ); } int blake2bp( void *out, size_t outlen, const void *in, size_t inlen, const void *key, size_t keylen ) { uint8_t hash[PARALLELISM_DEGREE][BLAKE2B_OUTBYTES]; blake2b_state S[PARALLELISM_DEGREE][1]; blake2b_state FS[1]; size_t i; /* Verify parameters */ if ( NULL == in && inlen > 0 ) return -1; if ( NULL == out ) return -1; if( NULL == key && keylen > 0 ) return -1; if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1; if( keylen > BLAKE2B_KEYBYTES ) return -1; for( i = 0; i < PARALLELISM_DEGREE; ++i ) if( blake2bp_init_leaf( S[i], outlen, keylen, i ) < 0 ) return -1; S[PARALLELISM_DEGREE - 1]->last_node = 1; /* mark last node */ if( keylen > 0 ) { uint8_t block[BLAKE2B_BLOCKBYTES]; memset( block, 0, BLAKE2B_BLOCKBYTES ); memcpy( block, key, keylen ); for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( S[i], block, BLAKE2B_BLOCKBYTES ); secure_zero_memory( block, BLAKE2B_BLOCKBYTES ); /* Burn the key from stack */ } #if defined(_OPENMP) #pragma omp parallel shared(S,hash), num_threads(PARALLELISM_DEGREE) #else for( i = 0; i < PARALLELISM_DEGREE; ++i ) #endif { #if defined(_OPENMP) size_t i = omp_get_thread_num(); #endif size_t inlen__ = inlen; const unsigned char *in__ = ( const unsigned char * )in; in__ += i * BLAKE2B_BLOCKBYTES; while( inlen__ >= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES ) { blake2b_update( S[i], in__, BLAKE2B_BLOCKBYTES ); in__ += PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; inlen__ -= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES; } if( inlen__ > i * BLAKE2B_BLOCKBYTES ) { const size_t left = inlen__ - i * BLAKE2B_BLOCKBYTES; const size_t len = left <= BLAKE2B_BLOCKBYTES ? left : BLAKE2B_BLOCKBYTES; blake2b_update( S[i], in__, len ); } blake2b_final( S[i], hash[i], BLAKE2B_OUTBYTES ); } if( blake2bp_init_root( FS, outlen, keylen ) < 0 ) return -1; FS->last_node = 1; /* Mark as last node */ for( i = 0; i < PARALLELISM_DEGREE; ++i ) blake2b_update( FS, hash[i], BLAKE2B_OUTBYTES ); return blake2b_final( FS, out, outlen ); } #if defined(BLAKE2BP_SELFTEST) #include <string.h> #include "blake2-kat.h" int main( void ) { uint8_t key[BLAKE2B_KEYBYTES]; uint8_t buf[BLAKE2_KAT_LENGTH]; size_t i, step; for( i = 0; i < BLAKE2B_KEYBYTES; ++i ) key[i] = ( uint8_t )i; for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) buf[i] = ( uint8_t )i; /* Test simple API */ for( i = 0; i < BLAKE2_KAT_LENGTH; ++i ) { uint8_t hash[BLAKE2B_OUTBYTES]; blake2bp( hash, BLAKE2B_OUTBYTES, buf, i, key, BLAKE2B_KEYBYTES ); if( 0 != memcmp( hash, blake2bp_keyed_kat[i], BLAKE2B_OUTBYTES ) ) { goto fail; } } /* Test streaming API */ for(step = 1; step < BLAKE2B_BLOCKBYTES; ++step) { for (i = 0; i < BLAKE2_KAT_LENGTH; ++i) { uint8_t hash[BLAKE2B_OUTBYTES]; blake2bp_state S; uint8_t * p = buf; size_t mlen = i; int err = 0; if( (err = blake2bp_init_key(&S, BLAKE2B_OUTBYTES, key, BLAKE2B_KEYBYTES)) < 0 ) { goto fail; } while (mlen >= step) { if ( (err = blake2bp_update(&S, p, step)) < 0 ) { goto fail; } mlen -= step; p += step; } if ( (err = blake2bp_update(&S, p, mlen)) < 0) { goto fail; } if ( (err = blake2bp_final(&S, hash, BLAKE2B_OUTBYTES)) < 0) { goto fail; } if (0 != memcmp(hash, blake2bp_keyed_kat[i], BLAKE2B_OUTBYTES)) { goto fail; } } } puts( "ok" ); return 0; fail: puts("error"); return -1; } #endif #endif
GB_unop__isfinite_bool_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__isfinite_bool_fp32) // op(A') function: GB (_unop_tran__isfinite_bool_fp32) // C type: bool // A type: float // cast: float cij = (aij) // unaryop: cij = isfinite (aij) #define GB_ATYPE \ float #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = isfinite (x) ; // casting #define GB_CAST(z, aij) \ float z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (aij) ; \ Cx [pC] = isfinite (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISFINITE || GxB_NO_BOOL || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__isfinite_bool_fp32) ( bool *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = (aij) ; Cx [p] = isfinite (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = (aij) ; Cx [p] = isfinite (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__isfinite_bool_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
tearprocessing.h
#ifndef TEARPROCESSING_H #define TEARPROCESSING_H #include <QDebug> #include <QList> #include <opencv2/core/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/imgcodecs.hpp> #include <memory> #include "headers/cpp_interface/fpsoptions.h" #include "headers/cpp_interface/teardata.h" //! TODO class TearProcessing { //! constructors public: //! TODO TearProcessing() : _received_first_frames(false) , _max_video_count(3) { _init_member(); } //! methods public: //! TODO QList<TearData> check_for_tears(const QList<cv::Mat> & cv_frame_list , std::shared_ptr<QList<FPSOptions>> shared_fps_options_list) { //! TODO Q_UNUSED(shared_fps_options_list); //Q_UNUSED(shared_tear_options_list); QList<cv::Mat> difference_frames; QList<TearData> tear_data_list; // default init for (int i = 0; i < cv_frame_list.size(); ++i) { difference_frames.push_back(cv::Mat()); const quint64 row_count = static_cast<quint64>(cv_frame_list[i].rows); tear_data_list.push_back(TearData(row_count)); } if (!_received_first_frames) { _received_first_frames = true; // save the current frame list _cache_framelist(cv_frame_list); // return the normal frames as we can't calculate a difference return tear_data_list; } else { // if multiple videos are loaded, the cache list has not all frames loaded, wait for next iteration // refactored this from the loop to allow omp bool all_cached_frames_filled = true; for (int i = 0; i < cv_frame_list.size(); ++i) { all_cached_frames_filled = all_cached_frames_filled && !_cached_frames[i].empty(); } // TODO test this for performance if (all_cached_frames_filled) { #pragma omp parallel for for (int i = 0; i < cv_frame_list.size(); ++i) { const quint32 pixel_difference = (*shared_fps_options_list)[i].pixel_difference.value(); difference_frames[i] = _get_difference(_cached_frames[i], cv_frame_list[i], pixel_difference).clone(); tear_data_list[i].set_tear_rows(_get_tear_rows(difference_frames[i])); } } else { // we could try to calculate the difference for each frame where we have a previous frame accessable // but it might be a hassle if the second video got deleted live, because the indices get moved // it's easier to simply wait until the new frames arrive at the correct index. I should probably // disable removing files while exporting } } // save the current frame list _cache_framelist(cv_frame_list); return tear_data_list; } //! TODO void reset_state() { _cached_frames.clear(); _init_member(); } //! methods private: //! TODO void _init_member() { // prepare buffer for each video for (int i = 0; i < _max_video_count; ++i) { _cached_frames.push_back(cv::Mat()); } // first frames can't be compared _received_first_frames = false; } //! make this chooseable? cv::Mat _get_difference(const cv::Mat & first_frame, const cv::Mat & second_frame, const quint32 pixel_difference) const { cv::Mat difference; //cv::absdiff(first_frame, second_frame, difference); _are_equal_with_draw(first_frame, second_frame, static_cast<int>(pixel_difference), difference); return difference; } //! TODO rethink this //! take a look at https://stackoverflow.com/questions/18464710/how-to-do-per-element-comparison-and-do-different-operation-according-to-result void _are_equal_with_draw(const cv::Mat & frame_a, const cv::Mat & frame_b, const int pixel_difference, cv::Mat & output) const { cv::Mat black_white_frame_a; cv::Mat black_white_frame_b; cv::cvtColor(frame_a, black_white_frame_a, cv::COLOR_BGRA2GRAY); cv::cvtColor(frame_b, black_white_frame_b, cv::COLOR_BGRA2GRAY); output = frame_a.clone(); for (int i = 0; i < black_white_frame_a.rows; i += 1) { for (int j = 0; j < black_white_frame_a.cols; j += 1) { int ac(std::max(black_white_frame_a.at<uchar>(i, j) , black_white_frame_b.at<uchar>(i, j))); int bc(std::min(black_white_frame_a.at<uchar>(i, j) , black_white_frame_b.at<uchar>(i, j))); if (ac - bc > pixel_difference) { // on difference, set to white output.at<cv::Vec3b>(i,j)[0] = 255; output.at<cv::Vec3b>(i,j)[1] = 255; output.at<cv::Vec3b>(i,j)[2] = 255; } else { // on "same" pixel, set to black output.at<cv::Vec3b>(i,j)[0] = 0; output.at<cv::Vec3b>(i,j)[1] = 0; output.at<cv::Vec3b>(i,j)[2] = 0; } } } } //! TODO void _cache_framelist(const QList<cv::Mat> _other) { for (int i = 0; i < _other.size(); ++i) { _cached_frames[i] = _other[i].clone(); } } //! get the rows where we detect a tear (may not be ordered from 0 to max_rows, e.g 0 3 2) std::vector<quint64> _get_tear_rows(const cv::Mat & difference) const { std::vector<quint64> tear_rows; #pragma omp parallel for for (int row = 0; row < difference.rows; ++row) { if (_is_row_a_tear(difference, row)) { tear_rows.push_back(static_cast<quint64>(row)); } } return tear_rows; } //! short circuits if any pixel in a row is found not to be full black (0,0,0) bool _is_row_a_tear(const cv::Mat & difference, const int row) const { for (int col = 0; col < difference.cols; ++col) { bool red_channel_is_not_black = difference.at<cv::Vec3b>(row,col)[0] != 0; bool green_channel_is_not_black = difference.at<cv::Vec3b>(row,col)[1] != 0; bool blue_channel_is_not_black = difference.at<cv::Vec3b>(row,col)[2] != 0; bool pixel_is_not_black = red_channel_is_not_black && green_channel_is_not_black && blue_channel_is_not_black; // if the difference frame is not black, we detected a change in the subsequent image if (pixel_is_not_black) { return false; } } return true; } //! member private: //! TODO bool _received_first_frames; //! TODO QList<cv::Mat> _cached_frames; //! TODO const quint8 _max_video_count; }; #endif // TEARPROCESSING_H
ex1-vector-addition-openmp.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #define VALIDATE 0 #if VALIDATE #include "validate.h" #endif void vec_add(const size_t, const int * restrict, const int * restrict, int * restrict); void usage(char**); int main(int argc, char **argv) { int *u,*v,*w; size_t i,n; double t0,t1; if(argc==2) sscanf(argv[1],"%zu",&n); else { usage(argv); return 1; } u = (int*)malloc(n*sizeof(int)); v = (int*)malloc(n*sizeof(int)); w = (int*)malloc(n*sizeof(int)); for(i=0; i<n; ++i) u[i]=v[i]=i; t0 = omp_get_wtime(); vec_add(n,u,v,w); t1 = omp_get_wtime(); #if VALIDATE if(!validate_vec_add(n,u,v,w)) { printf("Validation failed.\n"); return 1; } #endif printf("Total time taken: %f.\n",t1-t0); free(u); free(v); free(w); return 0; } void vec_add(const size_t n, const int * restrict u, const int * restrict v, int * restrict w) { int id,nt; size_t i,is,ie; #pragma omp parallel default(none) shared(u,v,w) private(i,is,ie,id,nt) { id = omp_get_thread_num(); nt = omp_get_num_threads(); is = id*n/nt; ie = (id==nt-1) ? n : (id+1)*n/nt; for(i=is; i<ie; ++i) w[i]=u[i]+v[i]; } } void usage(char **argv) { printf("Usage: %s <length>\n",argv[0]); }
VolumetricFractionalMaxPooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "THNN/generic/VolumetricFractionalMaxPooling.c" #else static int64_t* THNN_(VolumetricFractionalMaxPooling_generateIntervals)( scalar_t sample, int64_t inputSize, int64_t outputSize, int poolSize) { scalar_t alpha = (scalar_t) (inputSize - poolSize) / (scalar_t) (outputSize - 1); int64_t* sequence = (int64_t*) THAlloc(sizeof(int64_t) * outputSize); int64_t i; for (i = 0; i < outputSize - 1; ++i) { sequence[i] = (int64_t) ((i + sample) * alpha) - (int64_t) (sample * alpha); } sequence[outputSize - 1] = inputSize - poolSize; return sequence; } static void THNN_(VolumetricFractionalMaxPooling_updateOutput_frame)( scalar_t* input, scalar_t* output, THIndex_t* indices, scalar_t* randomSamples, int64_t numPlanes, int64_t inputT, int64_t inputW, int64_t inputH, int64_t outputT, int64_t outputW, int64_t outputH, int poolSizeT, int poolSizeW, int poolSizeH) { int64_t plane; #pragma omp parallel for private(plane) for (plane = 0; plane < numPlanes; ++plane) { /* each plane contains 3 random samples, one for T, one for W, and one for H */ scalar_t* randomSamplesForPlane = randomSamples + plane * 3; /* Generate interval sequence */ int64_t* sequenceT = THNN_(VolumetricFractionalMaxPooling_generateIntervals)( randomSamplesForPlane[0], inputT, outputT, poolSizeT); int64_t* sequenceW = THNN_(VolumetricFractionalMaxPooling_generateIntervals)( randomSamplesForPlane[1], inputW, outputW, poolSizeW); int64_t* sequenceH = THNN_(VolumetricFractionalMaxPooling_generateIntervals)( randomSamplesForPlane[2], inputH, outputH, poolSizeH); /* loop over output */ int64_t h, w, t; scalar_t* inputForPlane = input + plane * inputT * inputW * inputH; scalar_t* outputForPlane = output + plane * outputT * outputW * outputH; THIndex_t* indicesForPlane = indices + plane * outputT * outputW * outputH; for (h = 0; h < outputH; ++h) { int64_t inputHStart = sequenceH[h]; for (w = 0; w < outputW; ++w) { int64_t inputWStart = sequenceW[w]; for (t = 0; t < outputT; ++t) { int64_t inputTStart = sequenceT[t]; scalar_t maxVal = -THInf; int64_t maxIndex = -1; int64_t h2, w2, t2; for (h2 = inputHStart; h2 < inputHStart + poolSizeH; ++h2) { for (w2 = inputWStart; w2 < inputWStart + poolSizeW; ++w2) { for (t2 = inputTStart; t2 < inputTStart + poolSizeT; ++t2) { THAssert(h2 >= 0 && h2 < inputH); THAssert(w2 >= 0 && w2 < inputW); THAssert(t2 >= 0 && t2 < inputT); int64_t planeIndex = h2 * inputW * inputT + w2 * inputT + t2; scalar_t val = inputForPlane[planeIndex]; if (val > maxVal) { maxVal = val; maxIndex = planeIndex; } } } } THAssert(maxVal != -THInf); THAssert(maxIndex != -1); outputForPlane[h * outputW * outputT + w * outputT + t] = maxVal; /* +1 to lua index */ indicesForPlane[h * outputW * outputT + w * outputT + t] = maxIndex + TH_INDEX_BASE; } } } THFree(sequenceT); THFree(sequenceW); THFree(sequenceH); } } void THNN_(VolumetricFractionalMaxPooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, int outputT, int outputW, int outputH, int poolSizeT, int poolSizeW, int poolSizeH, THIndexTensor *indices, THTensor *randomSamples) { int64_t numBatch = 1; int planeDim = 0; int heightDim = 1; int widthDim = 2; int timeDim = 3; int64_t numInputDims = THTensor_(nDimensionLegacyNoScalars)(input); THNN_ARGCHECK(!input->is_empty() && (numInputDims == 4 || numInputDims == 5), 2, input, "non-empty 4D or 5D (batch mode) tensor expected for input, but got: %s"); if (numInputDims == 5) { numBatch = THTensor_(size)(input, 0); planeDim++; heightDim++; widthDim++; timeDim++; } /* sizes */ int64_t numPlanes = THTensor_(size)(input, planeDim); int64_t inputH = THTensor_(size)(input, heightDim); int64_t inputW = THTensor_(size)(input, widthDim); int64_t inputT = THTensor_(size)(input, timeDim); THArgCheck(outputH + poolSizeH - 1 < inputH, 9, "poolSizeH (%d) too large relative to input height (%d)", poolSizeH, inputH); THArgCheck(outputW + poolSizeW - 1 < inputW, 8, "poolSizeW (%d) too large relative to input width (%d)", poolSizeW, inputW); THArgCheck(outputT + poolSizeT - 1 < inputT, 7, "poolSizeT (%d) too large relative to input time (%d)", poolSizeT, inputT); /* get contiguous input */ input = THTensor_(newContiguous)(input); if (numInputDims == 4) { /* resize output */ THTensor_(resize4d)(output, numPlanes, outputH, outputW, outputT); /* indices will contain the locations for each output point */ THIndexTensor_(resize4d)(indices, numPlanes, outputH, outputW, outputT); THNN_(VolumetricFractionalMaxPooling_updateOutput_frame)( input->data<scalar_t>(), output->data<scalar_t>(), THIndexTensor_(data)(indices), randomSamples->data<scalar_t>(), numPlanes, inputT, inputW, inputH, outputT, outputW, outputH, poolSizeT, poolSizeW, poolSizeH); } else { THTensor_(resize5d)(output, numBatch, numPlanes, outputH, outputW, outputT); /* indices will contain the locations for each output point */ THIndexTensor_(resize5d)(indices, numBatch, numPlanes, outputH, outputW, outputT); int64_t batch; #pragma omp parallel for private(batch) for (batch = 0; batch < numBatch; ++batch) { THNN_(VolumetricFractionalMaxPooling_updateOutput_frame)( input->data<scalar_t>() + batch * numPlanes * inputH * inputW * inputT, output->data<scalar_t>() + batch * numPlanes * outputH * outputW * outputT, THIndexTensor_(data)(indices) + batch * numPlanes * outputH * outputW * outputT, randomSamples->data<scalar_t>() + batch * numPlanes * 3, numPlanes, inputT, inputW, inputH, outputT, outputW, outputH, poolSizeT, poolSizeW, poolSizeH); } } /* cleanup */ c10::raw::intrusive_ptr::decref(input); } static void THNN_(VolumetricFractionalMaxPooling_updateGradInput_frame)( scalar_t* gradInput, scalar_t* gradOutput, THIndex_t* indices, int64_t numPlanes, int64_t inputT, int64_t inputW, int64_t inputH, int64_t outputT, int64_t outputW, int64_t outputH) { int64_t plane; #pragma omp parallel for private(plane) for (plane = 0; plane < numPlanes; plane++) { scalar_t* gradInputForPlane = gradInput + plane * inputT * inputW * inputH; scalar_t* gradOutputForPlane = gradOutput + plane * outputT * outputW * outputH; THIndex_t* indicesForPlane = indices + plane * outputT * outputW * outputH; int64_t h, w, t; for (h = 0; h < outputH; ++h) { for (w = 0; w < outputW; ++w) { for (t = 0; t < outputT; ++t) { int64_t outputIndex = h * outputW * outputT + w * outputT + t; int64_t index = indicesForPlane[outputIndex] - TH_INDEX_BASE; THAssert(index >= 0 && index < inputT * inputW * inputH); gradInputForPlane[index] += gradOutputForPlane[outputIndex]; } } } } } void THNN_(VolumetricFractionalMaxPooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, int outputT, int outputW, int outputH, int poolSizeT, int poolSizeW, int poolSizeH, THIndexTensor *indices) { int64_t numBatch = 1; int planeDim = 0; int heightDim = 1; int widthDim = 2; int timeDim = 3; int64_t numInputDims = THTensor_(nDimensionLegacyNoScalars)(input); if (numInputDims == 5) { numBatch = THTensor_(size)(input, 0); planeDim = 1; heightDim++; widthDim++; timeDim++; } /* sizes */ int64_t numPlanes = THTensor_(size)(input, planeDim); int64_t inputH = THTensor_(size)(input, heightDim); int64_t inputW = THTensor_(size)(input, widthDim); int64_t inputT = THTensor_(size)(input, timeDim); THArgCheck(outputT == THTensor_(size)(gradOutput, timeDim), 3, "gradOutput time unexpected"); THArgCheck(outputW == THTensor_(size)(gradOutput, widthDim), 3, "gradOutput width unexpected"); THArgCheck(outputH == THTensor_(size)(gradOutput, heightDim), 3, "gradOutput height unexpected"); /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); /* backprop */ if (numInputDims == 4) { THNN_(VolumetricFractionalMaxPooling_updateGradInput_frame)( gradInput->data<scalar_t>(), gradOutput->data<scalar_t>(), THIndexTensor_(data)(indices), numPlanes, inputT, inputW, inputH, outputT, outputW, outputH); } else { int64_t batch; #pragma omp parallel for private(batch) for (batch = 0; batch < numBatch; ++batch) { THNN_(VolumetricFractionalMaxPooling_updateGradInput_frame)( gradInput->data<scalar_t>() + batch * numPlanes * inputH * inputW * inputT, gradOutput->data<scalar_t>() + batch * numPlanes * outputH * outputW * outputT, THIndexTensor_(data)(indices) + batch * numPlanes * outputH * outputW * outputT, numPlanes, inputT, inputW, inputH, outputT, outputW, outputH); } } /* cleanup */ c10::raw::intrusive_ptr::decref(gradOutput); } #endif
k2.c
#include <stdlib.h> #include <assert.h> #include <string.h> #include <stdio.h> #include <math.h> #include <float.h> #include <unistd.h> #include <omp.h> #include <time.h> #include "list.h" #include "matrix.h" #include "bnet.h" #include "rand.h" #define MPI 0 #define VERBOSE 0 #define SAVE_NETWORKS 0 #if MPI #include <mpi.h> #endif double dirichlet_score_family(Matrix *counts, CPD *cpd) { Matrix *ns = cpd->sizes, *prior = cpd->dirichlet; Matrix *ns_self = matrix_sub_indices(ns, ns->rows - 1, ns->rows, 0, ns->cols); Matrix *pnc = matrix_add_int_double(counts, prior); Matrix *gamma_pnc = matrix_lgamma(pnc), *gamma_prior = matrix_lgamma(prior); matrix_delete(pnc); Matrix *lu_mat = matrix_double_subtract(gamma_pnc, gamma_prior); matrix_delete(gamma_pnc); matrix_delete(gamma_prior); Matrix *LU = matrix_double_sum_n_cols(lu_mat, *(int *) matrix_element_by_index(ns_self, 0)); matrix_delete(lu_mat); Matrix *alpha_ij = matrix_double_sum_n_cols(prior, *(int *) matrix_element_by_index(ns_self, 0)); Matrix *N_ij = matrix_sum_n_cols(counts, *(int *) matrix_element_by_index(ns_self, 0)); matrix_scrap(ns_self); Matrix *gamma_alpha = matrix_lgamma(alpha_ij); Matrix *alpha_N = matrix_add_int_double(N_ij, alpha_ij); matrix_delete(N_ij); matrix_delete(alpha_ij); Matrix *gamma_alpha_N = matrix_lgamma(alpha_N); matrix_delete(alpha_N); Matrix *LV = matrix_double_subtract(gamma_alpha, gamma_alpha_N); matrix_delete(gamma_alpha); matrix_delete(gamma_alpha_N); Matrix *LU_LV = matrix_double_add(LU, LV); matrix_delete(LU); matrix_delete(LV); double score = matrix_double_sum(LU_LV); matrix_delete(LU_LV); return score; } int count_index(Matrix *sz, Matrix *sample_data, int col) { Matrix *mat_col = matrix_sub_col(sample_data, col); int index = 0; int **id = (int **) mat_col->data, **dd = (int **) sz->data; for (int i = 0, m = 1; i < mat_col->rows * mat_col->cols; m *= *dd[i++]) { assert((*id[i]) - 1 < *dd[i]); index += ((*id[i]) - 1) * m; } matrix_scrap(mat_col); return index; } Matrix *compute_counts(Matrix *data, Matrix *sz) { assert(sz->rows == data->rows); Matrix *count = matrix_zeros(matrix_prod(sz), 1); for (int i = 0; i < data->cols; ++i) { *((int *) matrix_element_by_index(count, count_index(sz, data, i))) += 1; } return count; } double log_marg_prob_node(CPD *cpd, Matrix *self_ev, Matrix *pev) { assert(self_ev->rows == 1); assert(cpd->sizes->cols == 1); assert(pev->cols == self_ev->cols); Matrix *data = matrix_sub_concat_rows(pev, self_ev, false); Matrix *counts = compute_counts(data, cpd->sizes); matrix_scrap(data); double score = dirichlet_score_family(counts, cpd); matrix_delete(counts); return score; } Matrix *prob_node(CPD *cpd, Matrix *self_ev, Matrix *pev) { Matrix *sample_data = matrix_sub_concat_rows(pev, self_ev, false); Matrix *prob = matrix_double_zeros(sample_data->rows, sample_data->cols); for (int i = 0; i < sample_data->cols; ++i) { Matrix *mat_col = matrix_sub_col(sample_data, i); int index = 0; int **id = (int **) mat_col->data, **dd = (int **) cpd->sizes->data; for (int j = 0, m = 1; j < mat_col->rows * mat_col->cols; m *= *dd[j++]) { assert((*id[j]) - 1 < *dd[j]); index += ((*id[j]) - 1) * m; } matrix_scrap(mat_col); *(double *) matrix_element_by_index(prob, i) = *(double *) matrix_element_by_index(cpd->cpt, index); } matrix_scrap(sample_data); return prob; } double log_prob_node(CPD *cpd, Matrix *self_ev, Matrix *pev) { double score = 0; Matrix *p = prob_node(cpd, self_ev, pev); double **data = (double **) p->data; for (int i = 0; i < p->rows * p->cols; ++i, ++data) { double d = **data; score += d <= 0 ? DBL_MIN : log(d); } matrix_delete(p); return score; } CPD *tabular_CPD(Matrix *dag, Matrix *ns, int self) { CPD *cpd = malloc(sizeof(CPD)); List *ps = adjacency_matrix_parents(dag, self); list_push_int(ps, self); Matrix *fam_sz = matrix_zeros(ps->count, 1); for (int i = 0; i < ps->count; ++i) { *(int *) matrix_element_by_index(fam_sz, i) = *(int *) matrix_element_by_index(ns, list_get_int(ps, i)); } cpd->sizes = fam_sz; Matrix *calc = matrix_sub_indices(fam_sz, 0, ps->count - 1, 0, 1); int psz = matrix_prod(calc); list_delete(ps); matrix_scrap(calc); cpd->dirichlet = matrix_double_create(matrix_prod(fam_sz), 1, (1.0 / psz) * (1.0 / *(int *) matrix_element_by_index(ns, self))); cpd->cpt = NULL; return cpd; } double score_family(int j, List *ps, Matrix *ns, List *discrete, Matrix *data, char *scoring_fn) { Matrix *dag = matrix_zeros(data->rows, data->rows); if (ps->count > 0) { Matrix *dag_sub = matrix_sub_list_index(dag, ps, j, j + 1); matrix_set(dag_sub, 1); matrix_scrap(dag_sub); //TODO: sort `ps` here. } Matrix *data_sub_1 = matrix_sub_indices(data, j, j + 1, 0, data->cols), *data_sub_2 = matrix_sub_list_index(data, ps, 0, data->cols); CPD *cpd = tabular_CPD(dag, ns, j); double score; if (!strcmp(scoring_fn, "bayesian")) { score = log_marg_prob_node(cpd, data_sub_1, data_sub_2); } else if (!strcmp(scoring_fn, "bic")) { List *fam = list_slice(ps, 0, ps->count); int a_index = list_push_int(fam, j); Matrix *data_sub_3 = matrix_sub_list_index(data, fam, 0, data->cols); Matrix *counts = compute_counts(data_sub_3, cpd->sizes); matrix_scrap(data_sub_3); cpd->cpt = matrix_add_int_double(counts, cpd->dirichlet); matrix_delete(counts); matrix_double_mk_stochastic(cpd->cpt, ns); double L = log_prob_node(cpd, data_sub_1, data_sub_2); Matrix *sz = cpd->sizes; int *last = (int *) sz->data[sz->rows * sz->cols - 1]; --*last; score = L - 0.5 * matrix_prod(sz) * log(data->cols); ++*last; free(list_remove(fam, a_index)); list_scrap(fam); } else { assert(1 == 2); } cpd_delete(cpd); matrix_scrap(data_sub_1); matrix_scrap(data_sub_2); matrix_delete(dag); return score; } Matrix *learn_struct_K2(Matrix *data, Matrix *ns, List *order, char *scoring_fn, int max_parents) { assert(order->count == data->rows); int n = data->rows; int max_fan_in = max_parents == 0 ? n : max_parents; List *discrete = list_empty(); for (int i = 0; i < n; ++i) list_push_int(discrete, i); Matrix *dag = matrix_zeros(n, n); int parent_order = 0; for (int i = 0; i < n; ++i) { List *ps = list_empty(); int j = list_get_int(order, i); double score = score_family(j, ps, ns, discrete, data, scoring_fn); #if VERBOSE printf("\nnode %d, empty score %6.4f\n", j, score); #endif for (; ps->count <= max_fan_in;) { List *order_sub = list_slice(order, 0, i); List *pps = list_difference_type_int(order_sub, ps); list_scrap(order_sub); int nps = pps->count; Matrix *pscore = matrix_double_zeros(1, nps); for (int pi = 0; pi < nps; ++pi) { int p = list_get_int(pps, pi); int n_index = list_push_int(ps, p); *((double *) matrix_element_by_index(pscore, pi)) = score_family(j, ps, ns, discrete, data, scoring_fn); #if VERBOSE printf("considering adding %d to %d, score %6.4f\n", p, j, *((double *) matrix_element_by_index(pscore, pi))); #endif free(list_remove(ps, n_index)); } double best_pscore = -DBL_MAX; int best_p = -1; for (int i = 0; i < nps; ++i) { double d = *(double *) matrix_element_by_index(pscore, i); if (d > best_pscore) { best_pscore = d; best_p = i; } } matrix_delete(pscore); if (best_p == -1) { list_scrap(pps); break; } best_p = list_get_int(pps, best_p); list_scrap(pps); if (best_pscore > score) { score = best_pscore; list_push_int(ps, best_p); #if VERBOSE printf("* adding %d to %d, score %6.4f\n", best_p, j, best_pscore); #endif } else { break; } } if (ps->count > 0) { Matrix *dag_sub = matrix_sub_list_index(dag, ps, j, j + 1); matrix_set(dag_sub, ++parent_order); matrix_scrap(dag_sub); } list_delete(ps); } list_delete(discrete); return dag; } #if MPI #define MPI_TAG_MATRIX_R 1 #define MPI_TAG_MATRIX_C 2 #define MPI_TAG_MATRIX_D 3 void MPI_Matrix_Send(int to_index, Matrix *matrix) { int rows = matrix->rows, cols = matrix->cols; int **data = (int **) matrix->data; int *extracted = malloc(rows * cols * sizeof(int)); int *extracted_start = extracted; for (int i = 0; i < rows * cols; ++i, ++extracted, ++data) { *extracted = **data; } MPI_Send(&rows, 1, MPI_INT, to_index, MPI_TAG_MATRIX_R, MPI_COMM_WORLD); MPI_Send(&cols, 1, MPI_INT, to_index, MPI_TAG_MATRIX_C, MPI_COMM_WORLD); MPI_Send(extracted_start, rows * cols, MPI_INT, to_index, MPI_TAG_MATRIX_D, MPI_COMM_WORLD); free(extracted_start); } Matrix *MPI_Matrix_Recv(int from_index) { int rows, cols; MPI_Recv(&rows, 1, MPI_INT, from_index, MPI_TAG_MATRIX_R, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&cols, 1, MPI_INT, from_index, MPI_TAG_MATRIX_C, MPI_COMM_WORLD, MPI_STATUS_IGNORE); Matrix *matrix = matrix_zeros(rows, cols); int **data = (int **) matrix->data; int *values = malloc(rows * cols * sizeof(int)); MPI_Recv(values, rows * cols, MPI_INT, from_index, MPI_TAG_MATRIX_D, MPI_COMM_WORLD, MPI_STATUS_IGNORE); int *values_start = values; for (int i = 0; i < rows * cols; ++i, ++values, ++data) { **data = *values; } free(values_start); return matrix; } #endif int exec(int forkIndex, int forkSize, bool data_transposed, char *f_data, int topologies, char *f_output, char *scoring_fn, int max_parents) { Matrix *data = matrix_from_file(f_data, data_transposed), *sz = matrix_create_sz(data); #if MPI assert(forkIndex > -1); assert(forkSize > 0); int top_d = topologies / forkSize, top_r = topologies % forkSize; if (forkIndex < top_r) ++top_d; topologies = top_d; #endif Matrix *orders = matrix_zeros(data->rows * topologies, data->rows); #if SAVE_NETWORKS Matrix *networks = matrix_zeros(data->rows * topologies, data->rows * data->rows); #endif #pragma omp parallel for for (int r = 0; r < orders->rows; ++r) { int start = r / topologies; int *arr = malloc(orders->cols * sizeof(int)); arr[0] = start; for (int i = 1; i < orders->cols; ++i) { arr[i] = i == start ? 0 : i; } shuffle_int(orders->cols - 1, arr + 1); for (int c = 0; c < orders->cols; ++c) { *(int *) matrix_element(orders, r, c) = arr[c]; } free(arr); } Matrix *consensus_network = matrix_zeros(data->rows, data->rows); int cn_n_elements = consensus_network->rows * consensus_network->cols; #pragma omp parallel for for (int o = 0; o < orders->rows; ++o) { Matrix *m_order = matrix_sub_indices(orders, o, o + 1, 0, orders->cols); List *order = matrix_to_list(m_order); Matrix *bnet = learn_struct_K2(data, sz, order, scoring_fn, max_parents); assert(consensus_network->rows == bnet->rows); assert(consensus_network->cols == bnet->cols); #pragma omp critical for (int i = 0; i < cn_n_elements; ++i) { *(int *) matrix_element_by_index(consensus_network, i) += *(int *) matrix_element_by_index(bnet, i) ? 1 : 0; } #if SAVE_NETWORKS for (int i = 0; i < cn_n_elements; ++i) { *(int *) matrix_element_by_index(networks, i + cn_n_elements * o) = *(int *) matrix_element_by_index(bnet, i); } #endif matrix_delete(bnet); list_delete(order); matrix_scrap(m_order); } matrix_delete(sz); matrix_delete(data); #if MPI //TODO: merge and write topologies if (forkIndex == 0) { for (int i = 1; i < forkSize; ++i) { Matrix *merge = MPI_Matrix_Recv(i); matrix_add_in(consensus_network, merge); matrix_delete(merge); } #if SAVE_NETWORKS for (int i = 1; i < forkSize; ++i) { Matrix *merge = MPI_Matrix_Recv(i), *old = orders; orders = matrix_sub_concat_rows(orders, merge, true); matrix_scrap(old); matrix_scrap(merge); } for (int i = 1; i < forkSize; ++i) { Matrix *merge = MPI_Matrix_Recv(i), *old = networks; networks = matrix_sub_concat_rows(networks, merge, true); matrix_scrap(old); matrix_scrap(merge); } #endif } else { MPI_Matrix_Send(0, consensus_network); #if SAVE_NETWORKS MPI_Matrix_Send(0, orders); MPI_Matrix_Send(0, networks); #endif } #endif if (forkIndex == 0) { matrix_to_file(consensus_network, f_output); #if SAVE_NETWORKS matrix_to_file(networks, "networks.csv"); matrix_to_file(orders, "topologies.csv"); #endif } #if SAVE_NETWORKS matrix_delete(networks); #endif matrix_delete(orders); matrix_delete(consensus_network); return 0; } int main(int argc, char **argv) { int forkIndex = 0, forkSize = 1; #if MPI MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &forkIndex); MPI_Comm_size(MPI_COMM_WORLD, &forkSize); #endif srand(time(NULL) ^ forkIndex); int threads = 1, topologies = 1, max_parents = 0; bool data_transposed = false; char *data = NULL, *output = "consensus.csv"; char *scoring_fn = "bayesian"; int c; while ((c = getopt(argc, argv, "Thp:d:t:o:s:m:")) != -1) { switch (c) { case 'T': { data_transposed = true; break; } case 'p': { threads = atoi(optarg); assert(threads > 0); assert(threads <= omp_get_num_procs()); break; } case 'm': { max_parents = atoi(optarg); assert(max_parents >= 0); break; } case 'd': { data = optarg; break; } case 't': { topologies = atoi(optarg); break; } case 'o': { output = optarg; break; } case 's': { scoring_fn = optarg; break; } case 'h': default: { puts(": -p <num_threads> -d <data file> -t <topologies per gene> -o <output file> -m <max parents>"); puts("~ -T (reads matrix transposed)"); return 1; } } } if (data == NULL) { puts("You must send a data file using -d <file name>."); return 1; } omp_set_num_threads(threads); int status = exec(forkIndex, forkSize, data_transposed, data, topologies, output, scoring_fn, max_parents); #if MPI MPI_Finalize(); #endif return status; }