source
stringlengths
3
92
c
stringlengths
26
2.25M
sum.h
#pragma once #include <vector> #include <unordered_map> #include <algorithm> #include <cmath> #include <omp.h> #include "_cuda.h" using std::vector; using std::unordered_map; using std::max; using std::abs; // SUM // --- template <class T> auto sum(T *x, int N) { T a = T(); for (int i=0; i<N; i++) a += x[i]; return a; } template <class T> auto sum(vector<T>& x) { return sum(x.data(), x.size()); } template <class K, class T> auto sum(unordered_map<K, T>& x) { T a = T(); for (auto&& p : x) a += p.second; return a; } // SUM-ABS // ------- template <class T> auto sumAbs(T *x, int N) { T a = T(); for (int i=0; i<N; i++) a += abs(x[i]); return a; } template <class T> auto sumAbs(vector<T>& x) { return sumAbs(x.data(), x.size()); } template <class K, class T> auto sumAbs(unordered_map<K, T>& x) { T a = T(); for (auto&& p : x) a += abs(p.second); return a; } // SUM-AT // ------ template <class T, class I> auto sumAt(T *x, I&& is) { T a = T(); for (int i : is) a += x[i]; return a; } template <class T, class I> auto sumAt(vector<T>& x, I&& is) { return sumAt(x.data(), is); } template <class K, class T, class I> auto sumAt(unordered_map<K, T>& x, I&& ks) { T a = T(); for (auto&& k : ks) a += x[k]; return a; } // SUM-ABS-AT // ---------- template <class T, class I> auto sumAbsAt(T *x, I&& is) { T a = T(); for (int i : is) a += abs(x[i]); return a; } template <class T, class I> auto sumAbsAt(vector<T>& x, I&& is) { return sumAbsAt(x.data(), is); } template <class K, class T, class I> auto sumAbsAt(unordered_map<K, T>& x, I&& ks) { T a = T(); for (auto&& k : ks) a += abs(x[k]); return a; } // SUM (OMP) // --------- template <class T> auto sumOmp(T *x, int N) { T a = T(); #pragma omp parallel for reduction (+:a) for (int i=0; i<N; i++) a += x[i]; return a; } template <class T> auto sumOmp(vector<T>& x) { return sumOmp(x.data(), x.size()); } // SUM (CUDA) // ---------- template <class T> __device__ void sumKernelReduce(T* a, int N, int i) { __syncthreads(); for (N=N/2; N>0; N/=2) { if (i < N) a[i] += a[N+i]; __syncthreads(); } } template <class T> __device__ T sumKernelLoop(T *x, int N, int i, int DI) { T a = T(); for (; i<N; i+=DI) a += x[i]; return a; } template <class T> __global__ void sumKernel(T *a, T *x, int N) { DEFINE(t, b, B, G); __shared__ T cache[BLOCK_DIM]; cache[t] = sumKernelLoop(x, N, B*b+t, G*B); sumKernelReduce(cache, B, t); if (t == 0) a[b] = cache[0]; } template <class T> auto sumCuda(T *x, int N) { int B = BLOCK_DIM; int G = min(ceilDiv(N, B), GRID_DIM); size_t N1 = N * sizeof(T); size_t G1 = G * sizeof(T); T a[GRID_DIM]; T *xD, *aD; TRY( cudaMalloc(&xD, N1) ); TRY( cudaMalloc(&aD, G1) ); TRY( cudaMemcpy(xD, x, N1, cudaMemcpyHostToDevice) ); sumKernel<<<G, B>>>(aD, xD, N); TRY( cudaMemcpy(a, aD, G1, cudaMemcpyDeviceToHost) ); TRY( cudaFree(xD) ); TRY( cudaFree(aD) ); return sum(a, G); } template <class T> auto sumCuda(vector<T>& x) { return sumCuda(x.data(), x.size()); } // SUM-ABS (CUDA) // -------------- template <class T> __device__ T sumAbsKernelLoop(T *x, int N, int i, int DI) { T a = T(); for (; i<N; i+=DI) a += abs(x[i]); return a; } template <class T> __global__ void sumAbsKernel(T *a, T *x, int N) { DEFINE(t, b, B, G); __shared__ T cache[BLOCK_DIM]; cache[t] = sumAbsKernelLoop(x, N, B*b+t, G*B); sumKernelReduce(cache, B, t); if (t == 0) a[b] = cache[0]; } template <class T> auto sumAbsCuda(T *x, int N) { int B = BLOCK_DIM; int G = min(ceilDiv(N, B), GRID_DIM); size_t N1 = N * sizeof(T); size_t G1 = G * sizeof(T); T a[GRID_DIM]; T *xD, *aD; TRY( cudaMalloc(&xD, N1) ); TRY( cudaMalloc(&aD, G1) ); TRY( cudaMemcpy(xD, x, N1, cudaMemcpyHostToDevice) ); sumAbsKernel<<<G, B>>>(aD, xD, N); TRY( cudaMemcpy(a, aD, G1, cudaMemcpyDeviceToHost) ); TRY( cudaFree(xD) ); TRY( cudaFree(aD) ); return sum(a, G); } template <class T> auto sumAbsCuda(vector<T>& x) { return sumAbsCuda(x.data(), x.size()); } // SUM-AT (CUDA) // ------------- template <class T> __device__ T sumAtKernelLoop(T *x, int *is, int IS, int i, int DI) { T a = T(); for (; i<IS; i+=DI) a += x[is[i]]; return a; } template <class T> __global__ void sumAtKernel(T *a, T *x, T *is, int IS) { DEFINE(t, b, B, G); __shared__ T cache[BLOCK_DIM]; cache[t] = sumAtKernelLoop(x, is, IS, B*b+t, G*B); sumKernelReduce(cache, B, t); if (t == 0) a[b] = cache[0]; } // SUM-ABS-AT (CUDA) // ----------------- template <class T> __device__ T sumAbsAtKernelLoop(T *x, int *is, int IS, int i, int DI) { T a = T(); for (; i<IS; i+=DI) a += abs(x[is[i]]); return a; } template <class T> __global__ void sumAbsAtKernel(T *a, T *x, T *is, int IS) { DEFINE(t, b, B, G); __shared__ T cache[BLOCK_DIM]; cache[t] = sumAbsAtKernelLoop(x, is, IS, B*b+t, G*B); sumKernelReduce(cache, B, t); if (t == 0) a[b] = cache[0]; } // SUM-IF-NOT (CUDA) // ----------------- template <class T, class C> __device__ T sumIfNotKernelLoop(T *x, C *cs, int N, int i, int DI) { T a = T(); for (; i<N; i+=DI) if (!cs[i]) a += x[i]; return a; } template <class T, class C> __global__ void sumIfNotKernel(T *a, T *x, C *cs, int N) { DEFINE(t, b, B, G); __shared__ T cache[BLOCK_DIM]; cache[t] = sumIfNotKernelLoop(x, cs, N, B*b+t, G*B); sumKernelReduce(cache, B, t); if (t == 0) a[b] = cache[0]; } // SUM-ABS-IF-NOT (CUDA) // --------------------- template <class T, class C> __device__ T sumAbsIfNotKernelLoop(T *x, C *cs, int N, int i, int DI) { T a = T(); for (; i<N; i+=DI) if (cs[i] == 0) a += abs(x[i]); return a; } template <class T, class C> __global__ void sumAbsIfNotKernel(T *a, T *x, C *cs, int N) { DEFINE(t, b, B, G); __shared__ T cache[BLOCK_DIM]; cache[t] = sumAbsIfNotKernelLoop(x, cs, N, B*b+t, G*B); sumKernelReduce(cache, B, t); if (t == 0) a[b] = cache[0]; }
SingleEndLink.c
int x; int main() { #pragma omp single { int x; } #pragma omp single { } }
GB_unop__log2_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__log2_fc32_fc32) // op(A') function: GB (_unop_tran__log2_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = GB_clog2f (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_clog2f (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = GB_clog2f (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LOG2 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__log2_fc32_fc32) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = GB_clog2f (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = GB_clog2f (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__log2_fc32_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp_threadprivate_for.c
// RUN: %libomp-compile-and-run // REQUIRES: !(abt && (clang || gcc)) #include "omp_testsuite.h" #include <stdlib.h> #include <stdio.h> static int i; #pragma omp threadprivate(i) int test_omp_threadprivate_for() { int known_sum; int sum; known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; sum = 0; #pragma omp parallel { int sum0 = 0, i0; #pragma omp for for (i0 = 1; i0 <= LOOPCOUNT; i0++) { i = i0; sum0 = sum0 + i; } #pragma omp critical { sum = sum + sum0; } } /* end of parallel */ if (known_sum != sum ) { fprintf(stderr, " known_sum = %d, sum = %d\n", known_sum, sum); } return (known_sum == sum); } /* end of check_threadprivate*/ int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_threadprivate_for()) { num_failed++; } } return num_failed; }
axpy_int_simdlen8.c
//axpy.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #define N_RUNS 1000 #define N 1200 // 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(int *X, int *Y) { for (int i = 0; i<N; i++) { X[i] = (int)rand()/(int)(RAND_MAX/10.0); Y[i] = (int)rand()/(int)(RAND_MAX/10.0); } } //Our sum function- what it does is pretty straight-forward. void axpy(int *X, int *Y, int a) { #pragma omp simd simdlen(8) for (int i = 0; i<N; i++) { Y[i] += a * X[i]; } } // Debug functions void axpy_serial(int *X, int *Y, int a) { for (int i = 0; i<N; i++) { Y[i] += a * X[i]; } } void print_vector(int *vector) { printf("["); for (int i = 0; i<8; i++) { printf("%d ", vector[i]); } puts("]"); } int check(int *A, int *B){ int difference = 0; for(int i = 0;i<N; i++){ difference += A[i]- B[i]; } return difference; } int main(int argc, char **argv) { //Set everything up int *X = malloc(sizeof(int)*N); int *Y = malloc(sizeof(int)*N); int *Y_serial = malloc(sizeof(int)*N); int a = 3; srand(time(NULL)); init(X, Y); for (int i = 0; i<N; i++) Y_serial[i] = Y[i]; print_vector(Y); print_vector(X); printf("%d\n", a); puts("=\n"); double start = read_timer(); for (int i = 0; i<N_RUNS; i++) axpy(X, Y, a); double t = (read_timer() - start); double start_serial = read_timer(); for (int i = 0; i<N_RUNS; i++) axpy_serial(X, Y_serial, a); double t_serial = (read_timer() - start_serial); print_vector(Y); puts("---------------------------------"); print_vector(Y_serial); double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t); double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial); printf("==================================================================\n"); printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------\n"); printf("AXPY (SIMD):\t\t%4f\t%4f\n", t, gflops); printf("AXPY (Serial):\t\t%4f\t%4f\n", t_serial, gflops_serial); printf("Correctness check: %d\n", check(Y,Y_serial)); free(X); free(Y); free(Y_serial); return 0; }
DRB063-outeronly1-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. */ /* Only the outmost loop can be parallelized. */ #include "omprace.h" #include <omp.h> int n=100, m=100; double b[100][100]; void foo() { int i,j; #pragma omp parallel for private(j) for (i=0;i<n;i++) for (j=0;j<m-1;j++) // Be careful about bounds of j b[i][j]=b[i][j+1]; } int main() { omprace_init(); foo(); omprace_fini(); return 0; }
sparseMatrix.h
/** Copyright 2016, 2017, 2018, 2019, 2020 Joachim Wolff PhD Thesis Copyright 2015, 2016 Joachim Wolff Master Thesis Tutor: Fabrizio Costa Winter semester 2015/2016 Chair of Bioinformatics Department of Computer Science Faculty of Engineering Albert-Ludwigs-University Freiburg im Breisgau **/ #include <math.h> #include <cstring> #include <algorithm> #include <iostream> #include "typeDefinitionsBasic.h" #ifdef OPENMP #include <omp.h> #endif #ifndef SPARSE_MATRIX_H #define SPARSE_MATRIX_H class SparseMatrixFloat { private: // stores only the pointer addresses to: // if even index: size_t which is pointer for vsize // if odd indeX: size_t which is pointer for vfloat uint64_t* mSparseMatrix = NULL; float* mSparseMatrixValues = NULL; size_t* mSizesOfInstances = NULL; size_t mMaxNnz; size_t mNumberOfInstances; std::unordered_map<size_t, float> mDotProductPrecomputed; public: SparseMatrixFloat(size_t pNumberOfInstances, size_t pMaxNnz) { pMaxNnz = pMaxNnz + 32 - (pMaxNnz % 32); mSparseMatrix = new uint64_t [pNumberOfInstances * pMaxNnz]; std::fill_n(mSparseMatrix, pNumberOfInstances * pMaxNnz, MAX_VALUE); mSparseMatrixValues = new float [pNumberOfInstances * pMaxNnz](); mSizesOfInstances = new size_t [pNumberOfInstances]; mMaxNnz = pMaxNnz; mNumberOfInstances = pNumberOfInstances; }; ~SparseMatrixFloat() { delete [] mSparseMatrix; delete [] mSparseMatrixValues; delete [] mSizesOfInstances; }; void precomputeDotProduct() { double value = 0.0; double value1 = 0.0; double value2 = 0.0; double value3 = 0.0; for (size_t i = 0; i < size(); ++i) { size_t j = 0; for (j = 0; j < getSizeOfInstance(i); j += 4) { value += pow(getNextValue(i, j), 2); value1 += pow(getNextValue(i, j+1), 2); value2 += pow(getNextValue(i, j+2), 2); value3 += pow(getNextValue(i, j+3), 2); } while (j < getSizeOfInstance(i)) { value += pow(getNextValue(i, j), 2); ++j; } value = value + value1 + value2 + value3; mDotProductPrecomputed[i] = (float) value; value = 0.0; value1 = 0.0; value2 = 0.0; value3 = 0.0; } }; float dotProduct(const size_t pIndex, const size_t pIndexNeighbor, SparseMatrixFloat* pQueryData=NULL) { SparseMatrixFloat* queryData = this; if (pQueryData != NULL) { queryData = pQueryData; } double value = 0.0; size_t counterInstance = 0; size_t counterNeighbor = 0; size_t sizeInstance = queryData->getSizeOfInstance(pIndex); size_t sizeNeighbor = this->getSizeOfInstance(pIndexNeighbor); while (counterInstance < sizeInstance && counterNeighbor < sizeNeighbor) { if (queryData->getNextElement(pIndex, counterInstance) < this->getNextElement(pIndexNeighbor, counterNeighbor)) { ++counterInstance; } else if (queryData->getNextElement(pIndex, counterInstance) > this->getNextElement(pIndexNeighbor, counterNeighbor)){ ++counterNeighbor; } else { value += (double) queryData->getNextValue(pIndex, counterInstance) * (double) this->getNextValue(pIndexNeighbor, counterNeighbor); ++counterInstance; ++counterNeighbor; } } return (float) value; }; float getDotProductPrecomputed(size_t pIndex, SparseMatrixFloat* pQueryData=NULL) { // return 1; auto it = mDotProductPrecomputed.find(pIndex); if (it != mDotProductPrecomputed.end()) { return it->second; } else { float value = dotProduct(pIndex, pIndex, pQueryData); #pragma omp critical mDotProductPrecomputed[pIndex] = value; } return mDotProductPrecomputed[pIndex]; } uint64_t* getSparseMatrixIndex() const{ return mSparseMatrix; }; float* getSparseMatrixValues() const{ return mSparseMatrixValues; }; uint64_t* getSparseMatrixIndexPointer(size_t pIndex) { // printf("pIndex: %u, mMaxNNZ: %u pIndex*mMaxNnz: %u maxIndex: %u\n", pIndex, mMaxNnz, pIndex * mMaxNnz, mNumberOfInstances * mMaxNnz); return &(mSparseMatrix[pIndex * mMaxNnz]); }; float* getSparseMatrixValuesPointer(size_t pIndex) { // printf("pIndex: %u, mMaxNNZ: %u pIndex*mMaxNnz: %u maxIndex: %u\n", pIndex, mMaxNnz, pIndex * mMaxNnz, mNumberOfInstances * mMaxNnz); return &(mSparseMatrixValues[pIndex * mMaxNnz]); }; size_t* getSparseMatrixSizeOfInstances() const { return mSizesOfInstances; }; size_t getMaxNnz() const { return mMaxNnz; }; size_t getNumberOfInstances() const { return mNumberOfInstances; }; uint64_t getNextElement(size_t pInstance, size_t pCounter) const { // if (pInstance*mMaxNnz+pCounter < mNumberOfInstances) { return mSparseMatrix[pInstance*mMaxNnz+pCounter]; // } // return 0; }; float getNextValue(size_t pInstance, size_t pCounter) const { // if (pInstance*mMaxNnz+pCounter < mNumberOfInstances) { return mSparseMatrixValues[pInstance*mMaxNnz+pCounter]; // } // return 0; }; size_t size() const { return mNumberOfInstances; }; size_t getSizeOfInstance(size_t pInstance) const { if (pInstance < mNumberOfInstances) { return mSizesOfInstances[pInstance]; } return 0; }; void insertElement(size_t pInstanceId, size_t pNnzCount, size_t pFeatureId, float pValue) { if (pInstanceId*mMaxNnz + pNnzCount < mNumberOfInstances * mMaxNnz) { mSparseMatrix[pInstanceId*mMaxNnz + pNnzCount] = static_cast<int> (pFeatureId); mSparseMatrixValues[pInstanceId*mMaxNnz + pNnzCount] = pValue; } }; void insertToSizesOfInstances(size_t pInstanceId, size_t pSizeOfInstance) { if (pInstanceId < mNumberOfInstances) { mSizesOfInstances[pInstanceId] = pSizeOfInstance; } }; void addNewInstancesPartialFit(const SparseMatrixFloat* pMatrix) { size_t numberOfInstances = this->getNumberOfInstances(); // std::cout << "numberOfInstances" << numberOfInstances<< std::endl; numberOfInstances += pMatrix->getNumberOfInstances(); // std::cout << "numberOfInstances" << numberOfInstances<< std::endl; size_t maxNnz = std::max(mMaxNnz, pMatrix->getMaxNnz()); // std::cout << "maxNnz" << maxNnz << std::endl; // std::cout << "mMaxNnz" << mMaxNnz << std::endl; // std::cout << "pMatrix->getMaxNnz()" << pMatrix->getMaxNnz() << std::endl; uint64_t* tmp_mSparseMatrix = new uint64_t [numberOfInstances * maxNnz]; float* tmp_mSparseMatrixValues = new float [numberOfInstances * maxNnz]; size_t* tmp_mSizesOfInstances = new size_t [numberOfInstances]; for (size_t i = 0; i < this->getNumberOfInstances(); ++i) { for (size_t j = 0; j < this->getSizeOfInstance(i); ++j) { tmp_mSparseMatrix[i*maxNnz + j] = this->getNextElement(i, j); tmp_mSparseMatrixValues[i*maxNnz + j] = this->getNextValue(i,j); } tmp_mSizesOfInstances[i] = this->getSizeOfInstance(i); } for (size_t i = 0; i < pMatrix->getNumberOfInstances(); ++i) { for (size_t j = 0; j < pMatrix->getSizeOfInstance(i); ++j) { tmp_mSparseMatrix[(i+this->getNumberOfInstances())*maxNnz + j] = pMatrix->getNextElement(i, j); tmp_mSparseMatrixValues[(i+this->getNumberOfInstances())*maxNnz + j] = pMatrix->getNextValue(i,j); } tmp_mSizesOfInstances[i+this->getNumberOfInstances()] = pMatrix->getSizeOfInstance(i); } // std::cout << "new mMaxNnz" << mMaxNnz << std::endl; // std::cout << "new mNumberOfInstances" << mNumberOfInstances << std::endl; mMaxNnz = maxNnz; mNumberOfInstances = numberOfInstances; delete [] mSparseMatrix; delete [] mSparseMatrixValues; delete [] mSizesOfInstances; // delete pMatrix; mSparseMatrix = tmp_mSparseMatrix; mSparseMatrixValues = tmp_mSparseMatrixValues; mSizesOfInstances = tmp_mSizesOfInstances; }; std::vector<sortMapFloat> euclidianDistance(const std::vector<size_t> pRowIdVector, const size_t pNneighbors, const size_t pQueryId, SparseMatrixFloat* pQueryData=NULL) { const size_t pRowId = pQueryId; std::vector<sortMapFloat> returnValue(pRowIdVector.size()); size_t valueXX; if (pQueryData == NULL) { valueXX = getDotProductPrecomputed(pRowId); } else { valueXX = pQueryData->getDotProductPrecomputed(pRowId, pQueryData); } float valueXY = 0; float valueYY = 0; size_t instance_id; for (size_t i = 0; i < pRowIdVector.size(); ++i) { instance_id = pRowIdVector[i]; sortMapFloat element; element.key = pRowIdVector[i]; element.val = 0; valueXY = this->dotProduct(pRowId, instance_id, pQueryData); valueYY = getDotProductPrecomputed(instance_id); element.val = valueXX - 2* valueXY + valueYY; if (element.val <= 0) { element.val = 0; } returnValue[i] = element; } size_t numberOfElementsToSort = pNneighbors; if (numberOfElementsToSort > returnValue.size()) { numberOfElementsToSort = returnValue.size(); } // sort the values by increasing order std::partial_sort(returnValue.begin(), returnValue.begin()+numberOfElementsToSort, returnValue.end(), mapSortAscByValueFloat); return returnValue; }; std::vector<sortMapFloat> cosineSimilarity(const std::vector<size_t> pRowIdVector, const size_t pNneighbors, const size_t pQueryId, SparseMatrixFloat* pQueryData=NULL) { const size_t pRowId = pQueryId; std::vector<sortMapFloat> returnValue(pRowIdVector.size()); size_t valueXX; if (pQueryData == NULL) { valueXX = getDotProductPrecomputed(pRowId); } else { valueXX = pQueryData->getDotProductPrecomputed(pRowId, pQueryData); } float valueXY = 0; float valueYY = 0; size_t instance_id; for (size_t i = 0; i < pRowIdVector.size(); ++i) { instance_id = pRowIdVector[i]; sortMapFloat element; element.key = pRowIdVector[i]; element.val = 0; valueXY = this->dotProduct(pRowId, instance_id, pQueryData); valueYY = getDotProductPrecomputed(instance_id); element.val = valueXY / (sqrt(valueXX) * sqrtf(valueYY)); if (element.val <= 0) { element.val = 0; } returnValue[i] = element; } size_t numberOfElementsToSort = pNneighbors; if (numberOfElementsToSort > returnValue.size()) { numberOfElementsToSort = returnValue.size(); } // sort the values by decreasing order std::partial_sort(returnValue.begin(), returnValue.begin()+numberOfElementsToSort, returnValue.end(), mapSortDescByValueFloat); return returnValue; }; }; #endif // SPARSE_MATRIX_H
main.c
void foo(int N, int *restrict A); void baz(int M, int *restrict T, int N, int *restrict A) { #pragma omp parallel default(shared) { #pragma omp for for (int I = 0; I < N; ++I) { for (int J = 0; J < M; ++J) A[I] = A[I] + T[J]; } } } void bar(int M, int *restrict T, int N, int *restrict A) { baz(M, T, N, A); #pragma spf region { if (N > 0 && A[0] < 0) foo(N, A); } } void foo(int N, int *A) { int TSize = 4; int T[4]; for (int I = 0; I < TSize; ++I) T[I] = I; bar(TSize, T, N, A); }
temporal_mean_method.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Suneth Warnakulasuriya (https://github.com/sunethwarna) // #if !defined(KRATOS_TEMPORAL_MEAN_METHOD_H_INCLUDED) #define KRATOS_TEMPORAL_MEAN_METHOD_H_INCLUDED // System includes // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" // Application includes #include "custom_methods/temporal_method.h" #include "custom_utilities/method_utilities.h" #include "custom_utilities/temporal_method_utilities.h" namespace Kratos { ///@addtogroup StatisticsApplication ///@{ ///@name Kratos Globals ///@{ namespace TemporalMethods { template <class TContainerType, class TContainerItemType, template <class T> class TDataRetrievalFunctor, template <class T> class TDataStorageFunctor> class TemporalMeanMethod { public: template <class TDataType> class ValueMethod : public TemporalMethod { public: KRATOS_CLASS_POINTER_DEFINITION(ValueMethod); ValueMethod( ModelPart& rModelPart, const std::string& rNormType, const Variable<TDataType>& rInputVariable, const int EchoLevel, const Variable<TDataType>& rOutputVariable) : TemporalMethod(rModelPart, EchoLevel), mrInputVariable(rInputVariable), mrOutputVariable(rOutputVariable) { } void CalculateStatistics() override { TContainerType& r_container = MethodUtilities::GetDataContainer<TContainerType>(this->GetModelPart()); const double delta_time = this->GetDeltaTime(); const double old_total_time = this->GetTotalTime(); const double total_time = old_total_time + delta_time; const int number_of_items = r_container.size(); #pragma omp parallel for for (int i = 0; i < number_of_items; ++i) { TContainerItemType& r_item = *(r_container.begin() + i); const TDataType& r_input_value = TDataRetrievalFunctor<TContainerItemType>()(r_item, mrInputVariable); TDataType& r_output_value = TDataStorageFunctor<TContainerItemType>()(r_item, mrOutputVariable); MethodUtilities::DataTypeSizeChecker(r_input_value, r_output_value); TemporalMeanMethod::CalculateMean<TDataType>( r_output_value, r_input_value, delta_time, old_total_time, total_time); } KRATOS_INFO_IF("TemporalValueMeanMethod", this->GetEchoLevel() > 1) << "Calculated temporal value mean for " << mrInputVariable.Name() << " input variable with " << mrOutputVariable.Name() << " mean variable for " << this->GetModelPart().Name() << ".\n"; } void InitializeStatisticsVariables() override { TContainerType& r_container = MethodUtilities::GetDataContainer<TContainerType>(this->GetModelPart()); auto& initializer_method = TemporalMethodUtilities::InitializeVariables<TContainerType, TContainerItemType, TDataRetrievalFunctor, TDataStorageFunctor, TDataType>; initializer_method(r_container, mrOutputVariable, mrInputVariable); KRATOS_INFO_IF("TemporalValueMeanMethod", this->GetEchoLevel() > 0) << "Initialized temporal value mean method for " << mrInputVariable.Name() << " input variable with " << mrOutputVariable.Name() << " mean variable for " << this->GetModelPart().Name() << ".\n"; } private: const Variable<TDataType>& mrInputVariable; const Variable<TDataType>& mrOutputVariable; }; template <class TDataType> class NormMethod : public TemporalMethod { public: KRATOS_CLASS_POINTER_DEFINITION(NormMethod); NormMethod( ModelPart& rModelPart, const std::string& rNormType, const Variable<TDataType>& rInputVariable, const int EchoLevel, const Variable<double>& rOutputVariable) : TemporalMethod(rModelPart, EchoLevel), mNormType(rNormType), mrInputVariable(rInputVariable), mrOutputVariable(rOutputVariable) { } void CalculateStatistics() override { TContainerType& r_container = MethodUtilities::GetDataContainer<TContainerType>(this->GetModelPart()); const auto& norm_method = MethodUtilities::GetNormMethod(mrInputVariable, mNormType); const double delta_time = this->GetDeltaTime(); const double old_total_time = this->GetTotalTime(); const double total_time = old_total_time + delta_time; const int number_of_items = r_container.size(); #pragma omp parallel for for (int i = 0; i < number_of_items; ++i) { TContainerItemType& r_item = *(r_container.begin() + i); const TDataType& r_input_value = TDataRetrievalFunctor<TContainerItemType>()(r_item, mrInputVariable); const double input_norm_value = norm_method(r_input_value); double& r_output_value = TDataStorageFunctor<TContainerItemType>()(r_item, mrOutputVariable); TemporalMeanMethod::CalculateMean<double>( r_output_value, input_norm_value, delta_time, old_total_time, total_time); } KRATOS_INFO_IF("TemporalNormMeanMethod", this->GetEchoLevel() > 1) << "Calculated temporal norm mean for " << mrInputVariable.Name() << " input variable with " << mrOutputVariable.Name() << " mean variable for " << this->GetModelPart().Name() << ".\n"; } void InitializeStatisticsVariables() override { TContainerType& r_container = MethodUtilities::GetDataContainer<TContainerType>(this->GetModelPart()); auto& initializer_method = TemporalMethodUtilities::InitializeVariables<TContainerType, TContainerItemType, TDataStorageFunctor>; initializer_method(r_container, mrOutputVariable, 0.0); KRATOS_INFO_IF("TemporalNormMeanMethod", this->GetEchoLevel() > 0) << "Initialized temporal norm mean method for " << mrInputVariable.Name() << " input variable with " << mrOutputVariable.Name() << " mean variable for " << this->GetModelPart().Name() << ".\n"; } private: const std::string mNormType; const Variable<TDataType>& mrInputVariable; const Variable<double>& mrOutputVariable; }; std::vector<TemporalMethod::Pointer> static CreateTemporalMethodObject( ModelPart& rModelPart, const std::string& rNormType, const int EchoLevel, Parameters Params) { KRATOS_TRY Parameters default_parameters = Parameters(R"( { "input_variables" : [], "output_variables" : [] })"); Params.RecursivelyValidateAndAssignDefaults(default_parameters); const std::vector<std::string>& input_variable_names_list = Params["input_variables"].GetStringArray(); const std::vector<std::string>& output_variable_names_list = Params["output_variables"].GetStringArray(); std::vector<TemporalMethod::Pointer> method_list; if (rNormType == "none") // for non norm types { MethodUtilities::CheckInputOutputVariables( input_variable_names_list, output_variable_names_list); const int number_of_variables = input_variable_names_list.size(); for (int i = 0; i < number_of_variables; ++i) { const std::string& r_variable_input_name = input_variable_names_list[i]; const std::string& r_variable_output_name = output_variable_names_list[i]; ADD_TEMPORAL_VALUE_METHOD_ONE_OUTPUT_VARIABLE_OBJECT( rModelPart, rNormType, r_variable_input_name, EchoLevel, r_variable_output_name, method_list, ValueMethod) } } else // for values with norms { MethodUtilities::CheckVariableType<double>(output_variable_names_list); const int number_of_variables = input_variable_names_list.size(); for (int i = 0; i < number_of_variables; ++i) { const std::string& r_variable_input_name = input_variable_names_list[i]; const std::string& r_variable_output_name = output_variable_names_list[i]; ADD_TEMPORAL_NORM_METHOD_ONE_OUTPUT_VARIABLE_OBJECT( rModelPart, rNormType, r_variable_input_name, EchoLevel, r_variable_output_name, method_list, NormMethod) } } return method_list; KRATOS_CATCH(""); } private: template <class TDataType> void static CalculateMean( TDataType& rMean, const TDataType& rNewDataPoint, const double DeltaTime, const double OldTotalTime, const double CurrentTotalTime) { rMean = (rMean * OldTotalTime + rNewDataPoint * DeltaTime) * (1.0 / CurrentTotalTime); } }; } // namespace TemporalMethods } // namespace Kratos #endif // KRATOS_TEMPORAL_MEAN_METHOD_H_INCLUDED
tensor_cpu-inl.h
/*! * Copyright (c) 2014 by Contributors * \file tensor_cpu-inl.h * \brief implementation of CPU host code * \author Bing Xu, Tianqi Chen */ #ifndef MSHADOW_TENSOR_CPU_INL_H_ #define MSHADOW_TENSOR_CPU_INL_H_ #include <cstring> #include "./base.h" #include "./tensor.h" #include "./packet-inl.h" #include "./dot_engine-inl.h" namespace mshadow { template<> inline void InitTensorEngine<cpu>(int dev_id) { } template<> inline void ShutdownTensorEngine<cpu>(void) { } template<> inline void SetDevice<cpu>(int devid) { } template<> inline Stream<cpu> *NewStream<cpu>(bool create_blas_handle, bool create_dnn_handle) { return new Stream<cpu>(); } template<> inline void DeleteStream<cpu>(Stream<cpu> *stream) { delete stream; } template<int ndim> inline std::ostream &operator<<(std::ostream &os, const Shape<ndim> &shape) { // NOLINT(*) os << '('; for (int i = 0; i < ndim; ++i) { if (i != 0) os << ','; os << shape[i]; } // python style tuple if (ndim == 1) os << ','; os << ')'; return os; } template<typename xpu> inline void *AllocHost_(size_t size); template<typename xpu> inline void FreeHost_(void * dptr); #ifdef __CUDACC__ template<> inline void *AllocHost_<gpu>(size_t size) { void *dptr; MSHADOW_CUDA_CALL(cudaMallocHost(&dptr, size, cudaHostAllocPortable)); return dptr; } template<> inline void FreeHost_<gpu>(void *dptr) { MSHADOW_CUDA_CALL(cudaFreeHost(dptr)); } #endif template<> inline void *AllocHost_<cpu>(size_t size) { size_t pitch; return packet::AlignedMallocPitch(&pitch, size, 1); } template<> inline void FreeHost_<cpu>(void *dptr) { packet::AlignedFree(dptr); } template<typename xpu, int dim, typename DType> inline void AllocHost(Tensor<cpu, dim, DType> *obj) { obj->stride_ = obj->size(dim - 1); CHECK_EQ(obj->CheckContiguous(), true) << "AllocHost"; void *dptr = AllocHost_<xpu>(obj->MSize() * sizeof(DType)); obj->dptr_ = reinterpret_cast<DType*>(dptr); } template<typename xpu, int dim, typename DType> inline void FreeHost(Tensor<cpu, dim, DType> *obj) { if (obj->dptr_ == NULL) { LOG(FATAL) << "FreeHost:: double free"; } FreeHost_<xpu>(obj->dptr_); obj->dptr_ = NULL; } template<int dim, typename DType> inline void AllocSpace(Tensor<cpu, dim, DType> *obj, bool pad) { size_t pitch; void *dptr; if (pad) { dptr = packet::AlignedMallocPitch (&pitch, obj->size(dim - 1) * sizeof(DType), obj->shape_.FlatTo2D()[0]); obj->stride_ = static_cast<index_t>(pitch / sizeof(DType)); } else { obj->stride_ = obj->size(dim - 1); dptr = packet::AlignedMallocPitch (&pitch, obj->shape_.Size() * sizeof(DType), 1); } obj->dptr_ = reinterpret_cast<DType*>(dptr); } template<typename Device, typename DType, int dim> inline Tensor<Device, dim, DType> NewTensor(const Shape<dim> &shape, DType initv, bool pad, Stream<Device> *stream_) { Tensor<Device, dim, DType> obj(shape); obj.stream_ = stream_; AllocSpace(&obj, pad); MapExp<sv::saveto>(&obj, expr::ScalarExp<DType>(initv)); return obj; } template<int dim, typename DType> inline void FreeSpace(Tensor<cpu, dim, DType> *obj) { packet::AlignedFree(obj->dptr_); obj->dptr_ = NULL; } template<int dim, typename DType> inline void Copy(Tensor<cpu, dim, DType> _dst, const Tensor<cpu, dim, DType> &_src, Stream<cpu> *stream) { CHECK_EQ(_dst.shape_, _src.shape_) << "Copy:shape mismatch:" << _dst.shape_ << " vs " << _src.shape_; if (_dst.CheckContiguous() && _src.CheckContiguous()) { memcpy(_dst.dptr_, _src.dptr_, sizeof(DType) * _dst.shape_.Size()); } else { Tensor<cpu, 2, DType> dst = _dst.FlatTo2D(); Tensor<cpu, 2, DType> src = _src.FlatTo2D(); for (index_t y = 0; y < dst.size(0); ++y) { memcpy(dst[y].dptr_, src[y].dptr_, sizeof(DType) * dst.size(1)); } } } template<typename Saver, typename R, int dim, typename DType, typename E> inline void MapPlan(TRValue<R, cpu, dim, DType> *dst, const expr::Plan<E, DType> &plan) { Shape<2> shape = expr::ShapeCheck<dim, R>::Check(dst->self()).FlatTo2D(); expr::Plan<R, DType> dplan = expr::MakePlan(dst->self()); // #pragma omp parallel for // temp remove openmp, as default setting throttles CPU for (index_t y = 0; y < shape[0]; ++y) { for (index_t x = 0; x < shape[1]; ++x) { // trust your compiler! -_- they will optimize it Saver::Save(dplan.REval(y, x), plan.Eval(y, x)); } } } // code to handle SSE optimization template<bool pass_check, typename Saver, typename R, int dim, typename DType, typename E, int etype> struct MapExpCPUEngine { inline static void Map(TRValue<R, cpu, dim, DType> *dst, const expr::Exp<E, DType, etype> &exp) { MapPlan<Saver>(dst, MakePlan(exp.self())); } }; template<typename SV, int dim, typename DType, typename E, int etype> struct MapExpCPUEngine<true, SV, Tensor<cpu, dim, DType>, dim, DType, E, etype> { inline static void Map(Tensor<cpu, dim, DType> *dst, const expr::Exp<E, DType, etype> &exp) { if (expr::PacketAlignCheck<dim, E, MSHADOW_DEFAULT_PACKET>::Check(exp.self()) && expr::PacketAlignCheck<dim, Tensor<cpu, dim, DType>, MSHADOW_DEFAULT_PACKET>::Check(*dst)) { expr::MapPacketPlan<SV>(dst->self(), expr::MakePacketPlan<MSHADOW_DEFAULT_PACKET>(exp.self())); } else { MapPlan<SV>(dst, MakePlan(exp.self())); } } }; template<typename Saver, typename R, int dim, typename DType, typename E, int etype> inline void MapExp(TRValue<R, cpu, dim, DType> *dst, const expr::Exp<E, DType, etype> &exp) { expr::TypeCheckPass<expr::TypeCheck<cpu, dim, DType, E>::kMapPass> ::Error_All_Tensor_in_Exp_Must_Have_Same_Type(); Shape<dim> eshape = expr::ShapeCheck<dim, E>::Check(exp.self()); Shape<dim> dshape = expr::ShapeCheck<dim, R>::Check(dst->self()); CHECK(eshape[0] == 0 || eshape == dshape) << "Assignment: Shape of Tensors are not consistent with target, " << "eshape: " << eshape << " dshape:" << dshape; MapExpCPUEngine<expr::PacketCheck<E, MSHADOW_DEFAULT_PACKET>::kPass, Saver, R, dim, DType, E, etype> ::Map(dst->ptrself(), exp); } template<typename Saver, typename Reducer, typename R, typename DType, typename E, int etype> inline void MapReduceKeepLowest(TRValue<R, cpu, 1, DType> *dst, const expr::Exp<E, DType, etype> &exp, DType scale) { expr::TypeCheckPass<expr::TypeCheck<cpu, 1, DType, E>::kRedPass> ::Error_TypeCheck_Not_Pass_For_Reduce_Exp(); Shape<2> eshape = expr::ShapeCheck<expr::ExpInfo<E>::kDim, E> ::Check(exp.self()).FlatTo2D(); Shape<1> dshape = expr::ShapeCheck<1, R>::Check(dst->self()); CHECK_EQ(eshape[1], dshape[0]) << "MapReduceKeepLowest::reduction dimension do not match"; CHECK_NE(eshape[0], 0) << "can not reduce over empty tensor"; // execution expr::Plan<R, DType> dplan = MakePlan(dst->self()); expr::Plan<E, DType> splan = MakePlan(exp.self()); for (index_t x = 0; x < eshape[1]; ++x) { DType res = splan.Eval(0, x); for (index_t y = 1; y < eshape[0]; ++y) { Reducer::Reduce(res, splan.Eval(y, x)); } Saver::Save(dplan.REval(0, x), res * scale); } } template<typename Saver, typename Reducer, int dimkeep, typename R, typename DType, typename E, int etype> inline void MapReduceKeepHighDim(TRValue<R, cpu, 1, DType> *dst, const expr::Exp<E, DType, etype> &exp, DType scale) { expr::TypeCheckPass<expr::TypeCheck<cpu, dimkeep, DType, E>::kRedPass> ::Error_TypeCheck_Not_Pass_For_Reduce_Exp(); typedef Shape<expr::ExpInfo<E>::kDim> EShape; EShape eshape = expr::ShapeCheck<expr::ExpInfo<E>::kDim, E> ::Check(exp.self()); Shape<1> dshape = expr::ShapeCheck<1, R>::Check(dst->self()); CHECK_EQ(eshape[dimkeep], dshape[0]) << "MapReduceKeepHighDim::reduction dimension do not match"; // use equvalent form Shape<4> pshape = Shape4(eshape.ProdShape(0, dimkeep), eshape[dimkeep], eshape.ProdShape(dimkeep + 1, EShape::kSubdim), eshape[EShape::kSubdim]); // execution expr::Plan<R, DType> dplan = MakePlan(dst->self()); expr::Plan<E, DType> splan = MakePlan(exp.self()); for (index_t c = 0; c < pshape[1]; ++c) { DType res; Reducer::SetInitValue(res); for (index_t n = 0; n < pshape[0]; ++n) { DType tres; Reducer::SetInitValue(tres); for (index_t y = 0; y < pshape[2]; ++y) { for (index_t x = 0; x < pshape[3]; ++x) { Reducer::Reduce(tres, splan.Eval((n * pshape[1] + c) * pshape[2] + y, x)); } } Reducer::Reduce(res, tres); } Saver::Save(dplan.REval(0, c), DType(res * scale)); } } template<typename DType> inline void Softmax(Tensor<cpu, 1, DType> dst, const Tensor<cpu, 1, DType> &energy) { DType mmax = energy[0]; for (index_t x = 1; x < dst.size(0); ++x) { if (mmax < energy[x]) mmax = energy[x]; } DType sum = DType(0.0f); for (index_t x = 0; x < dst.size(0); ++x) { dst[x] = std::exp(energy[x] - mmax); sum += dst[x]; } for (index_t x = 0; x < dst.size(0); ++x) { dst[x] /= sum; } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &src, const Tensor<cpu, 1, DType> &label) { for (index_t y = 0; y < dst.size(0); ++y) { const index_t k = static_cast<int>(label[y]); for (index_t x = 0; x < dst.size(1); ++x) { if (x == k) { dst[y][k] = src[y][k] - 1.0f; } else { dst[y][x] = src[y][x]; } } } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &src, const Tensor<cpu, 1, DType> &label, const DType &ignore_label) { for (index_t y = 0; y < dst.size(0); ++y) { const index_t k = static_cast<int>(label[y]); for (index_t x = 0; x < dst.size(1); ++x) { if (static_cast<int>(ignore_label) == k) { dst[y][x] = 0.0f; } else { if (x == k) { dst[y][k] = src[y][k] - 1.0f; } else { dst[y][x] = src[y][x]; } } } } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &src, const Tensor<cpu, 2, DType> &label) { for (index_t n = 0; n < dst.size(2); ++n) { for (index_t y = 0; y < dst.size(0); ++y) { const index_t k = static_cast<int>(label[y][n]); for (index_t x = 0; x < dst.size(1); ++x) { if (x == k) { dst[y][k][n] = src[y][k][n] - 1.0f; } else { dst[y][x][n] = src[y][x][n]; } } } } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &src, const Tensor<cpu, 2, DType> &label, const DType &ignore_label) { for (index_t n = 0; n < dst.size(2); ++n) { for (index_t y = 0; y < dst.size(0); ++y) { const index_t k = static_cast<int>(label[y][n]); if (k == static_cast<int>(ignore_label)) { for (index_t x = 0; x < dst.size(1); ++x) { dst[y][x][n] = DType(0.0f); } } else { for (index_t x = 0; x < dst.size(1); ++x) { if (x == k) { dst[y][k][n] = src[y][k][n] - 1.0f; } else { dst[y][x][n] = src[y][x][n]; } } } } } } template<typename DType> inline void Softmax(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &energy) { CHECK_EQ(dst.shape_, energy.shape_) << "Softmax: shape mismatch"; for (index_t y = 0; y < dst.size(0); ++y) { Softmax(dst[y], energy[y]); } } template<typename DType> inline void Softmax(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &energy) { CHECK_EQ(dst.shape_, energy.shape_) << "Softmax: shape mismatch"; for (index_t y = 0; y < dst.size(0); ++y) { for (index_t n = 0; n < dst.size(2); ++n) { DType mmax = energy[y][0][n]; for (index_t x = 1; x < dst.size(1); ++x) { if (mmax < energy[y][x][n]) mmax = energy[y][x][n]; } DType sum = DType(0.0f); for (index_t x = 0; x < dst.size(1); ++x) { dst[y][x][n] = std::exp(energy[y][x][n] - mmax); sum += dst[y][x][n]; } for (index_t x = 0; x < dst.size(1); ++x) { dst[y][x][n] /= sum; } } } } template<typename IndexType, typename DType> inline void AddTakeGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 1, IndexType>& index, const Tensor<cpu, 2, DType> &src) { for (index_t y = 0; y < index.size(0); ++y) { dst[index[y]] += src[y]; } } // blas related template<typename Device, typename DType> inline void VectorDot(Tensor<Device, 1, DType> dst, const Tensor<Device, 1, DType> &lhs, const Tensor<Device, 1, DType> &rhs) { CHECK_EQ(lhs.size(0), rhs.size(0)) << "VectorDot: Shape mismatch"; CHECK_EQ(dst.size(0), 1) << "VectorDot: expect dst to be scalar"; expr::BLASEngine<Device, DType>::SetStream(lhs.stream_); mshadow::expr::BLASEngine<Device, DType>::dot( lhs.stream_, lhs.size(0), lhs.dptr_, 1, rhs.dptr_, 1, dst.dptr_); } } // namespace mshadow #endif // MSHADOW_TENSOR_CPU_INL_H_
target-data-1.c
/* { dg-do compile } */ void foo (void) { int a[4] = { 1, 2, 3, 4 }; int *p = &a[0]; int x = 5; #pragma omp target data map(to:p[:4]) #pragma omp target data use_device_ptr(p) #pragma omp target is_device_ptr(p) { p[0]++; } #pragma omp target data map(to:a) #pragma omp target data use_device_addr(a) #pragma omp target is_device_ptr(a) { p[0]++; } #pragma omp target data map(to:x) #pragma omp target data use_device_addr(x) { int *q = &x; #pragma omp target is_device_ptr(q) { q[0]++; } } #pragma omp target data /* { dg-error "must contain at least one" } */ a[0]++; #pragma omp target data map(to:p) #pragma omp target data use_device_ptr(p) use_device_ptr(p) /* { dg-error "appears more than once in data clauses" } */ a[0]++; #pragma omp target data map(to:a) #pragma omp target data use_device_addr(a) use_device_addr(a) /* { dg-error "appears more than once in data clauses" } */ a[0]++; #pragma omp target data map(to:a) #pragma omp target data use_device_ptr(a) /* { dg-error "'use_device_ptr' variable is not a pointer" "" { target c } } */ /* { dg-error "'use_device_ptr' variable is neither a pointer nor reference to pointer" "" { target c++ } .-1 } */ a[0]++; /* { dg-error "must contain at least one" "" { target *-*-* } .-2 } */ }
cc_pool2d.c
#include <stdio.h> #include "cc_fmap2d.h" #include "cc_tsrmgr.h" #include "cc_pad2d.h" #include "cc_pool2d.h" #include "global_fn_cfg.h" extern fn_pool2d _max_pool2d; extern fn_pool2d _avg_pool2d; cc_ssize cc_pool2d_shape_calc( cc_ssize i, cc_ssize k, cc_ssize s, cc_ssize p) { return (cc_ssize)((i - k + 2 * p) / s) + 1; } cc_tensor_t *cc_pool2d(const cc_tensor_t *inp, cc_ssize k, cc_ssize s, cc_ssize p, cc_ssize off, fn_pool2d pool2d, const char *name) { cc_tensor_t *pool = NULL; const cc_tensor_t *inp_pad; cc_ssize i, i_ch_size, i_ch_mem_size, o_ch_size, o_ch_mem_size; cc_ssize shape[CC_CNN2D_SHAPE] = {0}; char pad_name[CC_TSR_NAME_LEN]; if (p) { sprintf(pad_name, "%s%s", inp->name, CC_POOL2D_PAD_NAME_SURFFIX); inp_pad = cc_pad2d(inp, p, off, pad_name); } else { inp_pad = inp; } #ifdef AUTO_TSRMGR pool = cc_tsrmgr_get(name); #endif if (!pool) { shape[CC_CNN2D_SHAPE_C] = inp_pad->shape[CC_CNN2D_SHAPE_C]; shape[CC_CNN2D_SHAPE_H] = cc_pool2d_shape_calc( inp_pad->shape[CC_CNN2D_SHAPE_H], k, s, p); shape[CC_CNN2D_SHAPE_W] = cc_pool2d_shape_calc( inp_pad->shape[CC_CNN2D_SHAPE_W], k, s, p); pool = cc_create(shape, *inp->dtype, name); } i_ch_size = inp_pad->shape[CC_CNN2D_SHAPE_H] * inp_pad->shape[CC_CNN2D_SHAPE_W]; i_ch_mem_size = i_ch_size * cc_dtype_size(*inp_pad->dtype); o_ch_size = pool->shape[CC_CNN2D_SHAPE_H] * pool->shape[CC_CNN2D_SHAPE_W]; o_ch_mem_size = o_ch_size * cc_dtype_size(*pool->dtype); #ifdef ENABLE_OPENMP #pragma omp parallel for private(i) #endif for (i = 0; i < inp_pad->shape[CC_CNN2D_SHAPE_C]; ++i) { pool2d(inp_pad->data + i_ch_mem_size * i, pool->data + o_ch_mem_size * i, inp_pad->shape[CC_CNN2D_SHAPE_W], inp_pad->shape[CC_CNN2D_SHAPE_H], s, s, k, *inp->dtype); } #ifndef AUTO_TSRMGR if (p) cc_free((cc_tensor_t*)inp_pad); #endif return pool; } cc_tensor_t *cc_max_pool2d(const cc_tensor_t *inp, cc_ssize k, cc_ssize s, cc_ssize p, cc_ssize off, const char *name) { return cc_pool2d(inp, k, s, p, off, _max_pool2d, name); } cc_tensor_t *cc_avg_pool2d(const cc_tensor_t *inp, cc_ssize k, cc_ssize s, cc_ssize p, cc_ssize off, const char *name) { return cc_pool2d(inp, k, s, p, off, _avg_pool2d, name); }
ops.c
#include <stdio.h> #include <stdlib.h> #include <string.h> /* #include "cuda_runtime_api.h" #include "cuda.h" #include "cublas_v2.h" */ #include "ops.h" #define SWAP(a,b) {float temp=0;temp=a;a=b;b=temp;} /*-----------general matrix summation-------*/ float gems(float *a, size_t size){ int i; float sum = 0; #pragma omp parallel for for(i = 0; i < size; i++){ sum += a[i]; } return sum; } /*----------general matrix additon--------*/ float* gema(float *a, float *b, size_t size){ float *data = (float*)calloc(size, sizeof(float)); int i; #pragma omp parallel for for(i = 0; i < size; i++) data[i] = a[i] + b[i]; return data; } /*-------matrix transpose------*/ void transpose(float *a, size_t r, size_t c) { /* Args: r: original rows c: original columns return: inplace transpose matrix a */ register float *temp = (float*)calloc(r*c, sizeof(float)); int i,j; for(i=0;i<r;i++){ for(j=0;j<c;j++){ temp[j*r + i] = a[i*c + j]; //printf("%ld: %f\n", j*r+i, temp[j*r + i]); } } memcpy(a, temp, r*c*sizeof(float)); free(temp); } /*-----------vector dot product-----------------*/ float gevdp(float *a, float *b, size_t size) { float data = 0; int i; #ifdef OPENMP size_t N = omp_get_max_threads(); //printf("maximum number of threads is: %ld\n", N); /* float *temp = (float*)calloc(N, sizeof(float)); #pragma omp parallel { int id = omp_get_thread_num(); #pragma omp parallel for for(i=id; i<size; i+=N){ temp[id] += a[i] * b[i]; } } for(i = 0; i < N; i++){ data += temp[i]; } */ float *temp = (float*)calloc(size, sizeof(float)); #pragma omp parallel { #pragma omp for for(i=0; i<size; i++){ temp[i] = a[i] * b[i]; } } for(i = 0; i < size; i++){ data += temp[i]; } return data; #endif for(i=0; i<size;i++){ data += a[i] * b[i]; } return data; } /*-----------general matrix added with constant value----------*/ void geac(float *a, size_t size, float b){ int i; #ifdef OPENMP #pragma omp parallel { #pragma omp for for(i = 0; i < size; i++){ a[i] += b; } } #else for(i = 0; i < size; i++){ a[i] += b; } //printf("this part is processed"); #endif } /*-----------general matrix multiplied with constant scalar------------*/ void gemc(float *a, size_t size, float scalar) { int i; #ifdef OPENMP #pragma omp parallel { #pragma omp for for(i = 0; i < size; i++){ a[i] *= scalar; } } #else for(i = 0; i < size; i++){ a[i] *= scalar; } #endif } /*-----------general matrix multiplicaton-------*/ void gemm(int TA, int TB, int M, int N, int K, float Alpha, float *A, int lda, float *B, int ldb, float Beta, float *C, int ldc){ /* C = Alpha * A * B + Beta * C Args: TA: A transpose or not TB: B transpose or not M: A.rows, C.rows N: B.columns, C.columns K: A.columns, B.rows Alpha: scalar Beta: scalar A: matrix in B: matrix in C: matrix out lda: leading dimension of matrix A ldb: leading dimension of matrix B ldc: leading dimension of matrix C */ if(Beta==0){ if(!TA&&TB){ gemm_nt(M,N,K,Alpha,A,lda,B,ldb,C,ldc); } } } void gemm_nt(int M, int N, int K, float Alpha, float *A, int lda, float *B, int ldb, float *C, int ldc){ int i,j,k; #pragma omp parallel for for(i = 0; i < M; ++i){ //rows of matrix A for(k = 0; k < K; ++k){ //inter dimension register float temp = Alpha * A[i*lda+k]; for(j = 0; j < N; ++j){ //columns of matrix B C[i*ldc+j] += temp * B[k*ldb+j]; } } } } void print_matrix(float *a, size_t r, size_t c){ int i,j; printf("\n-----------------------\n"); for(i=0;i<r;i++){ for(j=0;j<c;j++){ printf("%15.7f ",a[i*c+j]); } printf("\n-----------------------\n"); } } #ifdef GPU #include "cuda_runtime_api.h" #include "cuda.h" #include "cublas_v2.h" #include <math.h> void gemm_gpu(int TA, int TB, int M, int N, int K, float Alpha, float *A, int lda, float *B, int ldb, float Beta, float *C, int ldc) { //cublasHandle_t handle = blas_handle(); //print_matrix(A,M,K); //print_matrix(B,K,N); //printf("TA: %d, TB: %d, M: %d, N: %d, K: %d, Alpha: %f, Beta: %f",TA,TB,M,N,K,Alpha,Beta); /* cudaError_t status = cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N), (TA ? CUBLAS_OP_T : CUBLAS_OP_N),N,M,K,&Alpha,B,ldb,A,lda,&Beta,C,ldc); */ cublasHandle_t handle; cublasCreate(&handle); float *d_A, *d_B, *d_C; cudaMalloc(&d_A, sizeof(float)*M*K); cudaMalloc(&d_B, sizeof(float)*K*N); cudaMalloc(&d_C, sizeof(float)*M*N); cudaMemcpy(d_A,A,sizeof(float)*M*K,cudaMemcpyHostToDevice); cudaMemcpy(d_B,B,sizeof(float)*K*N,cudaMemcpyHostToDevice); cudaMemcpy(d_C,C,sizeof(float)*M*N,cudaMemcpyHostToDevice); //cudaMemcpy(C,d_C,sizeof(float)*9,cudaMemcpyDeviceToHost); //printf("matrix before gpu"); //print_matrix(C,M,N); cudaError_t status = cublasSgemm(handle, (TA ? CUBLAS_OP_T : CUBLAS_OP_N), (TB ? CUBLAS_OP_T : CUBLAS_OP_N), M,N,K,&Alpha, d_A,lda, d_B,ldb, &Beta, d_C,ldc); cudaMemcpy(C,d_C,sizeof(float)*M*N,cudaMemcpyDeviceToHost); //printf("matrix after gpu"); //print_matrix(C,M,N); } void mmul_gpu(int M, int N, int K, float *A, float *B, float *C) { cublasHandle_t handle; cublasCreate(&handle); float *d_A, *d_B, *d_C; cudaMalloc(&d_A, sizeof(float)*M*K); cudaMalloc(&d_B, sizeof(float)*K*N); cudaMalloc(&d_C, sizeof(float)*M*N); cudaMemcpy(d_A,A,sizeof(float)*M*K,cudaMemcpyHostToDevice); cudaMemcpy(d_B,B,sizeof(float)*K*N,cudaMemcpyHostToDevice); cudaMemcpy(d_C,C,sizeof(float)*M*N,cudaMemcpyHostToDevice); float Alpha = 1.f; float Beta = 0.f; cudaError_t status = cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, N,M,K,&Alpha, d_B,N, d_A,K, &Beta, d_C,N); cudaMemcpy(C,d_C,sizeof(float)*M*N,cudaMemcpyDeviceToHost); } /*--------------------matrix summation------------------*/ float gems_gpu(float *A, size_t size) { cublasHandle_t handle; cublasCreate(&handle); float *res = (float*)malloc(sizeof(float)); float *d_A; cudaMalloc(&d_A, sizeof(float)*size); cudaMemcpy(d_A,A,sizeof(float)*size,cudaMemcpyHostToDevice); int incx = 1; cudaError_t status = cublasSasum(handle, size, d_A, incx, res); return res[0]; } /*-----------------matrix addition------------------*/ void gema_gpu(float *A, float *B, float *C, size_t N) { cublasHandle_t handle; cublasCreate(&handle); memcpy(C,B,N * sizeof(float)); float *d_A, *d_C; cudaMalloc(&d_A, sizeof(float)*N); cudaMalloc(&d_C, sizeof(float)*N); cudaMemcpy(d_A,A,sizeof(float)*N, cudaMemcpyHostToDevice); cudaMemcpy(d_C,C,sizeof(float)*N, cudaMemcpyHostToDevice); float alpha = 1.0; cublasSaxpy_v2(handle, N, &alpha, d_A, 1, d_C, 1); //vector addition cudaMemcpy(C,d_C,sizeof(float)*N, cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_C); cublasDestroy(handle); } /*-----------------matrix transpose----------------*/ void transpose_gpu(float *a, size_t r, size_t c) { cublasHandle_t handle; cublasCreate(&handle); float const alpha = 1.f; float const beta = 0.f; float *d_A, *d_B; cudaMemcpy(d_A,a,sizeof(float)*r*c,cudaMemcpyHostToDevice); cudaMemcpy(d_B,a,sizeof(float)*r*c,cudaMemcpyHostToDevice); cublasSgeam( handle, CUBLAS_OP_T, CUBLAS_OP_N, r, c, &alpha, d_A, c, &beta, d_B, r, d_B, r ); cudaMemcpy(a,d_A,sizeof(float)*r*c,cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_B); cublasDestroy(handle); } /*-----------------vector dot product---------------*/ float gevdp_gpu(float *a, float *b, size_t size) { cublasHandle_t handle; cublasCreate(&handle); float *d_A, *d_B; cudaMalloc(&d_A, sizeof(float)*size); cudaMalloc(&d_B, sizeof(float)*size); cudaMemcpy(d_A,a,sizeof(float)*size,cudaMemcpyHostToDevice); cudaMemcpy(d_B,b,sizeof(float)*size,cudaMemcpyHostToDevice); float result; cublasSdot(handle, size, d_A, 1, d_B, 1, &result); cudaDeviceSynchronize(); cudaFree(d_A); cudaFree(d_B); cublasDestroy(handle); printf("current result value is: %.5f\n",result); return result; } /*---------matrix added with constant value-----------*/ void geac_gpu(float *a, size_t size, float b) { cublasHandle_t handle; cublasCreate(&handle); float *d_A; cudaMalloc(&d_A, sizeof(float)*size); cudaMemcpy(d_A,a,sizeof(float)*size,cudaMemcpyHostToDevice); //generating unit vector const unsigned int one_bits = 1; //const int* one_bits = reinterpret_cast<const int*>(&one); //cudaMemset(d_I, 0x12, size); unsigned int pBuffer; cuMemAlloc(&pBuffer, sizeof(unsigned int) * size); cuMemsetD32(pBuffer, 1, size); int *d_I; cudaMalloc(&d_I, sizeof(int)*size); int *I = (int*)malloc(size*sizeof(int)); cudaMemcpy(I, pBuffer, sizeof(int)*size,cudaMemcpyDeviceToHost); print_matrix(I,1,size); cuMemsetD32(d_I,0x1,size); cudaMemcpy(I,d_I,sizeof(float)*size,cudaMemcpyDeviceToHost); printf("unit vector is: \n"); print_matrix(I,1,size); printf("////////////////////////////////\n"); cublasSaxpy(handle, size, &b, d_I, 1, d_A, 1); cudaMemcpy(a,d_A,size*sizeof(float),cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_I); cublasDestroy(handle); } void gemc_gpu(float *a, size_t size, float scalar) { /* overwrite value to d_zeros instead of a */ cublasHandle_t handle; cublasCreate(&handle); float *d_A; cudaMalloc(&d_A, sizeof(float)*size); cudaMemcpy(d_A,a,sizeof(float)*size,cudaMemcpyHostToDevice); float *zeros = (float*)calloc(size, sizeof(float)); float *d_zeros; cudaMalloc(&d_zeros, size * sizeof(float)); cudaMemcpy(d_zeros,zeros, size * sizeof(float), cudaMemcpyHostToDevice); cublasSaxpy(handle, size, &scalar, d_A, 1, d_zeros,1); cudaDeviceSynchronize(); cudaMemcpy(a, d_zeros, size * sizeof(float), cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_zeros); cublasDestroy(handle); } #endif #ifdef NEON #include <arm_neon.h> float gems_arm(float *arr, size_t size){ if(arr == NULL || size < 1) { // printf("input error\n"); return 0; } int dim4 = size >> 2; // size//4 int left4 = size & 3; // size & 4 1000(8) & 0011(3) = 0001(1) float32x4_t sum_vec = vdupq_n_f32(0.f); //initialize accumulative register for temporarily store for(; dim4 > 0; dim4--, arr+=4) { float32x4_t data_vec = vld1q_f32(arr); //temporarily store 4 elements into data_vec sum_vec = vaddq_f32(sum_vec, data_vec); //sum_vec = sum_vec + data_vec } //put all elements inside sum_vec register into final value float sum = vgetq_lane_f32(sum_vec, 0) + vgetq_lane_f32(sum_vec, 1) + vgetq_lane_f32(sum_vec, 2) + vgetq_lane_f32(sum_vec, 3); for(; left4>0; left4--, arr++) sum += (*arr); return sum; } float gevdp_arm(float *a, float *b, size_t size) { if(a == NULL || b == NULL || size < 1) { return 0; } int dim4 = size>>2; // size//4 int left4 = size & 3; // size %4 float32x4_t sum_vec = vdupq_n_f32(0.f); //initialize accumulative register for temporarily store float32x4_t a_vec, b_vec; //store every four float number in these two registers for a and b for(; dim4 > 0; dim4--, a+=4, b+=4) { a_vec = vld1q_f32(a); //temporarily store 4 elements into data_vec b_vec = vld1q_f32(b); sum_vec = vmlaq_f32(sum_vec, a_vec, b_vec); //sum_vec = sum_vec + a_vec * b_vec } //put all elements inside sum_vec register into final value //printf("current first output is: %.5f",vgetq_lane_f32(sum_vec, 0)); float sum = vgetq_lane_f32(sum_vec, 0) + vgetq_lane_f32(sum_vec, 1) + vgetq_lane_f32(sum_vec, 2) + vgetq_lane_f32(sum_vec, 3); for(; left4>0; left4--, a++, b++) sum += ((*a)*(*b)); return sum; } float* gema_arm(float *a, float *b, size_t size){ if(a == NULL || b == NULL || size < 1) { printf("input error"); return 0; } int dim4 = size >> 2; // size//4 int left4 = size & 3; // size & 4 1000(8) & 0011(3) = 0001(1) float *res = (float*)malloc(size*sizeof(float)); float32x4_t sum_vec = vdupq_n_f32(0.f); //initialize accumulative register for temporarily store float32x4_t a_vec, b_vec; for(int i = 0; i+4 <= size; i+=4, a+=4, b+=4) { a_vec = vld1q_f32(a); //temporarily store 4 elements into data_vec b_vec = vld1q_f32(b); sum_vec = vaddq_f32(a_vec,b_vec); res[i] = vgetq_lane_f32(sum_vec, 0); res[i+1] = vgetq_lane_f32(sum_vec, 1); res[i+2] = vgetq_lane_f32(sum_vec, 2); res[i+3] = vgetq_lane_f32(sum_vec, 3); } for(; left4>0; left4--, a++, b++) res[size-left4] = *a + *b; return res; } void transpose_arm(float *a, size_t r, size_t c){ /* Args: r: original rows c: original columns return: inplace transpose matrix a */ register float *temp = (float*)calloc(r*c, sizeof(float)); int i,j; for(i=0;i<r;i++){ for(j=0;j<c;j++){ temp[j*r + i] = a[i*c + j]; //printf("%ld: %f\n", j*r+i, temp[j*r + i]); } } memcpy(a, temp, r*c*sizeof(float)); free(temp); } void geac_arm(float *a, size_t size, float b){ if(a == NULL || size < 1) { return; } int dim4 = size>>2; // size//4 int left4 = size & 3; // size %4 float32x4_t bias_vec = vdupq_n_f32(b); float32x4_t temp_vec; for(; dim4 > 0; dim4--, a+=4) { temp_vec = vld1q_f32(a); temp_vec = vaddq_f32(temp_vec, bias_vec); vst1q_f32(a, temp_vec); } for(; left4>0; left4--,a++) *a = b+(*a); } void gemc_arm(float *a, size_t size, float scalar){ if(a == NULL || size < 1) { return; } int dim4 = size>>2; // size//4 int left4 = size & 3; // size %4 float32x4_t scalar_vec = vdupq_n_f32(scalar); float32x4_t temp_vec; for(; dim4 > 0; dim4--, a+=4) { temp_vec = vld1q_f32(a); temp_vec = vmulq_f32(temp_vec, scalar_vec); vst1q_f32(a, temp_vec); } for(; left4>0; left4--,a++) *a = scalar*(*a); } #endif
zpbtrs.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_pbtrs * * Solves a system of linear equations A * X = B with a Hermitian positive definite * matrix A using the Cholesky factorization of A (i.e., A = L*L^T or A = U^T*U) * computed by plasma_zpbtrf. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in] kd * The number of suuperdiagonals within the band of A if uplo is upper, * or the number of suuperdiagonals if uplo is lower. kd >= 0. * * @param[in] nrhs * The number of right hand sides, i.e., the number of * columns of the matrix B. nrhs >= 0. * * @param[in,out] AB * The triangular factor U or L from the Cholesky * factorization A = U^H*U or A = L*L^H, computed by * plasma_zpotrf. * Remark: If out-of-place layout translation is used, the * matrix A can be considered as input, however if inplace * layout translation is enabled, the content of A will be * reordered for computation and restored before exiting the * function. * * @param[in] ldab * The leading dimension of the array AB. * * @param[in,out] B * On entry, the n-by-nrhs right hand side matrix B. * On exit, if return value = 0, the n-by-nrhs solution matrix X. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,n). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************* * * @sa plasma_omp_zpbtrs * @sa plasma_cpbtrs * @sa plasma_dpbtrs * @sa plasma_spbtrs * @sa plasma_zpbtrf * ******************************************************************************/ int plasma_zpbtrs(plasma_enum_t uplo, int n, int kd, int nrhs, plasma_complex64_t *pAB, int ldab, plasma_complex64_t *pB, int ldb) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); return -1; } if (n < 0) { plasma_error("illegal value of n"); return -2; } if (kd < 0) { plasma_error("illegal value of kd"); return -4; } if (nrhs < 0) { plasma_error("illegal value of nrhs"); return -5; } if (ldab < imax(1, 1+kd)) { plasma_error("illegal value of ldab"); return -7; } if (ldb < imax(1, n)) { plasma_error("illegal value of ldb"); return -10; } // quick return if (imax(n, nrhs) == 0) return PlasmaSuccess; // Set tiling parameters. int nb = plasma->nb; // Initialize tile matrix descriptors. int lm = nb*(1+(kd+nb-1)/nb); plasma_desc_t AB; plasma_desc_t B; int retval; retval = plasma_desc_general_band_create(PlasmaComplexDouble, uplo, nb, nb, lm, n, 0, 0, n, n, kd, kd, &AB); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_band_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, n, nrhs, 0, 0, n, nrhs, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&AB); return retval; } // Create sequence. plasma_sequence_t *sequence = NULL; retval = plasma_sequence_create(&sequence); if (retval != PlasmaSuccess) { plasma_error("plasma_sequence_create() failed"); return retval; } // Initialize request. plasma_request_t request = PlasmaRequestInitializer; // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zpb2desc(pAB, ldab, AB, sequence, &request); plasma_omp_zge2desc(pB, ldb, B, sequence, &request); // Call the tile async function. plasma_omp_zpbtrs(uplo, AB, B, sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(B, pB, ldb, sequence, &request); } // implicit synchronization // Free matrix A in tile layout. plasma_desc_destroy(&AB); plasma_desc_destroy(&B); // Return status. int status = sequence->status; plasma_sequence_destroy(sequence); return status; } /***************************************************************************//** * * @ingroup plasma_pbtrs * * Solves a system of linear equations using previously * computed Cholesky factorization. * Non-blocking tile version of plasma_zpbtrs(). * May return before the computation is finished. * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] AB * The triangular factor U or L from the Cholesky factorization * A = U^H*U or A = L*L^H, computed by plasma_zpotrf. * * @param[in,out] B * On entry, the n-by-nrhs right hand side matrix B. * On exit, if return value = 0, the n-by-nrhs solution matrix X. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zpbtrs * @sa plasma_omp_zpbtrs * @sa plasma_omp_cpbtrs * @sa plasma_omp_dpbtrs * @sa plasma_omp_spbtrs * @sa plasma_omp_zpbtrf * ******************************************************************************/ void plasma_omp_zpbtrs(plasma_enum_t uplo, plasma_desc_t AB, plasma_desc_t B, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(AB) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_fatal_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_fatal_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (AB.n == 0 || B.n == 0) return; // Call the parallel functions. plasma_pztbsm(PlasmaLeft, uplo, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans, PlasmaNonUnit, 1.0, AB, B, NULL, sequence, request); plasma_pztbsm(PlasmaLeft, uplo, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans, PlasmaNonUnit, 1.0, AB, B, NULL, sequence, request); }
hci.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Alexander Sokolov <alexander.y.sokolov@gmail.com> * * Slater-Condon rule implementation for Heat-Bath CI */ #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include "hci.h" //#include <omp.h> #include <limits.h> // Computes C' = H * C in the selected CI basis void contract_h_c(double *h1, double *eri, int norb, int neleca, int nelecb, uint64_t *strs, double *civec, double *hdiag, uint64_t ndet, double *ci1) { int *ts = malloc(sizeof(int) * ndet); #pragma omp parallel { size_t ip, jp, p; int nset = (norb + 63) / 64; // Calculate excitation level for prescreening ts[0] = 0; uint64_t *str1a = strs; uint64_t *str1b = strs + nset; #pragma omp for schedule(static) for (ip = 1; ip < ndet; ++ip) { uint64_t *stria = strs + ip * 2 * nset; uint64_t *strib = strs + ip * 2 * nset + nset; ts[ip] = (n_excitations(stria, str1a, nset) + n_excitations(strib, str1b, nset)); } // Loop over pairs of determinants #pragma omp for schedule(static) for (ip = 0; ip < ndet; ++ip) { for (jp = 0; jp < ndet; ++jp) { if (abs(ts[ip] - ts[jp]) < 3) { uint64_t *stria = strs + ip * 2 * nset; uint64_t *strib = strs + ip * 2 * nset + nset; uint64_t *strja = strs + jp * 2 * nset; uint64_t *strjb = strs + jp * 2 * nset + nset; int n_excit_a = n_excitations(stria, strja, nset); int n_excit_b = n_excitations(strib, strjb, nset); // Diagonal term if (ip == jp) { ci1[ip] += hdiag[ip] * civec[ip]; } // Single excitation else if ((n_excit_a + n_excit_b) == 1) { int *ia; // alpha->alpha if (n_excit_b == 0) { ia = get_single_excitation(stria, strja, nset); int i = ia[0]; int a = ia[1]; double sign = compute_cre_des_sign(a, i, stria, nset); int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); double fai = h1[a * norb + i]; for (p = 0; p < neleca; ++p) { int k = occsa[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; int kiak = k * norb * norb * norb + i * norb * norb + a * norb + k; fai += eri[kkai] - eri[kiak]; } for (p = 0; p < nelecb; ++p) { int k = occsb[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; fai += eri[kkai]; } if (fabs(fai) > 1.0E-14) ci1[ip] += sign * fai * civec[jp]; free(occsa); free(occsb); } // beta->beta else if (n_excit_a == 0) { ia = get_single_excitation(strib, strjb, nset); int i = ia[0]; int a = ia[1]; double sign = compute_cre_des_sign(a, i, strib, nset); int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); double fai = h1[a * norb + i]; for (p = 0; p < nelecb; ++p) { int k = occsb[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; int kiak = k * norb * norb * norb + i * norb * norb + a * norb + k; fai += eri[kkai] - eri[kiak]; } for (p = 0; p < neleca; ++p) { int k = occsa[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; fai += eri[kkai]; } if (fabs(fai) > 1.0E-14) ci1[ip] += sign * fai * civec[jp]; free(occsa); free(occsb); } free(ia); } // Double excitation else if ((n_excit_a + n_excit_b) == 2) { int i, j, a, b; // alpha,alpha->alpha,alpha if (n_excit_b == 0) { int *ijab = get_double_excitation(stria, strja, nset); i = ijab[0]; j = ijab[1]; a = ijab[2]; b = ijab[3]; double v, sign; int ajbi = a * norb * norb * norb + j * norb * norb + b * norb + i; int aibj = a * norb * norb * norb + i * norb * norb + b * norb + j; if (a > j || i > b) { v = eri[ajbi] - eri[aibj]; sign = compute_cre_des_sign(b, i, stria, nset); sign *= compute_cre_des_sign(a, j, stria, nset); } else { v = eri[aibj] - eri[ajbi]; sign = compute_cre_des_sign(b, j, stria, nset); sign *= compute_cre_des_sign(a, i, stria, nset); } if (fabs(v) > 1.0E-14) ci1[ip] += sign * v * civec[jp]; free(ijab); } // beta,beta->beta,beta else if (n_excit_a == 0) { int *ijab = get_double_excitation(strib, strjb, nset); i = ijab[0]; j = ijab[1]; a = ijab[2]; b = ijab[3]; double v, sign; int ajbi = a * norb * norb * norb + j * norb * norb + b * norb + i; int aibj = a * norb * norb * norb + i * norb * norb + b * norb + j; if (a > j || i > b) { v = eri[ajbi] - eri[aibj]; sign = compute_cre_des_sign(b, i, strib, nset); sign *= compute_cre_des_sign(a, j, strib, nset); } else { v = eri[aibj] - eri[ajbi]; sign = compute_cre_des_sign(b, j, strib, nset); sign *= compute_cre_des_sign(a, i, strib, nset); } if (fabs(v) > 1.0E-14) ci1[ip] += sign * v * civec[jp]; free(ijab); } // alpha,beta->alpha,beta else { int *ia = get_single_excitation(stria, strja, nset); int *jb = get_single_excitation(strib, strjb, nset); i = ia[0]; a = ia[1]; j = jb[0]; b = jb[1]; double v = eri[a * norb * norb * norb + i * norb * norb + b * norb + j]; double sign = compute_cre_des_sign(a, i, stria, nset); sign *= compute_cre_des_sign(b, j, strib, nset); if (fabs(v) > 1.0E-14) ci1[ip] += sign * v * civec[jp]; free(ia); free(jb); } } } // end if over ts } // end loop over jp } // end loop over ip } // end omp free(ts); } // Compare two strings and compute excitation level int n_excitations(uint64_t *str1, uint64_t *str2, int nset) { size_t p; int d = 0; for (p = 0; p < nset; ++p) { d += popcount(str1[p] ^ str2[p]); } return d / 2; } // Compute number of set bits in a string int popcount(uint64_t x) { const uint64_t m1 = 0x5555555555555555; //binary: 0101... const uint64_t m2 = 0x3333333333333333; //binary: 00110011.. const uint64_t m4 = 0x0f0f0f0f0f0f0f0f; //binary: 4 zeros, 4 ones ... const uint64_t m8 = 0x00ff00ff00ff00ff; //binary: 8 zeros, 8 ones ... const uint64_t m16 = 0x0000ffff0000ffff; //binary: 16 zeros, 16 ones ... const uint64_t m32 = 0x00000000ffffffff; //binary: 32 zeros, 32 ones x = (x & m1 ) + ((x >> 1) & m1 ); //put count of each 2 bits into those 2 bits x = (x & m2 ) + ((x >> 2) & m2 ); //put count of each 4 bits into those 4 bits x = (x & m4 ) + ((x >> 4) & m4 ); //put count of each 8 bits into those 8 bits x = (x & m8 ) + ((x >> 8) & m8 ); //put count of each 16 bits into those 16 bits x = (x & m16) + ((x >> 16) & m16); //put count of each 32 bits into those 32 bits x = (x & m32) + ((x >> 32) & m32); //put count of each 64 bits into those 64 bits return x; } // Compute orbital indices for a single excitation int *get_single_excitation(uint64_t *str1, uint64_t *str2, int nset) { size_t p; int *ia = malloc(sizeof(int) * 2); for (p = 0; p < nset; ++p) { size_t pp = nset - p - 1; uint64_t str_tmp = str1[pp] ^ str2[pp]; uint64_t str_particle = str_tmp & str2[pp]; uint64_t str_hole = str_tmp & str1[pp]; if (popcount(str_particle) == 1) { ia[1] = trailz(str_particle) + 64 * p; } if (popcount(str_hole) == 1) { ia[0] = trailz(str_hole) + 64 * p; } } return ia; } // Compute orbital indices for a double excitation int *get_double_excitation(uint64_t *str1, uint64_t *str2, int nset) { size_t p; int *ijab = malloc(sizeof(int) * 4); int particle_ind = 2; int hole_ind = 0; for (p = 0; p < nset; ++p) { size_t pp = nset - p - 1; uint64_t str_tmp = str1[pp] ^ str2[pp]; uint64_t str_particle = str_tmp & str2[pp]; uint64_t str_hole = str_tmp & str1[pp]; int n_particle = popcount(str_particle); int n_hole = popcount(str_hole); if (n_particle == 1) { ijab[particle_ind] = trailz(str_particle) + 64 * p; particle_ind++; } else if (n_particle == 2) { int a = trailz(str_particle); ijab[2] = a + 64 * p; str_particle &= ~(1ULL << a); int b = trailz(str_particle); ijab[3] = b + 64 * p; } if (n_hole == 1) { ijab[hole_ind] = trailz(str_hole) + 64 * p; hole_ind++; } else if (n_hole == 2) { int i = trailz(str_hole); ijab[0] = i + 64 * p; str_hole &= ~(1ULL << i); int j = trailz(str_hole); ijab[1] = j + 64 * p; } } return ijab; } // Compute number of trailing zeros in a bit string int trailz(uint64_t v) { int c = 64; // Trick to unset all bits but the first one v &= -(int64_t) v; if (v) c--; if (v & 0x00000000ffffffff) c -= 32; if (v & 0x0000ffff0000ffff) c -= 16; if (v & 0x00ff00ff00ff00ff) c -= 8; if (v & 0x0f0f0f0f0f0f0f0f) c -= 4; if (v & 0x3333333333333333) c -= 2; if (v & 0x5555555555555555) c -= 1; return c; } // Function to print int as a char for debug purposes char *int2bin(uint64_t i) { size_t bits = sizeof(uint64_t) * CHAR_BIT; char * str = malloc(bits + 1); if(!str) return NULL; str[bits] = 0; // type punning because signed shift is implementation-defined uint64_t u = *(uint64_t *)&i; for(; bits--; u >>= 1) str[bits] = u & 1 ? '1' : '0'; return str; } // Compute sign for a pair of creation and desctruction operators double compute_cre_des_sign(int p, int q, uint64_t *str, int nset) { double sign; int nperm; size_t i; int pg = p / 64; int qg = q / 64; int pb = p % 64; int qb = q % 64; if (pg > qg) { nperm = 0; for (i = nset-pg; i < nset-qg-1; ++i) { nperm += popcount(str[i]); } nperm += popcount(str[nset -1 - pg] & ((1ULL << pb) - 1)); nperm += str[nset -1 - qg] >> (qb + 1); } else if (pg < qg) { nperm = 0; for (i = nset-qg; i < nset-pg-1; ++i) { nperm += popcount(str[i]); } nperm += popcount(str[nset -1 - qg] & ((1ULL << qb) - 1)); nperm += str[nset -1 - pg] >> (pb + 1); } else { uint64_t mask; if (p > q) mask = (1ULL << pb) - (1ULL << (qb + 1)); else mask = (1ULL << qb) - (1ULL << (pb + 1)); nperm = popcount(str[nset -1 - pg] & mask); } if (nperm % 2) sign = -1.0; else sign = 1.0; return sign; } // Compute a list of occupied orbitals for a given string int *compute_occ_list(uint64_t *string, int nset, int norb, int nelec) { size_t k, i; int *occ = malloc(sizeof(int) * nelec); int off = 0; int occ_ind = 0; for (k = nset; k > 0; --k) { int i_max = ((norb - off) < 64 ? (norb - off) : 64); for (i = 0; i < i_max; ++i) { int i_occ = (string[k-1] >> i) & 1; if (i_occ) { occ[occ_ind] = i + off; occ_ind++; } } off += 64; } return occ; } // Compute a list of occupied orbitals for a given string int *compute_vir_list(uint64_t *string, int nset, int norb, int nelec) { size_t k, i; int *vir = malloc(sizeof(int) * (norb-nelec)); int off = 0; int vir_ind = 0; for (k = nset; k > 0; --k) { int i_max = ((norb - off) < 64 ? (norb - off) : 64); for (i = 0; i < i_max; ++i) { int i_occ = (string[k-1] >> i) & 1; if (!i_occ) { vir[vir_ind] = i + off; vir_ind++; } } off += 64; } return vir; } // Select determinants to include in the CI space void select_strs(double *h1, double *eri, double *jk, uint64_t *eri_sorted, uint64_t *jk_sorted, int norb, int neleca, int nelecb, uint64_t *strs, double *civec, uint64_t ndet_start, uint64_t ndet_finish, double select_cutoff, uint64_t *strs_add, uint64_t* strs_add_size) { size_t p, q, r, i, k, a, ip, jp, kp, lp, ij, iset, idet; uint64_t max_strs_add = strs_add_size[0]; int nset = (norb + 63) / 64; // Compute Fock intermediates double *focka = malloc(sizeof(double) * norb * norb); double *fockb = malloc(sizeof(double) * norb * norb); for (p = 0; p < norb; ++p) { for (q = 0; q < norb; ++q) { double vja = 0.0; double vka = 0.0; for (i = 0; i < neleca; ++i) { size_t iipq = i * norb * norb * norb + i * norb * norb + p * norb + q; size_t piiq = p * norb * norb * norb + i * norb * norb + i * norb + q; vja += eri[iipq]; vka += eri[piiq]; } double vjb = 0.0; double vkb = 0.0; for (i = 0; i < nelecb; ++i) { size_t iipq = i * norb * norb * norb + i * norb * norb + p * norb + q; size_t piiq = p * norb * norb * norb + i * norb * norb + i * norb + q; vjb += eri[iipq]; vkb += eri[piiq]; } focka[p * norb + q] = h1[p * norb + q] + vja + vjb - vka; fockb[p * norb + q] = h1[p * norb + q] + vja + vjb - vkb; } } int *holes_a = malloc(sizeof(int) * norb); int *holes_b = malloc(sizeof(int) * norb); int *particles_a = malloc(sizeof(int) * norb); int *particles_b = malloc(sizeof(int) * norb); uint64_t strs_added = 0; // Loop over determinants for (idet = ndet_start; idet < ndet_finish; ++idet) { uint64_t *stra = strs + idet * 2 * nset; uint64_t *strb = strs + idet * 2 * nset + nset; int *occsa = compute_occ_list(stra, nset, norb, neleca); int *occsb = compute_occ_list(strb, nset, norb, nelecb); int *virsa = compute_vir_list(stra, nset, norb, neleca); int *virsb = compute_vir_list(strb, nset, norb, nelecb); double tol = select_cutoff / fabs(civec[idet]); // Single excitations int n_holes_a = 0; int n_holes_b = 0; int n_particles_a = 0; int n_particles_b = 0; for (p = 0; p < (norb - neleca); ++p) { i = virsa[p]; if (i < neleca) { holes_a[n_holes_a] = i; n_holes_a++; } } for (p = 0; p < neleca; ++p) { i = occsa[p]; if (i >= neleca) { particles_a[n_particles_a] = i; n_particles_a++; } } for (p = 0; p < (norb - nelecb); ++p) { i = virsb[p]; if (i < nelecb) { holes_b[n_holes_b] = i; n_holes_b++; } } for (p = 0; p < nelecb; ++p) { i = occsb[p]; if (i >= nelecb) { particles_b[n_particles_b] = i; n_particles_b++; } } // TODO: recompute Fock for each |Phi_I> and make sure it matches Fock in the code below // alpha->alpha for (p = 0; p < neleca; ++p) { i = occsa[p]; for (q = 0; q < (norb - neleca); ++q) { a = virsa[q]; double fai = focka[a * norb + i]; for (r = 0; r < n_particles_a; ++r) { k = particles_a[r]; fai += jk[k * norb * norb * norb + k * norb * norb + a * norb + i]; } for (r = 0; r < n_holes_a; ++r) { k = holes_a[r]; fai -= jk[k * norb * norb * norb + k * norb * norb + a * norb + i]; } for (r = 0; r < n_particles_b; ++r) { k = particles_b[r]; fai += eri[k * norb * norb * norb + k * norb * norb + a * norb + i]; } for (r = 0; r < n_holes_b; ++r) { k = holes_b[r]; fai -= eri[k * norb * norb * norb + k * norb * norb + a * norb + i]; } if (fabs(fai) > tol) { uint64_t *tmp = toggle_bit(stra, nset, a); uint64_t *new_str = toggle_bit(tmp, nset, i); for (iset = 0; iset < nset; ++iset) { // new alpha string strs_add[strs_added * 2 * nset + iset] = new_str[iset]; // old beta string strs_add[strs_added * 2 * nset + nset + iset] = strb[iset]; } free(tmp); free(new_str); strs_added++; } } } // beta->beta for (p = 0; p < nelecb; ++p) { i = occsb[p]; for (q = 0; q < (norb - nelecb); ++q) { a = virsb[q]; double fai = fockb[a * norb + i]; for (r = 0; r < n_particles_b; ++r) { k = particles_b[r]; fai += jk[k * norb * norb * norb + k * norb * norb + a * norb + i]; } for (r = 0; r < n_holes_b; ++r) { k = holes_b[r]; fai -= jk[k * norb * norb * norb + k * norb * norb + a * norb + i]; } for (r = 0; r < n_particles_a; ++r) { k = particles_a[r]; fai += eri[k * norb * norb * norb + k * norb * norb + a * norb + i]; } for (r = 0; r < n_holes_a; ++r) { k = holes_a[r]; fai -= eri[k * norb * norb * norb + k * norb * norb + a * norb + i]; } if (fabs(fai) > tol) { uint64_t *tmp = toggle_bit(strb, nset, a); uint64_t *new_str = toggle_bit(tmp, nset, i); for (iset = 0; iset < nset; ++iset) { // old alpha string strs_add[strs_added * 2 * nset + iset] = stra[iset]; // new beta string strs_add[strs_added * 2 * nset + nset + iset] = new_str[iset]; } free(tmp); free(new_str); strs_added++; } } } size_t ip_occ, jp_occ, kp_occ, lp_occ, ih; // Double excitations for (p = 0; p < norb * norb * norb * norb; ++p) { ih = jk_sorted[p]; int aaaa_bbbb_done = (fabs(jk[ih]) < tol); if (!aaaa_bbbb_done) { lp = ih % norb; ij = ih / norb; kp = ij % norb; ij = ij / norb; jp = ij % norb; ip = ij / norb; // alpha,alpha->alpha,alpha ip_occ = 0; jp_occ = 0; kp_occ = 0; lp_occ = 0; for (r = 0; r < neleca; ++r) { int occ_index = occsa[r]; if (ip == occ_index) ip_occ = 1; if (jp == occ_index) jp_occ = 1; if (kp == occ_index) kp_occ = 1; if (lp == occ_index) lp_occ = 1; } if (jp_occ && lp_occ && !ip_occ && !kp_occ) { uint64_t *tmp = toggle_bit(stra, nset, jp); uint64_t *new_str = toggle_bit(tmp, nset, ip); tmp = toggle_bit(new_str, nset, lp); new_str = toggle_bit(tmp, nset, kp); for (iset = 0; iset < nset; ++iset) { strs_add[strs_added * 2 * nset + iset] = new_str[iset]; strs_add[strs_added * 2 * nset + nset + iset] = strb[iset]; } free(tmp); free(new_str); strs_added++; } // beta,beta->beta,beta ip_occ = 0; jp_occ = 0; kp_occ = 0; lp_occ = 0; for (r = 0; r < nelecb; ++r) { int occ_index = occsb[r]; if (ip == occ_index) ip_occ = 1; if (jp == occ_index) jp_occ = 1; if (kp == occ_index) kp_occ = 1; if (lp == occ_index) lp_occ = 1; } if (jp_occ && lp_occ && !ip_occ && !kp_occ) { uint64_t *tmp = toggle_bit(strb, nset, jp); uint64_t *new_str = toggle_bit(tmp, nset, ip); tmp = toggle_bit(new_str, nset, lp); new_str = toggle_bit(tmp, nset, kp); for (iset = 0; iset < nset; ++iset) { strs_add[strs_added * 2 * nset + iset] = stra[iset]; strs_add[strs_added * 2 * nset + nset + iset] = new_str[iset]; } free(tmp); free(new_str); strs_added++; } } // alpha,beta->alpha,beta ih = eri_sorted[p]; int aabb_done = (fabs(eri[ih]) < tol); if (!aabb_done) { lp = ih % norb; ij = ih / norb; kp = ij % norb; ij = ij / norb; jp = ij % norb; ip = ij / norb; ip_occ = 0; jp_occ = 0; kp_occ = 0; lp_occ = 0; for (r = 0; r < neleca; ++r) { int occ_index = occsa[r]; if (ip == occ_index) ip_occ = 1; if (jp == occ_index) jp_occ = 1; } for (r = 0; r < nelecb; ++r) { int occ_index = occsb[r]; if (kp == occ_index) kp_occ = 1; if (lp == occ_index) lp_occ = 1; } if (jp_occ && lp_occ && !ip_occ && !kp_occ) { uint64_t *tmp = toggle_bit(stra, nset, jp); uint64_t *new_str_a = toggle_bit(tmp, nset, ip); tmp = toggle_bit(strb, nset, lp); uint64_t *new_str_b = toggle_bit(tmp, nset, kp); for (iset = 0; iset < nset; ++iset) { strs_add[strs_added * 2 * nset + iset] = new_str_a[iset]; strs_add[strs_added * 2 * nset + nset + iset] = new_str_b[iset]; } free(tmp); free(new_str_a); free(new_str_b); strs_added++; } } // Break statement if (aaaa_bbbb_done && aabb_done) { break; } } free(occsa); free(occsb); free(virsa); free(virsb); if (strs_added > max_strs_add) { printf("\nError: Number of selected strings is greater than the size of the buffer array (%ld vs %ld).\n", strs_added, max_strs_add); exit(EXIT_FAILURE); } } // end loop over determinants free(focka); free(fockb); free(holes_a); free(holes_b); free(particles_a); free(particles_b); strs_add_size[0] = strs_added; } // Toggle bit at a specified position uint64_t *toggle_bit(uint64_t *str, int nset, int p) { size_t i; uint64_t *new_str = malloc(sizeof(uint64_t) * nset); for (i = 0; i < nset; ++i) { new_str[i] = str[i]; } int p_set = p / 64; int p_rel = p % 64; new_str[nset - p_set - 1] ^= 1ULL << p_rel; return new_str; } // Compares two string indices and determines the order int order(uint64_t *strs_i, uint64_t *strs_j, int nset) { size_t i; for (i = 0; i < nset; ++i) { if (strs_i[i] > strs_j[i]) return 1; else if (strs_j[i] > strs_i[i]) return -1; } return 0; } // Recursive quick sort of string array indices void qsort_idx(uint64_t *strs, uint64_t *idx, uint64_t *nstrs_, int nset, uint64_t *new_idx) { size_t p; uint64_t nstrs = nstrs_[0]; if (nstrs <= 1) { for (p = 0; p < nstrs; ++p) new_idx[p] = idx[p]; } else { uint64_t ref = idx[nstrs - 1]; uint64_t *group_lt = malloc(sizeof(uint64_t) * nstrs); uint64_t *group_gt = malloc(sizeof(uint64_t) * nstrs); uint64_t group_lt_nstrs = 0; uint64_t group_gt_nstrs = 0; for (p = 0; p < (nstrs - 1); ++p) { uint64_t i = idx[p]; uint64_t *stri = strs + i * nset; uint64_t *strj = strs + ref * nset; int c = order(stri, strj, nset); if (c == -1) { group_lt[group_lt_nstrs] = i; group_lt_nstrs++; } else if (c == 1) { group_gt[group_gt_nstrs] = i; group_gt_nstrs++; } } uint64_t *new_idx_lt = malloc(sizeof(uint64_t) * group_lt_nstrs); uint64_t *new_idx_gt = malloc(sizeof(uint64_t) * group_gt_nstrs); qsort_idx(strs, group_lt, &group_lt_nstrs, nset, new_idx_lt); qsort_idx(strs, group_gt, &group_gt_nstrs, nset, new_idx_gt); nstrs = group_lt_nstrs + group_gt_nstrs + 1; nstrs_[0] = nstrs; for (p = 0; p < nstrs; ++p) { if (p < group_lt_nstrs) new_idx[p] = new_idx_lt[p]; else if (p == group_lt_nstrs) new_idx[p] = ref; else new_idx[p] = new_idx_gt[p - group_lt_nstrs - 1]; } free(new_idx_lt); free(new_idx_gt); free(group_lt); free(group_gt); } } // Helper function to perform recursive sort (nset is a total number of strings) void argunique(uint64_t *strs, uint64_t *sort_idx, uint64_t *nstrs_, int nset) { size_t p; uint64_t *init_idx = malloc(sizeof(uint64_t) * nstrs_[0]); for (p = 0; p < nstrs_[0]; ++p) init_idx[p] = p; qsort_idx(strs, init_idx, nstrs_, nset, sort_idx); free(init_idx); } // Computes C' = S2 * C in the selected CI basis void contract_ss_c(int norb, int neleca, int nelecb, uint64_t *strs, double *civec, uint64_t ndet, double *ci1) { int *ts = malloc(sizeof(int) * ndet); #pragma omp parallel { size_t ip, jp, p, q; int nset = (norb + 63) / 64; // Calculate excitation level for prescreening ts[0] = 0; uint64_t *str1a = strs; uint64_t *str1b = strs + nset; #pragma omp for schedule(static) for (ip = 1; ip < ndet; ++ip) { uint64_t *stria = strs + ip * 2 * nset; uint64_t *strib = strs + ip * 2 * nset + nset; ts[ip] = (n_excitations(stria, str1a, nset) + n_excitations(strib, str1b, nset)); } // Loop over pairs of determinants #pragma omp for schedule(static) for (ip = 0; ip < ndet; ++ip) { for (jp = 0; jp < ndet; ++jp) { if (abs(ts[ip] - ts[jp]) < 3) { uint64_t *stria = strs + ip * 2 * nset; uint64_t *strib = strs + ip * 2 * nset + nset; uint64_t *strja = strs + jp * 2 * nset; uint64_t *strjb = strs + jp * 2 * nset + nset; int n_excit_a = n_excitations(stria, strja, nset); int n_excit_b = n_excitations(strib, strjb, nset); // Diagonal term if (ip == jp) { double apb = (double) (neleca + nelecb); double amb = (double) (neleca - nelecb); double prefactor = apb / 2.0 + amb * amb / 4.0; int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); for (p = 0; p < neleca; ++p) { int pa = occsa[p]; for (q = 0; q < nelecb; ++q) { int qb = occsb[q]; if (pa == qb) prefactor -= 1.0; } } ci1[ip] += prefactor * civec[ip]; free(occsa); free(occsb); } // Double excitation else if ((n_excit_a + n_excit_b) == 2) { int i, j, a, b; // alpha,beta->alpha,beta if (n_excit_a == n_excit_b) { int *ia = get_single_excitation(stria, strja, nset); int *jb = get_single_excitation(strib, strjb, nset); i = ia[0]; a = ia[1]; j = jb[0]; b = jb[1]; if (i == b && j == a) { double sign = compute_cre_des_sign(a, i, stria, nset); sign *= compute_cre_des_sign(b, j, strib, nset); ci1[ip] -= sign * civec[jp]; } free(ia); free(jb); } } } // end if over ts } // end loop over jp } // end loop over ip } // end omp free(ts); } // Computes C' = H * C and C'' = S2 * C simultaneously in the selected CI basis void contract_h_c_ss_c(double *h1, double *eri, int norb, int neleca, int nelecb, uint64_t *strs, double *civec, double *hdiag, uint64_t ndet, double *ci1, double *ci2) { int *ts = malloc(sizeof(int) * ndet); #pragma omp parallel { size_t ip, jp, p, q; int nset = (norb + 63) / 64; // Calculate excitation level for prescreening ts[0] = 0; uint64_t *str1a = strs; uint64_t *str1b = strs + nset; #pragma omp for schedule(static) for (ip = 1; ip < ndet; ++ip) { uint64_t *stria = strs + ip * 2 * nset; uint64_t *strib = strs + ip * 2 * nset + nset; ts[ip] = (n_excitations(stria, str1a, nset) + n_excitations(strib, str1b, nset)); } // Loop over pairs of determinants #pragma omp for schedule(static) for (ip = 0; ip < ndet; ++ip) { for (jp = 0; jp < ndet; ++jp) { if (abs(ts[ip] - ts[jp]) < 3) { uint64_t *stria = strs + ip * 2 * nset; uint64_t *strib = strs + ip * 2 * nset + nset; uint64_t *strja = strs + jp * 2 * nset; uint64_t *strjb = strs + jp * 2 * nset + nset; int n_excit_a = n_excitations(stria, strja, nset); int n_excit_b = n_excitations(strib, strjb, nset); // Diagonal term if (ip == jp) { ci1[ip] += hdiag[ip] * civec[ip]; // S^2 double apb = (double) (neleca + nelecb); double amb = (double) (neleca - nelecb); double prefactor = apb / 2.0 + amb * amb / 4.0; int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); for (p = 0; p < neleca; ++p) { int pa = occsa[p]; for (q = 0; q < nelecb; ++q) { int qb = occsb[q]; if (pa == qb) prefactor -= 1.0; } } ci2[ip] += prefactor * civec[ip]; free(occsa); free(occsb); } // Single excitation else if ((n_excit_a + n_excit_b) == 1) { int *ia; // alpha->alpha if (n_excit_b == 0) { ia = get_single_excitation(stria, strja, nset); int i = ia[0]; int a = ia[1]; double sign = compute_cre_des_sign(a, i, stria, nset); int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); double fai = h1[a * norb + i]; for (p = 0; p < neleca; ++p) { int k = occsa[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; int kiak = k * norb * norb * norb + i * norb * norb + a * norb + k; fai += eri[kkai] - eri[kiak]; } for (p = 0; p < nelecb; ++p) { int k = occsb[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; fai += eri[kkai]; } if (fabs(fai) > 1.0E-14) ci1[ip] += sign * fai * civec[jp]; free(occsa); free(occsb); } // beta->beta else if (n_excit_a == 0) { ia = get_single_excitation(strib, strjb, nset); int i = ia[0]; int a = ia[1]; double sign = compute_cre_des_sign(a, i, strib, nset); int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); double fai = h1[a * norb + i]; for (p = 0; p < nelecb; ++p) { int k = occsb[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; int kiak = k * norb * norb * norb + i * norb * norb + a * norb + k; fai += eri[kkai] - eri[kiak]; } for (p = 0; p < neleca; ++p) { int k = occsa[p]; int kkai = k * norb * norb * norb + k * norb * norb + a * norb + i; fai += eri[kkai]; } if (fabs(fai) > 1.0E-14) ci1[ip] += sign * fai * civec[jp]; free(occsa); free(occsb); } free(ia); } // Double excitation else if ((n_excit_a + n_excit_b) == 2) { int i, j, a, b; // alpha,alpha->alpha,alpha if (n_excit_b == 0) { int *ijab = get_double_excitation(stria, strja, nset); i = ijab[0]; j = ijab[1]; a = ijab[2]; b = ijab[3]; double v, sign; int ajbi = a * norb * norb * norb + j * norb * norb + b * norb + i; int aibj = a * norb * norb * norb + i * norb * norb + b * norb + j; if (a > j || i > b) { v = eri[ajbi] - eri[aibj]; sign = compute_cre_des_sign(b, i, stria, nset); sign *= compute_cre_des_sign(a, j, stria, nset); } else { v = eri[aibj] - eri[ajbi]; sign = compute_cre_des_sign(b, j, stria, nset); sign *= compute_cre_des_sign(a, i, stria, nset); } if (fabs(v) > 1.0E-14) ci1[ip] += sign * v * civec[jp]; free(ijab); } // beta,beta->beta,beta else if (n_excit_a == 0) { int *ijab = get_double_excitation(strib, strjb, nset); i = ijab[0]; j = ijab[1]; a = ijab[2]; b = ijab[3]; double v, sign; int ajbi = a * norb * norb * norb + j * norb * norb + b * norb + i; int aibj = a * norb * norb * norb + i * norb * norb + b * norb + j; if (a > j || i > b) { v = eri[ajbi] - eri[aibj]; sign = compute_cre_des_sign(b, i, strib, nset); sign *= compute_cre_des_sign(a, j, strib, nset); } else { v = eri[aibj] - eri[ajbi]; sign = compute_cre_des_sign(b, j, strib, nset); sign *= compute_cre_des_sign(a, i, strib, nset); } if (fabs(v) > 1.0E-14) ci1[ip] += sign * v * civec[jp]; free(ijab); } // alpha,beta->alpha,beta else { int *ia = get_single_excitation(stria, strja, nset); int *jb = get_single_excitation(strib, strjb, nset); i = ia[0]; a = ia[1]; j = jb[0]; b = jb[1]; double v = eri[a * norb * norb * norb + i * norb * norb + b * norb + j]; double sign = compute_cre_des_sign(a, i, stria, nset); sign *= compute_cre_des_sign(b, j, strib, nset); if (fabs(v) > 1.0E-14) ci1[ip] += sign * v * civec[jp]; // S^2 if (i == b && j == a) { ci2[ip] -= sign * civec[jp]; } free(ia); free(jb); } } } // end if over ts } // end loop over jp } // end loop over ip } // end omp free(ts); } // 2-RDM is sorted in physicists notation: gamma_pqsr=<\Phi|a_p^dag a_q^dag a_r a_s|\Phi> void compute_rdm12s(int norb, int neleca, int nelecb, uint64_t *strs, double *civec, uint64_t ndet, double *rdm1a, double *rdm1b, double *rdm2aa, double *rdm2ab, double *rdm2bb) { #pragma omp parallel { size_t ip, jp, p, q, r, s; int nset = (norb + 63) / 64; double ci_sq = 0.0; double *rdm1a_private = malloc(sizeof(double) * norb * norb); double *rdm1b_private = malloc(sizeof(double) * norb * norb); double *rdm2aa_private = malloc(sizeof(double) * norb * norb * norb * norb); double *rdm2ab_private = malloc(sizeof(double) * norb * norb * norb * norb); double *rdm2bb_private = malloc(sizeof(double) * norb * norb * norb * norb); for (p = 0; p < norb * norb; ++p) { rdm1a_private[p] = 0.0; rdm1b_private[p] = 0.0; } for (p = 0; p < norb * norb * norb * norb; ++p) { rdm2aa_private[p] = 0.0; rdm2ab_private[p] = 0.0; rdm2bb_private[p] = 0.0; } // Loop over pairs of determinants #pragma omp for schedule(static) for (ip = 0; ip < ndet; ++ip) { for (jp = 0; jp < ndet; ++jp) { uint64_t *stria = strs + ip * 2 * nset; uint64_t *strib = strs + ip * 2 * nset + nset; uint64_t *strja = strs + jp * 2 * nset; uint64_t *strjb = strs + jp * 2 * nset + nset; int n_excit_a = n_excitations(stria, strja, nset); int n_excit_b = n_excitations(strib, strjb, nset); // Diagonal term if (ip == jp) { int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); ci_sq = civec[ip] * civec[ip]; // Diagonal rdm1_aa for (p = 0; p < neleca; ++p) { int k = occsa[p]; int kk = k * norb + k; rdm1a_private[kk] += ci_sq; } // Diagonal rdm1_bb for (p = 0; p < nelecb; ++p) { int k = occsb[p]; int kk = k * norb + k; rdm1b_private[kk] += ci_sq; } // Diagonal rdm2_aaaa for (p = 0; p < neleca; ++p) { int k = occsa[p]; for (q = 0; q < neleca; ++q) { int j = occsa[q]; int kjkj = k * norb * norb * norb + j * norb * norb + k * norb + j; int kjjk = k * norb * norb * norb + j * norb * norb + j * norb + k; rdm2aa_private[kjkj] += ci_sq; rdm2aa_private[kjjk] -= ci_sq; } // Diagonal rdm2_abab for (q = 0; q < nelecb; ++q) { int j = occsb[q]; int kjkj = k * norb * norb * norb + j * norb * norb + k * norb + j; rdm2ab_private[kjkj] += ci_sq; } } // Diagonal rdm2_bbbb for (p = 0; p < nelecb; ++p) { int k = occsb[p]; for (q = 0; q < nelecb; ++q) { int j = occsb[q]; int kjkj = k * norb * norb * norb + j * norb * norb + k * norb + j; int kjjk = k * norb * norb * norb + j * norb * norb + j * norb + k; rdm2bb_private[kjkj] += ci_sq; rdm2bb_private[kjjk] -= ci_sq; } } free(occsa); free(occsb); } // Single excitation else if ((n_excit_a + n_excit_b) == 1) { int *ia; // alpha->alpha if (n_excit_b == 0) { ia = get_single_excitation(stria, strja, nset); int i = ia[0]; int a = ia[1]; double sign = compute_cre_des_sign(a, i, stria, nset); int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); ci_sq = sign * civec[ip] * civec[jp]; // rdm1_aa rdm1a_private[a * norb + i] += ci_sq; // rdm2_aaaa for (p = 0; p < neleca; ++p) { int k = occsa[p]; int akik = a * norb * norb * norb + k * norb * norb + i * norb + k; int akki = a * norb * norb * norb + k * norb * norb + k * norb + i; int kaki = k * norb * norb * norb + a * norb * norb + k * norb + i; int kaik = k * norb * norb * norb + a * norb * norb + i * norb + k; rdm2aa_private[akik] += ci_sq; rdm2aa_private[akki] -= ci_sq; rdm2aa_private[kaik] -= ci_sq; rdm2aa_private[kaki] += ci_sq; } // rdm2_abab for (p = 0; p < nelecb; ++p) { int k = occsb[p]; int akik = a * norb * norb * norb + k * norb * norb + i * norb + k; rdm2ab_private[akik] += ci_sq; } free(occsa); free(occsb); } // beta->beta else if (n_excit_a == 0) { ia = get_single_excitation(strib, strjb, nset); int i = ia[0]; int a = ia[1]; double sign = compute_cre_des_sign(a, i, strib, nset); int *occsa = compute_occ_list(stria, nset, norb, neleca); int *occsb = compute_occ_list(strib, nset, norb, nelecb); ci_sq = sign * civec[ip] * civec[jp]; // rdm1_bb rdm1b_private[a * norb + i] += ci_sq; // rdm2_bbbb for (p = 0; p < nelecb; ++p) { int k = occsb[p]; int akik = a * norb * norb * norb + k * norb * norb + i * norb + k; int akki = a * norb * norb * norb + k * norb * norb + k * norb + i; int kaki = k * norb * norb * norb + a * norb * norb + k * norb + i; int kaik = k * norb * norb * norb + a * norb * norb + i * norb + k; rdm2bb_private[akik] += ci_sq; rdm2bb_private[akki] -= ci_sq; rdm2bb_private[kaik] -= ci_sq; rdm2bb_private[kaki] += ci_sq; } // rdm2_abab for (p = 0; p < neleca; ++p) { int k = occsa[p]; int kaki = k * norb * norb * norb + a * norb * norb + k * norb + i; rdm2ab_private[kaki] += ci_sq; } free(occsa); free(occsb); } free(ia); } // Double excitation else if ((n_excit_a + n_excit_b) == 2) { int i, j, a, b; // rdm2_aaaa if (n_excit_b == 0) { int *ijab = get_double_excitation(stria, strja, nset); i = ijab[0]; j = ijab[1]; a = ijab[2]; b = ijab[3]; double sign; int baij = b * norb * norb * norb + a * norb * norb + i * norb + j; int baji = b * norb * norb * norb + a * norb * norb + j * norb + i; int abij = a * norb * norb * norb + b * norb * norb + i * norb + j; int abji = a * norb * norb * norb + b * norb * norb + j * norb + i; if (a > j || i > b) { sign = compute_cre_des_sign(b, i, stria, nset); sign *= compute_cre_des_sign(a, j, stria, nset); ci_sq = sign * civec[ip] * civec[jp]; rdm2aa_private[baij] += ci_sq; rdm2aa_private[baji] -= ci_sq; rdm2aa_private[abij] -= ci_sq; rdm2aa_private[abji] += ci_sq; } else { sign = compute_cre_des_sign(b, j, stria, nset); sign *= compute_cre_des_sign(a, i, stria, nset); ci_sq = sign * civec[ip] * civec[jp]; rdm2aa_private[baij] -= ci_sq; rdm2aa_private[baji] += ci_sq; rdm2aa_private[abij] += ci_sq; rdm2aa_private[abji] -= ci_sq; } free(ijab); } // rdm2_bbbb else if (n_excit_a == 0) { int *ijab = get_double_excitation(strib, strjb, nset); i = ijab[0]; j = ijab[1]; a = ijab[2]; b = ijab[3]; double v, sign; int baij = b * norb * norb * norb + a * norb * norb + i * norb + j; int baji = b * norb * norb * norb + a * norb * norb + j * norb + i; int abij = a * norb * norb * norb + b * norb * norb + i * norb + j; int abji = a * norb * norb * norb + b * norb * norb + j * norb + i; if (a > j || i > b) { sign = compute_cre_des_sign(b, i, strib, nset); sign *= compute_cre_des_sign(a, j, strib, nset); ci_sq = sign * civec[ip] * civec[jp]; rdm2bb_private[baij] += ci_sq; rdm2bb_private[baji] -= ci_sq; rdm2bb_private[abij] -= ci_sq; rdm2bb_private[abji] += ci_sq; } else { sign = compute_cre_des_sign(b, j, strib, nset); sign *= compute_cre_des_sign(a, i, strib, nset); ci_sq = sign * civec[ip] * civec[jp]; rdm2bb_private[baij] -= ci_sq; rdm2bb_private[baji] += ci_sq; rdm2bb_private[abij] += ci_sq; rdm2bb_private[abji] -= ci_sq; } free(ijab); } // rdm2_abab else { int *ia = get_single_excitation(stria, strja, nset); int *jb = get_single_excitation(strib, strjb, nset); i = ia[0]; a = ia[1]; j = jb[0]; b = jb[1]; double sign = compute_cre_des_sign(a, i, stria, nset); sign *= compute_cre_des_sign(b, j, strib, nset); ci_sq = sign * civec[ip] * civec[jp]; int abij = a * norb * norb * norb + b * norb * norb + i * norb + j; rdm2ab_private[abij] += ci_sq; free(ia); free(jb); } } } // end loop over jp } // end loop over ip #pragma omp critical { for (p = 0; p < norb * norb; ++p) { rdm1a[p] += rdm1a_private[p]; rdm1b[p] += rdm1b_private[p]; } for (p = 0; p < norb * norb * norb * norb; ++p) { rdm2aa[p] += rdm2aa_private[p]; rdm2ab[p] += rdm2ab_private[p]; rdm2bb[p] += rdm2bb_private[p]; } } free(rdm1a_private); free(rdm1b_private); free(rdm2aa_private); free(rdm2ab_private); free(rdm2bb_private); } // end omp }
GB_binop__max_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__max_uint32 // A.*B function (eWiseMult): GB_AemultB__max_uint32 // A*D function (colscale): GB_AxD__max_uint32 // D*A function (rowscale): GB_DxB__max_uint32 // C+=B function (dense accum): GB_Cdense_accumB__max_uint32 // C+=b function (dense accum): GB_Cdense_accumb__max_uint32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__max_uint32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__max_uint32 // C=scalar+B GB_bind1st__max_uint32 // C=scalar+B' GB_bind1st_tran__max_uint32 // C=A+scalar GB_bind2nd__max_uint32 // C=A'+scalar GB_bind2nd_tran__max_uint32 // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = GB_IMAX (aij, bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_IMAX (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MAX || GxB_NO_UINT32 || GxB_NO_MAX_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__max_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__max_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__max_uint32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__max_uint32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__max_uint32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__max_uint32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__max_uint32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__max_uint32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__max_uint32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t bij = Bx [p] ; Cx [p] = GB_IMAX (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__max_uint32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t aij = Ax [p] ; Cx [p] = GB_IMAX (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = GB_IMAX (x, aij) ; \ } GrB_Info GB_bind1st_tran__max_uint32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = GB_IMAX (aij, y) ; \ } GrB_Info GB_bind2nd_tran__max_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
new.c
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <math.h> #include <time.h> #include <mpi.h> #include <omp.h> #include <limits.h> #include "constants.h" #include "functions.h" int main(int argc, char **argv) { FILE *input = stdin, *knowenWordsFile; unsigned int keyInt, startIndex, endIndex; char *keyString; int numBytesInKey; char *dictStr, *decodedText, **dict, **decodedSplitArray; char *encodedText; int dictStrLen, decodedWordsCounter, cmpRes, maxNum; int i, j; int matchCounter, comSize, procRank, numOfWords; int partSize, encodedTextLen; double start; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &comSize); MPI_Comm_rank(MPI_COMM_WORLD, &procRank); start = MPI_Wtime(); if (procRank == 0) { // * open crypted file input = fopen(argv[2], "r"); if (!input) { fprintf(stderr, "Error opening words file\n"); return 0; } // * open words file if (argc > 3) knowenWordsFile = fopen(argv[3], "r"); else knowenWordsFile = fopen("linux_words.txt", "r"); if (!knowenWordsFile) { fprintf(stderr, "Error opening file words\n"); return 0; } // * get number of words for words array dynamic memory allocation fscanf(knowenWordsFile, "%d", &numOfWords); // * allocate knowen words array and each of it's words dictStr = inputString(knowenWordsFile, ALLOCATION_SIZE); dictStrLen = strlen(dictStr); encodedText = inputString(input, ALLOCATION_SIZE); encodedTextLen = strlen(encodedText); fclose(input); fclose(knowenWordsFile); } MPI_Bcast(&numOfWords, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&dictStrLen, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&encodedTextLen, 1, MPI_INT, 0, MPI_COMM_WORLD); if (procRank != 0) { dictStr = (char *)calloc(dictStrLen + 1, sizeof(char)); encodedText = (char *)calloc(encodedTextLen + 1, sizeof(char)); } MPI_Bcast(dictStr, dictStrLen, MPI_CHAR, 0, MPI_COMM_WORLD); dict = splitStringByDelimiter(ALLOCATION_SIZE, dictStr, "\n", &decodedWordsCounter); MPI_Bcast(encodedText, encodedTextLen, MPI_CHAR, 0, MPI_COMM_WORLD); maxNum = determineMaxNum(argv[1], &partSize); startIndex = partSize * procRank; endIndex = startIndex + partSize + 1; if (procRank == comSize - 1) { endIndex = maxNum; } for (keyInt = startIndex; keyInt < endIndex; keyInt++) { matchCounter = 0; keyString = createKey(keyInt); numBytesInKey = processKey(keyString); // * encode the text to a string decodedText = encodeStr(numBytesInKey, encodedText, encodedTextLen); // * split text string into a string array by 'space' delimiter decodedSplitArray = splitStringByDelimiter(ALLOCATION_SIZE, strdup(decodedText), " ", &decodedWordsCounter); // * match all words of decoded text with each of the knowen words #pragma omp parallel for collapse(2) private(j) num_threads(4) for (i = 0; i < decodedWordsCounter; i++) { for (j = 0; j < numOfWords; j++) { if (strlen(dict[j]) > 2) { cmpRes = strcmp(decodedSplitArray[i], dict[j]); if (cmpRes == 0) // * words match { matchCounter++; } } } } if (matchCounter >= 2) break; // * free current iteration free(decodedSplitArray); free(decodedText); } if (matchCounter >= 2) { printf("\nProcess %d - Success!\nKey is: 0x%s\nDecoded text is:\n%s\n", procRank, keyString, decodedText); free(decodedSplitArray); free(decodedText); } else { printf("\nProcess %d - Failure! No valid key was found\n", procRank); } // * clean all clean(dict, keyString, dictStr); if (procRank == 0) { fprintf(stderr, "Time taken to calculate the key is %f seconds\n", MPI_Wtime() - start); } MPI_Finalize(); return 0; } // * main
RCCE_synch.c
///************************************************************************************* // Synchronization functions. // Single-bit and whole-cache-line flags are sufficiently different that we provide // separate implementations of the synchronization routines for each case //************************************************************************************** // // Author: Rob F. Van der Wijngaart // Intel Corporation // Date: 008/30/2010 // //************************************************************************************** // // Copyright 2010 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "RCCE_lib.h" #ifdef __hermit__ #include "rte_memcpy.h" #define memcpy_scc rte_memcpy #elif defined(COPPERRIDGE) #include "scc_memcpy.h" #else #define memcpy_scc memcpy #endif #ifdef USE_BYTE_FLAGS #include "RCCE_byte_synch.c" #else #ifdef SINGLEBITFLAGS ////////////////////////////////////////////////////////////////// // LOCKING SYNCHRONIZATION USING ONE BIT PER FLAG ////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------------- // FUNCTION: RCCE_wait_until //-------------------------------------------------------------------------------------- // wait until flag in local MPB becomes set or unset. To avoid reading stale data from // the cache instead of new flag value from the MPB, issue MPB cache invalidation before // each read, including within the spin cycle //-------------------------------------------------------------------------------------- int RCCE_wait_until(RCCE_FLAG flag, RCCE_FLAG_STATUS val) { t_vcharp cflag; cflag = flag.line_address; // avoid tests if we use the simplified API #ifdef GORY if (val != RCCE_FLAG_UNSET && val != RCCE_FLAG_SET) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_STATUS_UNDEFINED)); if (!cflag) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_ALLOCATED)); // check to see if flag is properly contained in the local comm buffer if (cflag - RCCE_comm_buffer[RCCE_IAM]>=0 && cflag+RCCE_LINE_SIZE - (RCCE_comm_buffer[RCCE_IAM] + RCCE_BUFF_SIZE)<0){} else { return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_IN_COMM_BUFFER)); } #endif // always flush/invalidate to ensure we read the most recent value of *flag // keep reading it until it has the required value do { #ifdef _OPENMP #pragma omp flush #endif RC_cache_invalidate(); } while ((RCCE_bit_value(cflag, flag.location) != val)); return(RCCE_SUCCESS); } int RCCE_test_flag(RCCE_FLAG flag, RCCE_FLAG_STATUS val, int *result) { t_vcharp cflag; cflag = flag.line_address; // avoid tests if we use the simplified API #ifdef GORY if (val != RCCE_FLAG_UNSET && val != RCCE_FLAG_SET) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_STATUS_UNDEFINED)); if (!cflag) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_ALLOCATED)); // check to see if flag is properly contained in the local comm buffer if (cflag - RCCE_comm_buffer[RCCE_IAM]>=0 && cflag+RCCE_LINE_SIZE - (RCCE_comm_buffer[RCCE_IAM] + RCCE_BUFF_SIZE)<0){} else { return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_IN_COMM_BUFFER)); } #endif // always flush/invalidate to ensure we read the most recent value of *flag // keep reading it until it has the required value #ifdef _OPENMP #pragma omp flush #endif RC_cache_invalidate(); if(RCCE_bit_value(cflag, flag.location) != val) { (*result) = 0; } else { (*result) = 1; } return(RCCE_SUCCESS); } //-------------------------------------------------------------------------------------- // FUNCTION: RCCE_barrier //-------------------------------------------------------------------------------------- // very simple, linear barrier //-------------------------------------------------------------------------------------- int RCCE_barrier(RCCE_COMM *comm) { t_vchar cyclechar[RCCE_LINE_SIZE] __attribute__ ((aligned (RCCE_LINE_SIZE))); t_vchar valchar [RCCE_LINE_SIZE] __attribute__ ((aligned (RCCE_LINE_SIZE))); int counter, i, error; int ROOT = 0; t_vcharp gatherp, releasep; RCCE_FLAG_STATUS cycle; counter = 0; gatherp = comm->gather.line_address; if (RCCE_debug_synch) fprintf(STDERR,"UE %d has checked into barrier\n", RCCE_IAM); // flip local barrier variable if (error = RCCE_get(cyclechar, gatherp, RCCE_LINE_SIZE, RCCE_IAM)) return(RCCE_error_return(RCCE_debug_synch,error)); cycle = RCCE_flip_bit_value(cyclechar, comm->gather.location); if (error = RCCE_put(comm->gather.line_address, cyclechar, RCCE_LINE_SIZE, RCCE_IAM)) return(RCCE_error_return(RCCE_debug_synch,error)); if (RCCE_IAM==comm->member[ROOT]) { // read "remote" gather flags; once all equal "cycle" (i.e counter==comm->size), // we know all UEs have reached the barrier while (counter != comm->size) { // skip the first member (#0), because that is the ROOT for (counter=i=1; i<comm->size; i++) { // copy flag values out of comm buffer if (error = RCCE_get(valchar, comm->gather.line_address, RCCE_LINE_SIZE, comm->member[i])) return(RCCE_error_return(RCCE_debug_synch,error)); if (RCCE_bit_value(valchar, comm->gather.location) == cycle) counter++; } } // set release flags for (i=1; i<comm->size; i++) if (error = RCCE_flag_write(&(comm->release), cycle, comm->member[i])) return(RCCE_error_return(RCCE_debug_synch,error)); } else { if (error = RCCE_wait_until(comm->release, cycle)) return(RCCE_error_return(RCCE_debug_synch,error)); } if (RCCE_debug_synch) fprintf(STDERR,"UE %d has cleared barrier\n", RCCE_IAM); return(RCCE_SUCCESS); } #else ////////////////////////////////////////////////////////////////// // LOCKLESS SYNCHRONIZATION USING ONE WHOLE CACHE LINE PER FLAG // ////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------------- // FUNCTION: RCCE_wait_until //-------------------------------------------------------------------------------------- // wait until flag in local MPB becomes set or unset. To avoid reading stale data from // the cache instead of new flag value from the MPB, issue MPB cache invalidation before // each read, including within the spin cycle //-------------------------------------------------------------------------------------- int RCCE_wait_until(RCCE_FLAG flag, RCCE_FLAG_STATUS val) { t_vcharp cflag; cflag = (t_vcharp) flag; #ifdef GORY if (val != RCCE_FLAG_UNSET && val != RCCE_FLAG_SET) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_STATUS_UNDEFINED)); if (!cflag) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_ALLOCATED)); // check to see if flag is properly contained in the local comm buffer if (cflag - RCCE_comm_buffer[RCCE_IAM]>=0 && cflag+RCCE_LINE_SIZE - (RCCE_comm_buffer[RCCE_IAM] + RCCE_BUFF_SIZE)<0){} else { return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_IN_COMM_BUFFER)); } #endif #ifdef USE_REVERTED_FLAGS flag = flag + RCCE_LINE_SIZE / sizeof(int) - 1; #endif // always flush/invalidate to ensure we read the most recent value of *flag // keep reading it until it has the required value. We only need to read the // first int of the MPB cache line containing the flag #ifndef USE_FLAG_EXPERIMENTAL do { #ifdef _OPENMP #pragma omp flush #endif RC_cache_invalidate(); } while ((*flag) != val); #else if (RCCE_debug_synch) fprintf(STDERR,"UE %d wait flag: %x from address %X \n", RCCE_IAM,val,flag); flag = RCCE_flag_buffer[RCCE_IAM]+(flag-RCCE_comm_buffer[RCCE_IAM]); while ((*flag) != val); #endif return(RCCE_SUCCESS); } #ifdef USE_TAGGED_FLAGS int RCCE_wait_tagged(RCCE_FLAG flag, RCCE_FLAG_STATUS val, void *tag, int len) { int i, j; RCCE_FLAG flag_pos; #ifndef USE_REVERTED_FLAGS flag_pos = flag; #else flag_pos = flag + RCCE_LINE_SIZE / sizeof(int) - 1; #endif do { #ifdef _OPENMP #pragma omp flush #endif RC_cache_invalidate(); } while ((*flag_pos) != val); if(tag) { if( len > ( RCCE_LINE_SIZE - sizeof(int) ) ) len = RCCE_LINE_SIZE - sizeof(int); #ifndef USE_REVERTED_FLAGS memcpy_scc(tag, &((char*)flag)[sizeof(int)], len); #else memcpy_scc(tag, &((char*)flag)[0], len); #endif } return(RCCE_SUCCESS); } #endif int RCCE_test_flag(RCCE_FLAG flag, RCCE_FLAG_STATUS val, int *result) { t_vcharp cflag; cflag = (t_vcharp) flag; #ifdef GORY if (val != RCCE_FLAG_UNSET && val != RCCE_FLAG_SET) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_STATUS_UNDEFINED)); if (!cflag) return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_ALLOCATED)); // check to see if flag is properly contained in the local comm buffer if (cflag - RCCE_comm_buffer[RCCE_IAM]>=0 && cflag+RCCE_LINE_SIZE - (RCCE_comm_buffer[RCCE_IAM] + RCCE_BUFF_SIZE)<0){} else { return(RCCE_error_return(RCCE_debug_synch,RCCE_ERROR_FLAG_NOT_IN_COMM_BUFFER)); } #endif #ifdef USE_REVERTED_FLAGS flag = flag + RCCE_LINE_SIZE / sizeof(int) - 1; #endif // always flush/invalidate to ensure we read the most recent value of *flag // keep reading it until it has the required value. We only need to read the // first int of the MPB cache line containing the flag #ifdef _OPENMP #pragma omp flush #endif #ifndef USE_FLAG_EXPERIMENTAL RC_cache_invalidate(); #endif if((*flag) != val) { (*result) = 0; } else { (*result) = 1; } return(RCCE_SUCCESS); } #ifdef USE_TAGGED_FLAGS int RCCE_test_tagged(RCCE_FLAG flag, RCCE_FLAG_STATUS val, int *result, void *tag, int len) { int i, j; RCCE_FLAG flag_pos; #ifndef USE_REVERTED_FLAGS flag_pos = flag; #else flag_pos = flag + RCCE_LINE_SIZE / sizeof(int) -1; #endif RC_cache_invalidate(); if((*flag_pos) != val) { (*result) = 0; } else { (*result) = 1; } if((*result) && tag) { if( len > ( RCCE_LINE_SIZE - sizeof(int) ) ) len = RCCE_LINE_SIZE - sizeof(int); #ifndef USE_REVERTED_FLAGS memcpy_scc(tag, &((char*)flag)[sizeof(int)], len); #else memcpy_scc(tag, &((char*)flag)[0], len); #endif } return(RCCE_SUCCESS); } #endif //-------------------------------------------------------------------------------------- // FUNCTION: RCCE_barrier //-------------------------------------------------------------------------------------- // very simple, linear barrier //-------------------------------------------------------------------------------------- int RCCE_barrier(RCCE_COMM *comm) { volatile unsigned char cyclechar[RCCE_LINE_SIZE] __attribute__ ((aligned (RCCE_LINE_SIZE))); volatile unsigned char valchar[RCCE_LINE_SIZE] __attribute__ ((aligned (RCCE_LINE_SIZE))); volatile char *cycle; volatile char *val; int counter, i, error; int ROOT = 0; counter = 0; cycle = (volatile char *)cyclechar; val = (volatile char *)valchar; if (RCCE_debug_synch) fprintf(STDERR,"UE %d has checked into barrier\n", RCCE_IAM); #ifdef USE_FAT_BARRIER // flip local barrier variable #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(cyclechar, (t_vcharp)(comm->gather[RCCE_IAM]), RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_get_flag(cyclechar, (t_vcharp)(comm->gather[RCCE_IAM]), RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); *cycle = !(*cycle); #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_put((t_vcharp)(comm->gather[RCCE_IAM]), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_put_flag((t_vcharp)(comm->gather[RCCE_IAM]), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if ((error = RCCE_put((t_vcharp)(comm->gather[RCCE_IAM]), cyclechar, RCCE_LINE_SIZE, comm->member[ROOT]))) return(RCCE_error_return(RCCE_debug_synch,error)); if (RCCE_IAM==comm->member[ROOT]) { // read "remote" gather flags; once all equal "cycle" (i.e counter==comm->size), // we know all UEs have reached the barrier while (counter != comm->size) { // skip the first member (#0), because that is the ROOT for (counter=i=1; i<comm->size; i++) { /* copy flag values out of comm buffer */ #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(valchar, (t_vcharp)(comm->gather[i]), RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_get_flag(valchar, (t_vcharp)(comm->gather[i]), RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if (*val == *cycle) counter++; } } // set release flags for (i=1; i<comm->size; i++) { if ((error = RCCE_flag_write(&(comm->release), *cycle, comm->member[i]))) return(RCCE_error_return(RCCE_debug_synch,error)); } } else { if ((error = RCCE_wait_until(comm->release, *cycle))) return(RCCE_error_return(RCCE_debug_synch,error)); } #else // !USE_FAT_BARRIER // flip local barrier variable #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(cyclechar, (t_vcharp)(comm->gather), RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_get_flag(cyclechar, (t_vcharp)(comm->gather), RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); *cycle = !(*cycle); #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_put((t_vcharp)(comm->gather), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_put_flag((t_vcharp)(comm->gather), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if (RCCE_IAM==comm->member[ROOT]) { // read "remote" gather flags; once all equal "cycle" (i.e counter==comm->size), // we know all UEs have reached the barrier while (counter != comm->size) { // skip the first member (#0), because that is the ROOT for (counter=i=1; i<comm->size; i++) { /* copy flag values out of comm buffer */ #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(valchar, (t_vcharp)(comm->gather), RCCE_LINE_SIZE, comm->member[i]))) #else if ((error = RCCE_get_flag(valchar, (t_vcharp)(comm->gather), RCCE_LINE_SIZE, comm->member[i]))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if (*val == *cycle) counter++; } } // set release flags for (i=1; i<comm->size; i++) { if ((error = RCCE_flag_write(&(comm->release), *cycle, comm->member[i]))) return(RCCE_error_return(RCCE_debug_synch,error)); } } else { if ((error = RCCE_wait_until(comm->release, *cycle))) { return(RCCE_error_return(RCCE_debug_synch,error)); } } #endif // !USE_FAT_BARRIER if (RCCE_debug_synch) fprintf(STDERR,"UE %d has cleared barrier\n", RCCE_IAM); return(RCCE_SUCCESS); } //-------------------------------------------------------------------------------------- // FUNCTION: RCCE_nb_barrier //-------------------------------------------------------------------------------------- // non-blocking version of the linear barrier //-------------------------------------------------------------------------------------- int RCCE_nb_barrier(RCCE_COMM *comm) { volatile unsigned char cyclechar[RCCE_LINE_SIZE] __attribute__ ((aligned (RCCE_LINE_SIZE))); volatile unsigned char valchar[RCCE_LINE_SIZE] __attribute__ ((aligned (RCCE_LINE_SIZE))); int i, error; int ROOT = 0; #ifdef USE_FLAG_EXPERIMENTAL volatile char *cycle; volatile char *val; cycle = (volatile char *)cyclechar; val = (volatile char *)valchar; #else volatile int *cycle; volatile int *val; cycle = (volatile int *)cyclechar; val = (volatile int *)valchar; #endif if(comm->label == 1) goto label1; if(comm->label == 2) goto label2; comm->count = 0; if (RCCE_debug_synch) fprintf(STDERR,"UE %d has checked into barrier\n", RCCE_IAM); #ifdef USE_FAT_BARRIER // flip local barrier variable #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(cyclechar, (t_vcharp)(comm->gather[RCCE_IAM]), RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_get_flag(cyclechar, (t_vcharp)(comm->gather[RCCE_IAM]), RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); *cycle = !(*cycle); #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_put((t_vcharp)(comm->gather[RCCE_IAM]), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_put_flag((t_vcharp)(comm->gather[RCCE_IAM]), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if ((error = RCCE_put((t_vcharp)(comm->gather[RCCE_IAM]), cyclechar, RCCE_LINE_SIZE, comm->member[ROOT]))) return(RCCE_error_return(RCCE_debug_synch,error)); if (RCCE_IAM==comm->member[ROOT]) { // read "remote" gather flags; once all equal "cycle" (i.e counter==comm->size), // we know all UEs have reached the barrier comm->cycle = *cycle; label1: while (comm->count != comm->size) { // skip the first member (#0), because that is the ROOT for (comm->count=i=1; i<comm->size; i++) { /* copy flag values out of comm buffer */ #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(valchar, (t_vcharp)(comm->gather[i]), RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_get_flag(valchar, (t_vcharp)(comm->gather[i]), RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if (*val == comm->cycle) comm->count++; } if(comm->count != comm->size) { comm->label = 1; return(RCCE_PENDING); } } // set release flags for (i=1; i<comm->size; i++) { if ((error = RCCE_flag_write(&(comm->release), comm->cycle, comm->member[i]))) return(RCCE_error_return(RCCE_debug_synch,error)); } } else { int test; comm->cycle = *cycle; label2: RCCE_test_flag(comm->release, comm->cycle, &test); if(!test) { comm->label = 2; return(RCCE_PENDING); } } comm->label = 0; #else // !USE_FAT_BARRIER // flip local barrier variable #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(cyclechar, (t_vcharp)(comm->gather[0]), RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_get_flag(cyclechar, (t_vcharp)(comm->gather[0]), RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); *cycle = !(*cycle); #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_put((t_vcharp)(comm->gather[0]), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #else if ((error = RCCE_put_flag((t_vcharp)(comm->gather[0]), cyclechar, RCCE_LINE_SIZE, RCCE_IAM))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if (RCCE_IAM==comm->member[ROOT]) { // read "remote" gather flags; once all equal "cycle" (i.e counter==comm->size), // we know all UEs have reached the barrier comm->cycle = *cycle; label1: while (comm->count != comm->size) { // skip the first member (#0), because that is the ROOT for (comm->count=i=1; i<comm->size; i++) { /* copy flag values out of comm buffer */ #ifndef USE_FLAG_EXPERIMENTAL if ((error = RCCE_get(valchar, (t_vcharp)(comm->gather[0]), RCCE_LINE_SIZE, comm->member[i]))) #else if ((error = RCCE_get_flag(valchar, (t_vcharp)(comm->gather[0]), RCCE_LINE_SIZE, comm->member[i]))) #endif return(RCCE_error_return(RCCE_debug_synch,error)); if (*val == comm->cycle) comm->count++; } if(comm->count != comm->size) { comm->label = 1; return(RCCE_PENDING); } } // set release flags for (i=1; i<comm->size; i++) { if ((error = RCCE_flag_write(&(comm->release), comm->cycle, comm->member[i]))) return(RCCE_error_return(RCCE_debug_synch,error)); } } else { int test; comm->cycle = *cycle; label2: RCCE_test_flag(comm->release, comm->cycle, &test); if(!test) { comm->label = 2; return(RCCE_PENDING); } } comm->label = 0; #endif // !USE_FAT_BARRIER if (RCCE_debug_synch) fprintf(STDERR,"UE %d has cleared barrier\n", RCCE_IAM); return(RCCE_SUCCESS); } #endif void RCCE_fence() { return; } #endif
openmp-ex03.c
#include <stdio.h> #include <omp.h> int main(void) { int num_threads, my_thread; /* OpenMP implements "fork-join", where one master thread runs outside of * the parallel regions, forks to create them, and joins them at the end of * the region. Let's see if we can confirm this. */ /* Count the number of threads and my thread number before ... */ num_threads = omp_get_num_threads(); my_thread = omp_get_thread_num(); printf ("\"You're all individuals!\" said %d of %d.\n", my_thread, num_threads); #pragma omp parallel { /* during ... */ num_threads = omp_get_num_threads(); my_thread = omp_get_thread_num(); printf("\"Yes, we're all individuals!\" replied %d of %d.\n", my_thread, num_threads); } /* and after the parallel region */ num_threads = omp_get_num_threads(); my_thread = omp_get_thread_num(); printf ("\"I'm not,\" said %d of %d.\n", my_thread, num_threads); return 0; }
aix_smd5_fmt_plug.c
/* AIX smd5 cracker patch for JtR. Hacked together during April of 2013 by Dhiru * Kholia <dhiru at openwall.com>. * * 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. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_smd5; #elif FMT_REGISTERS_H john_register_one(&fmt_smd5); #else #include <string.h> #include <assert.h> #include <errno.h> #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 16 // tuned on i7 w/HT #endif #endif #include "md5.h" #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "memdbg.h" #define FORMAT_LABEL "aix-smd5" #define FORMAT_NAME "AIX LPA {smd5} (modified crypt-md5)" #define FORMAT_TAG "{smd5}" #define FORMAT_TAG1 "$1$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define FORMAT_TAG1_LEN (sizeof(FORMAT_TAG1)-1) #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 16 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(int) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests smd5_tests[] = { /* following hashes are AIX non-standard smd5 hashes */ {"{smd5}s8/xSJ/v$uGam4GB8hOjTLQqvBfxJ2/", "password"}, {"{smd5}alRJaSLb$aKM3H1.h1ycXl5GEVDH1e1", "aixsucks?"}, {"{smd5}eLB0QWeS$Eg.YfWY8clZuCxF0xNrKg.", "0123456789ABCDE"}, /* following hashes are AIX standard smd5 hashes (with corrected tag) * lpa_options = std_hash=true */ {"$1$JVDbGx8K$T9h8HK4LZxeLPMTAxCfpc1", "password"}, {"$1$1Cu6fEvv$42kuaJ5fMEqyVStPuFG040", "0123456789ABCDE"}, {"$1$ql5x.xXL$vYVDhExol2xUBBpERRWcn1", "jtr>hashcat"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static struct custom_salt { int is_standard; unsigned char salt[16]; } *cur_salt; 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_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p; char *ctcopy; char *keeptr; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0 && strncmp(ciphertext, FORMAT_TAG1, FORMAT_TAG1_LEN)) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; if (!strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) ctcopy += FORMAT_TAG_LEN; else ctcopy += FORMAT_TAG1_LEN; if ((p = strtokm(ctcopy, "$")) == NULL) /* salt */ goto err; if (strlen(p) != 8) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* hash */ goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); keeptr = ctcopy; if (!strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) { ctcopy += FORMAT_TAG_LEN; cs.is_standard = 0; } else { ctcopy += FORMAT_TAG1_LEN; cs.is_standard = 1; } p = strtokm(ctcopy, "$"); strncpy((char*)cs.salt, p, 9); p = strtokm(NULL, "$"); MEM_FREE(keeptr); return (void *)&cs; } #define TO_BINARY(b1, b2, b3) \ value = \ (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6) | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[2])] << 12) | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[3])] << 18); \ pos += 4; \ out.b[b1] = value >> 16; \ out.b[b2] = value >> 8; \ out.b[b3] = value; static void* get_binary(char *ciphertext) { static union { char b[16]; ARCH_WORD w; } out; char *pos; ARCH_WORD_32 value; if (!strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) pos = ciphertext + FORMAT_TAG_LEN; else pos = ciphertext + FORMAT_TAG1_LEN; while (*pos++ != '$'); TO_BINARY(0, 6, 12); TO_BINARY(1, 7, 13); TO_BINARY(2, 8, 14); TO_BINARY(3, 9, 15); TO_BINARY(4, 10, 5); out.b[11] = (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] | ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6); return out.b; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } /* * $Id: md5_crypt.c,v 1.1 2002-05-11 14:42:35 cpbotha Exp $ * * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <phk@login.dknet.dk> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp * ---------------------------------------------------------------------------- * * Origin: Id: crypt.c,v 1.3 1995/05/30 05:42:22 rgrimes Exp * */ static void crypt_md5(char *pw, char *salt, int is_standard, char *passwd) { char *magic = "$1$"; /* This string is magic for this algorithm. Having * it this way, we can get get better later on */ char *sp, *ep; unsigned char final[16]; int sl, pl, i, j; MD5_CTX ctx, ctx1; /* Refine the Salt first */ sp = salt; /* If it starts with the magic string, then skip that */ if (!strncmp(sp, magic, strlen(magic))) sp += strlen(magic); /* It stops at the first '$', max 8 chars */ for (ep = sp; *ep && *ep != '$' && ep < (sp + 8); ep++) continue; /* get the length of the true salt */ sl = ep - sp; MD5_Init(&ctx); /* The password first, since that is what is most unknown */ MD5_Update(&ctx,(unsigned char *)pw,strlen(pw)); // The following license text applies to the "if" code block // License: belongs to the PUBLIC DOMAIN, donated to hashcat, credits MUST go to atom // (hashcat) and philsmd for their hard work. Thx // Disclaimer: WE PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER // EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // Furthermore, NO GUARANTEES THAT IT WORKS FOR YOU AND WORKS CORRECTLY if (is_standard) { /* Then our magic string */ MD5_Update(&ctx,(unsigned char *)magic,strlen(magic)); /* Then the raw salt */ MD5_Update(&ctx,(unsigned char *)sp,sl); } else { MD5_Update(&ctx,(unsigned char *)sp,sl); } /* Then just as many characters of the MD5_(pw,salt,pw) */ MD5_Init(&ctx1); MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); MD5_Update(&ctx1,(unsigned char *)sp,sl); MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); MD5_Final(final,&ctx1); for (pl = strlen(pw); pl > 0; pl -= 16) MD5_Update(&ctx,(unsigned char *)final,pl>16 ? 16 : pl); memset(final, 0, sizeof final); /* Then something really weird... */ for (j = 0, i = strlen(pw); i; i >>= 1) if (i & 1) MD5_Update(&ctx, (unsigned char *)final+j, 1); else MD5_Update(&ctx, (unsigned char *)pw+j, 1); /* Now make the output string */ strcpy(passwd, magic); strncat(passwd, sp, sl); strcat(passwd, "$"); MD5_Final(final,&ctx); /* * and now, just to make sure things don't run too fast * On a 60 Mhz Pentium this takes 34 msec, so you would * need 30 seconds to build a 1000 entry dictionary... */ for (i = 0; i < 1000; i++) { MD5_Init(&ctx1); if (i & 1) MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); else MD5_Update(&ctx1,(unsigned char *)final,16); if (i % 3) MD5_Update(&ctx1,(unsigned char *)sp,sl); if (i % 7) MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); if (i & 1) MD5_Update(&ctx1,(unsigned char *)final,16); else MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); MD5_Final(final,&ctx1); } memcpy(passwd, final, 16); } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { crypt_md5(saved_key[index], (char*)cur_salt->salt, cur_salt->is_standard, (char *)crypt_out[index]); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void smd5_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 salt_hash(void *salt) { return *(unsigned int*)salt & (SALT_HASH_SIZE - 1); } struct fmt_main fmt_smd5 = { { 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 }, { FORMAT_TAG, FORMAT_TAG1 }, smd5_tests }, { init, done, fmt_default_reset, fmt_default_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 }, salt_hash, NULL, set_salt, smd5_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 */
threading.h
#ifndef LIGHTGBM_UTILS_THREADING_H_ #define LIGHTGBM_UTILS_THREADING_H_ #include <omp.h> #include <vector> #include <functional> namespace LightGBM { class Threading { public: template<typename INDEX_T> static inline void For(INDEX_T start, INDEX_T end, const std::function<void(int, INDEX_T, INDEX_T)>& inner_fun) { int num_threads = 1; #pragma omp parallel #pragma omp master { num_threads = omp_get_num_threads(); } INDEX_T num_inner = (end - start + num_threads - 1) / num_threads; if (num_inner <= 0) { num_inner = 1; } #pragma omp parallel for schedule(static,1) for (int i = 0; i < num_threads; ++i) { INDEX_T inner_start = start + num_inner * i; INDEX_T inner_end = inner_start + num_inner; if (inner_end > end) { inner_end = end; } if (inner_start < end) { inner_fun(i, inner_start, inner_end); } } } }; } // namespace LightGBM #endif // LightGBM_UTILS_THREADING_H_
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; } }; // TODO SYCL Integration header approach relies on an assumption that kernel // lambda objects created by the host compiler and any of the device compilers // will be identical wrt to field types, order and offsets. Some verification // mechanism should be developed to enforce that. // TODO FIXME SYCL Support for SYCL in FE should be refactored: // - kernel identification and generation should be made a separate pass over // AST. RecursiveASTVisitor + VisitFunctionTemplateDecl + // FunctionTemplateDecl::getSpecializations() mechanism could be used for that. // - All SYCL stuff on Sema level should be encapsulated into a single Sema // field // - Move SYCL stuff into a separate header // Represents contents of a SYCL integration header file produced by a SYCL // device compiler and used by SYCL host compiler (via forced inclusion into // compiled SYCL source): // - SYCL kernel names // - SYCL kernel parameters and offsets of corresponding actual arguments class SYCLIntegrationHeader { public: // Kind of kernel's parameters as captured by the compiler in the // kernel lambda or function object enum kernel_param_kind_t { kind_first, kind_accessor = kind_first, kind_std_layout, kind_sampler, kind_pointer, kind_last = kind_pointer }; public: SYCLIntegrationHeader(DiagnosticsEngine &Diag, bool UnnamedLambdaSupport); /// Emits contents of the header into given stream. void emit(raw_ostream &Out); /// Emits contents of the header into a file with given name. /// Returns true/false on success/failure. bool emit(const StringRef &MainSrc); /// Signals that subsequent parameter descriptor additions will go to /// the kernel with given name. Starts new kernel invocation descriptor. void startKernel(StringRef KernelName, QualType KernelNameType, StringRef KernelStableName); /// Adds a kernel parameter descriptor to current kernel invocation /// descriptor. void addParamDesc(kernel_param_kind_t Kind, int Info, unsigned Offset); /// Signals that addition of parameter descriptors to current kernel /// invocation descriptor has finished. void endKernel(); private: // Kernel actual parameter descriptor. struct KernelParamDesc { // Represents a parameter kind. kernel_param_kind_t Kind = kind_last; // If Kind is kind_scalar or kind_struct, then // denotes parameter size in bytes (includes padding for structs) // If Kind is kind_accessor // denotes access target; possible access targets are defined in // access/access.hpp int Info = 0; // Offset of the captured parameter value in the lambda or function object. unsigned Offset = 0; KernelParamDesc() = default; }; // Kernel invocation descriptor struct KernelDesc { /// Kernel name. std::string Name; /// Kernel name type. QualType NameType; /// Kernel name with stable lambda name mangling std::string StableName; /// Descriptor of kernel actual parameters. SmallVector<KernelParamDesc, 8> Params; KernelDesc() = default; }; /// Returns the latest invocation descriptor started by /// SYCLIntegrationHeader::startKernel KernelDesc *getCurKernelDesc() { return KernelDescs.size() > 0 ? &KernelDescs[KernelDescs.size() - 1] : nullptr; } /// Emits a forward declaration for given declaration. void emitFwdDecl(raw_ostream &O, const Decl *D); /// Emits forward declarations of classes and template classes on which /// declaration of given type depends. See example in the comments for the /// implementation. /// \param O /// stream to emit to /// \param T /// type to emit forward declarations for /// \param Emitted /// a set of declarations forward declrations has been emitted for already void emitForwardClassDecls(raw_ostream &O, QualType T, llvm::SmallPtrSetImpl<const void*> &Emitted); private: /// Keeps invocation descriptors for each kernel invocation started by /// SYCLIntegrationHeader::startKernel SmallVector<KernelDesc, 4> KernelDescs; /// Used for emitting diagnostics. DiagnosticsEngine &Diag; /// Whether header is generated with unnamed lambda support bool UnnamedLambdaSupport; }; /// 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; /// 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); 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; /// 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); /// 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(); /// 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, llvm::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, llvm::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); bool CheckConstexprFunctionDecl(const FunctionDecl *FD); bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); 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); 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); ExprResult BuildUniqueStableName(SourceLocation OpLoc, TypeSourceInfo *Operand); ExprResult BuildUniqueStableName(SourceLocation OpLoc, Expr *E); ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation L, SourceLocation R, ParsedType Ty); ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation L, SourceLocation R, Expr *Operand); 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); 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); 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); template <typename AttrType> bool checkRangedIntegralArgument(Expr *E, const AttrType *TmpAttr, ExprResult &Result); template <typename AttrType> void AddOneConstantValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex); template <typename AttrType> void AddOneConstantPowerTwoValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex); /// 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); /// Check if the expression is allowed to be used in expressions for the /// OpenMP devices. void checkOpenMPDeviceExpr(const Expr *E); /// 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. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) 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(); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OMPDeclareTargetDeclAttr::MapTypeTy MT, NamedDeclSetType &SameDirectiveDecls); /// 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); 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); 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 CheckIntelFPGABuiltinFunctionCall(unsigned BuiltinID, CallExpr *Call); 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; 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 }; private: // We store SYCL Kernels here and handle separately -- which is a hack. // FIXME: It would be best to refactor this. SmallVector<Decl*, 4> SyclDeviceDecls; // SYCL integration header instance for current compilation unit this Sema // is associated with. std::unique_ptr<SYCLIntegrationHeader> SyclIntHeader; public: void addSyclDeviceDecl(Decl *d) { SyclDeviceDecls.push_back(d); } SmallVectorImpl<Decl *> &syclDeviceDecls() { return SyclDeviceDecls; } /// Lazily creates and returns SYCL integration header instance. SYCLIntegrationHeader &getSyclIntegrationHeader() { if (SyclIntHeader == nullptr) SyclIntHeader = llvm::make_unique<SYCLIntegrationHeader>( getDiagnostics(), getLangOpts().SYCLUnnamedLambda); return *SyclIntHeader.get(); } enum SYCLRestrictKind { KernelGlobalVariable, KernelRTTI, KernelNonConstStaticDataVariable, KernelCallVirtualFunction, KernelUseExceptions, KernelCallRecursiveFunction, KernelCallFunctionPointer, KernelAllocateStorage, KernelUseAssembly, KernelHavePolymorphicClass, KernelCallVariadicFunction }; DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); void ConstructOpenCLKernel(FunctionDecl *KernelCallerFunc); void MarkDevice(void); bool CheckSYCLCall(SourceLocation Loc, FunctionDecl *Callee); }; /// 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
GB_unaryop__lnot_uint64_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_uint64_uint8 // op(A') function: GB_tran__lnot_uint64_uint8 // C type: uint64_t // A type: uint8_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT64 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint64_uint8 ( uint64_t *Cx, // Cx and Ax may be aliased uint8_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_uint64_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp-low.c
/* * Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved. */ /* Lowering pass for OpenMP directives. Converts OpenMP directives into explicit calls to the runtime library (libgomp) and data marshalling to implement data sharing and copying clauses. Contributed by Diego Novillo <dnovillo@redhat.com> Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, 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 COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "rtl.h" #include "tree-gimple.h" #include "tree-inline.h" #include "langhooks.h" #include "diagnostic.h" #include "tree-flow.h" #include "timevar.h" #include "flags.h" #include "function.h" #include "expr.h" #include "toplev.h" #include "tree-pass.h" #include "ggc.h" #include "except.h" /* Lowering of OpenMP parallel and workshare constructs proceeds in two phases. The first phase scans the function looking for OMP statements and then for variables that must be replaced to satisfy data sharing clauses. The second phase expands code for the constructs, as well as re-gimplifying things when variables have been replaced with complex expressions. Final code generation is done by pass_expand_omp. The flowgraph is scanned for parallel regions which are then moved to a new function, to be invoked by the thread library. */ /* Context structure. Used to store information about each parallel directive in the code. */ typedef struct omp_context { /* This field must be at the beginning, as we do "inheritance": Some callback functions for tree-inline.c (e.g., omp_copy_decl) receive a copy_body_data pointer that is up-casted to an omp_context pointer. */ copy_body_data cb; /* The tree of contexts corresponding to the encountered constructs. */ struct omp_context *outer; tree stmt; /* Map variables to fields in a structure that allows communication between sending and receiving threads. */ splay_tree field_map; tree record_type; tree sender_decl; tree receiver_decl; /* These are used just by task contexts, if task firstprivate fn is needed. srecord_type is used to communicate from the thread that encountered the task construct to task firstprivate fn, record_type is allocated by GOMP_task, initialized by task firstprivate fn and passed to the task body fn. */ splay_tree sfield_map; tree srecord_type; /* A chain of variables to add to the top-level block surrounding the construct. In the case of a parallel, this is in the child function. */ tree block_vars; /* What to do with variables with implicitly determined sharing attributes. */ enum omp_clause_default_kind default_kind; /* Nesting depth of this context. Used to beautify error messages re invalid gotos. The outermost ctx is depth 1, with depth 0 being reserved for the main body of the function. */ int depth; /* True if this parallel directive is nested within another. */ bool is_nested; } omp_context; struct omp_for_data_loop { tree v, n1, n2, step; enum tree_code cond_code; }; /* A structure describing the main elements of a parallel loop. */ struct omp_for_data { struct omp_for_data_loop loop; tree chunk_size, for_stmt; tree pre, iter_type; int collapse; bool have_nowait, have_ordered; enum omp_clause_schedule_kind sched_kind; struct omp_for_data_loop *loops; }; static splay_tree all_contexts; static int taskreg_nesting_level; struct omp_region *root_omp_region; static bitmap task_shared_vars; static void scan_omp (tree *, omp_context *); static void lower_omp (tree *, omp_context *); static tree lookup_decl_in_outer_ctx (tree, omp_context *); static tree maybe_lookup_decl_in_outer_ctx (tree, omp_context *); /* Find an OpenMP clause of type KIND within CLAUSES. */ static tree find_omp_clause (tree clauses, enum tree_code kind) { for (; clauses ; clauses = OMP_CLAUSE_CHAIN (clauses)) if (OMP_CLAUSE_CODE (clauses) == kind) return clauses; return NULL_TREE; } /* Return true if CTX is for an omp parallel. */ static inline bool is_parallel_ctx (omp_context *ctx) { return TREE_CODE (ctx->stmt) == OMP_PARALLEL; } /* Return true if CTX is for an omp task. */ static inline bool is_task_ctx (omp_context *ctx) { return TREE_CODE (ctx->stmt) == OMP_TASK; } /* Return true if CTX is for an omp parallel or omp task. */ static inline bool is_taskreg_ctx (omp_context *ctx) { return TREE_CODE (ctx->stmt) == OMP_PARALLEL || TREE_CODE (ctx->stmt) == OMP_TASK; } /* Return true if REGION is a combined parallel+workshare region. */ static inline bool is_combined_parallel (struct omp_region *region) { return region->is_combined_parallel; } /* Extract the header elements of parallel loop FOR_STMT and store them into *FD. */ static void extract_omp_for_data (tree for_stmt, struct omp_for_data *fd, struct omp_for_data_loop *loops) { tree t, *collapse_iter, *collapse_count; tree count = NULL_TREE, iter_type = long_integer_type_node; struct omp_for_data_loop *loop; int i; struct omp_for_data_loop dummy_loop; fd->for_stmt = for_stmt; fd->pre = NULL; fd->collapse = TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); if (fd->collapse > 1) fd->loops = loops; else fd->loops = &fd->loop; fd->have_nowait = fd->have_ordered = false; fd->sched_kind = OMP_CLAUSE_SCHEDULE_STATIC; fd->chunk_size = NULL_TREE; collapse_iter = NULL; collapse_count = NULL; for (t = OMP_FOR_CLAUSES (for_stmt); t ; t = OMP_CLAUSE_CHAIN (t)) switch (OMP_CLAUSE_CODE (t)) { case OMP_CLAUSE_NOWAIT: fd->have_nowait = true; break; case OMP_CLAUSE_ORDERED: fd->have_ordered = true; break; case OMP_CLAUSE_SCHEDULE: fd->sched_kind = OMP_CLAUSE_SCHEDULE_KIND (t); fd->chunk_size = OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (t); break; case OMP_CLAUSE_COLLAPSE: if (fd->collapse > 1) { collapse_iter = &OMP_CLAUSE_COLLAPSE_ITERVAR (t); collapse_count = &OMP_CLAUSE_COLLAPSE_COUNT (t); } default: break; } /* FIXME: for now map schedule(auto) to schedule(static). There should be analysis to determine whether all iterations are approximately the same amount of work (then schedule(static) is best) or if it varries (then schedule(dynamic,N) is better). */ if (fd->sched_kind == OMP_CLAUSE_SCHEDULE_AUTO) { fd->sched_kind = OMP_CLAUSE_SCHEDULE_STATIC; gcc_assert (fd->chunk_size == NULL); } gcc_assert (fd->collapse == 1 || collapse_iter != NULL); if (fd->sched_kind == OMP_CLAUSE_SCHEDULE_RUNTIME) gcc_assert (fd->chunk_size == NULL); else if (fd->chunk_size == NULL) { /* We only need to compute a default chunk size for ordered static loops and dynamic loops. */ if (fd->sched_kind != OMP_CLAUSE_SCHEDULE_STATIC || fd->have_ordered || fd->collapse > 1) fd->chunk_size = (fd->sched_kind == OMP_CLAUSE_SCHEDULE_STATIC) ? integer_zero_node : integer_one_node; } for (i = 0; i < fd->collapse; i++) { if (fd->collapse == 1) loop = &fd->loop; else if (loops != NULL) loop = loops + i; else loop = &dummy_loop; t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); loop->v = TREE_OPERAND (t, 0); gcc_assert (DECL_P (loop->v)); gcc_assert (TREE_CODE (TREE_TYPE (loop->v)) == INTEGER_TYPE); loop->n1 = TREE_OPERAND (t, 1); t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i); loop->cond_code = TREE_CODE (t); gcc_assert (TREE_OPERAND (t, 0) == loop->v); loop->n2 = TREE_OPERAND (t, 1); switch (loop->cond_code) { case LT_EXPR: case GT_EXPR: break; case LE_EXPR: if (POINTER_TYPE_P (TREE_TYPE (loop->n2))) loop->n2 = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (loop->n2), loop->n2, size_one_node); else loop->n2 = fold_build2 (PLUS_EXPR, TREE_TYPE (loop->n2), loop->n2, build_int_cst (TREE_TYPE (loop->n2), 1)); loop->cond_code = LT_EXPR; break; case GE_EXPR: if (POINTER_TYPE_P (TREE_TYPE (loop->n2))) loop->n2 = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (loop->n2), loop->n2, size_int (-1)); else loop->n2 = fold_build2 (MINUS_EXPR, TREE_TYPE (loop->n2), loop->n2, build_int_cst (TREE_TYPE (loop->n2), 1)); loop->cond_code = GT_EXPR; break; default: gcc_unreachable (); } t = TREE_VEC_ELT (OMP_FOR_INCR (fd->for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); gcc_assert (TREE_OPERAND (t, 0) == loop->v); t = TREE_OPERAND (t, 1); gcc_assert (TREE_OPERAND (t, 0) == loop->v); switch (TREE_CODE (t)) { case PLUS_EXPR: loop->step = TREE_OPERAND (t, 1); break; case MINUS_EXPR: loop->step = TREE_OPERAND (t, 1); loop->step = fold_build1 (NEGATE_EXPR, TREE_TYPE (loop->step), loop->step); break; default: gcc_unreachable (); } if (iter_type != long_long_unsigned_type_node) { if (POINTER_TYPE_P (TREE_TYPE (loop->v))) iter_type = long_long_unsigned_type_node; else if (TYPE_UNSIGNED (TREE_TYPE (loop->v)) && TYPE_PRECISION (TREE_TYPE (loop->v)) >= TYPE_PRECISION (iter_type)) { tree n; if (loop->cond_code == LT_EXPR) n = fold_build2 (PLUS_EXPR, TREE_TYPE (loop->v), loop->n2, loop->step); else n = loop->n1; if (TREE_CODE (n) != INTEGER_CST || tree_int_cst_lt (TYPE_MAX_VALUE (iter_type), n)) iter_type = long_long_unsigned_type_node; } else if (TYPE_PRECISION (TREE_TYPE (loop->v)) > TYPE_PRECISION (iter_type)) { tree n1, n2; if (loop->cond_code == LT_EXPR) { n1 = loop->n1; n2 = fold_build2 (PLUS_EXPR, TREE_TYPE (loop->v), loop->n2, loop->step); } else { n1 = fold_build2 (MINUS_EXPR, TREE_TYPE (loop->v), loop->n2, loop->step); n2 = loop->n1; } if (TREE_CODE (n1) != INTEGER_CST || TREE_CODE (n2) != INTEGER_CST || !tree_int_cst_lt (TYPE_MIN_VALUE (iter_type), n1) || !tree_int_cst_lt (n2, TYPE_MAX_VALUE (iter_type))) iter_type = long_long_unsigned_type_node; } } if (collapse_count && *collapse_count == NULL) { if ((i == 0 || count != NULL_TREE) && TREE_CODE (TREE_TYPE (loop->v)) == INTEGER_TYPE && TREE_CONSTANT (loop->n1) && TREE_CONSTANT (loop->n2) && TREE_CODE (loop->step) == INTEGER_CST) { tree itype = TREE_TYPE (loop->v); if (POINTER_TYPE_P (itype)) itype = lang_hooks.types.type_for_size (TYPE_PRECISION (itype), 0); t = build_int_cst (itype, (loop->cond_code == LT_EXPR ? -1 : 1)); t = fold_build2 (PLUS_EXPR, itype, fold_convert (itype, loop->step), t); t = fold_build2 (PLUS_EXPR, itype, t, fold_convert (itype, loop->n2)); t = fold_build2 (MINUS_EXPR, itype, t, fold_convert (itype, loop->n1)); if (TYPE_UNSIGNED (itype) && loop->cond_code == GT_EXPR) t = fold_build2 (TRUNC_DIV_EXPR, itype, fold_build1 (NEGATE_EXPR, itype, t), fold_build1 (NEGATE_EXPR, itype, fold_convert (itype, loop->step))); else t = fold_build2 (TRUNC_DIV_EXPR, itype, t, fold_convert (itype, loop->step)); t = fold_convert (long_long_unsigned_type_node, t); if (count != NULL_TREE) count = fold_build2 (MULT_EXPR, long_long_unsigned_type_node, count, t); else count = t; if (TREE_CODE (count) != INTEGER_CST) count = NULL_TREE; } else count = NULL_TREE; } } if (count) { if (!tree_int_cst_lt (count, TYPE_MAX_VALUE (long_integer_type_node))) iter_type = long_long_unsigned_type_node; else iter_type = long_integer_type_node; } else if (collapse_iter && *collapse_iter != NULL) iter_type = TREE_TYPE (*collapse_iter); fd->iter_type = iter_type; if (collapse_iter && *collapse_iter == NULL) *collapse_iter = create_tmp_var (iter_type, ".iter"); if (collapse_count && *collapse_count == NULL) { if (count) *collapse_count = fold_convert (iter_type, count); else *collapse_count = create_tmp_var (iter_type, ".count"); } if (fd->collapse > 1) { fd->loop.v = *collapse_iter; fd->loop.n1 = build_int_cst (TREE_TYPE (fd->loop.v), 0); fd->loop.n2 = *collapse_count; fd->loop.step = build_int_cst (TREE_TYPE (fd->loop.v), 1); fd->loop.cond_code = LT_EXPR; } } /* Given two blocks PAR_ENTRY_BB and WS_ENTRY_BB such that WS_ENTRY_BB is the immediate dominator of PAR_ENTRY_BB, return true if there are no data dependencies that would prevent expanding the parallel directive at PAR_ENTRY_BB as a combined parallel+workshare region. When expanding a combined parallel+workshare region, the call to the child function may need additional arguments in the case of OMP_FOR regions. In some cases, these arguments are computed out of variables passed in from the parent to the child via 'struct .omp_data_s'. For instance: #pragma omp parallel for schedule (guided, i * 4) for (j ...) Is lowered into: # BLOCK 2 (PAR_ENTRY_BB) .omp_data_o.i = i; #pragma omp parallel [child fn: bar.omp_fn.0 ( ..., D.1598) # BLOCK 3 (WS_ENTRY_BB) .omp_data_i = &.omp_data_o; D.1667 = .omp_data_i->i; D.1598 = D.1667 * 4; #pragma omp for schedule (guided, D.1598) When we outline the parallel region, the call to the child function 'bar.omp_fn.0' will need the value D.1598 in its argument list, but that value is computed *after* the call site. So, in principle we cannot do the transformation. To see whether the code in WS_ENTRY_BB blocks the combined parallel+workshare call, we collect all the variables used in the OMP_FOR header check whether they appear on the LHS of any statement in WS_ENTRY_BB. If so, then we cannot emit the combined call. FIXME. If we had the SSA form built at this point, we could merely hoist the code in block 3 into block 2 and be done with it. But at this point we don't have dataflow information and though we could hack something up here, it is really not worth the aggravation. */ static bool workshare_safe_to_combine_p (basic_block par_entry_bb, basic_block ws_entry_bb) { struct omp_for_data fd; tree par_stmt, ws_stmt; par_stmt = last_stmt (par_entry_bb); ws_stmt = last_stmt (ws_entry_bb); if (TREE_CODE (ws_stmt) == OMP_SECTIONS) return true; gcc_assert (TREE_CODE (ws_stmt) == OMP_FOR); extract_omp_for_data (ws_stmt, &fd, NULL); if (fd.collapse > 1 && TREE_CODE (fd.loop.n2) != INTEGER_CST) return false; if (fd.iter_type != long_integer_type_node) return false; /* FIXME. We give up too easily here. If any of these arguments are not constants, they will likely involve variables that have been mapped into fields of .omp_data_s for sharing with the child function. With appropriate data flow, it would be possible to see through this. */ if (!is_gimple_min_invariant (fd.loop.n1) || !is_gimple_min_invariant (fd.loop.n2) || !is_gimple_min_invariant (fd.loop.step) || (fd.chunk_size && !is_gimple_min_invariant (fd.chunk_size))) return false; return true; } /* Collect additional arguments needed to emit a combined parallel+workshare call. WS_STMT is the workshare directive being expanded. */ static tree get_ws_args_for (tree ws_stmt) { tree t; if (TREE_CODE (ws_stmt) == OMP_FOR) { struct omp_for_data fd; tree ws_args; extract_omp_for_data (ws_stmt, &fd, NULL); ws_args = NULL_TREE; if (fd.chunk_size) { t = fold_convert (long_integer_type_node, fd.chunk_size); ws_args = tree_cons (NULL, t, ws_args); } t = fold_convert (long_integer_type_node, fd.loop.step); ws_args = tree_cons (NULL, t, ws_args); t = fold_convert (long_integer_type_node, fd.loop.n2); ws_args = tree_cons (NULL, t, ws_args); t = fold_convert (long_integer_type_node, fd.loop.n1); ws_args = tree_cons (NULL, t, ws_args); return ws_args; } else if (TREE_CODE (ws_stmt) == OMP_SECTIONS) { basic_block bb = bb_for_stmt (ws_stmt); t = build_int_cst (unsigned_type_node, EDGE_COUNT (bb->succs)); t = tree_cons (NULL, t, NULL); return t; } gcc_unreachable (); } /* Discover whether REGION is a combined parallel+workshare region. */ static void determine_parallel_type (struct omp_region *region) { basic_block par_entry_bb, par_exit_bb; basic_block ws_entry_bb, ws_exit_bb; if (region == NULL || region->inner == NULL || region->exit == NULL || region->inner->exit == NULL) return; /* We only support parallel+for and parallel+sections. */ if (region->type != OMP_PARALLEL || (region->inner->type != OMP_FOR && region->inner->type != OMP_SECTIONS)) return; /* Check for perfect nesting PAR_ENTRY_BB -> WS_ENTRY_BB and WS_EXIT_BB -> PAR_EXIT_BB. */ par_entry_bb = region->entry; par_exit_bb = region->exit; ws_entry_bb = region->inner->entry; ws_exit_bb = region->inner->exit; if (single_succ (par_entry_bb) == ws_entry_bb && single_succ (ws_exit_bb) == par_exit_bb && workshare_safe_to_combine_p (par_entry_bb, ws_entry_bb)) { tree ws_stmt = last_stmt (region->inner->entry); if (region->inner->type == OMP_FOR) { /* If this is a combined parallel loop, we need to determine whether or not to use the combined library calls. There are two cases where we do not apply the transformation: static loops and any kind of ordered loop. In the first case, we already open code the loop so there is no need to do anything else. In the latter case, the combined parallel loop call would still need extra synchronization to implement ordered semantics, so there would not be any gain in using the combined call. */ tree clauses = OMP_FOR_CLAUSES (ws_stmt); tree c = find_omp_clause (clauses, OMP_CLAUSE_SCHEDULE); if (c == NULL || OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_STATIC || find_omp_clause (clauses, OMP_CLAUSE_ORDERED)) { region->is_combined_parallel = false; region->inner->is_combined_parallel = false; return; } } region->is_combined_parallel = true; region->inner->is_combined_parallel = true; region->ws_args = get_ws_args_for (ws_stmt); } } /* Return true if EXPR is variable sized. */ static inline bool is_variable_sized (tree expr) { return !TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (expr))); } /* Return true if DECL is a reference type. */ static inline bool is_reference (tree decl) { return lang_hooks.decls.omp_privatize_by_reference (decl); } /* Lookup variables in the decl or field splay trees. The "maybe" form allows for the variable form to not have been entered, otherwise we assert that the variable must have been entered. */ static inline tree lookup_decl (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->cb.decl_map, (splay_tree_key) var); return (tree) n->value; } static inline tree maybe_lookup_decl (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->cb.decl_map, (splay_tree_key) var); return n ? (tree) n->value : NULL_TREE; } static inline tree lookup_field (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) var); return (tree) n->value; } static inline tree lookup_sfield (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->sfield_map ? ctx->sfield_map : ctx->field_map, (splay_tree_key) var); return (tree) n->value; } static inline tree maybe_lookup_field (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) var); return n ? (tree) n->value : NULL_TREE; } /* Return true if DECL should be copied by pointer. SHARED_CTX is the parallel context if DECL is to be shared. */ static bool use_pointer_for_field (tree decl, omp_context *shared_ctx) { if (AGGREGATE_TYPE_P (TREE_TYPE (decl))) return true; /* We can only use copy-in/copy-out semantics for shared variables when we know the value is not accessible from an outer scope. */ if (shared_ctx) { /* ??? Trivially accessible from anywhere. But why would we even be passing an address in this case? Should we simply assert this to be false, or should we have a cleanup pass that removes these from the list of mappings? */ if (TREE_STATIC (decl) || DECL_EXTERNAL (decl)) return true; /* For variables with DECL_HAS_VALUE_EXPR_P set, we cannot tell without analyzing the expression whether or not its location is accessible to anyone else. In the case of nested parallel regions it certainly may be. */ if (TREE_CODE (decl) != RESULT_DECL && DECL_HAS_VALUE_EXPR_P (decl)) return true; /* Do not use copy-in/copy-out for variables that have their address taken. */ if (TREE_ADDRESSABLE (decl)) return true; /* Disallow copy-in/out in nested parallel if decl is shared in outer parallel, otherwise each thread could store the shared variable in its own copy-in location, making the variable no longer really shared. */ if (!TREE_READONLY (decl) && shared_ctx->is_nested) { omp_context *up; for (up = shared_ctx->outer; up; up = up->outer) if (is_taskreg_ctx (up) && maybe_lookup_decl (decl, up)) break; if (up && is_taskreg_ctx (up)) { tree c; for (c = OMP_TASKREG_CLAUSES (up->stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED && OMP_CLAUSE_DECL (c) == decl) break; if (c) return true; } } /* For tasks avoid using copy-in/out, unless they are readonly (in which case just copy-in is used). As tasks can be deferred or executed in different thread, when GOMP_task returns, the task hasn't necessarily terminated. */ if (!TREE_READONLY (decl) && is_task_ctx (shared_ctx)) { tree outer = maybe_lookup_decl_in_outer_ctx (decl, shared_ctx); if (is_gimple_reg (outer)) { /* Taking address of OUTER in lower_send_shared_vars might need regimplification of everything that uses the variable. */ if (!task_shared_vars) task_shared_vars = BITMAP_ALLOC (NULL); bitmap_set_bit (task_shared_vars, DECL_UID (outer)); TREE_ADDRESSABLE (outer) = 1; } return true; } } return false; } /* Construct a new automatic decl similar to VAR. */ static tree omp_copy_decl_2 (tree var, tree name, tree type, omp_context *ctx) { tree copy = build_decl (VAR_DECL, name, type); TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (var); DECL_COMPLEX_GIMPLE_REG_P (copy) = DECL_COMPLEX_GIMPLE_REG_P (var); DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (var); DECL_IGNORED_P (copy) = DECL_IGNORED_P (var); TREE_USED (copy) = 1; DECL_CONTEXT (copy) = current_function_decl; DECL_SEEN_IN_BIND_EXPR_P (copy) = 1; TREE_CHAIN (copy) = ctx->block_vars; ctx->block_vars = copy; return copy; } static tree omp_copy_decl_1 (tree var, omp_context *ctx) { return omp_copy_decl_2 (var, DECL_NAME (var), TREE_TYPE (var), ctx); } /* Build tree nodes to access the field for VAR on the receiver side. */ static tree build_receiver_ref (tree var, bool by_ref, omp_context *ctx) { tree x, field = lookup_field (var, ctx); /* If the receiver record type was remapped in the child function, remap the field into the new record type. */ x = maybe_lookup_field (field, ctx); if (x != NULL) field = x; x = build_fold_indirect_ref (ctx->receiver_decl); x = build3 (COMPONENT_REF, TREE_TYPE (field), x, field, NULL); if (by_ref) x = build_fold_indirect_ref (x); return x; } /* Build tree nodes to access VAR in the scope outer to CTX. In the case of a parallel, this is a component reference; for workshare constructs this is some variable. */ static tree build_outer_var_ref (tree var, omp_context *ctx) { tree x; if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx))) x = var; else if (is_variable_sized (var)) { x = TREE_OPERAND (DECL_VALUE_EXPR (var), 0); x = build_outer_var_ref (x, ctx); x = build_fold_indirect_ref (x); } else if (is_taskreg_ctx (ctx)) { bool by_ref = use_pointer_for_field (var, NULL); x = build_receiver_ref (var, by_ref, ctx); } else if (ctx->outer) x = lookup_decl (var, ctx->outer); else if (is_reference (var)) /* This can happen with orphaned constructs. If var is reference, it is possible it is shared and as such valid. */ x = var; else gcc_unreachable (); if (is_reference (var)) x = build_fold_indirect_ref (x); return x; } /* Build tree nodes to access the field for VAR on the sender side. */ static tree build_sender_ref (tree var, omp_context *ctx) { tree field = lookup_sfield (var, ctx); return build3 (COMPONENT_REF, TREE_TYPE (field), ctx->sender_decl, field, NULL); } /* Add a new field for VAR inside the structure CTX->SENDER_DECL. */ static void install_var_field (tree var, bool by_ref, int mask, omp_context *ctx) { tree field, type, sfield = NULL_TREE; gcc_assert ((mask & 1) == 0 || !splay_tree_lookup (ctx->field_map, (splay_tree_key) var)); gcc_assert ((mask & 2) == 0 || !ctx->sfield_map || !splay_tree_lookup (ctx->sfield_map, (splay_tree_key) var)); type = TREE_TYPE (var); if (by_ref) type = build_pointer_type (type); else if ((mask & 3) == 1 && is_reference (var)) type = TREE_TYPE (type); field = build_decl (FIELD_DECL, DECL_NAME (var), type); /* Remember what variable this field was created for. This does have a side effect of making dwarf2out ignore this member, so for helpful debugging we clear it later in delete_omp_context. */ DECL_ABSTRACT_ORIGIN (field) = var; if (type == TREE_TYPE (var)) { DECL_ALIGN (field) = DECL_ALIGN (var); DECL_USER_ALIGN (field) = DECL_USER_ALIGN (var); TREE_THIS_VOLATILE (field) = TREE_THIS_VOLATILE (var); } else DECL_ALIGN (field) = TYPE_ALIGN (type); if ((mask & 3) == 3) { insert_field_into_struct (ctx->record_type, field); if (ctx->srecord_type) { sfield = build_decl (FIELD_DECL, DECL_NAME (var), type); DECL_ABSTRACT_ORIGIN (sfield) = var; DECL_ALIGN (sfield) = DECL_ALIGN (field); DECL_USER_ALIGN (sfield) = DECL_USER_ALIGN (field); TREE_THIS_VOLATILE (sfield) = TREE_THIS_VOLATILE (field); insert_field_into_struct (ctx->srecord_type, sfield); } } else { if (ctx->srecord_type == NULL_TREE) { tree t; ctx->srecord_type = lang_hooks.types.make_type (RECORD_TYPE); ctx->sfield_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); for (t = TYPE_FIELDS (ctx->record_type); t ; t = TREE_CHAIN (t)) { sfield = build_decl (FIELD_DECL, DECL_NAME (t), TREE_TYPE (t)); DECL_ABSTRACT_ORIGIN (sfield) = DECL_ABSTRACT_ORIGIN (t); insert_field_into_struct (ctx->srecord_type, sfield); splay_tree_insert (ctx->sfield_map, (splay_tree_key) DECL_ABSTRACT_ORIGIN (t), (splay_tree_value) sfield); } } sfield = field; insert_field_into_struct ((mask & 1) ? ctx->record_type : ctx->srecord_type, field); } if (mask & 1) splay_tree_insert (ctx->field_map, (splay_tree_key) var, (splay_tree_value) field); if ((mask & 2) && ctx->sfield_map) splay_tree_insert (ctx->sfield_map, (splay_tree_key) var, (splay_tree_value) sfield); } static tree install_var_local (tree var, omp_context *ctx) { tree new_var = omp_copy_decl_1 (var, ctx); insert_decl_map (&ctx->cb, var, new_var); return new_var; } /* Adjust the replacement for DECL in CTX for the new context. This means copying the DECL_VALUE_EXPR, and fixing up the type. */ static void fixup_remapped_decl (tree decl, omp_context *ctx, bool private_debug) { tree new_decl, size; new_decl = lookup_decl (decl, ctx); TREE_TYPE (new_decl) = remap_type (TREE_TYPE (decl), &ctx->cb); if ((!TREE_CONSTANT (DECL_SIZE (new_decl)) || private_debug) && DECL_HAS_VALUE_EXPR_P (decl)) { tree ve = DECL_VALUE_EXPR (decl); walk_tree (&ve, copy_body_r, &ctx->cb, NULL); SET_DECL_VALUE_EXPR (new_decl, ve); DECL_HAS_VALUE_EXPR_P (new_decl) = 1; } if (!TREE_CONSTANT (DECL_SIZE (new_decl))) { size = remap_decl (DECL_SIZE (decl), &ctx->cb); if (size == error_mark_node) size = TYPE_SIZE (TREE_TYPE (new_decl)); DECL_SIZE (new_decl) = size; size = remap_decl (DECL_SIZE_UNIT (decl), &ctx->cb); if (size == error_mark_node) size = TYPE_SIZE_UNIT (TREE_TYPE (new_decl)); DECL_SIZE_UNIT (new_decl) = size; } } /* The callback for remap_decl. Search all containing contexts for a mapping of the variable; this avoids having to duplicate the splay tree ahead of time. We know a mapping doesn't already exist in the given context. Create new mappings to implement default semantics. */ static tree omp_copy_decl (tree var, copy_body_data *cb) { omp_context *ctx = (omp_context *) cb; tree new_var; if (TREE_CODE (var) == LABEL_DECL) { new_var = create_artificial_label (); DECL_CONTEXT (new_var) = current_function_decl; insert_decl_map (&ctx->cb, var, new_var); return new_var; } while (!is_task_ctx (ctx)) { ctx = ctx->outer; if (ctx == NULL) return var; new_var = maybe_lookup_decl (var, ctx); if (new_var) return new_var; } if (is_global_var (var) || decl_function_context (var) != ctx->cb.src_fn) return var; return error_mark_node; } /* Return the parallel region associated with STMT. */ /* Debugging dumps for parallel regions. */ void dump_omp_region (FILE *, struct omp_region *, int); void debug_omp_region (struct omp_region *); void debug_all_omp_regions (void); /* Dump the parallel region tree rooted at REGION. */ void dump_omp_region (FILE *file, struct omp_region *region, int indent) { fprintf (file, "%*sbb %d: %s\n", indent, "", region->entry->index, tree_code_name[region->type]); if (region->inner) dump_omp_region (file, region->inner, indent + 4); if (region->cont) { fprintf (file, "%*sbb %d: OMP_CONTINUE\n", indent, "", region->cont->index); } if (region->exit) fprintf (file, "%*sbb %d: OMP_RETURN\n", indent, "", region->exit->index); else fprintf (file, "%*s[no exit marker]\n", indent, ""); if (region->next) dump_omp_region (file, region->next, indent); } void debug_omp_region (struct omp_region *region) { dump_omp_region (stderr, region, 0); } void debug_all_omp_regions (void) { dump_omp_region (stderr, root_omp_region, 0); } /* Create a new parallel region starting at STMT inside region PARENT. */ struct omp_region * new_omp_region (basic_block bb, enum tree_code type, struct omp_region *parent) { struct omp_region *region = xcalloc (1, sizeof (*region)); region->outer = parent; region->entry = bb; region->type = type; if (parent) { /* This is a nested region. Add it to the list of inner regions in PARENT. */ region->next = parent->inner; parent->inner = region; } else { /* This is a toplevel region. Add it to the list of toplevel regions in ROOT_OMP_REGION. */ region->next = root_omp_region; root_omp_region = region; } return region; } /* Release the memory associated with the region tree rooted at REGION. */ static void free_omp_region_1 (struct omp_region *region) { struct omp_region *i, *n; for (i = region->inner; i ; i = n) { n = i->next; free_omp_region_1 (i); } free (region); } /* Release the memory for the entire omp region tree. */ void free_omp_regions (void) { struct omp_region *r, *n; for (r = root_omp_region; r ; r = n) { n = r->next; free_omp_region_1 (r); } root_omp_region = NULL; } /* Create a new context, with OUTER_CTX being the surrounding context. */ static omp_context * new_omp_context (tree stmt, omp_context *outer_ctx) { omp_context *ctx = XCNEW (omp_context); splay_tree_insert (all_contexts, (splay_tree_key) stmt, (splay_tree_value) ctx); ctx->stmt = stmt; if (outer_ctx) { ctx->outer = outer_ctx; ctx->cb = outer_ctx->cb; ctx->cb.block = NULL; ctx->depth = outer_ctx->depth + 1; } else { ctx->cb.src_fn = current_function_decl; ctx->cb.dst_fn = current_function_decl; ctx->cb.src_node = cgraph_node (current_function_decl); ctx->cb.dst_node = ctx->cb.src_node; ctx->cb.src_cfun = cfun; ctx->cb.copy_decl = omp_copy_decl; ctx->cb.eh_region = -1; ctx->cb.transform_call_graph_edges = CB_CGE_MOVE; ctx->depth = 1; } ctx->cb.decl_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); return ctx; } /* Destroy a omp_context data structures. Called through the splay tree value delete callback. */ static void delete_omp_context (splay_tree_value value) { omp_context *ctx = (omp_context *) value; splay_tree_delete (ctx->cb.decl_map); if (ctx->field_map) splay_tree_delete (ctx->field_map); if (ctx->sfield_map) splay_tree_delete (ctx->sfield_map); /* We hijacked DECL_ABSTRACT_ORIGIN earlier. We need to clear it before it produces corrupt debug information. */ if (ctx->record_type) { tree t; for (t = TYPE_FIELDS (ctx->record_type); t ; t = TREE_CHAIN (t)) DECL_ABSTRACT_ORIGIN (t) = NULL; } if (ctx->srecord_type) { tree t; for (t = TYPE_FIELDS (ctx->srecord_type); t ; t = TREE_CHAIN (t)) DECL_ABSTRACT_ORIGIN (t) = NULL; } XDELETE (ctx); } /* Fix up RECEIVER_DECL with a type that has been remapped to the child context. */ static void fixup_child_record_type (omp_context *ctx) { tree f, type = ctx->record_type; /* ??? It isn't sufficient to just call remap_type here, because variably_modified_type_p doesn't work the way we expect for record types. Testing each field for whether it needs remapping and creating a new record by hand works, however. */ for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) break; if (f) { tree name, new_fields = NULL; type = lang_hooks.types.make_type (RECORD_TYPE); name = DECL_NAME (TYPE_NAME (ctx->record_type)); name = build_decl (TYPE_DECL, name, type); TYPE_NAME (type) = name; for (f = TYPE_FIELDS (ctx->record_type); f ; f = TREE_CHAIN (f)) { tree new_f = copy_node (f); DECL_CONTEXT (new_f) = type; TREE_TYPE (new_f) = remap_type (TREE_TYPE (f), &ctx->cb); TREE_CHAIN (new_f) = new_fields; walk_tree (&DECL_SIZE (new_f), copy_body_r, &ctx->cb, NULL); walk_tree (&DECL_SIZE_UNIT (new_f), copy_body_r, &ctx->cb, NULL); walk_tree (&DECL_FIELD_OFFSET (new_f), copy_body_r, &ctx->cb, NULL); new_fields = new_f; /* Arrange to be able to look up the receiver field given the sender field. */ splay_tree_insert (ctx->field_map, (splay_tree_key) f, (splay_tree_value) new_f); } TYPE_FIELDS (type) = nreverse (new_fields); layout_type (type); } TREE_TYPE (ctx->receiver_decl) = build_pointer_type (type); } /* Instantiate decls as necessary in CTX to satisfy the data sharing specified by CLAUSES. */ static void scan_sharing_clauses (tree clauses, omp_context *ctx) { tree c, decl; bool scan_array_reductions = false; for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { bool by_ref; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: decl = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) goto do_private; else if (!is_variable_sized (decl)) install_var_local (decl, ctx); break; case OMP_CLAUSE_SHARED: gcc_assert (is_taskreg_ctx (ctx)); decl = OMP_CLAUSE_DECL (c); gcc_assert (!is_variable_sized (decl)); by_ref = use_pointer_for_field (decl, ctx); /* Global variables don't need to be copied, the receiver side will use them directly. */ if (is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx))) break; if (! TREE_READONLY (decl) || TREE_ADDRESSABLE (decl) || by_ref || is_reference (decl)) { install_var_field (decl, by_ref, 3, ctx); install_var_local (decl, ctx); break; } /* We don't need to copy const scalar vars back. */ OMP_CLAUSE_SET_CODE (c, OMP_CLAUSE_FIRSTPRIVATE); goto do_private; case OMP_CLAUSE_LASTPRIVATE: /* Let the corresponding firstprivate clause create the variable. */ if (OMP_CLAUSE_LASTPRIVATE_STMT (c)) scan_array_reductions = true; if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_REDUCTION: decl = OMP_CLAUSE_DECL (c); do_private: if (is_variable_sized (decl)) { if (is_task_ctx (ctx)) install_var_field (decl, false, 1, ctx); break; } else if (is_taskreg_ctx (ctx)) { bool global = is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx)); by_ref = use_pointer_for_field (decl, NULL); if (is_task_ctx (ctx) && (global || by_ref || is_reference (decl))) { install_var_field (decl, false, 1, ctx); if (!global) install_var_field (decl, by_ref, 2, ctx); } else if (!global) install_var_field (decl, by_ref, 3, ctx); } install_var_local (decl, ctx); break; case OMP_CLAUSE_COPYPRIVATE: if (ctx->outer) scan_omp (&OMP_CLAUSE_DECL (c), ctx->outer); /* FALLTHRU */ case OMP_CLAUSE_COPYIN: decl = OMP_CLAUSE_DECL (c); by_ref = use_pointer_for_field (decl, NULL); install_var_field (decl, by_ref, 3, ctx); break; case OMP_CLAUSE_DEFAULT: ctx->default_kind = OMP_CLAUSE_DEFAULT_KIND (c); break; case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_SCHEDULE: if (ctx->outer) scan_omp (&OMP_CLAUSE_OPERAND (c, 0), ctx->outer); break; case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_UNTIED: break; default: gcc_unreachable (); } } for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_LASTPRIVATE: /* Let the corresponding firstprivate clause create the variable. */ if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_REDUCTION: decl = OMP_CLAUSE_DECL (c); if (is_variable_sized (decl)) install_var_local (decl, ctx); fixup_remapped_decl (decl, ctx, OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE && OMP_CLAUSE_PRIVATE_DEBUG (c)); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) scan_array_reductions = true; break; case OMP_CLAUSE_SHARED: decl = OMP_CLAUSE_DECL (c); if (! is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx))) fixup_remapped_decl (decl, ctx, false); break; case OMP_CLAUSE_COPYPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_UNTIED: break; default: gcc_unreachable (); } } if (scan_array_reductions) for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { scan_omp (&OMP_CLAUSE_REDUCTION_INIT (c), ctx); scan_omp (&OMP_CLAUSE_REDUCTION_MERGE (c), ctx); } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_STMT (c)) scan_omp (&OMP_CLAUSE_LASTPRIVATE_STMT (c), ctx); } /* Create a new name for omp child function. Returns an identifier. */ static GTY(()) unsigned int tmp_ompfn_id_num; static tree create_omp_child_function_name (bool task_copy) { tree name = DECL_ASSEMBLER_NAME (current_function_decl); size_t len = IDENTIFIER_LENGTH (name); char *tmp_name, *prefix; const char *suffix; suffix = task_copy ? "_omp_cpyfn" : "_omp_fn"; prefix = alloca (len + strlen (suffix) + 1); memcpy (prefix, IDENTIFIER_POINTER (name), len); strcpy (prefix + len, suffix); #ifndef NO_DOT_IN_LABEL prefix[len] = '.'; #elif !defined NO_DOLLAR_IN_LABEL prefix[len] = '$'; #endif ASM_FORMAT_PRIVATE_NAME (tmp_name, prefix, tmp_ompfn_id_num++); return get_identifier (tmp_name); } /* Build a decl for the omp child function. It'll not contain a body yet, just the bare decl. */ static void create_omp_child_function (omp_context *ctx, bool task_copy) { tree decl, type, name, t; name = create_omp_child_function_name (task_copy); if (task_copy) type = build_function_type_list (void_type_node, ptr_type_node, ptr_type_node, NULL_TREE); else type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE); decl = build_decl (FUNCTION_DECL, name, type); decl = lang_hooks.decls.pushdecl (decl); if (!task_copy) ctx->cb.dst_fn = decl; else OMP_TASK_COPYFN (ctx->stmt) = decl; TREE_STATIC (decl) = 1; TREE_USED (decl) = 1; DECL_ARTIFICIAL (decl) = 1; DECL_IGNORED_P (decl) = 0; TREE_PUBLIC (decl) = 0; DECL_UNINLINABLE (decl) = 1; DECL_EXTERNAL (decl) = 0; DECL_CONTEXT (decl) = NULL_TREE; DECL_INITIAL (decl) = make_node (BLOCK); t = build_decl (RESULT_DECL, NULL_TREE, void_type_node); DECL_ARTIFICIAL (t) = 1; DECL_IGNORED_P (t) = 1; DECL_RESULT (decl) = t; t = build_decl (PARM_DECL, get_identifier (".omp_data_i"), ptr_type_node); DECL_ARTIFICIAL (t) = 1; DECL_ARG_TYPE (t) = ptr_type_node; DECL_CONTEXT (t) = current_function_decl; TREE_USED (t) = 1; DECL_ARGUMENTS (decl) = t; if (!task_copy) ctx->receiver_decl = t; else { t = build_decl (PARM_DECL, get_identifier (".omp_data_o"), ptr_type_node); DECL_ARTIFICIAL (t) = 1; DECL_ARG_TYPE (t) = ptr_type_node; DECL_CONTEXT (t) = current_function_decl; TREE_USED (t) = 1; TREE_CHAIN (t) = DECL_ARGUMENTS (decl); DECL_ARGUMENTS (decl) = t; } /* Allocate memory for the function structure. The call to allocate_struct_function clobbers CFUN, so we need to restore it afterward. */ allocate_struct_function (decl); DECL_SOURCE_LOCATION (decl) = EXPR_LOCATION (ctx->stmt); cfun->function_end_locus = EXPR_LOCATION (ctx->stmt); cfun = ctx->cb.src_cfun; } /* Scan an OpenMP parallel directive. */ static void scan_omp_parallel (tree *stmt_p, omp_context *outer_ctx) { omp_context *ctx; tree name; /* Ignore parallel directives with empty bodies, unless there are copyin clauses. */ if (optimize > 0 && empty_body_p (OMP_PARALLEL_BODY (*stmt_p)) && find_omp_clause (OMP_CLAUSES (*stmt_p), OMP_CLAUSE_COPYIN) == NULL) { *stmt_p = build_empty_stmt (); return; } ctx = new_omp_context (*stmt_p, outer_ctx); if (taskreg_nesting_level > 1) ctx->is_nested = true; ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->default_kind = OMP_CLAUSE_DEFAULT_SHARED; ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_data_s"); name = build_decl (TYPE_DECL, name, ctx->record_type); TYPE_NAME (ctx->record_type) = name; create_omp_child_function (ctx, false); OMP_PARALLEL_FN (*stmt_p) = ctx->cb.dst_fn; scan_sharing_clauses (OMP_PARALLEL_CLAUSES (*stmt_p), ctx); scan_omp (&OMP_PARALLEL_BODY (*stmt_p), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) ctx->record_type = ctx->receiver_decl = NULL; else { layout_type (ctx->record_type); fixup_child_record_type (ctx); } } /* Scan an OpenMP task directive. */ static void scan_omp_task (tree *stmt_p, omp_context *outer_ctx) { omp_context *ctx; tree name; /* Ignore task directives with empty bodies. */ if (optimize > 0 && empty_body_p (OMP_TASK_BODY (*stmt_p))) { *stmt_p = build_empty_stmt (); return; } ctx = new_omp_context (*stmt_p, outer_ctx); if (taskreg_nesting_level > 1) ctx->is_nested = true; ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->default_kind = OMP_CLAUSE_DEFAULT_SHARED; ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_data_s"); name = build_decl (TYPE_DECL, name, ctx->record_type); TYPE_NAME (ctx->record_type) = name; create_omp_child_function (ctx, false); OMP_TASK_FN (*stmt_p) = ctx->cb.dst_fn; scan_sharing_clauses (OMP_TASK_CLAUSES (*stmt_p), ctx); if (ctx->srecord_type) { name = create_tmp_var_name (".omp_data_a"); name = build_decl (TYPE_DECL, name, ctx->srecord_type); TYPE_NAME (ctx->srecord_type) = name; create_omp_child_function (ctx, true); } scan_omp (&OMP_TASK_BODY (*stmt_p), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) { ctx->record_type = ctx->receiver_decl = NULL; OMP_TASK_ARG_SIZE (*stmt_p) = build_int_cst (long_integer_type_node, 0); OMP_TASK_ARG_ALIGN (*stmt_p) = build_int_cst (long_integer_type_node, 1); } else { tree *p, vla_fields = NULL_TREE, *q = &vla_fields; /* Move VLA fields to the end. */ p = &TYPE_FIELDS (ctx->record_type); while (*p) if (!TYPE_SIZE_UNIT (TREE_TYPE (*p)) || ! TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (*p)))) { *q = *p; *p = TREE_CHAIN (*p); TREE_CHAIN (*q) = NULL_TREE; q = &TREE_CHAIN (*q); } else p = &TREE_CHAIN (*p); *p = vla_fields; layout_type (ctx->record_type); fixup_child_record_type (ctx); if (ctx->srecord_type) layout_type (ctx->srecord_type); OMP_TASK_ARG_SIZE (*stmt_p) = fold_convert (long_integer_type_node, TYPE_SIZE_UNIT (ctx->record_type)); OMP_TASK_ARG_ALIGN (*stmt_p) = build_int_cst (long_integer_type_node, TYPE_ALIGN_UNIT (ctx->record_type)); } } /* Scan an OpenMP loop directive. */ static void scan_omp_for (tree *stmt_p, omp_context *outer_ctx) { omp_context *ctx; tree stmt; int i; stmt = *stmt_p; ctx = new_omp_context (stmt, outer_ctx); scan_sharing_clauses (OMP_FOR_CLAUSES (stmt), ctx); scan_omp (&OMP_FOR_PRE_BODY (stmt), ctx); for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (stmt)); i++) { scan_omp (&TREE_VEC_ELT (OMP_FOR_INIT (stmt), i), ctx); scan_omp (&TREE_VEC_ELT (OMP_FOR_COND (stmt), i), ctx); scan_omp (&TREE_VEC_ELT (OMP_FOR_INCR (stmt), i), ctx); } scan_omp (&OMP_FOR_BODY (stmt), ctx); } /* Scan an OpenMP sections directive. */ static void scan_omp_sections (tree *stmt_p, omp_context *outer_ctx) { tree stmt; omp_context *ctx; stmt = *stmt_p; ctx = new_omp_context (stmt, outer_ctx); scan_sharing_clauses (OMP_SECTIONS_CLAUSES (stmt), ctx); scan_omp (&OMP_SECTIONS_BODY (stmt), ctx); } /* Scan an OpenMP single directive. */ static void scan_omp_single (tree *stmt_p, omp_context *outer_ctx) { tree stmt = *stmt_p; omp_context *ctx; tree name; ctx = new_omp_context (stmt, outer_ctx); ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_copy_s"); name = build_decl (TYPE_DECL, name, ctx->record_type); TYPE_NAME (ctx->record_type) = name; scan_sharing_clauses (OMP_SINGLE_CLAUSES (stmt), ctx); scan_omp (&OMP_SINGLE_BODY (stmt), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) ctx->record_type = NULL; else layout_type (ctx->record_type); } /* Check OpenMP nesting restrictions. */ static void check_omp_nesting_restrictions (tree t, omp_context *ctx) { switch (TREE_CODE (t)) { case OMP_FOR: case OMP_SECTIONS: case OMP_SINGLE: case CALL_EXPR: for (; ctx != NULL; ctx = ctx->outer) switch (TREE_CODE (ctx->stmt)) { case OMP_FOR: case OMP_SECTIONS: case OMP_SINGLE: case OMP_ORDERED: case OMP_MASTER: case OMP_TASK: if (TREE_CODE (t) == CALL_EXPR) { warning (0, "barrier region may not be closely nested inside " "of work-sharing, critical, ordered, master or " "explicit task region"); return; } warning (0, "work-sharing region may not be closely nested inside " "of work-sharing, critical, ordered or master or explicit " "task region"); return; case OMP_PARALLEL: return; default: break; } break; case OMP_MASTER: for (; ctx != NULL; ctx = ctx->outer) switch (TREE_CODE (ctx->stmt)) { case OMP_FOR: case OMP_SECTIONS: case OMP_SINGLE: warning (0, "master region may not be closely nested inside " "of work-sharing or explicit task region"); return; case OMP_PARALLEL: return; default: break; } break; case OMP_ORDERED: for (; ctx != NULL; ctx = ctx->outer) switch (TREE_CODE (ctx->stmt)) { case OMP_CRITICAL: case OMP_TASK: warning (0, "ordered region may not be closely nested inside " "of critical or explicit task region"); return; case OMP_FOR: if (find_omp_clause (OMP_CLAUSES (ctx->stmt), OMP_CLAUSE_ORDERED) == NULL) warning (0, "ordered region must be closely nested inside " "a loop region with an ordered clause"); return; case OMP_PARALLEL: return; default: break; } break; case OMP_CRITICAL: for (; ctx != NULL; ctx = ctx->outer) if (TREE_CODE (ctx->stmt) == OMP_CRITICAL && OMP_CRITICAL_NAME (t) == OMP_CRITICAL_NAME (ctx->stmt)) { warning (0, "critical region may not be nested inside a critical " "region with the same name"); return; } break; default: break; } } /* Callback for walk_stmts used to scan for OpenMP directives at TP. */ static tree scan_omp_1 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; omp_context *ctx = wi->info; tree t = *tp; if (EXPR_HAS_LOCATION (t)) input_location = EXPR_LOCATION (t); /* Check the OpenMP nesting restrictions. */ if (ctx != NULL) { if (OMP_DIRECTIVE_P (t)) check_omp_nesting_restrictions (t, ctx); else if (TREE_CODE (t) == CALL_EXPR) { tree fndecl = get_callee_fndecl (t); if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_GOMP_BARRIER) check_omp_nesting_restrictions (t, ctx); } } *walk_subtrees = 0; switch (TREE_CODE (t)) { case OMP_PARALLEL: taskreg_nesting_level++; scan_omp_parallel (tp, ctx); taskreg_nesting_level--; break; case OMP_TASK: taskreg_nesting_level++; scan_omp_task (tp, ctx); taskreg_nesting_level--; break; case OMP_FOR: scan_omp_for (tp, ctx); break; case OMP_SECTIONS: scan_omp_sections (tp, ctx); break; case OMP_SINGLE: scan_omp_single (tp, ctx); break; case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: ctx = new_omp_context (*tp, ctx); scan_omp (&OMP_BODY (*tp), ctx); break; case BIND_EXPR: { tree var; *walk_subtrees = 1; for (var = BIND_EXPR_VARS (t); var ; var = TREE_CHAIN (var)) insert_decl_map (&ctx->cb, var, var); } break; case VAR_DECL: case PARM_DECL: case LABEL_DECL: case RESULT_DECL: if (ctx) *tp = remap_decl (t, &ctx->cb); break; default: if (ctx && TYPE_P (t)) *tp = remap_type (t, &ctx->cb); else if (!DECL_P (t)) *walk_subtrees = 1; break; } return NULL_TREE; } /* Scan all the statements starting at STMT_P. CTX contains context information about the OpenMP directives and clauses found during the scan. */ static void scan_omp (tree *stmt_p, omp_context *ctx) { location_t saved_location; struct walk_stmt_info wi; memset (&wi, 0, sizeof (wi)); wi.callback = scan_omp_1; wi.info = ctx; wi.want_bind_expr = (ctx != NULL); wi.want_locations = true; saved_location = input_location; walk_stmts (&wi, stmt_p); input_location = saved_location; } /* Re-gimplification and code generation routines. */ /* Build a call to GOMP_barrier. */ static void build_omp_barrier (tree *stmt_list) { tree t; t = built_in_decls[BUILT_IN_GOMP_BARRIER]; t = build_function_call_expr (t, NULL); gimplify_and_add (t, stmt_list); } /* If a context was created for STMT when it was scanned, return it. */ static omp_context * maybe_lookup_ctx (tree stmt) { splay_tree_node n; n = splay_tree_lookup (all_contexts, (splay_tree_key) stmt); return n ? (omp_context *) n->value : NULL; } /* Find the mapping for DECL in CTX or the immediately enclosing context that has a mapping for DECL. If CTX is a nested parallel directive, we may have to use the decl mappings created in CTX's parent context. Suppose that we have the following parallel nesting (variable UIDs showed for clarity): iD.1562 = 0; #omp parallel shared(iD.1562) -> outer parallel iD.1562 = iD.1562 + 1; #omp parallel shared (iD.1562) -> inner parallel iD.1562 = iD.1562 - 1; Each parallel structure will create a distinct .omp_data_s structure for copying iD.1562 in/out of the directive: outer parallel .omp_data_s.1.i -> iD.1562 inner parallel .omp_data_s.2.i -> iD.1562 A shared variable mapping will produce a copy-out operation before the parallel directive and a copy-in operation after it. So, in this case we would have: iD.1562 = 0; .omp_data_o.1.i = iD.1562; #omp parallel shared(iD.1562) -> outer parallel .omp_data_i.1 = &.omp_data_o.1 .omp_data_i.1->i = .omp_data_i.1->i + 1; .omp_data_o.2.i = iD.1562; -> ** #omp parallel shared(iD.1562) -> inner parallel .omp_data_i.2 = &.omp_data_o.2 .omp_data_i.2->i = .omp_data_i.2->i - 1; ** This is a problem. The symbol iD.1562 cannot be referenced inside the body of the outer parallel region. But since we are emitting this copy operation while expanding the inner parallel directive, we need to access the CTX structure of the outer parallel directive to get the correct mapping: .omp_data_o.2.i = .omp_data_i.1->i Since there may be other workshare or parallel directives enclosing the parallel directive, it may be necessary to walk up the context parent chain. This is not a problem in general because nested parallelism happens only rarely. */ static tree lookup_decl_in_outer_ctx (tree decl, omp_context *ctx) { tree t; omp_context *up; gcc_assert (ctx->is_nested); for (up = ctx->outer, t = NULL; up && t == NULL; up = up->outer) t = maybe_lookup_decl (decl, up); gcc_assert (t); return t; } /* Similar to lookup_decl_in_outer_ctx, but return DECL if not found in outer contexts. */ static tree maybe_lookup_decl_in_outer_ctx (tree decl, omp_context *ctx) { tree t = NULL; omp_context *up; if (ctx->is_nested) for (up = ctx->outer, t = NULL; up && t == NULL; up = up->outer) t = maybe_lookup_decl (decl, up); return t ? t : decl; } /* Construct the initialization value for reduction CLAUSE. */ tree omp_reduction_init (tree clause, tree type) { switch (OMP_CLAUSE_REDUCTION_CODE (clause)) { case PLUS_EXPR: case MINUS_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR: case TRUTH_XOR_EXPR: case NE_EXPR: return fold_convert (type, integer_zero_node); case MULT_EXPR: case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR: case EQ_EXPR: return fold_convert (type, integer_one_node); case BIT_AND_EXPR: return fold_convert (type, integer_minus_one_node); case MAX_EXPR: if (SCALAR_FLOAT_TYPE_P (type)) { REAL_VALUE_TYPE max, min; if (HONOR_INFINITIES (TYPE_MODE (type))) { real_inf (&max); real_arithmetic (&min, NEGATE_EXPR, &max, NULL); } else real_maxval (&min, 1, TYPE_MODE (type)); return build_real (type, min); } else { gcc_assert (INTEGRAL_TYPE_P (type)); return TYPE_MIN_VALUE (type); } case MIN_EXPR: if (SCALAR_FLOAT_TYPE_P (type)) { REAL_VALUE_TYPE max; if (HONOR_INFINITIES (TYPE_MODE (type))) real_inf (&max); else real_maxval (&max, 0, TYPE_MODE (type)); return build_real (type, max); } else { gcc_assert (INTEGRAL_TYPE_P (type)); return TYPE_MAX_VALUE (type); } default: gcc_unreachable (); } } /* Generate code to implement the input clauses, FIRSTPRIVATE and COPYIN, from the receiver (aka child) side and initializers for REFERENCE_TYPE private variables. Initialization statements go in ILIST, while calls to destructors go in DLIST. */ static void lower_rec_input_clauses (tree clauses, tree *ilist, tree *dlist, omp_context *ctx) { tree_stmt_iterator diter; tree c, dtor, copyin_seq, x, args, ptr; bool copyin_by_ref = false; bool lastprivate_firstprivate = false; int pass; *dlist = alloc_stmt_list (); diter = tsi_start (*dlist); copyin_seq = NULL; /* Do all the fixed sized types in the first pass, and the variable sized types in the second pass. This makes sure that the scalar arguments to the variable sized types are processed before we use them in the variable sized operations. */ for (pass = 0; pass < 2; ++pass) { for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { enum omp_clause_code c_kind = OMP_CLAUSE_CODE (c); tree var, new_var; bool by_ref; switch (c_kind) { case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_PRIVATE_DEBUG (c)) continue; break; case OMP_CLAUSE_SHARED: if (maybe_lookup_decl (OMP_CLAUSE_DECL (c), ctx) == NULL) { gcc_assert (is_global_var (OMP_CLAUSE_DECL (c))); continue; } case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_REDUCTION: break; case OMP_CLAUSE_LASTPRIVATE: if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) { lastprivate_firstprivate = true; if (pass != 0) continue; } break; default: continue; } new_var = var = OMP_CLAUSE_DECL (c); if (c_kind != OMP_CLAUSE_COPYIN) new_var = lookup_decl (var, ctx); if (c_kind == OMP_CLAUSE_SHARED || c_kind == OMP_CLAUSE_COPYIN) { if (pass != 0) continue; } else if (is_variable_sized (var)) { /* For variable sized types, we need to allocate the actual storage here. Call alloca and store the result in the pointer decl that we created elsewhere. */ if (pass == 0) continue; if (c_kind != OMP_CLAUSE_FIRSTPRIVATE || !is_task_ctx (ctx)) { ptr = DECL_VALUE_EXPR (new_var); gcc_assert (TREE_CODE (ptr) == INDIRECT_REF); ptr = TREE_OPERAND (ptr, 0); gcc_assert (DECL_P (ptr)); x = TYPE_SIZE_UNIT (TREE_TYPE (new_var)); args = tree_cons (NULL, x, NULL); x = built_in_decls[BUILT_IN_ALLOCA]; x = build_function_call_expr (x, args); x = fold_convert (TREE_TYPE (ptr), x); x = build2 (MODIFY_EXPR, void_type_node, ptr, x); gimplify_and_add (x, ilist); } } else if (is_reference (var)) { /* For references that are being privatized for Fortran, allocate new backing storage for the new pointer variable. This allows us to avoid changing all the code that expects a pointer to something that expects a direct variable. Note that this doesn't apply to C++, since reference types are disallowed in data sharing clauses there, except for NRV optimized return values. */ if (pass == 0) continue; x = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (new_var))); if (c_kind == OMP_CLAUSE_FIRSTPRIVATE && is_task_ctx (ctx)) { x = build_receiver_ref (var, false, ctx); x = build_fold_addr_expr (x); } else if (TREE_CONSTANT (x)) { const char *name = NULL; if (DECL_NAME (var)) name = IDENTIFIER_POINTER (DECL_NAME (new_var)); x = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (new_var)), name); gimple_add_tmp_var (x); x = build_fold_addr_expr_with_type (x, TREE_TYPE (new_var)); } else { args = tree_cons (NULL, x, NULL); x = built_in_decls[BUILT_IN_ALLOCA]; x = build_function_call_expr (x, args); x = fold_convert (TREE_TYPE (new_var), x); } x = build2 (MODIFY_EXPR, void_type_node, new_var, x); gimplify_and_add (x, ilist); new_var = build_fold_indirect_ref (new_var); } else if (c_kind == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { if (pass == 0) continue; } else if (pass != 0) continue; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: /* Shared global vars are just accessed directly. */ if (is_global_var (new_var)) break; /* Set up the DECL_VALUE_EXPR for shared variables now. This needs to be delayed until after fixup_child_record_type so that we get the correct type during the dereference. */ by_ref = use_pointer_for_field (var, ctx); x = build_receiver_ref (var, by_ref, ctx); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; /* ??? If VAR is not passed by reference, and the variable hasn't been initialized yet, then we'll get a warning for the store into the omp_data_s structure. Ideally, we'd be able to notice this and not store anything at all, but we're generating code too early. Suppress the warning. */ if (!by_ref) TREE_NO_WARNING (var) = 1; break; case OMP_CLAUSE_LASTPRIVATE: if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_PRIVATE) x = build_outer_var_ref (var, ctx); else if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) { if (is_task_ctx (ctx)) x = build_receiver_ref (var, false, ctx); else x = build_outer_var_ref (var, ctx); } else x = NULL; x = lang_hooks.decls.omp_clause_default_ctor (c, new_var, x); if (x) gimplify_and_add (x, ilist); /* FALLTHRU */ do_dtor: x = lang_hooks.decls.omp_clause_dtor (c, new_var); if (x) { dtor = x; gimplify_stmt (&dtor); tsi_link_before (&diter, dtor, TSI_SAME_STMT); } break; case OMP_CLAUSE_FIRSTPRIVATE: if (is_task_ctx (ctx)) { if (is_reference (var) || is_variable_sized (var)) goto do_dtor; else if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx)) || use_pointer_for_field (var, NULL)) { x = build_receiver_ref (var, false, ctx); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; goto do_dtor; } } x = build_outer_var_ref (var, ctx); x = lang_hooks.decls.omp_clause_copy_ctor (c, new_var, x); gimplify_and_add (x, ilist); goto do_dtor; break; case OMP_CLAUSE_COPYIN: by_ref = use_pointer_for_field (var, NULL); x = build_receiver_ref (var, by_ref, ctx); x = lang_hooks.decls.omp_clause_assign_op (c, new_var, x); append_to_statement_list (x, &copyin_seq); copyin_by_ref |= by_ref; break; case OMP_CLAUSE_REDUCTION: if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); x = build_outer_var_ref (var, ctx); if (is_reference (var)) x = build_fold_addr_expr (x); SET_DECL_VALUE_EXPR (placeholder, x); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; gimplify_and_add (OMP_CLAUSE_REDUCTION_INIT (c), ilist); OMP_CLAUSE_REDUCTION_INIT (c) = NULL; DECL_HAS_VALUE_EXPR_P (placeholder) = 0; } else { x = omp_reduction_init (c, TREE_TYPE (new_var)); gcc_assert (TREE_CODE (TREE_TYPE (new_var)) != ARRAY_TYPE); x = build2 (MODIFY_EXPR, void_type_node, new_var, x); gimplify_and_add (x, ilist); } break; default: gcc_unreachable (); } } } /* The copyin sequence is not to be executed by the main thread, since that would result in self-copies. Perhaps not visible to scalars, but it certainly is to C++ operator=. */ if (copyin_seq) { x = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; x = build_function_call_expr (x, NULL); x = build2 (NE_EXPR, boolean_type_node, x, build_int_cst (TREE_TYPE (x), 0)); x = build3 (COND_EXPR, void_type_node, x, copyin_seq, NULL); gimplify_and_add (x, ilist); } /* If any copyin variable is passed by reference, we must ensure the master thread doesn't modify it before it is copied over in all threads. Similarly for variables in both firstprivate and lastprivate clauses we need to ensure the lastprivate copying happens after firstprivate copying in all threads. */ if (copyin_by_ref || lastprivate_firstprivate) build_omp_barrier (ilist); } /* Generate code to implement the LASTPRIVATE clauses. This is used for both parallel and workshare constructs. PREDICATE may be NULL if it's always true. */ static void lower_lastprivate_clauses (tree clauses, tree predicate, tree *stmt_list, omp_context *ctx) { tree sub_list, x, c; bool par_clauses = false; /* Early exit if there are no lastprivate clauses. */ clauses = find_omp_clause (clauses, OMP_CLAUSE_LASTPRIVATE); if (clauses == NULL) { /* If this was a workshare clause, see if it had been combined with its parallel. In that case, look for the clauses on the parallel statement itself. */ if (is_parallel_ctx (ctx)) return; ctx = ctx->outer; if (ctx == NULL || !is_parallel_ctx (ctx)) return; clauses = find_omp_clause (OMP_PARALLEL_CLAUSES (ctx->stmt), OMP_CLAUSE_LASTPRIVATE); if (clauses == NULL) return; par_clauses = true; } sub_list = alloc_stmt_list (); for (c = clauses; c ;) { tree var, new_var; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE) { var = OMP_CLAUSE_DECL (c); new_var = lookup_decl (var, ctx); if (OMP_CLAUSE_LASTPRIVATE_STMT (c)) gimplify_and_add (OMP_CLAUSE_LASTPRIVATE_STMT (c), &sub_list); OMP_CLAUSE_LASTPRIVATE_STMT (c) = NULL; x = build_outer_var_ref (var, ctx); if (is_reference (var)) new_var = build_fold_indirect_ref (new_var); x = lang_hooks.decls.omp_clause_assign_op (c, x, new_var); append_to_statement_list (x, &sub_list); } c = OMP_CLAUSE_CHAIN (c); if (c == NULL && !par_clauses) { /* If this was a workshare clause, see if it had been combined with its parallel. In that case, continue looking for the clauses also on the parallel statement itself. */ if (is_parallel_ctx (ctx)) break; ctx = ctx->outer; if (ctx == NULL || !is_parallel_ctx (ctx)) break; c = find_omp_clause (OMP_PARALLEL_CLAUSES (ctx->stmt), OMP_CLAUSE_LASTPRIVATE); par_clauses = true; } } if (predicate) x = build3 (COND_EXPR, void_type_node, predicate, sub_list, NULL); else x = sub_list; gimplify_and_add (x, stmt_list); } /* Generate code to implement the REDUCTION clauses. */ static void lower_reduction_clauses (tree clauses, tree *stmt_list, omp_context *ctx) { tree sub_list = NULL, x, c; int count = 0; /* First see if there is exactly one reduction clause. Use OMP_ATOMIC update in that case, otherwise use a lock. */ for (c = clauses; c && count < 2; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION) { if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { /* Never use OMP_ATOMIC for array reductions. */ count = -1; break; } count++; } if (count == 0) return; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree var, ref, new_var; enum tree_code code; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_REDUCTION) continue; var = OMP_CLAUSE_DECL (c); new_var = lookup_decl (var, ctx); if (is_reference (var)) new_var = build_fold_indirect_ref (new_var); ref = build_outer_var_ref (var, ctx); code = OMP_CLAUSE_REDUCTION_CODE (c); /* reduction(-:var) sums up the partial results, so it acts identically to reduction(+:var). */ if (code == MINUS_EXPR) code = PLUS_EXPR; if (count == 1) { tree addr = build_fold_addr_expr (ref); addr = save_expr (addr); ref = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (addr)), addr); x = fold_build2 (code, TREE_TYPE (ref), ref, new_var); x = build2 (OMP_ATOMIC, void_type_node, addr, x); gimplify_and_add (x, stmt_list); return; } if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); if (is_reference (var)) ref = build_fold_addr_expr (ref); SET_DECL_VALUE_EXPR (placeholder, ref); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; gimplify_and_add (OMP_CLAUSE_REDUCTION_MERGE (c), &sub_list); OMP_CLAUSE_REDUCTION_MERGE (c) = NULL; OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = NULL; } else { x = build2 (code, TREE_TYPE (ref), ref, new_var); ref = build_outer_var_ref (var, ctx); x = build2 (MODIFY_EXPR, void_type_node, ref, x); append_to_statement_list (x, &sub_list); } } x = built_in_decls[BUILT_IN_GOMP_ATOMIC_START]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, stmt_list); gimplify_and_add (sub_list, stmt_list); x = built_in_decls[BUILT_IN_GOMP_ATOMIC_END]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, stmt_list); } /* Generate code to implement the COPYPRIVATE clauses. */ static void lower_copyprivate_clauses (tree clauses, tree *slist, tree *rlist, omp_context *ctx) { tree c; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree var, ref, x; bool by_ref; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_COPYPRIVATE) continue; var = OMP_CLAUSE_DECL (c); by_ref = use_pointer_for_field (var, NULL); ref = build_sender_ref (var, ctx); x = (ctx->is_nested) ? lookup_decl_in_outer_ctx (var, ctx) : var; x = by_ref ? build_fold_addr_expr (x) : x; x = build2 (MODIFY_EXPR, void_type_node, ref, x); gimplify_and_add (x, slist); ref = build_receiver_ref (var, by_ref, ctx); if (is_reference (var)) { ref = build_fold_indirect_ref (ref); var = build_fold_indirect_ref (var); } x = lang_hooks.decls.omp_clause_assign_op (c, var, ref); gimplify_and_add (x, rlist); } } /* Generate code to implement the clauses, FIRSTPRIVATE, COPYIN, LASTPRIVATE, and REDUCTION from the sender (aka parent) side. */ static void lower_send_clauses (tree clauses, tree *ilist, tree *olist, omp_context *ctx) { tree c; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree val, ref, x, var; bool by_ref, do_in = false, do_out = false; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) break; continue; case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_LASTPRIVATE: case OMP_CLAUSE_REDUCTION: break; default: continue; } var = val = OMP_CLAUSE_DECL (c); if (ctx->is_nested) var = maybe_lookup_decl_in_outer_ctx (val, ctx); if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_COPYIN && is_global_var (var)) continue; if (is_variable_sized (val)) continue; by_ref = use_pointer_for_field (val, NULL); switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: do_in = true; break; case OMP_CLAUSE_LASTPRIVATE: if (by_ref || is_reference (val)) { if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) continue; do_in = true; } else { do_out = true; if (lang_hooks.decls.omp_private_outer_ref (val)) do_in = true; } break; case OMP_CLAUSE_REDUCTION: do_in = true; do_out = !(by_ref || is_reference (val)); break; default: gcc_unreachable (); } if (do_in) { ref = build_sender_ref (val, ctx); x = by_ref ? build_fold_addr_expr (var) : var; x = build2 (MODIFY_EXPR, void_type_node, ref, x); gimplify_and_add (x, ilist); if (is_task_ctx (ctx)) DECL_ABSTRACT_ORIGIN (TREE_OPERAND (ref, 1)) = NULL; } if (do_out) { ref = build_sender_ref (val, ctx); x = build2 (MODIFY_EXPR, void_type_node, var, ref); gimplify_and_add (x, olist); } } } /* Generate code to implement SHARED from the sender (aka parent) side. This is trickier, since OMP_PARALLEL_CLAUSES doesn't list things that got automatically shared. */ static void lower_send_shared_vars (tree *ilist, tree *olist, omp_context *ctx) { tree var, ovar, nvar, f, x, record_type; if (ctx->record_type == NULL) return; record_type = ctx->srecord_type ? ctx->srecord_type : ctx->record_type; for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f)) { ovar = DECL_ABSTRACT_ORIGIN (f); nvar = maybe_lookup_decl (ovar, ctx); if (!nvar || !DECL_HAS_VALUE_EXPR_P (nvar)) continue; var = ovar; /* If CTX is a nested parallel directive. Find the immediately enclosing parallel or workshare construct that contains a mapping for OVAR. */ if (ctx->is_nested) var = lookup_decl_in_outer_ctx (ovar, ctx); if (use_pointer_for_field (ovar, ctx)) { x = build_sender_ref (ovar, ctx); var = build_fold_addr_expr (var); x = build2 (MODIFY_EXPR, void_type_node, x, var); gimplify_and_add (x, ilist); } else { x = build_sender_ref (ovar, ctx); x = build2 (MODIFY_EXPR, void_type_node, x, var); gimplify_and_add (x, ilist); if (!TREE_READONLY (var)) { x = build_sender_ref (ovar, ctx); x = build2 (MODIFY_EXPR, void_type_node, var, x); gimplify_and_add (x, olist); } } } } /* Build the function calls to GOMP_parallel_start etc to actually generate the parallel operation. REGION is the parallel region being expanded. BB is the block where to insert the code. WS_ARGS will be set if this is a call to a combined parallel+workshare construct, it contains the list of additional arguments needed by the workshare construct. */ static void expand_parallel_call (struct omp_region *region, basic_block bb, tree entry_stmt, tree ws_args) { tree t, args, val, cond, c, list, clauses; block_stmt_iterator si; int start_ix; clauses = OMP_PARALLEL_CLAUSES (entry_stmt); push_gimplify_context (); /* Determine what flavor of GOMP_parallel_start we will be emitting. */ start_ix = BUILT_IN_GOMP_PARALLEL_START; if (is_combined_parallel (region)) { switch (region->inner->type) { case OMP_FOR: gcc_assert (region->inner->sched_kind != OMP_CLAUSE_SCHEDULE_AUTO); start_ix = BUILT_IN_GOMP_PARALLEL_LOOP_STATIC_START + (region->inner->sched_kind == OMP_CLAUSE_SCHEDULE_RUNTIME ? 3 : region->inner->sched_kind); break; case OMP_SECTIONS: start_ix = BUILT_IN_GOMP_PARALLEL_SECTIONS_START; break; default: gcc_unreachable (); } } /* By default, the value of NUM_THREADS is zero (selected at run time) and there is no conditional. */ cond = NULL_TREE; val = build_int_cst (unsigned_type_node, 0); c = find_omp_clause (clauses, OMP_CLAUSE_IF); if (c) cond = OMP_CLAUSE_IF_EXPR (c); c = find_omp_clause (clauses, OMP_CLAUSE_NUM_THREADS); if (c) val = OMP_CLAUSE_NUM_THREADS_EXPR (c); /* Ensure 'val' is of the correct type. */ val = fold_convert (unsigned_type_node, val); /* If we found the clause 'if (cond)', build either (cond != 0) or (cond ? val : 1u). */ if (cond) { block_stmt_iterator si; cond = gimple_boolify (cond); if (integer_zerop (val)) val = build2 (EQ_EXPR, unsigned_type_node, cond, build_int_cst (TREE_TYPE (cond), 0)); else { basic_block cond_bb, then_bb, else_bb; edge e; tree t, then_lab, else_lab, tmp; tmp = create_tmp_var (TREE_TYPE (val), NULL); e = split_block (bb, NULL); cond_bb = e->src; bb = e->dest; remove_edge (e); then_bb = create_empty_bb (cond_bb); else_bb = create_empty_bb (then_bb); then_lab = create_artificial_label (); else_lab = create_artificial_label (); t = build3 (COND_EXPR, void_type_node, cond, build_and_jump (&then_lab), build_and_jump (&else_lab)); si = bsi_start (cond_bb); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); si = bsi_start (then_bb); t = build1 (LABEL_EXPR, void_type_node, then_lab); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); t = build2 (MODIFY_EXPR, void_type_node, tmp, val); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); si = bsi_start (else_bb); t = build1 (LABEL_EXPR, void_type_node, else_lab); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); t = build2 (MODIFY_EXPR, void_type_node, tmp, build_int_cst (unsigned_type_node, 1)); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); make_edge (cond_bb, then_bb, EDGE_TRUE_VALUE); make_edge (cond_bb, else_bb, EDGE_FALSE_VALUE); make_edge (then_bb, bb, EDGE_FALLTHRU); make_edge (else_bb, bb, EDGE_FALLTHRU); val = tmp; } list = NULL_TREE; val = get_formal_tmp_var (val, &list); si = bsi_start (bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); } list = NULL_TREE; args = tree_cons (NULL, val, NULL); t = OMP_PARALLEL_DATA_ARG (entry_stmt); if (t == NULL) t = null_pointer_node; else t = build_fold_addr_expr (t); args = tree_cons (NULL, t, args); t = build_fold_addr_expr (OMP_PARALLEL_FN (entry_stmt)); args = tree_cons (NULL, t, args); if (ws_args) args = chainon (args, ws_args); t = built_in_decls[start_ix]; t = build_function_call_expr (t, args); gimplify_and_add (t, &list); t = OMP_PARALLEL_DATA_ARG (entry_stmt); if (t == NULL) t = null_pointer_node; else t = build_fold_addr_expr (t); args = tree_cons (NULL, t, NULL); t = build_function_call_expr (OMP_PARALLEL_FN (entry_stmt), args); gimplify_and_add (t, &list); t = built_in_decls[BUILT_IN_GOMP_PARALLEL_END]; t = build_function_call_expr (t, NULL); gimplify_and_add (t, &list); si = bsi_last (bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); pop_gimplify_context (NULL_TREE); } static void maybe_catch_exception (tree *stmt_p); /* Build the function call to GOMP_task to actually generate the task operation. BB is the block where to insert the code. */ static void expand_task_call (basic_block bb, tree entry_stmt) { tree t, t1, t2, t3, flags, cond, c, clauses; block_stmt_iterator si; tree args; clauses = OMP_TASK_CLAUSES (entry_stmt); c = find_omp_clause (clauses, OMP_CLAUSE_IF); if (c) cond = gimple_boolify (OMP_CLAUSE_IF_EXPR (c)); else cond = boolean_true_node; c = find_omp_clause (clauses, OMP_CLAUSE_UNTIED); flags = build_int_cst (unsigned_type_node, (c ? 1 : 0)); si = bsi_last (bb); t = OMP_TASK_DATA_ARG (entry_stmt); if (t == NULL) t2 = null_pointer_node; else t2 = build_fold_addr_expr (t); t1 = build_fold_addr_expr (OMP_TASK_FN (entry_stmt)); t = OMP_TASK_COPYFN (entry_stmt); if (t == NULL) t3 = null_pointer_node; else t3 = build_fold_addr_expr (t); args = tree_cons (NULL, flags, NULL); args = tree_cons (NULL, cond, args); args = tree_cons (NULL, OMP_TASK_ARG_ALIGN (entry_stmt), args); args = tree_cons (NULL, OMP_TASK_ARG_SIZE (entry_stmt), args); args = tree_cons (NULL, t3, NULL); args = tree_cons (NULL, t2, NULL); args = tree_cons (NULL, t1, NULL); t = build_function_call_expr (built_in_decls[BUILT_IN_GOMP_TASK], args); force_gimple_operand_bsi (&si, t, true, NULL_TREE); } /* If exceptions are enabled, wrap *STMT_P in a MUST_NOT_THROW catch handler. This prevents programs from violating the structured block semantics with throws. */ static void maybe_catch_exception (tree *stmt_p) { tree f, t; if (!flag_exceptions) return; if (lang_protect_cleanup_actions) t = lang_protect_cleanup_actions (); else { t = built_in_decls[BUILT_IN_TRAP]; t = build_function_call_expr (t, NULL); } f = build2 (EH_FILTER_EXPR, void_type_node, NULL, NULL); EH_FILTER_MUST_NOT_THROW (f) = 1; gimplify_and_add (t, &EH_FILTER_FAILURE (f)); t = build2 (TRY_CATCH_EXPR, void_type_node, *stmt_p, NULL); append_to_statement_list (f, &TREE_OPERAND (t, 1)); *stmt_p = NULL; append_to_statement_list (t, stmt_p); } /* Chain all the DECLs in LIST by their TREE_CHAIN fields. */ static tree list2chain (tree list) { tree t; for (t = list; t; t = TREE_CHAIN (t)) { tree var = TREE_VALUE (t); if (TREE_CHAIN (t)) TREE_CHAIN (var) = TREE_VALUE (TREE_CHAIN (t)); else TREE_CHAIN (var) = NULL_TREE; } return list ? TREE_VALUE (list) : NULL_TREE; } /* Remove barriers in REGION->EXIT's block. Note that this is only valid for OMP_PARALLEL regions. Since the end of a parallel region is an implicit barrier, any workshare inside the OMP_PARALLEL that left a barrier at the end of the OMP_PARALLEL region can now be removed. */ static void remove_exit_barrier (struct omp_region *region) { block_stmt_iterator si; basic_block exit_bb; edge_iterator ei; edge e; tree t; exit_bb = region->exit; /* If the parallel region doesn't return, we don't have REGION->EXIT block at all. */ if (! exit_bb) return; /* The last insn in the block will be the parallel's OMP_RETURN. The workshare's OMP_RETURN will be in a preceding block. The kinds of statements that can appear in between are extremely limited -- no memory operations at all. Here, we allow nothing at all, so the only thing we allow to precede this OMP_RETURN is a label. */ si = bsi_last (exit_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_RETURN); bsi_prev (&si); if (!bsi_end_p (si) && TREE_CODE (bsi_stmt (si)) != LABEL_EXPR) return; FOR_EACH_EDGE (e, ei, exit_bb->preds) { si = bsi_last (e->src); if (bsi_end_p (si)) continue; t = bsi_stmt (si); if (TREE_CODE (t) == OMP_RETURN) OMP_RETURN_NOWAIT (t) = 1; } } static void remove_exit_barriers (struct omp_region *region) { if (region->type == OMP_PARALLEL) remove_exit_barrier (region); if (region->inner) { region = region->inner; remove_exit_barriers (region); while (region->next) { region = region->next; remove_exit_barriers (region); } } } /* Expand the OpenMP parallel or task directive starting at REGION. */ static void expand_omp_taskreg (struct omp_region *region) { basic_block entry_bb, exit_bb, new_bb; struct function *child_cfun, *saved_cfun; tree child_fn, block, t, ws_args; block_stmt_iterator si; tree entry_stmt; edge e; bool do_cleanup_cfg = false; entry_stmt = last_stmt (region->entry); child_fn = OMP_TASKREG_FN (entry_stmt); child_cfun = DECL_STRUCT_FUNCTION (child_fn); saved_cfun = cfun; entry_bb = region->entry; exit_bb = region->exit; if (is_combined_parallel (region)) ws_args = region->ws_args; else ws_args = NULL_TREE; if (child_cfun->cfg) { /* Due to inlining, it may happen that we have already outlined the region, in which case all we need to do is make the sub-graph unreachable and emit the parallel call. */ edge entry_succ_e, exit_succ_e; block_stmt_iterator si; entry_succ_e = single_succ_edge (entry_bb); si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_PARALLEL || TREE_CODE (bsi_stmt (si)) == OMP_TASK); bsi_remove (&si, true); new_bb = entry_bb; remove_edge (entry_succ_e); if (exit_bb) { exit_succ_e = single_succ_edge (exit_bb); make_edge (new_bb, exit_succ_e->dest, EDGE_FALLTHRU); } do_cleanup_cfg = true; } else { /* If the parallel region needs data sent from the parent function, then the very first statement (except possible tree profile counter updates) of the parallel body is a copy assignment .OMP_DATA_I = &.OMP_DATA_O. Since &.OMP_DATA_O is passed as an argument to the child function, we need to replace it with the argument as seen by the child function. In most cases, this will end up being the identity assignment .OMP_DATA_I = .OMP_DATA_I. However, if the parallel body had a function call that has been inlined, the original PARM_DECL .OMP_DATA_I may have been converted into a different local variable. In which case, we need to keep the assignment. */ if (OMP_TASKREG_DATA_ARG (entry_stmt)) { basic_block entry_succ_bb = single_succ (entry_bb); block_stmt_iterator si; for (si = bsi_start (entry_succ_bb); ; bsi_next (&si)) { tree stmt, arg; gcc_assert (!bsi_end_p (si)); stmt = bsi_stmt (si); if (TREE_CODE (stmt) != MODIFY_EXPR) continue; arg = TREE_OPERAND (stmt, 1); STRIP_NOPS (arg); if (TREE_CODE (arg) == ADDR_EXPR && TREE_OPERAND (arg, 0) == OMP_TASKREG_DATA_ARG (entry_stmt)) { if (TREE_OPERAND (stmt, 0) == DECL_ARGUMENTS (child_fn)) bsi_remove (&si, true); else TREE_OPERAND (stmt, 1) = DECL_ARGUMENTS (child_fn); break; } } } /* Declare local variables needed in CHILD_CFUN. */ block = DECL_INITIAL (child_fn); BLOCK_VARS (block) = list2chain (child_cfun->unexpanded_var_list); DECL_SAVED_TREE (child_fn) = single_succ (entry_bb)->stmt_list; /* Reset DECL_CONTEXT on locals and function arguments. */ for (t = BLOCK_VARS (block); t; t = TREE_CHAIN (t)) DECL_CONTEXT (t) = child_fn; for (t = DECL_ARGUMENTS (child_fn); t; t = TREE_CHAIN (t)) DECL_CONTEXT (t) = child_fn; /* Split ENTRY_BB at OMP_PARALLEL or OMP_TASK, so that it can be moved to the child function. */ si = bsi_last (entry_bb); t = bsi_stmt (si); gcc_assert (t && (TREE_CODE (t) == OMP_PARALLEL || TREE_CODE (t) == OMP_TASK)); bsi_remove (&si, true); e = split_block (entry_bb, t); entry_bb = e->dest; single_succ_edge (entry_bb)->flags = EDGE_FALLTHRU; /* Move the parallel region into CHILD_CFUN. We need to reset dominance information because the expansion of the inner regions has invalidated it. */ free_dominance_info (CDI_DOMINATORS); new_bb = move_sese_region_to_fn (child_cfun, entry_bb, exit_bb); if (exit_bb) single_succ_edge (new_bb)->flags = EDGE_FALLTHRU; cgraph_add_new_function (child_fn); /* Convert OMP_RETURN into a RETURN_EXPR. */ if (exit_bb) { si = bsi_last (exit_bb); gcc_assert (!bsi_end_p (si) && TREE_CODE (bsi_stmt (si)) == OMP_RETURN); t = build1 (RETURN_EXPR, void_type_node, NULL); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); } } /* Emit a library call to launch the children threads. */ if (TREE_CODE (entry_stmt) == OMP_PARALLEL) expand_parallel_call (region, new_bb, entry_stmt, ws_args); else expand_task_call (new_bb, entry_stmt); if (do_cleanup_cfg) { /* Clean up the unreachable sub-graph we created above. */ free_dominance_info (CDI_DOMINATORS); free_dominance_info (CDI_POST_DOMINATORS); cleanup_tree_cfg (); } } /* A subroutine of expand_omp_for. Generate code for a parallel loop with any schedule. Given parameters: for (V = N1; V cond N2; V += STEP) BODY; where COND is "<" or ">", we generate pseudocode more = GOMP_loop_foo_start (N1, N2, STEP, CHUNK, &istart0, &iend0); if (more) goto L0; else goto L3; L0: V = istart0; iend = iend0; L1: BODY; V += STEP; if (V cond iend) goto L1; else goto L2; L2: if (GOMP_loop_foo_next (&istart0, &iend0)) goto L0; else goto L3; L3: If this is a combined omp parallel loop, instead of the call to GOMP_loop_foo_start, we call GOMP_loop_foo_next. For collapsed loops, given parameters: collapse(3) for (V1 = N11; V1 cond1 N12; V1 += STEP1) for (V2 = N21; V2 cond2 N22; V2 += STEP2) for (V3 = N31; V3 cond3 N32; V3 += STEP3) BODY; we generate pseudocode if (cond3 is <) adj = STEP3 - 1; else adj = STEP3 + 1; count3 = (adj + N32 - N31) / STEP3; if (cond2 is <) adj = STEP2 - 1; else adj = STEP2 + 1; count2 = (adj + N22 - N21) / STEP2; if (cond1 is <) adj = STEP1 - 1; else adj = STEP1 + 1; count1 = (adj + N12 - N11) / STEP1; count = count1 * count2 * count3; more = GOMP_loop_foo_start (0, count, 1, CHUNK, &istart0, &iend0); if (more) goto L0; else goto L3; L0: V = istart0; T = V; V3 = N31 + (T % count3) * STEP3; T = T / count3; V2 = N21 + (T % count2) * STEP2; T = T / count2; V1 = N11 + T * STEP1; iend = iend0; L1: BODY; V += 1; if (V < iend) goto L10; else goto L2; L10: V3 += STEP3; if (V3 cond3 N32) goto L1; else goto L11; L11: V3 = N31; V2 += STEP2; if (V2 cond2 N22) goto L1; else goto L12; L12: V2 = N21; V1 += STEP1; goto L1; L2: if (GOMP_loop_foo_next (&istart0, &iend0)) goto L0; else goto L3; L3: */ static void expand_omp_for_generic (struct omp_region *region, struct omp_for_data *fd, enum built_in_function start_fn, enum built_in_function next_fn) { tree l0, l1, l2 = NULL, l3 = NULL; tree type, istart0, iend0, iend; tree t, args, list; basic_block entry_bb, cont_bb, exit_bb, l0_bb, l1_bb; basic_block l2_bb = NULL, l3_bb = NULL; block_stmt_iterator si; bool in_combined_parallel = is_combined_parallel (region); type = TREE_TYPE (fd->loop.v); istart0 = create_tmp_var (long_integer_type_node, ".istart0"); iend0 = create_tmp_var (long_integer_type_node, ".iend0"); iend = create_tmp_var (type, NULL); TREE_ADDRESSABLE (istart0) = 1; TREE_ADDRESSABLE (iend0) = 1; gcc_assert ((region->cont != NULL) ^ (region->exit == NULL)); entry_bb = region->entry; l0_bb = create_empty_bb (entry_bb); l1_bb = single_succ (entry_bb); l0 = tree_block_label (l0_bb); l1 = tree_block_label (l1_bb); cont_bb = region->cont; exit_bb = region->exit; if (cont_bb) { l2_bb = create_empty_bb (cont_bb); l3_bb = single_succ (cont_bb); l2 = tree_block_label (l2_bb); l3 = tree_block_label (l3_bb); } si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_FOR); if (!in_combined_parallel) { /* If this is not a combined parallel loop, emit a call to GOMP_loop_foo_start in ENTRY_BB. */ list = alloc_stmt_list (); t = build_fold_addr_expr (iend0); args = tree_cons (NULL, t, NULL); t = build_fold_addr_expr (istart0); args = tree_cons (NULL, t, args); if (fd->chunk_size) { t = fold_convert (long_integer_type_node, fd->chunk_size); args = tree_cons (NULL, t, args); } t = fold_convert (long_integer_type_node, fd->loop.step); args = tree_cons (NULL, t, args); t = fold_convert (long_integer_type_node, fd->loop.n2); args = tree_cons (NULL, t, args); t = fold_convert (long_integer_type_node, fd->loop.n1); args = tree_cons (NULL, t, args); t = build_function_call_expr (built_in_decls[start_fn], args); //t = get_formal_tmp_var (t, &list); if (cont_bb) { t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l0), build_and_jump (&l3)); append_to_statement_list (t, &list); } bsi_insert_after (&si, list, BSI_SAME_STMT); } bsi_remove (&si, true); /* Iteration setup for sequential loop goes in L0_BB. */ list = alloc_stmt_list (); t = fold_convert (type, istart0); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = fold_convert (type, iend0); t = build2 (MODIFY_EXPR, void_type_node, iend, t); gimplify_and_add (t, &list); si = bsi_start (l0_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Handle the rare case where BODY doesn't ever return. */ if (cont_bb == NULL) { remove_edge (single_succ_edge (entry_bb)); make_edge (entry_bb, l0_bb, EDGE_FALLTHRU); make_edge (l0_bb, l1_bb, EDGE_FALLTHRU); return; } /* Code to control the increment and predicate for the sequential loop goes in the first half of EXIT_BB (we split EXIT_BB so that we can inherit all the edges going out of the loop body). */ list = alloc_stmt_list (); t = build2 (PLUS_EXPR, type, fd->loop.v, fd->loop.step); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = build2 (fd->loop.cond_code, boolean_type_node, fd->loop.v, iend); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l1), build_and_jump (&l2)); append_to_statement_list (t, &list); si = bsi_last (cont_bb); bsi_insert_after (&si, list, BSI_SAME_STMT); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); bsi_remove (&si, true); /* Emit code to get the next parallel iteration in L2_BB. */ list = alloc_stmt_list (); t = build_fold_addr_expr (iend0); args = tree_cons (NULL, t, NULL); t = build_fold_addr_expr (istart0); args = tree_cons (NULL, t, args); t = build_function_call_expr (built_in_decls[next_fn], args); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l0), build_and_jump (&l3)); append_to_statement_list (t, &list); si = bsi_start (l2_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Add the loop cleanup function. */ si = bsi_last (exit_bb); if (OMP_RETURN_NOWAIT (bsi_stmt (si))) t = built_in_decls[BUILT_IN_GOMP_LOOP_END_NOWAIT]; else t = built_in_decls[BUILT_IN_GOMP_LOOP_END]; t = build_function_call_expr (t, NULL); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); /* Connect the new blocks. */ remove_edge (single_succ_edge (entry_bb)); if (in_combined_parallel) make_edge (entry_bb, l2_bb, EDGE_FALLTHRU); else { make_edge (entry_bb, l0_bb, EDGE_TRUE_VALUE); make_edge (entry_bb, l3_bb, EDGE_FALSE_VALUE); } make_edge (l0_bb, l1_bb, EDGE_FALLTHRU); remove_edge (single_succ_edge (cont_bb)); make_edge (cont_bb, l1_bb, EDGE_TRUE_VALUE); make_edge (cont_bb, l2_bb, EDGE_FALSE_VALUE); make_edge (l2_bb, l0_bb, EDGE_TRUE_VALUE); make_edge (l2_bb, l3_bb, EDGE_FALSE_VALUE); } /* A subroutine of expand_omp_for. Generate code for a parallel loop with static schedule and no specified chunk size. Given parameters: for (V = N1; V cond N2; V += STEP) BODY; where COND is "<" or ">", we generate pseudocode if (cond is <) adj = STEP - 1; else adj = STEP + 1; if ((__typeof (V)) -1 > 0 && cond is >) n = -(adj + N2 - N1) / -STEP; else n = (adj + N2 - N1) / STEP; q = n / nthreads; q += (q * nthreads != n); s0 = q * threadid; e0 = min(s0 + q, n); if (s0 >= e0) goto L2; else goto L0; L0: V = s0 * STEP + N1; e = e0 * STEP + N1; L1: BODY; V += STEP; if (V cond e) goto L1; L2: */ static void expand_omp_for_static_nochunk (struct omp_region *region, struct omp_for_data *fd) { tree l0, l1, l2, n, q, s0, e0, e, t, nthreads, threadid; tree type, list; basic_block entry_bb, exit_bb, seq_start_bb, body_bb, cont_bb; basic_block fin_bb; block_stmt_iterator si; type = TREE_TYPE (fd->loop.v); entry_bb = region->entry; seq_start_bb = create_empty_bb (entry_bb); body_bb = single_succ (entry_bb); cont_bb = region->cont; fin_bb = single_succ (cont_bb); exit_bb = region->exit; l0 = tree_block_label (seq_start_bb); l1 = tree_block_label (body_bb); l2 = tree_block_label (fin_bb); /* Iteration space partitioning goes in ENTRY_BB. */ list = alloc_stmt_list (); t = built_in_decls[BUILT_IN_OMP_GET_NUM_THREADS]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); nthreads = get_formal_tmp_var (t, &list); t = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); threadid = get_formal_tmp_var (t, &list); fd->loop.n1 = fold_convert (type, fd->loop.n1); if (!is_gimple_val (fd->loop.n1)) fd->loop.n1 = get_formal_tmp_var (fd->loop.n1, &list); fd->loop.n2 = fold_convert (type, fd->loop.n2); if (!is_gimple_val (fd->loop.n2)) fd->loop.n2 = get_formal_tmp_var (fd->loop.n2, &list); fd->loop.step = fold_convert (type, fd->loop.step); if (!is_gimple_val (fd->loop.step)) fd->loop.step = get_formal_tmp_var (fd->loop.step, &list); t = build_int_cst (type, (fd->loop.cond_code == LT_EXPR ? -1 : 1)); t = fold_build2 (PLUS_EXPR, type, fd->loop.step, t); t = fold_build2 (PLUS_EXPR, type, t, fd->loop.n2); t = fold_build2 (MINUS_EXPR, type, t, fd->loop.n1); t = fold_build2 (TRUNC_DIV_EXPR, type, t, fd->loop.step); t = fold_convert (type, t); if (is_gimple_val (t)) n = t; else n = get_formal_tmp_var (t, &list); t = build2 (TRUNC_DIV_EXPR, type, n, nthreads); q = get_formal_tmp_var (t, &list); t = build2 (MULT_EXPR, type, q, nthreads); t = build2 (NE_EXPR, type, t, n); t = build2 (PLUS_EXPR, type, q, t); q = get_formal_tmp_var (t, &list); t = build2 (MULT_EXPR, type, q, threadid); s0 = get_formal_tmp_var (t, &list); t = build2 (PLUS_EXPR, type, s0, q); t = build2 (MIN_EXPR, type, t, n); e0 = get_formal_tmp_var (t, &list); t = build2 (GE_EXPR, boolean_type_node, s0, e0); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l2), build_and_jump (&l0)); append_to_statement_list (t, &list); si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_FOR); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Setup code for sequential iteration goes in SEQ_START_BB. */ list = alloc_stmt_list (); t = fold_convert (type, s0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = fold_convert (type, e0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); e = get_formal_tmp_var (t, &list); si = bsi_start (seq_start_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* The code controlling the sequential loop replaces the OMP_CONTINUE. */ list = alloc_stmt_list (); t = build2 (PLUS_EXPR, type, fd->loop.v, fd->loop.step); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = build2 (fd->loop.cond_code, boolean_type_node, fd->loop.v, e); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l1), build_and_jump (&l2)); append_to_statement_list (t, &list); si = bsi_last (cont_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Replace the OMP_RETURN with a barrier, or nothing. */ si = bsi_last (exit_bb); if (!OMP_RETURN_NOWAIT (bsi_stmt (si))) { list = alloc_stmt_list (); build_omp_barrier (&list); bsi_insert_after (&si, list, BSI_SAME_STMT); } bsi_remove (&si, true); /* Connect all the blocks. */ make_edge (seq_start_bb, body_bb, EDGE_FALLTHRU); remove_edge (single_succ_edge (entry_bb)); make_edge (entry_bb, fin_bb, EDGE_TRUE_VALUE); make_edge (entry_bb, seq_start_bb, EDGE_FALSE_VALUE); make_edge (cont_bb, body_bb, EDGE_TRUE_VALUE); find_edge (cont_bb, fin_bb)->flags = EDGE_FALSE_VALUE; } /* A subroutine of expand_omp_for. Generate code for a parallel loop with static schedule and a specified chunk size. Given parameters: for (V = N1; V cond N2; V += STEP) BODY; where COND is "<" or ">", we generate pseudocode if (cond is <) adj = STEP - 1; else adj = STEP + 1; if ((__typeof (V)) -1 > 0 && cond is >) n = -(adj + N2 - N1) / -STEP; else n = (adj + N2 - N1) / STEP; trip = 0; L0: s0 = (trip * nthreads + threadid) * CHUNK; e0 = min(s0 + CHUNK, n); if (s0 < n) goto L1; else goto L4; L1: V = s0 * STEP + N1; e = e0 * STEP + N1; L2: BODY; V += STEP; if (V cond e) goto L2; else goto L3; L3: trip += 1; goto L0; L4: */ static void expand_omp_for_static_chunk (struct omp_region *region, struct omp_for_data *fd) { tree l0, l1, l2, l3, l4, n, s0, e0, e, t; tree trip, nthreads, threadid; tree type; basic_block entry_bb, exit_bb, body_bb, seq_start_bb, iter_part_bb; basic_block trip_update_bb, cont_bb, fin_bb; tree list; block_stmt_iterator si; type = TREE_TYPE (fd->loop.v); entry_bb = region->entry; iter_part_bb = create_empty_bb (entry_bb); seq_start_bb = create_empty_bb (iter_part_bb); body_bb = single_succ (entry_bb); cont_bb = region->cont; trip_update_bb = create_empty_bb (cont_bb); fin_bb = single_succ (cont_bb); exit_bb = region->exit; l0 = tree_block_label (iter_part_bb); l1 = tree_block_label (seq_start_bb); l2 = tree_block_label (body_bb); l3 = tree_block_label (trip_update_bb); l4 = tree_block_label (fin_bb); /* Trip and adjustment setup goes in ENTRY_BB. */ list = alloc_stmt_list (); t = built_in_decls[BUILT_IN_OMP_GET_NUM_THREADS]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); nthreads = get_formal_tmp_var (t, &list); t = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); threadid = get_formal_tmp_var (t, &list); fd->loop.n1 = fold_convert (type, fd->loop.n1); if (!is_gimple_val (fd->loop.n1)) fd->loop.n1 = get_formal_tmp_var (fd->loop.n1, &list); fd->loop.n2 = fold_convert (type, fd->loop.n2); if (!is_gimple_val (fd->loop.n2)) fd->loop.n2 = get_formal_tmp_var (fd->loop.n2, &list); fd->loop.step = fold_convert (type, fd->loop.step); if (!is_gimple_val (fd->loop.step)) fd->loop.step = get_formal_tmp_var (fd->loop.step, &list); fd->chunk_size = fold_convert (type, fd->chunk_size); if (!is_gimple_val (fd->chunk_size)) fd->chunk_size = get_formal_tmp_var (fd->chunk_size, &list); t = build_int_cst (type, (fd->loop.cond_code == LT_EXPR ? -1 : 1)); t = fold_build2 (PLUS_EXPR, type, fd->loop.step, t); t = fold_build2 (PLUS_EXPR, type, t, fd->loop.n2); t = fold_build2 (MINUS_EXPR, type, t, fd->loop.n1); t = fold_build2 (TRUNC_DIV_EXPR, type, t, fd->loop.step); t = fold_convert (type, t); if (is_gimple_val (t)) n = t; else n = get_formal_tmp_var (t, &list); t = build_int_cst (type, 0); trip = get_initialized_tmp_var (t, &list, NULL); si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_FOR); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Iteration space partitioning goes in ITER_PART_BB. */ list = alloc_stmt_list (); t = build2 (MULT_EXPR, type, trip, nthreads); t = build2 (PLUS_EXPR, type, t, threadid); t = build2 (MULT_EXPR, type, t, fd->chunk_size); s0 = get_formal_tmp_var (t, &list); t = build2 (PLUS_EXPR, type, s0, fd->chunk_size); t = build2 (MIN_EXPR, type, t, n); e0 = get_formal_tmp_var (t, &list); t = build2 (LT_EXPR, boolean_type_node, s0, n); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l1), build_and_jump (&l4)); append_to_statement_list (t, &list); si = bsi_start (iter_part_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Setup code for sequential iteration goes in SEQ_START_BB. */ list = alloc_stmt_list (); t = fold_convert (type, s0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = fold_convert (type, e0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); e = get_formal_tmp_var (t, &list); si = bsi_start (seq_start_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* The code controlling the sequential loop goes in CONT_BB, replacing the OMP_CONTINUE. */ list = alloc_stmt_list (); t = build2 (PLUS_EXPR, type, fd->loop.v, fd->loop.step); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = build2 (fd->loop.cond_code, boolean_type_node, fd->loop.v, e); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l2), build_and_jump (&l3)); append_to_statement_list (t, &list); si = bsi_last (cont_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Trip update code goes into TRIP_UPDATE_BB. */ list = alloc_stmt_list (); t = build_int_cst (type, 1); t = build2 (PLUS_EXPR, type, trip, t); t = build2 (MODIFY_EXPR, void_type_node, trip, t); gimplify_and_add (t, &list); si = bsi_start (trip_update_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Replace the OMP_RETURN with a barrier, or nothing. */ si = bsi_last (exit_bb); if (!OMP_RETURN_NOWAIT (bsi_stmt (si))) { list = alloc_stmt_list (); build_omp_barrier (&list); bsi_insert_after (&si, list, BSI_SAME_STMT); } bsi_remove (&si, true); /* Connect the new blocks. */ remove_edge (single_succ_edge (entry_bb)); make_edge (entry_bb, iter_part_bb, EDGE_FALLTHRU); make_edge (iter_part_bb, seq_start_bb, EDGE_TRUE_VALUE); make_edge (iter_part_bb, fin_bb, EDGE_FALSE_VALUE); make_edge (seq_start_bb, body_bb, EDGE_FALLTHRU); remove_edge (single_succ_edge (cont_bb)); make_edge (cont_bb, body_bb, EDGE_TRUE_VALUE); make_edge (cont_bb, trip_update_bb, EDGE_FALSE_VALUE); make_edge (trip_update_bb, iter_part_bb, EDGE_FALLTHRU); } /* Expand the OpenMP loop defined by REGION. */ static void expand_omp_for (struct omp_region *region) { struct omp_for_data fd; struct omp_for_data_loop *loops; loops = (struct omp_for_data_loop *) alloca (TREE_VEC_LENGTH (OMP_FOR_INIT (last_stmt (region->entry))) * sizeof (struct omp_for_data_loop)); extract_omp_for_data (last_stmt (region->entry), &fd, loops); region->sched_kind = fd.sched_kind; if (fd.sched_kind == OMP_CLAUSE_SCHEDULE_STATIC && !fd.have_ordered && fd.collapse == 1 && region->cont && region->exit) { if (fd.chunk_size == NULL) expand_omp_for_static_nochunk (region, &fd); else expand_omp_for_static_chunk (region, &fd); } else { int fn_index, start_ix, next_ix; gcc_assert (fd.sched_kind != OMP_CLAUSE_SCHEDULE_AUTO); fn_index = (fd.sched_kind == OMP_CLAUSE_SCHEDULE_RUNTIME) ? 3 : fd.sched_kind; fn_index += fd.have_ordered * 4; start_ix = BUILT_IN_GOMP_LOOP_STATIC_START + fn_index; next_ix = BUILT_IN_GOMP_LOOP_STATIC_NEXT + fn_index; if (fd.iter_type == long_long_unsigned_type_node) { start_ix += BUILT_IN_GOMP_LOOP_ULL_STATIC_START - BUILT_IN_GOMP_LOOP_STATIC_START; next_ix += BUILT_IN_GOMP_LOOP_ULL_STATIC_NEXT - BUILT_IN_GOMP_LOOP_STATIC_NEXT; } expand_omp_for_generic (region, &fd, start_ix, next_ix); } pop_gimplify_context (NULL); } /* Expand code for an OpenMP sections directive. In pseudo code, we generate v = GOMP_sections_start (n); L0: switch (v) { case 0: goto L2; case 1: section 1; goto L1; case 2: ... case n: ... default: abort (); } L1: v = GOMP_sections_next (); goto L0; L2: reduction; If this is a combined parallel sections, replace the call to GOMP_sections_start with 'goto L1'. */ static void expand_omp_sections (struct omp_region *region) { tree label_vec, l0, l1, l2, t, u, v, sections_stmt; unsigned i, len; basic_block entry_bb, exit_bb, l0_bb, l1_bb, l2_bb, default_bb; block_stmt_iterator si; struct omp_region *inner; edge e; entry_bb = region->entry; l0_bb = create_empty_bb (entry_bb); l0 = tree_block_label (l0_bb); gcc_assert ((region->cont != NULL) ^ (region->exit == NULL)); l1_bb = region->cont; if (l1_bb) { l2_bb = single_succ (l1_bb); default_bb = create_empty_bb (l1_bb->prev_bb); l1 = tree_block_label (l1_bb); } else { l2_bb = create_empty_bb (l0_bb); default_bb = l2_bb; l1 = NULL; } l2 = tree_block_label (l2_bb); exit_bb = region->exit; v = create_tmp_var (unsigned_type_node, ".section"); /* We will build a switch() with enough cases for all the OMP_SECTION regions, a '0' case to handle the end of more work and a default case to abort if something goes wrong. */ len = EDGE_COUNT (entry_bb->succs); label_vec = make_tree_vec (len + 2); /* The call to GOMP_sections_start goes in ENTRY_BB, replacing the OMP_SECTIONS statement. */ si = bsi_last (entry_bb); sections_stmt = bsi_stmt (si); gcc_assert (TREE_CODE (sections_stmt) == OMP_SECTIONS); if (!is_combined_parallel (region)) { /* If we are not inside a combined parallel+sections region, call GOMP_sections_start. */ t = build_int_cst (unsigned_type_node, len); t = tree_cons (NULL, t, NULL); u = built_in_decls[BUILT_IN_GOMP_SECTIONS_START]; t = build_function_call_expr (u, t); t = build2 (MODIFY_EXPR, void_type_node, v, t); bsi_insert_after (&si, t, BSI_SAME_STMT); } bsi_remove (&si, true); /* The switch() statement replacing OMP_SECTIONS goes in L0_BB. */ si = bsi_start (l0_bb); t = build3 (SWITCH_EXPR, void_type_node, v, NULL, label_vec); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); t = build3 (CASE_LABEL_EXPR, void_type_node, build_int_cst (unsigned_type_node, 0), NULL, l2); TREE_VEC_ELT (label_vec, 0) = t; make_edge (l0_bb, l2_bb, 0); /* Convert each OMP_SECTION into a CASE_LABEL_EXPR. */ for (inner = region->inner, i = 1; inner; inner = inner->next, ++i) { basic_block s_entry_bb, s_exit_bb; s_entry_bb = inner->entry; s_exit_bb = inner->exit; t = tree_block_label (s_entry_bb); u = build_int_cst (unsigned_type_node, i); u = build3 (CASE_LABEL_EXPR, void_type_node, u, NULL, t); TREE_VEC_ELT (label_vec, i) = u; si = bsi_last (s_entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_SECTION); gcc_assert (i < len || OMP_SECTION_LAST (bsi_stmt (si))); bsi_remove (&si, true); e = single_pred_edge (s_entry_bb); e->flags = 0; redirect_edge_pred (e, l0_bb); single_succ_edge (s_entry_bb)->flags = EDGE_FALLTHRU; if (s_exit_bb == NULL) continue; si = bsi_last (s_exit_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_RETURN); bsi_remove (&si, true); single_succ_edge (s_exit_bb)->flags = EDGE_FALLTHRU; } /* Error handling code goes in DEFAULT_BB. */ t = tree_block_label (default_bb); u = build3 (CASE_LABEL_EXPR, void_type_node, NULL, NULL, t); TREE_VEC_ELT (label_vec, len + 1) = u; make_edge (l0_bb, default_bb, 0); si = bsi_start (default_bb); t = built_in_decls[BUILT_IN_TRAP]; t = build_function_call_expr (t, NULL); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); /* Code to get the next section goes in L1_BB. */ if (l1_bb) { si = bsi_last (l1_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); t = built_in_decls[BUILT_IN_GOMP_SECTIONS_NEXT]; t = build_function_call_expr (t, NULL); t = build2 (MODIFY_EXPR, void_type_node, v, t); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); } /* Cleanup function replaces OMP_RETURN in EXIT_BB. */ if (exit_bb) { si = bsi_last (exit_bb); if (OMP_RETURN_NOWAIT (bsi_stmt (si))) t = built_in_decls[BUILT_IN_GOMP_SECTIONS_END_NOWAIT]; else t = built_in_decls[BUILT_IN_GOMP_SECTIONS_END]; t = build_function_call_expr (t, NULL); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); } /* Connect the new blocks. */ if (is_combined_parallel (region)) { /* If this was a combined parallel+sections region, we did not emit a GOMP_sections_start in the entry block, so we just need to jump to L1_BB to get the next section. */ make_edge (entry_bb, l1_bb, EDGE_FALLTHRU); } else make_edge (entry_bb, l0_bb, EDGE_FALLTHRU); if (l1_bb) { e = single_succ_edge (l1_bb); redirect_edge_succ (e, l0_bb); e->flags = EDGE_FALLTHRU; } } /* Expand code for an OpenMP single directive. We've already expanded much of the code, here we simply place the GOMP_barrier call. */ static void expand_omp_single (struct omp_region *region) { basic_block entry_bb, exit_bb; block_stmt_iterator si; bool need_barrier = false; entry_bb = region->entry; exit_bb = region->exit; si = bsi_last (entry_bb); /* The terminal barrier at the end of a GOMP_single_copy sequence cannot be removed. We need to ensure that the thread that entered the single does not exit before the data is copied out by the other threads. */ if (find_omp_clause (OMP_SINGLE_CLAUSES (bsi_stmt (si)), OMP_CLAUSE_COPYPRIVATE)) need_barrier = true; gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_SINGLE); bsi_remove (&si, true); single_succ_edge (entry_bb)->flags = EDGE_FALLTHRU; si = bsi_last (exit_bb); if (!OMP_RETURN_NOWAIT (bsi_stmt (si)) || need_barrier) { tree t = alloc_stmt_list (); build_omp_barrier (&t); bsi_insert_after (&si, t, BSI_SAME_STMT); } bsi_remove (&si, true); single_succ_edge (exit_bb)->flags = EDGE_FALLTHRU; } /* Generic expansion for OpenMP synchronization directives: master, ordered and critical. All we need to do here is remove the entry and exit markers for REGION. */ static void expand_omp_synch (struct omp_region *region) { basic_block entry_bb, exit_bb; block_stmt_iterator si; entry_bb = region->entry; exit_bb = region->exit; si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_SINGLE || TREE_CODE (bsi_stmt (si)) == OMP_MASTER || TREE_CODE (bsi_stmt (si)) == OMP_ORDERED || TREE_CODE (bsi_stmt (si)) == OMP_CRITICAL); bsi_remove (&si, true); single_succ_edge (entry_bb)->flags = EDGE_FALLTHRU; if (exit_bb) { si = bsi_last (exit_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_RETURN); bsi_remove (&si, true); single_succ_edge (exit_bb)->flags = EDGE_FALLTHRU; } } /* Expand the parallel region tree rooted at REGION. Expansion proceeds in depth-first order. Innermost regions are expanded first. This way, parallel regions that require a new function to be created (e.g., OMP_PARALLEL) can be expanded without having any internal dependencies in their body. */ static void expand_omp (struct omp_region *region) { while (region) { if (region->inner) expand_omp (region->inner); switch (region->type) { case OMP_PARALLEL: expand_omp_taskreg (region); break; case OMP_TASK: expand_omp_taskreg (region); break; case OMP_FOR: expand_omp_for (region); break; case OMP_SECTIONS: expand_omp_sections (region); break; case OMP_SECTION: /* Individual omp sections are handled together with their parent OMP_SECTIONS region. */ break; case OMP_SINGLE: expand_omp_single (region); break; case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: expand_omp_synch (region); break; default: gcc_unreachable (); } region = region->next; } } /* Helper for build_omp_regions. Scan the dominator tree starting at block BB. PARENT is the region that contains BB. */ static void build_omp_regions_1 (basic_block bb, struct omp_region *parent) { block_stmt_iterator si; tree stmt; basic_block son; si = bsi_last (bb); if (!bsi_end_p (si) && OMP_DIRECTIVE_P (bsi_stmt (si))) { struct omp_region *region; enum tree_code code; stmt = bsi_stmt (si); code = TREE_CODE (stmt); if (code == OMP_RETURN) { /* STMT is the return point out of region PARENT. Mark it as the exit point and make PARENT the immediately enclosing region. */ gcc_assert (parent); region = parent; region->exit = bb; parent = parent->outer; /* If REGION is a parallel region, determine whether it is a combined parallel+workshare region. */ if (region->type == OMP_PARALLEL) determine_parallel_type (region); } else if (code == OMP_CONTINUE) { gcc_assert (parent); parent->cont = bb; } else { /* Otherwise, this directive becomes the parent for a new region. */ region = new_omp_region (bb, code, parent); parent = region; } } for (son = first_dom_son (CDI_DOMINATORS, bb); son; son = next_dom_son (CDI_DOMINATORS, son)) build_omp_regions_1 (son, parent); } /* Scan the CFG and build a tree of OMP regions. Return the root of the OMP region tree. */ static void build_omp_regions (void) { gcc_assert (root_omp_region == NULL); calculate_dominance_info (CDI_DOMINATORS); build_omp_regions_1 (ENTRY_BLOCK_PTR, NULL); } /* Main entry point for expanding OMP-GIMPLE into runtime calls. */ static unsigned int execute_expand_omp (void) { #if 0 build_omp_regions (); if (!root_omp_region) return 0; if (dump_file) { fprintf (dump_file, "\nOMP region tree\n\n"); dump_omp_region (dump_file, root_omp_region, 0); fprintf (dump_file, "\n"); } remove_exit_barriers (root_omp_region); expand_omp (root_omp_region); free_dominance_info (CDI_DOMINATORS); free_dominance_info (CDI_POST_DOMINATORS); cleanup_tree_cfg (); free_omp_regions (); #endif return 0; } static bool gate_expand_omp (void) { return flag_openmp != 0 && errorcount == 0; } struct tree_opt_pass pass_expand_omp = { "ompexp", /* name */ gate_expand_omp, /* gate */ execute_expand_omp, /* execute */ NULL, /* sub */ NULL, /* next */ 0, /* static_pass_number */ 0, /* tv_id */ PROP_gimple_any, /* properties_required */ PROP_gimple_lomp, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ TODO_dump_func, /* todo_flags_finish */ 0 /* letter */ }; /* Routines to lower OpenMP directives into OMP-GIMPLE. */ /* Lower the OpenMP sections directive in *STMT_P. */ static void lower_omp_sections (tree *stmt_p, omp_context *ctx) { tree new_stmt, stmt, body, bind, block, ilist, olist, new_body; tree t, dlist; tree_stmt_iterator tsi; unsigned i, len; stmt = *stmt_p; push_gimplify_context (); dlist = NULL; ilist = NULL; lower_rec_input_clauses (OMP_SECTIONS_CLAUSES (stmt), &ilist, &dlist, ctx); tsi = tsi_start (OMP_SECTIONS_BODY (stmt)); for (len = 0; !tsi_end_p (tsi); len++, tsi_next (&tsi)) continue; tsi = tsi_start (OMP_SECTIONS_BODY (stmt)); body = alloc_stmt_list (); for (i = 0; i < len; i++, tsi_next (&tsi)) { omp_context *sctx; tree sec_start, sec_end; sec_start = tsi_stmt (tsi); sctx = maybe_lookup_ctx (sec_start); gcc_assert (sctx); append_to_statement_list (sec_start, &body); lower_omp (&OMP_SECTION_BODY (sec_start), sctx); append_to_statement_list (OMP_SECTION_BODY (sec_start), &body); OMP_SECTION_BODY (sec_start) = NULL; if (i == len - 1) { tree l = alloc_stmt_list (); lower_lastprivate_clauses (OMP_SECTIONS_CLAUSES (stmt), NULL, &l, ctx); append_to_statement_list (l, &body); OMP_SECTION_LAST (sec_start) = 1; } sec_end = make_node (OMP_RETURN); append_to_statement_list (sec_end, &body); } block = make_node (BLOCK); bind = build3 (BIND_EXPR, void_type_node, NULL, body, block); olist = NULL_TREE; lower_reduction_clauses (OMP_SECTIONS_CLAUSES (stmt), &olist, ctx); pop_gimplify_context (NULL_TREE); record_vars_into (ctx->block_vars, ctx->cb.dst_fn); new_stmt = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (new_stmt) = 1; new_body = alloc_stmt_list (); append_to_statement_list (ilist, &new_body); append_to_statement_list (stmt, &new_body); append_to_statement_list (bind, &new_body); t = make_node (OMP_CONTINUE); append_to_statement_list (t, &new_body); append_to_statement_list (olist, &new_body); append_to_statement_list (dlist, &new_body); maybe_catch_exception (&new_body); t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = !!find_omp_clause (OMP_SECTIONS_CLAUSES (stmt), OMP_CLAUSE_NOWAIT); append_to_statement_list (t, &new_body); BIND_EXPR_BODY (new_stmt) = new_body; OMP_SECTIONS_BODY (stmt) = NULL; *stmt_p = new_stmt; } /* A subroutine of lower_omp_single. Expand the simple form of an OMP_SINGLE, without a copyprivate clause: if (GOMP_single_start ()) BODY; [ GOMP_barrier (); ] -> unless 'nowait' is present. FIXME. It may be better to delay expanding the logic of this until pass_expand_omp. The expanded logic may make the job more difficult to a synchronization analysis pass. */ static void lower_omp_single_simple (tree single_stmt, tree *pre_p) { tree t; t = built_in_decls[BUILT_IN_GOMP_SINGLE_START]; t = build_function_call_expr (t, NULL); if (TREE_TYPE (t) != boolean_type_node) t = fold_build2 (NE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); t = build3 (COND_EXPR, void_type_node, t, OMP_SINGLE_BODY (single_stmt), NULL); gimplify_and_add (t, pre_p); } /* A subroutine of lower_omp_single. Expand the simple form of an OMP_SINGLE, with a copyprivate clause: #pragma omp single copyprivate (a, b, c) Create a new structure to hold copies of 'a', 'b' and 'c' and emit: { if ((copyout_p = GOMP_single_copy_start ()) == NULL) { BODY; copyout.a = a; copyout.b = b; copyout.c = c; GOMP_single_copy_end (&copyout); } else { a = copyout_p->a; b = copyout_p->b; c = copyout_p->c; } GOMP_barrier (); } FIXME. It may be better to delay expanding the logic of this until pass_expand_omp. The expanded logic may make the job more difficult to a synchronization analysis pass. */ static void lower_omp_single_copy (tree single_stmt, tree *pre_p, omp_context *ctx) { tree ptr_type, t, args, l0, l1, l2, copyin_seq; ctx->sender_decl = create_tmp_var (ctx->record_type, ".omp_copy_o"); ptr_type = build_pointer_type (ctx->record_type); ctx->receiver_decl = create_tmp_var (ptr_type, ".omp_copy_i"); l0 = create_artificial_label (); l1 = create_artificial_label (); l2 = create_artificial_label (); t = built_in_decls[BUILT_IN_GOMP_SINGLE_COPY_START]; t = build_function_call_expr (t, NULL); t = fold_convert (ptr_type, t); t = build2 (MODIFY_EXPR, void_type_node, ctx->receiver_decl, t); gimplify_and_add (t, pre_p); t = build2 (EQ_EXPR, boolean_type_node, ctx->receiver_decl, build_int_cst (ptr_type, 0)); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l0), build_and_jump (&l1)); gimplify_and_add (t, pre_p); t = build1 (LABEL_EXPR, void_type_node, l0); gimplify_and_add (t, pre_p); append_to_statement_list (OMP_SINGLE_BODY (single_stmt), pre_p); copyin_seq = NULL; lower_copyprivate_clauses (OMP_SINGLE_CLAUSES (single_stmt), pre_p, &copyin_seq, ctx); t = build_fold_addr_expr (ctx->sender_decl); args = tree_cons (NULL, t, NULL); t = built_in_decls[BUILT_IN_GOMP_SINGLE_COPY_END]; t = build_function_call_expr (t, args); gimplify_and_add (t, pre_p); t = build_and_jump (&l2); gimplify_and_add (t, pre_p); t = build1 (LABEL_EXPR, void_type_node, l1); gimplify_and_add (t, pre_p); append_to_statement_list (copyin_seq, pre_p); t = build1 (LABEL_EXPR, void_type_node, l2); gimplify_and_add (t, pre_p); } /* Expand code for an OpenMP single directive. */ static void lower_omp_single (tree *stmt_p, omp_context *ctx) { tree t, bind, block, single_stmt = *stmt_p, dlist; push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; lower_rec_input_clauses (OMP_SINGLE_CLAUSES (single_stmt), &BIND_EXPR_BODY (bind), &dlist, ctx); lower_omp (&OMP_SINGLE_BODY (single_stmt), ctx); append_to_statement_list (single_stmt, &BIND_EXPR_BODY (bind)); if (ctx->record_type) lower_omp_single_copy (single_stmt, &BIND_EXPR_BODY (bind), ctx); else lower_omp_single_simple (single_stmt, &BIND_EXPR_BODY (bind)); OMP_SINGLE_BODY (single_stmt) = NULL; append_to_statement_list (dlist, &BIND_EXPR_BODY (bind)); maybe_catch_exception (&BIND_EXPR_BODY (bind)); t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = !!find_omp_clause (OMP_SINGLE_CLAUSES (single_stmt), OMP_CLAUSE_NOWAIT); append_to_statement_list (t, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* Expand code for an OpenMP master directive. */ static void lower_omp_master (tree *stmt_p, omp_context *ctx) { tree bind, block, stmt = *stmt_p, lab = NULL, x; push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); x = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; x = build_function_call_expr (x, NULL); x = build2 (EQ_EXPR, boolean_type_node, x, integer_zero_node); x = build3 (COND_EXPR, void_type_node, x, NULL, build_and_jump (&lab)); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); lower_omp (&OMP_MASTER_BODY (stmt), ctx); maybe_catch_exception (&OMP_MASTER_BODY (stmt)); append_to_statement_list (OMP_MASTER_BODY (stmt), &BIND_EXPR_BODY (bind)); OMP_MASTER_BODY (stmt) = NULL; x = build1 (LABEL_EXPR, void_type_node, lab); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); x = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (x) = 1; append_to_statement_list (x, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* Expand code for an OpenMP ordered directive. */ static void lower_omp_ordered (tree *stmt_p, omp_context *ctx) { tree bind, block, stmt = *stmt_p, x; push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); x = built_in_decls[BUILT_IN_GOMP_ORDERED_START]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); lower_omp (&OMP_ORDERED_BODY (stmt), ctx); maybe_catch_exception (&OMP_ORDERED_BODY (stmt)); append_to_statement_list (OMP_ORDERED_BODY (stmt), &BIND_EXPR_BODY (bind)); OMP_ORDERED_BODY (stmt) = NULL; x = built_in_decls[BUILT_IN_GOMP_ORDERED_END]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); x = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (x) = 1; append_to_statement_list (x, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* Gimplify an OMP_CRITICAL statement. This is a relatively simple substitution of a couple of function calls. But in the NAMED case, requires that languages coordinate a symbol name. It is therefore best put here in common code. */ static GTY((param1_is (tree), param2_is (tree))) splay_tree critical_name_mutexes; static void lower_omp_critical (tree *stmt_p, omp_context *ctx) { tree bind, block, stmt = *stmt_p; tree t, lock, unlock, name; name = OMP_CRITICAL_NAME (stmt); if (name) { tree decl, args; splay_tree_node n; if (!critical_name_mutexes) critical_name_mutexes = splay_tree_new_ggc (splay_tree_compare_pointers); n = splay_tree_lookup (critical_name_mutexes, (splay_tree_key) name); if (n == NULL) { char *new_str; decl = create_tmp_var_raw (ptr_type_node, NULL); new_str = ACONCAT ((".gomp_critical_user_", IDENTIFIER_POINTER (name), NULL)); DECL_NAME (decl) = get_identifier (new_str); TREE_PUBLIC (decl) = 1; TREE_STATIC (decl) = 1; DECL_COMMON (decl) = 1; DECL_ARTIFICIAL (decl) = 1; DECL_IGNORED_P (decl) = 1; cgraph_varpool_finalize_decl (decl); splay_tree_insert (critical_name_mutexes, (splay_tree_key) name, (splay_tree_value) decl); } else decl = (tree) n->value; args = tree_cons (NULL, build_fold_addr_expr (decl), NULL); lock = built_in_decls[BUILT_IN_GOMP_CRITICAL_NAME_START]; lock = build_function_call_expr (lock, args); args = tree_cons (NULL, build_fold_addr_expr (decl), NULL); unlock = built_in_decls[BUILT_IN_GOMP_CRITICAL_NAME_END]; unlock = build_function_call_expr (unlock, args); } else { lock = built_in_decls[BUILT_IN_GOMP_CRITICAL_START]; lock = build_function_call_expr (lock, NULL); unlock = built_in_decls[BUILT_IN_GOMP_CRITICAL_END]; unlock = build_function_call_expr (unlock, NULL); } push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); gimplify_and_add (lock, &BIND_EXPR_BODY (bind)); lower_omp (&OMP_CRITICAL_BODY (stmt), ctx); maybe_catch_exception (&OMP_CRITICAL_BODY (stmt)); append_to_statement_list (OMP_CRITICAL_BODY (stmt), &BIND_EXPR_BODY (bind)); OMP_CRITICAL_BODY (stmt) = NULL; gimplify_and_add (unlock, &BIND_EXPR_BODY (bind)); t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = 1; append_to_statement_list (t, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* A subroutine of lower_omp_for. Generate code to emit the predicate for a lastprivate clause. Given a loop control predicate of (V cond N2), we gate the clause on (!(V cond N2)). The lowered form is appended to *DLIST, iterator initialization is appended to *BODY_P. */ static void lower_omp_for_lastprivate (struct omp_for_data *fd, tree *body_p, tree *dlist, struct omp_context *ctx) { tree clauses, cond, stmts, vinit, t; enum tree_code cond_code; cond_code = fd->loop.cond_code; cond_code = cond_code == LT_EXPR ? GE_EXPR : LE_EXPR; /* When possible, use a strict equality expression. This can let VRP type optimizations deduce the value and remove a copy. */ if (host_integerp (fd->loop.step, 0)) { HOST_WIDE_INT step = TREE_INT_CST_LOW (fd->loop.step); if (step == 1 || step == -1) cond_code = EQ_EXPR; } cond = build2 (cond_code, boolean_type_node, fd->loop.v, fd->loop.n2); clauses = OMP_FOR_CLAUSES (fd->for_stmt); stmts = NULL; lower_lastprivate_clauses (clauses, cond, &stmts, ctx); if (stmts != NULL) { append_to_statement_list (*dlist, &stmts); *dlist = stmts; /* Optimize: v = 0; is usually cheaper than v = some_other_constant. */ vinit = fd->loop.n1; if (cond_code == EQ_EXPR && host_integerp (fd->loop.n2, 0) && ! integer_zerop (fd->loop.n2)) vinit = build_int_cst (TREE_TYPE (fd->loop.v), 0); /* Initialize the iterator variable, so that threads that don't execute any iterations don't execute the lastprivate clauses by accident. */ t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, vinit); gimplify_and_add (t, body_p); } } /* Lower code for an OpenMP loop directive. */ static void lower_omp_for (tree *stmt_p, omp_context *ctx) { tree t, stmt, ilist, dlist, new_stmt, *body_p, *rhs_p; struct omp_for_data fd; int i; stmt = *stmt_p; push_gimplify_context (); lower_omp (&OMP_FOR_PRE_BODY (stmt), ctx); lower_omp (&OMP_FOR_BODY (stmt), ctx); /* Move declaration of temporaries in the loop body before we make it go away. */ if (TREE_CODE (OMP_FOR_BODY (stmt)) == BIND_EXPR) record_vars_into (BIND_EXPR_VARS (OMP_FOR_BODY (stmt)), ctx->cb.dst_fn); new_stmt = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (new_stmt) = 1; body_p = &BIND_EXPR_BODY (new_stmt); /* The pre-body and input clauses go before the lowered OMP_FOR. */ ilist = NULL; dlist = NULL; lower_rec_input_clauses (OMP_FOR_CLAUSES (stmt), body_p, &dlist, ctx); append_to_statement_list (OMP_FOR_PRE_BODY (stmt), body_p); /* Lower the header expressions. At this point, we can assume that the header is of the form: #pragma omp for (V = VAL1; V {<|>|<=|>=} VAL2; V = V [+-] VAL3) We just need to make sure that VAL1, VAL2 and VAL3 are lowered using the .omp_data_s mapping, if needed. */ for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (stmt)); i++) { rhs_p = &TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_INIT (stmt), i), 1); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); rhs_p = &TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_COND (stmt), i), 1); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); rhs_p = &TREE_OPERAND (TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_INCR (stmt), i), 1), 1); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); } /* Once lowered, extract the bounds and clauses. */ extract_omp_for_data (stmt, &fd, NULL); lower_omp_for_lastprivate (&fd, body_p, &dlist, ctx); append_to_statement_list (stmt, body_p); append_to_statement_list (OMP_FOR_BODY (stmt), body_p); t = make_node (OMP_CONTINUE); append_to_statement_list (t, body_p); /* After the loop, add exit clauses. */ lower_reduction_clauses (OMP_FOR_CLAUSES (stmt), body_p, ctx); append_to_statement_list (dlist, body_p); maybe_catch_exception (body_p); /* Region exit marker goes at the end of the loop body. */ t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = fd.have_nowait; append_to_statement_list (t, body_p); pop_gimplify_context (NULL_TREE); record_vars_into (ctx->block_vars, ctx->cb.dst_fn); OMP_FOR_BODY (stmt) = NULL_TREE; OMP_FOR_PRE_BODY (stmt) = NULL_TREE; *stmt_p = new_stmt; } struct omp_taskcopy_context { /* This field must be at the beginning, as we do "inheritance": Some callback functions for tree-inline.c (e.g., omp_copy_decl) receive a copy_body_data pointer that is up-casted to an omp_context pointer. */ copy_body_data cb; omp_context *ctx; }; static tree task_copyfn_copy_decl (tree var, copy_body_data *cb) { struct omp_taskcopy_context *tcctx = (struct omp_taskcopy_context *) cb; if (splay_tree_lookup (tcctx->ctx->sfield_map, (splay_tree_key) var)) return create_tmp_var (TREE_TYPE (var), NULL); return var; } static tree task_copyfn_remap_type (struct omp_taskcopy_context *tcctx, tree orig_type) { tree name, new_fields = NULL, type, f; type = lang_hooks.types.make_type (RECORD_TYPE); name = DECL_NAME (TYPE_NAME (orig_type)); name = build_decl (TYPE_DECL, name, type); TYPE_NAME (type) = name; for (f = TYPE_FIELDS (orig_type); f ; f = TREE_CHAIN (f)) { tree new_f = copy_node (f); DECL_CONTEXT (new_f) = type; TREE_TYPE (new_f) = remap_type (TREE_TYPE (f), &tcctx->cb); TREE_CHAIN (new_f) = new_fields; walk_tree (&DECL_SIZE (new_f), copy_body_r, &tcctx->cb, NULL); walk_tree (&DECL_SIZE_UNIT (new_f), copy_body_r, &tcctx->cb, NULL); walk_tree (&DECL_FIELD_OFFSET (new_f), copy_body_r, &tcctx->cb, NULL); new_fields = new_f; splay_tree_insert (tcctx->cb.decl_map, (splay_tree_key) f, (splay_tree_value) new_f); } TYPE_FIELDS (type) = nreverse (new_fields); layout_type (type); return type; } /* Create task copyfn. */ static void create_task_copyfn (tree task_stmt, omp_context *ctx) { struct function *child_cfun; tree child_fn, t, c, src, dst, f, sf, arg, sarg, decl; tree record_type, srecord_type, bind, list; bool record_needs_remap = false, srecord_needs_remap = false; splay_tree_node n; struct omp_taskcopy_context tcctx; child_fn = OMP_TASK_COPYFN (task_stmt); child_cfun = DECL_STRUCT_FUNCTION (child_fn); gcc_assert (child_cfun->cfg == NULL); child_cfun->x_dont_save_pending_sizes_p = 1; DECL_SAVED_TREE (child_fn) = alloc_stmt_list (); /* Reset DECL_CONTEXT on function arguments. */ for (t = DECL_ARGUMENTS (child_fn); t; t = TREE_CHAIN (t)) DECL_CONTEXT (t) = child_fn; /* Populate the function. */ push_gimplify_context (); current_function_decl = child_fn; bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (bind) = 1; list = NULL; DECL_SAVED_TREE (child_fn) = bind; DECL_SOURCE_LOCATION (child_fn) = EXPR_LOCATION (task_stmt); /* Remap src and dst argument types if needed. */ record_type = ctx->record_type; srecord_type = ctx->srecord_type; for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) { record_needs_remap = true; break; } for (f = TYPE_FIELDS (srecord_type); f ; f = TREE_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) { srecord_needs_remap = true; break; } if (record_needs_remap || srecord_needs_remap) { memset (&tcctx, '\0', sizeof (tcctx)); tcctx.cb.src_fn = ctx->cb.src_fn; tcctx.cb.dst_fn = child_fn; tcctx.cb.src_node = cgraph_node (tcctx.cb.src_fn); tcctx.cb.dst_node = tcctx.cb.src_node; tcctx.cb.src_cfun = ctx->cb.src_cfun; tcctx.cb.copy_decl = task_copyfn_copy_decl; tcctx.cb.eh_region = -1; tcctx.cb.transform_call_graph_edges = CB_CGE_MOVE; tcctx.cb.decl_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); tcctx.ctx = ctx; if (record_needs_remap) record_type = task_copyfn_remap_type (&tcctx, record_type); if (srecord_needs_remap) srecord_type = task_copyfn_remap_type (&tcctx, srecord_type); } else tcctx.cb.decl_map = NULL; push_cfun (child_cfun); arg = DECL_ARGUMENTS (child_fn); TREE_TYPE (arg) = build_pointer_type (record_type); sarg = TREE_CHAIN (arg); TREE_TYPE (sarg) = build_pointer_type (srecord_type); /* First pass: initialize temporaries used in record_type and srecord_type sizes and field offsets. */ if (tcctx.cb.decl_map) for (c = OMP_TASK_CLAUSES (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { tree *p; decl = OMP_CLAUSE_DECL (c); p = (tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) decl); if (p == NULL) continue; n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); sf = (tree) n->value; sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); t = build2 (MODIFY_EXPR, void_type_node, *p, src); append_to_statement_list (t, &list); } /* Second pass: copy shared var pointers and copy construct non-VLA firstprivate vars. */ for (c = OMP_TASK_CLAUSES (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) break; f = (tree) n->value; if (tcctx.cb.decl_map) f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = build2 (MODIFY_EXPR, void_type_node, dst, src); append_to_statement_list (t, &list); break; case OMP_CLAUSE_FIRSTPRIVATE: decl = OMP_CLAUSE_DECL (c); if (is_variable_sized (decl)) break; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) break; f = (tree) n->value; if (tcctx.cb.decl_map) f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); if (n != NULL) { sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); if (use_pointer_for_field (decl, NULL) || is_reference (decl)) src = build_fold_indirect_ref (src); } else src = decl; dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = lang_hooks.decls.omp_clause_copy_ctor (c, dst, src); append_to_statement_list (t, &list); break; case OMP_CLAUSE_PRIVATE: if (! OMP_CLAUSE_PRIVATE_OUTER_REF (c)) break; decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); f = (tree) n->value; if (tcctx.cb.decl_map) f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); if (n != NULL) { sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); if (use_pointer_for_field (decl, NULL)) src = build_fold_indirect_ref (src); } else src = decl; dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = build2 (MODIFY_EXPR, void_type_node, dst, src); append_to_statement_list (t, &list); break; default: break; } /* Last pass: handle VLA firstprivates. */ if (tcctx.cb.decl_map) for (c = OMP_TASK_CLAUSES (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { tree ind, ptr, df; decl = OMP_CLAUSE_DECL (c); if (!is_variable_sized (decl)) continue; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) continue; f = (tree) n->value; f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); gcc_assert (DECL_HAS_VALUE_EXPR_P (decl)); ind = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (ind) == INDIRECT_REF); gcc_assert (DECL_P (TREE_OPERAND (ind, 0))); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) TREE_OPERAND (ind, 0)); sf = (tree) n->value; sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); src = build_fold_indirect_ref (src); dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = lang_hooks.decls.omp_clause_copy_ctor (c, dst, src); append_to_statement_list (t, &list); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) TREE_OPERAND (ind, 0)); df = (tree) n->value; df = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) df); ptr = build_fold_indirect_ref (arg); ptr = build3 (COMPONENT_REF, TREE_TYPE (df), ptr, df, NULL); t = build2 (MODIFY_EXPR, void_type_node, ptr, build_fold_addr_expr (dst)); append_to_statement_list (t, &list); } t = build1 (RETURN_EXPR, void_type_node, NULL); append_to_statement_list (t, &list); if (tcctx.cb.decl_map) splay_tree_delete (tcctx.cb.decl_map); pop_gimplify_context (NULL); BIND_EXPR_BODY (bind) = list; pop_cfun (); current_function_decl = ctx->cb.src_fn; } /* Lower the OpenMP parallel or task directive in *STMT_P. CTX holds context information for the directive. */ static void lower_omp_taskreg (tree *stmt_p, omp_context *ctx) { tree clauses, par_bind, par_body, new_body, bind; tree olist, ilist, par_olist, par_ilist; tree stmt, child_fn, t; stmt = *stmt_p; clauses = OMP_TASKREG_CLAUSES (stmt); par_bind = OMP_TASKREG_BODY (stmt); par_body = BIND_EXPR_BODY (par_bind); child_fn = ctx->cb.dst_fn; if (ctx->srecord_type) create_task_copyfn (stmt, ctx); push_gimplify_context (); par_olist = NULL_TREE; par_ilist = NULL_TREE; lower_rec_input_clauses (clauses, &par_ilist, &par_olist, ctx); lower_omp (&par_body, ctx); if (TREE_CODE (stmt) == OMP_PARALLEL) lower_reduction_clauses (clauses, &par_olist, ctx); /* Declare all the variables created by mapping and the variables declared in the scope of the parallel body. */ record_vars_into (ctx->block_vars, child_fn); record_vars_into (BIND_EXPR_VARS (par_bind), child_fn); if (ctx->record_type) { ctx->sender_decl = create_tmp_var (ctx->srecord_type ? ctx->srecord_type : ctx->record_type, ".omp_data_o"); OMP_TASKREG_DATA_ARG (stmt) = ctx->sender_decl; } if (ctx->srecord_type) create_task_copyfn (stmt, ctx); olist = NULL_TREE; ilist = NULL_TREE; lower_send_clauses (clauses, &ilist, &olist, ctx); lower_send_shared_vars (&ilist, &olist, ctx); /* Once all the expansions are done, sequence all the different fragments inside OMP_TASKREG_BODY. */ bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); append_to_statement_list (ilist, &BIND_EXPR_BODY (bind)); new_body = alloc_stmt_list (); if (ctx->record_type) { t = build_fold_addr_expr (ctx->sender_decl); /* fixup_child_record_type might have changed receiver_decl's type. */ t = fold_convert (TREE_TYPE (ctx->receiver_decl), t); t = build2 (MODIFY_EXPR, void_type_node, ctx->receiver_decl, t); append_to_statement_list (t, &new_body); } append_to_statement_list (par_ilist, &new_body); append_to_statement_list (par_body, &new_body); append_to_statement_list (par_olist, &new_body); maybe_catch_exception (&new_body); t = make_node (OMP_RETURN); append_to_statement_list (t, &new_body); OMP_TASKREG_BODY (stmt) = new_body; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); append_to_statement_list (olist, &BIND_EXPR_BODY (bind)); *stmt_p = bind; pop_gimplify_context (NULL_TREE); } /* Pass *TP back through the gimplifier within the context determined by WI. This handles replacement of DECL_VALUE_EXPR, as well as adjusting the flags on ADDR_EXPR. */ static void lower_regimplify (tree *tp, struct walk_stmt_info *wi) { enum gimplify_status gs; tree pre = NULL; if (wi->is_lhs) gs = gimplify_expr (tp, &pre, NULL, is_gimple_lvalue, fb_lvalue); else if (wi->val_only) gs = gimplify_expr (tp, &pre, NULL, is_gimple_val, fb_rvalue); else gs = gimplify_expr (tp, &pre, NULL, is_gimple_formal_tmp_var, fb_rvalue); gcc_assert (gs == GS_ALL_DONE); if (pre) tsi_link_before (&wi->tsi, pre, TSI_SAME_STMT); } /* Copy EXP into a temporary. Insert the initialization statement before TSI. */ static tree init_tmp_var (tree exp, tree_stmt_iterator *tsi) { tree t, stmt; t = create_tmp_var (TREE_TYPE (exp), NULL); if (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE) DECL_COMPLEX_GIMPLE_REG_P (t) = 1; stmt = build2 (MODIFY_EXPR, TREE_TYPE (t), t, exp); SET_EXPR_LOCUS (stmt, EXPR_LOCUS (tsi_stmt (*tsi))); tsi_link_before (tsi, stmt, TSI_SAME_STMT); return t; } /* Similarly, but copy from the temporary and insert the statement after the iterator. */ static tree save_tmp_var (tree exp, tree_stmt_iterator *tsi) { tree t, stmt; t = create_tmp_var (TREE_TYPE (exp), NULL); if (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE) DECL_COMPLEX_GIMPLE_REG_P (t) = 1; stmt = build2 (MODIFY_EXPR, TREE_TYPE (t), exp, t); SET_EXPR_LOCUS (stmt, EXPR_LOCUS (tsi_stmt (*tsi))); tsi_link_after (tsi, stmt, TSI_SAME_STMT); return t; } /* Callback for walk_stmts. Lower the OpenMP directive pointed by TP. */ static tree lower_omp_1 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; omp_context *ctx = wi->info; tree t = *tp; /* If we have issued syntax errors, avoid doing any heavy lifting. Just replace the OpenMP directives with a NOP to avoid confusing RTL expansion. */ if (errorcount && OMP_DIRECTIVE_P (*tp)) { *tp = build_empty_stmt (); return NULL_TREE; } *walk_subtrees = 0; switch (TREE_CODE (*tp)) { case OMP_PARALLEL: case OMP_TASK: ctx = maybe_lookup_ctx (t); lower_omp_taskreg (tp, ctx); break; case OMP_FOR: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_for (tp, ctx); break; case OMP_SECTIONS: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_sections (tp, ctx); break; case OMP_SINGLE: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_single (tp, ctx); break; case OMP_MASTER: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_master (tp, ctx); break; case OMP_ORDERED: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_ordered (tp, ctx); break; case OMP_CRITICAL: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_critical (tp, ctx); break; case VAR_DECL: if (ctx && DECL_HAS_VALUE_EXPR_P (t)) { lower_regimplify (&t, wi); if (wi->val_only) { if (wi->is_lhs) t = save_tmp_var (t, &wi->tsi); else t = init_tmp_var (t, &wi->tsi); } *tp = t; } break; case ADDR_EXPR: if (ctx) lower_regimplify (tp, wi); break; case ARRAY_REF: case ARRAY_RANGE_REF: case REALPART_EXPR: case IMAGPART_EXPR: case COMPONENT_REF: case VIEW_CONVERT_EXPR: if (ctx) lower_regimplify (tp, wi); break; case INDIRECT_REF: if (ctx) { wi->is_lhs = false; wi->val_only = true; lower_regimplify (&TREE_OPERAND (t, 0), wi); } break; default: if (!TYPE_P (t) && !DECL_P (t)) *walk_subtrees = 1; break; } return NULL_TREE; } static void lower_omp (tree *stmt_p, omp_context *ctx) { struct walk_stmt_info wi; memset (&wi, 0, sizeof (wi)); wi.callback = lower_omp_1; wi.info = ctx; wi.val_only = true; wi.want_locations = true; walk_stmts (&wi, stmt_p); } /* Main entry point. */ static unsigned int execute_lower_omp (void) { all_contexts = splay_tree_new (splay_tree_compare_pointers, 0, delete_omp_context); scan_omp (&DECL_SAVED_TREE (current_function_decl), NULL); gcc_assert (taskreg_nesting_level == 0); if (all_contexts->root) { if (task_shared_vars) push_gimplify_context (); lower_omp (&DECL_SAVED_TREE (current_function_decl), NULL); if (task_shared_vars) pop_gimplify_context (NULL); } if (all_contexts) { splay_tree_delete (all_contexts); all_contexts = NULL; } BITMAP_FREE (task_shared_vars); return 0; } static bool gate_lower_omp (void) { return flag_openmp != 0; } struct tree_opt_pass pass_lower_omp = { "omplower", /* name */ gate_lower_omp, /* gate */ execute_lower_omp, /* execute */ NULL, /* sub */ NULL, /* next */ 0, /* static_pass_number */ 0, /* tv_id */ PROP_gimple_any, /* properties_required */ PROP_gimple_lomp, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ TODO_dump_func, /* todo_flags_finish */ 0 /* letter */ }; /* The following is a utility to diagnose OpenMP structured block violations. It is not part of the "omplower" pass, as that's invoked too late. It should be invoked by the respective front ends after gimplification. */ static splay_tree all_labels; /* Check for mismatched contexts and generate an error if needed. Return true if an error is detected. */ static bool diagnose_sb_0 (tree *stmt_p, tree branch_ctx, tree label_ctx) { bool exit_p = true; if ((label_ctx ? TREE_VALUE (label_ctx) : NULL) == branch_ctx) return false; /* Try to avoid confusing the user by producing and error message with correct "exit" or "enter" verbiage. We prefer "exit" unless we can show that LABEL_CTX is nested within BRANCH_CTX. */ if (branch_ctx == NULL) exit_p = false; else { while (label_ctx) { if (TREE_VALUE (label_ctx) == branch_ctx) { exit_p = false; break; } label_ctx = TREE_CHAIN (label_ctx); } } if (exit_p) error ("invalid exit from OpenMP structured block"); else error ("invalid entry to OpenMP structured block"); *stmt_p = build_empty_stmt (); return true; } /* Pass 1: Create a minimal tree of OpenMP structured blocks, and record where in the tree each label is found. */ static tree diagnose_sb_1 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; tree context = (tree) wi->info; tree inner_context; tree t = *tp; int i; *walk_subtrees = 0; switch (TREE_CODE (t)) { case OMP_PARALLEL: case OMP_TASK: case OMP_SECTIONS: case OMP_SINGLE: walk_tree (&OMP_CLAUSES (t), diagnose_sb_1, wi, NULL); /* FALLTHRU */ case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: /* The minimal context here is just a tree of statements. */ inner_context = tree_cons (NULL, t, context); wi->info = inner_context; walk_stmts (wi, &OMP_BODY (t)); wi->info = context; break; case OMP_FOR: walk_tree (&OMP_FOR_CLAUSES (t), diagnose_sb_1, wi, NULL); inner_context = tree_cons (NULL, t, context); wi->info = inner_context; for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++) { walk_tree (&TREE_VEC_ELT (OMP_FOR_INIT (t), i), diagnose_sb_1, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_COND (t), i), diagnose_sb_1, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_INCR (t), i), diagnose_sb_1, wi, NULL); } walk_stmts (wi, &OMP_FOR_PRE_BODY (t)); walk_stmts (wi, &OMP_FOR_BODY (t)); wi->info = context; break; case LABEL_EXPR: splay_tree_insert (all_labels, (splay_tree_key) LABEL_EXPR_LABEL (t), (splay_tree_value) context); break; default: break; } return NULL_TREE; } /* Pass 2: Check each branch and see if its context differs from that of the destination label's context. */ static tree diagnose_sb_2 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; tree context = (tree) wi->info; splay_tree_node n; tree t = *tp; int i; *walk_subtrees = 0; switch (TREE_CODE (t)) { case OMP_PARALLEL: case OMP_TASK: case OMP_SECTIONS: case OMP_SINGLE: walk_tree (&OMP_CLAUSES (t), diagnose_sb_2, wi, NULL); /* FALLTHRU */ case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: wi->info = t; walk_stmts (wi, &OMP_BODY (t)); wi->info = context; break; case OMP_FOR: walk_tree (&OMP_FOR_CLAUSES (t), diagnose_sb_2, wi, NULL); wi->info = t; for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++) { walk_tree (&TREE_VEC_ELT (OMP_FOR_INIT (t), i), diagnose_sb_2, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_COND (t), i), diagnose_sb_2, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_INCR (t), i), diagnose_sb_2, wi, NULL); } walk_stmts (wi, &OMP_FOR_PRE_BODY (t)); walk_stmts (wi, &OMP_FOR_BODY (t)); wi->info = context; break; case GOTO_EXPR: { tree lab = GOTO_DESTINATION (t); if (TREE_CODE (lab) != LABEL_DECL) break; n = splay_tree_lookup (all_labels, (splay_tree_key) lab); diagnose_sb_0 (tp, context, n ? (tree) n->value : NULL_TREE); } break; case SWITCH_EXPR: { tree vec = SWITCH_LABELS (t); int i, len = TREE_VEC_LENGTH (vec); for (i = 0; i < len; ++i) { tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i)); n = splay_tree_lookup (all_labels, (splay_tree_key) lab); if (diagnose_sb_0 (tp, context, (tree) n->value)) break; } } break; case RETURN_EXPR: diagnose_sb_0 (tp, context, NULL_TREE); break; default: break; } return NULL_TREE; } void diagnose_omp_structured_block_errors (tree fndecl) { tree save_current = current_function_decl; struct walk_stmt_info wi; current_function_decl = fndecl; all_labels = splay_tree_new (splay_tree_compare_pointers, 0, 0); memset (&wi, 0, sizeof (wi)); wi.callback = diagnose_sb_1; walk_stmts (&wi, &DECL_SAVED_TREE (fndecl)); memset (&wi, 0, sizeof (wi)); wi.callback = diagnose_sb_2; wi.want_locations = true; wi.want_return_expr = true; walk_stmts (&wi, &DECL_SAVED_TREE (fndecl)); splay_tree_delete (all_labels); all_labels = NULL; current_function_decl = save_current; } #include "gt-omp-low.h"
DRACC_OMP_035_SAXPY_without_Task_Barrier_yes.c
/* SAXPY without a barrier at the end of execution to wait for the tasks to finish. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define C 4096 float a; float x[C]; float y[C]; int init(){ for(int i=0; i<C; i++){ a=5; x[i]=0; y[i]=3; } return 0; } int saxpy(){ #pragma omp target map(to:y[0:C],a) map(tofrom:x[0:C]) nowait device(0) { for(int i=0; i<C; i++){ #pragma omp task depend(inout:x[i]) { x[i] = a * x[i]; } #pragma omp task depend(inout:x[i]) { x[i] = x[i] + y[i]; } } } return 0; } int check(){ bool test = false; for(int i=0; i<C; i++){ if(x[i]!=3){ test = true; } } printf("Memory Access Issue visible: %s\n",test ? "true" : "false"); return 0; } int main(){ init(); saxpy(); check(); #pragma omp taskwait return 0; }
bml_trace_ellpack_typed.c
#include "../../macros.h" #include "../../typed.h" #include "../bml_allocate.h" #include "../bml_logger.h" #include "../bml_parallel.h" #include "../bml_submatrix.h" #include "../bml_trace.h" #include "../bml_types.h" #include "bml_submatrix_ellpack.h" #include "bml_trace_ellpack.h" #include "bml_types_ellpack.h" #include <complex.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /** Calculate the trace of a matrix. * * \ingroup trace_group * * \param A The matrix to calculate a trace for * \return the trace of A */ double TYPED_FUNC( bml_trace_ellpack) ( bml_matrix_ellpack_t * A) { int N = A->N; int M = A->M; int *A_index = (int *) A->index; int *A_nnz = (int *) A->nnz; int *A_localRowMin = (int *) A->domain->localRowMin; int *A_localRowMax = (int *) A->domain->localRowMax; REAL_T trace = 0.0; REAL_T *A_value = (REAL_T *) A->value; int myRank = bml_getMyRank(); #pragma omp parallel for \ shared(N, M, A_value, A_index, A_nnz) \ shared(A_localRowMin, A_localRowMax, myRank) \ reduction(+:trace) //for (int i = 0; i < N; i++) for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++) { for (int j = 0; j < A_nnz[i]; j++) { if (i == A_index[ROWMAJOR(i, j, N, M)]) { trace += A_value[ROWMAJOR(i, j, N, M)]; break; } } } return (double) REAL_PART(trace); } /** Calculate the trace of a matrix multiplication. * Both matrices must have the same size. * * \ingroup trace_group * * \param A The matrix A * \param A The matrix B * \return the trace of A*B */ double TYPED_FUNC( bml_trace_mult_ellpack) ( bml_matrix_ellpack_t * A, bml_matrix_ellpack_t * B) { int A_N = A->N; int A_M = A->M; int *A_index = (int *) A->index; int *A_nnz = (int *) A->nnz; int *A_localRowMin = (int *) A->domain->localRowMin; int *A_localRowMax = (int *) A->domain->localRowMax; REAL_T trace = 0.0; REAL_T *A_value = (REAL_T *) A->value; REAL_T *rvalue; int myRank = bml_getMyRank(); if (A_N != B->N || A_M != B->M) { LOG_ERROR ("bml_trace_mult_ellpack: Matrices A and B have different sizes."); } #pragma omp parallel for \ private(rvalue) \ shared(B, A_N, A_M, A_value, A_index, A_nnz) \ shared(A_localRowMin, A_localRowMax, myRank) \ reduction(+:trace) //for (int i = 0; i < A_N; i++) for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++) { rvalue = TYPED_FUNC(bml_getVector_ellpack) (B, &A_index[ROWMAJOR (i, 0, A_N, A_M)], i, A_nnz[i]); for (int j = 0; j < A_nnz[i]; j++) { trace += A_value[ROWMAJOR(i, j, A_N, A_M)] * rvalue[j]; } bml_free_memory(rvalue); } return (double) REAL_PART(trace); }
seidel.pluto.par.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> double A[N][N+17]; void init_arrays() { int i, j; for (i=0; i<N; i++) for (j=0; j<N; j++) A[i][j] = i*i+j*j; } double rtclock() { struct timezone tzp; struct timeval tp; int stat; gettimeofday (&tp, &tzp); return (tp.tv_sec + tp.tv_usec*1.0e-6); } int main() { init_arrays(); double annot_t_start=0, annot_t_end=0, annot_t_total=0; int annot_i; for (annot_i=0; annot_i<REPS; annot_i++) { annot_t_start = rtclock(); register int i,j,t; #include <math.h> #include <assert.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)) #define S1(zT0,zT1,zT2,zT3,zT4,zT5,t,i,j) {A[i][j]=(A[1+i][1+j]+A[1+i][j]+A[1+i][j-1]+A[i][1+j]+A[i][j]+A[i][j-1]+A[i-1][1+j]+A[i-1][j]+A[i-1][j-1])/9;} int c1, c2, c3, c4, c5, c6, c7, c8, c9; register int lb, ub, lb1, ub1, lb2, ub2; register int lbv, ubv; /* Generated from PLuTo-produced CLooG file by CLooG v0.14.1 64 bits in 4.44s. */ for (c1=-1;c1<=floord(2*T+N-4,256);c1++) { lb1=max(max(0,ceild(128*c1-127,256)),ceild(256*c1-T+1,256)); ub1=min(min(floord(T+N-3,256),floord(256*c1+255,256)),floord(256*c1+N+253,512)); #pragma omp parallel for shared(c1,lb1,ub1) private(c2,c3,c4,c5,c6,c7,c8,c9) for (c2=lb1; c2<=ub1; c2++) { for (c3=max(max(max(max(ceild(128*c2-127,128),ceild(512*c2-N-252,256)),ceild(128*c1-127,128)),0),ceild(512*c1-512*c2-253,256));c3<=min(min(min(min(floord(256*c1-256*c2+N+253,128),floord(256*c1+N+508,256)),floord(T+N-3,128)),floord(512*c2+N+507,256)),floord(256*c2+T+N+252,256));c3++) { for (c4=max(max(max(max(8*c1-8*c2,ceild(128*c3-N-29,32)),0),ceild(-256*c2+256*c3-N-284,32)),ceild(256*c2-N-29,32));c4<=min(min(min(min(8*c1-8*c2+7,floord(T-1,32)),floord(128*c2+127,16)),floord(-128*c2+128*c3+127,16)),floord(256*c3+253,64));c4++) { for (c5=max(max(max(max(max(8*c2,0),ceild(16*c4-15,16)),ceild(256*c3-32*c4-N-60,32)),ceild(256*c3-T-N-28,32)),ceild(256*c3-N-59,64));c5<=min(min(min(min(min(floord(256*c3+N+252,64),floord(32*c4+N+29,32)),floord(128*c3-16*c4+127,16)),floord(T+N-3,32)),8*c2+7),floord(128*c3+127,16));c5++) { for (c6=max(max(max(max(max(ceild(64*c4-29,32),8*c3),ceild(16*c4+16*c5-15,16)),ceild(64*c5-N-28,32)),ceild(16*c5-15,16)),0);c6<=min(min(min(min(min(8*c3+7,floord(64*c5+N+59,32)),floord(T+N-3,16)),floord(32*c4+N+29,16)),floord(32*c4+32*c5+N+60,32)),floord(32*c5+T+N+28,32));c6++) { for (c7=max(max(max(max(0,32*c4),16*c6-N+2),32*c5-N+2),-32*c5+32*c6-N-29);c7<=min(min(min(min(32*c5+30,32*c4+31),floord(32*c6+29,2)),-32*c5+32*c6+30),T-1);c7++) { /*@ begin Loop( transform UnrollJam(ufactor=8) for (c8=max(max(32*c5,32*c6-c7-N+2),c7+1);c8<=min(min(c7+N-2,32*c5+31),32*c6-c7+30);c8++) transform Unroll(ufactor=8) for (c9=max(32*c6,c7+c8+1);c9<=min(c7+c8+N-2,32*c6+31);c9++) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4-c5+c6,c7,-c7+c8,-c7-c8+c9) ; } ) @*/{ for (c8=max(max(32*c5,32*c6-c7-N+2),c7+1); c8<=min(min(c7+N-2,32*c5+31),32*c6-c7+30)-7; c8=c8+8) { for (c9=max(32*c6,c7+c8+1); c9<=min(c7+c8+N-2,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+5); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+6); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+7); } for (c9=max(32*c6,c7+c8+2); c9<=min(c7+c8+N-1,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8-1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8+1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8+2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8+3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8+4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8+5); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8+6); } for (c9=max(32*c6,c7+c8+3); c9<=min(c7+c8+N,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8-2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8-1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8+1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8+2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8+3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8+4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8+5); } for (c9=max(32*c6,c7+c8+4); c9<=min(c7+c8+N+1,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8-3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8-2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8-1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8+1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8+2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8+3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8+4); } for (c9=max(32*c6,c7+c8+5); c9<=min(c7+c8+N+2,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8-4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8-3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8-2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8-1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8+1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8+2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8+3); } for (c9=max(32*c6,c7+c8+6); c9<=min(c7+c8+N+3,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8-5); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8-4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8-3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8-2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8-1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8+1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8+2); } for (c9=max(32*c6,c7+c8+7); c9<=min(c7+c8+N+4,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8-6); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8-5); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8-4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8-3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8-2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8-1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8+1); } for (c9=max(32*c6,c7+c8+8); c9<=min(c7+c8+N+5,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-7); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-6); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-5); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8); } for (; c9<=min(c7+c8+N-2,32*c6+31); c9=c9+1) S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8); for (; c9<=min(c7+c8+N-1,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+1,-c7+c9-c8-1); } for (; c9<=min(c7+c8+N,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+2,-c7+c9-c8-2); } for (; c9<=min(c7+c8+N+1,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+3,-c7+c9-c8-3); } for (; c9<=min(c7+c8+N+2,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+4,-c7+c9-c8-4); } for (; c9<=min(c7+c8+N+3,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+5,-c7+c9-c8-5); } for (; c9<=min(c7+c8+N+4,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+6,-c7+c9-c8-6); } for (; c9<=min(c7+c8+N+5,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8+7,-c7+c9-c8-7); } } for (; c8<=min(min(c7+N-2,32*c5+31),32*c6-c7+30); c8=c8+1) { for (c9=max(32*c6,c7+c8+1); c9<=min(c7+c8+N-2,32*c6+31)-7; c9=c9+8) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+1); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+2); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+3); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+4); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+5); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+6); S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4+c6-c5,c7,-c7+c8,-c7+c9-c8+7); } for (; c9<=min(c7+c8+N-2,32*c6+31); c9=c9+1) { S1(c1-c2,-c1+2*c2,-c1+c3,c4,-c4+c5,-c4-c5+c6,c7,-c7+c8,-c7-c8+c9); } } } /*@ end @*/ } } } } } } } /* End of CLooG code */ annot_t_end = rtclock(); annot_t_total += annot_t_end - annot_t_start; } annot_t_total = annot_t_total / REPS; printf("%f\n", annot_t_total); return ((int) A[0][0]); }
paulimat.h
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDQUANTUM_SPARSE_PAULI_MAT_H_ #define MINDQUANTUM_SPARSE_PAULI_MAT_H_ #include "core/utils.h" #include "pybind11/numpy.h" namespace mindquantum { namespace sparse { namespace py = pybind11; template <typename T> struct PauliMat { char *coeff_; Index *col_; Index n_qubits_; Index dim_; T p_; inline void FreeMemory() { if (coeff_ != nullptr) { free(coeff_); } if (col_ != nullptr) { free(col_); } } void Reset() { FreeMemory(); coeff_ = nullptr; col_ = nullptr; } ~PauliMat() { FreeMemory(); } PauliMat() : coeff_(nullptr), col_(nullptr), n_qubits_(0), dim_(0) { } PauliMat(const PauliTerm<T> pt, Index n_qubits) : n_qubits_(n_qubits), p_(pt.second) { dim_ = (1UL << n_qubits_); coeff_ = reinterpret_cast<char *>(malloc(sizeof(char) * dim_)); col_ = reinterpret_cast<Index *>(malloc(sizeof(Index) * dim_)); auto mask = GetPauliMask(pt.first); auto mask_f = mask.mask_x | mask.mask_y; #pragma omp parallel for schedule(static) for (Index i = 0; i < dim_; i++) { auto j = (i ^ mask_f); col_[i] = j; auto axis2power = CountOne(i & mask.mask_z); // -1 auto axis3power = CountOne(i & mask.mask_y); // -1j // (-1)^a2*(-1j)^a3*(1j)^a1=(1j)^2a2*(1j)^3a3*(1j)^a1=(1j)^(a1+2*a2+3*a3) coeff_[j] = static_cast<char>((mask.num_y + 2 * axis3power + 2 * axis2power) & 3); } } void PrintInfo() { std::cout << "<--Pauli Matrix with Dimension: "; std::cout << dim_ << " X " << dim_ << std::endl; std::cout << " Data:\n "; for (Index i = 0; i < dim_; i++) { std::cout << POLAR[coeff_[i]]; if (i != dim_ - 1) { std::cout << ","; } } std::cout << "\n Col:\n "; for (Index i = 0; i < dim_; i++) { std::cout << col_[i]; if (i != dim_ - 1) { std::cout << ","; } } std::cout << "-->\n\n"; } }; } // namespace sparse } // namespace mindquantum #endif // MINDQUANTUM_SPARSE_PAULI_MAT_H_
GB_binop__bxor_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__bxor_uint8 // A.*B function (eWiseMult): GB_AemultB__bxor_uint8 // A*D function (colscale): GB_AxD__bxor_uint8 // D*A function (rowscale): GB_DxB__bxor_uint8 // C+=B function (dense accum): GB_Cdense_accumB__bxor_uint8 // C+=b function (dense accum): GB_Cdense_accumb__bxor_uint8 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bxor_uint8 // C=scalar+B GB_bind1st__bxor_uint8 // C=scalar+B' GB_bind1st_tran__bxor_uint8 // C=A+scalar GB_bind2nd__bxor_uint8 // C=A'+scalar GB_bind2nd_tran__bxor_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) \ uint8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint8_t bij = Bx [pB] // 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) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x) ^ (y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BXOR || GxB_NO_UINT8 || GxB_NO_BXOR_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__bxor_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__bxor_uint8 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__bxor_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__bxor_uint8 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *GB_RESTRICT Cx = (uint8_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__bxor_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 *GB_RESTRICT Cx = (uint8_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__bxor_uint8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__bxor_uint8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__bxor_uint8 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else 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 < anz ; p++) { uint8_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__bxor_uint8 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; 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++) { uint8_t aij = Ax [p] ; Cx [p] = (aij) ^ (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = (x) ^ (aij) ; \ } GrB_Info GB_bind1st_tran__bxor_uint8 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #define GB_PHASE_2_OF_2 #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 typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = (aij) ^ (y) ; \ } GrB_Info GB_bind2nd_tran__bxor_uint8 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ParallelBeginLink.c
int main() { #pragma omp parallel { } }
streamingbc.c
#include <omp.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <math.h> #include <unistd.h> #include "stinger.h" #include "streamingbc.h" #include "streamingbc_aux.h" #include "timer.h" bcForest * streamingBCCreateForestExact(int64_t NV) { return CreateForestExact(NV); } bcForest * streamingBCCreateForestApproximate(int64_t NV, int64_t NK, int64_t * rootArray) { return CreateForestApproximate(NV, rootArray, NK); } extraArraysPerThread ** streamingBCCreateAuxilary(int64_t threadCount, int64_t NV) { return createExtraArraysForThreads(threadCount, NV); } void streamingBCInitStaticExact(bcForest * forest, struct stinger * stingerGraph, int64_t NT, extraArraysPerThread ** auxilary) { BrandesExactParallel(forest, stingerGraph, NT, auxilary); } void streamingBCInitStaticApproximate(bcForest * forest, struct stinger * stingerGraph, int64_t NT, extraArraysPerThread ** auxilary, int64_t NK, int64_t * rootArray) { BrandesApproxCaseParallel(forest, stingerGraph, rootArray, NK, auxilary, NT); } void streamingBCDeleteAuxilary(extraArraysPerThread ** parallelExtra, int64_t threadCount, int64_t NV) { destroyExtraArraysForThreads(parallelExtra, threadCount, NV); } void streamingBCDeleteForestExact(bcForestPtr * deadForest) { DestroyForestExact(deadForest); } void streamingBCDeleteForestApproximate(bcForestPtr * deadForest, int64_t rootArraySize, int64_t * rootArray) { DestroyForestApproximate(deadForest, rootArray, rootArraySize); } StreamingExtraInfo insertVertexStreamingBC(bcForest * forest, struct stinger * sStinger, int64_t src, int64_t * adjacencyArray, int64_t adjacencySize, int64_t * rootArrayForApproximation, int64_t NK, int64_t NV, int64_t NT, extraArraysPerThread ** eAPT) { StreamingExtraInfo oneSEI, returnsei; returnsei.adjacent = 0; returnsei.movement = 0; returnsei.sameLevel = 0; for (int64_t d = 0; d < adjacencySize; d++) { int64_t dest = adjacencyArray[d]; stinger_insert_edge(sStinger, 0, src, dest, 0, 0); stinger_insert_edge(sStinger, 0, dest, src, 0, 0); // Set to load balancing and coarse-grained implementation. oneSEI = insertEdgeStreamingBC(forest, sStinger, src, dest, rootArrayForApproximation, NK, NV, NT, eAPT, 1, 1); returnsei.adjacent += oneSEI.adjacent; returnsei.movement += oneSEI.movement; returnsei.sameLevel += oneSEI.sameLevel; } return returnsei; } int compareArrays(const void * arr1, const void * arr2) { const int64_t * one = (const int64_t *) arr1; const int64_t * two = (const int64_t *) arr2; return two[1] - one[1]; } StreamingExtraInfo insertEdgeStreamingBC(bcForest * forest, struct stinger * sStinger, int64_t newU, int64_t newV, int64_t * rootArrayForApproximation, int64_t NK, int64_t NV, int64_t NT, extraArraysPerThread ** eAPT, uint32_t loadBalancing, uint32_t granularity) { int64_t workPerVertex[NK][2]; // First column has vertex ids, second col has work values per id. int64_t currRoot = 0; int64_t samelevel = 0, compConn = 0, adjacent = 0, movement = 0; int64_t workIndex = 0; for (currRoot = 0; currRoot < NK; currRoot++) { int64_t i = rootArrayForApproximation[currRoot]; int64_t thread = 0; extraArraysPerThread * myExtraArrays = eAPT[thread]; bcTree * tree = forest->forest[i]; if (loadBalancing == BALANCE) workPerVertex[workIndex][0] = i; int64_t diff = tree->vArr[newU].level - tree->vArr[newV].level; if (loadBalancing == BALANCE) { if (diff < 0) { workPerVertex[workIndex++][1] = 2 * tree->vArr[newV].edgesBelow + tree->vArr[newV].edgesAbove; } else if (diff > 0) { workPerVertex[workIndex++][1] = 2 * tree->vArr[newU].edgesBelow + tree->vArr[newU].edgesAbove; } else { workPerVertex[workIndex++][1] = 0; } } } if (loadBalancing == BALANCE) { qsort((void *)&workPerVertex, workIndex, sizeof(int64_t[2]), compareArrays); } if (granularity == FINE) { // fine-grain portion. for (int64_t r = 0; r < NK; r++) { int64_t i = workPerVertex[r][0]; if (loadBalancing == 0) { i = rootArrayForApproximation[r]; } int64_t thread = omp_get_thread_num(); extraArraysPerThread * myExtraArrays = eAPT[thread]; bcTree * tree = forest->forest[i]; int64_t diff = tree->vArr[newU].level - tree->vArr[newV].level; if (diff < -1 || diff > 1) { // Case 3 -- non-adjacent level insertion if (diff < -1) { moveUpTreeBrandesFG(forest, sStinger, i, newV, newU, (-diff) - 1, myExtraArrays, (int64_t)NT); } else { moveUpTreeBrandesFG(forest, sStinger, i, newU, newV, (diff) - 1, myExtraArrays, (int64_t)NT); } eAPT[thread]->movementCounter++; } // Newly inserted edge is connecting vertices that were in adjacent levels before insertions else if (diff == -1 || diff == 1) { // Case 2 -- adjacent level insertion if (diff == -1) { addEdgeWithoutMovementBrandesFG(forest, sStinger, i, newV, newU, tree->vArr[newU].sigma, myExtraArrays, (int64_t)NT); } else { addEdgeWithoutMovementBrandesFG(forest, sStinger, i, newU, newV, tree->vArr[newV].sigma, myExtraArrays, (int64_t)NT); } eAPT[thread]->adjacentCounter++; } } } else { omp_set_num_threads(NT); // coarse-grain portion. #pragma omp parallel for schedule(dynamic,1) for (int64_t r = 0; r < NK; r++) { int64_t i = workPerVertex[r][0]; if (loadBalancing == 0) { i = rootArrayForApproximation[r]; } int64_t thread = omp_get_thread_num(); extraArraysPerThread * myExtraArrays = eAPT[thread]; bcTree * tree = forest->forest[i]; int64_t diff = tree->vArr[newU].level - tree->vArr[newV].level; if (diff < -1 || diff > 1) { if (diff < -1) { moveUpTreeBrandes(forest, sStinger, i, newV, newU, (-diff) - 1, myExtraArrays); } else { moveUpTreeBrandes(forest, sStinger, i, newU, newV, (diff) - 1, myExtraArrays); } eAPT[thread]->movementCounter++; } // Newly inserted edge is connecting vertices that were in adjacent levels before insertions else if (diff == -1 || diff == 1) { if (diff == -1) { addEdgeWithoutMovementBrandes(forest, sStinger, i, newV, newU, tree->vArr[newU].sigma, myExtraArrays); } else { addEdgeWithoutMovementBrandes(forest, sStinger, i, newU, newV, tree->vArr[newV].sigma, myExtraArrays); } eAPT[thread]->adjacentCounter++; } } } #pragma omp parallel for for (int64_t v = 0; v < NV; v++) { for (int64_t t = 0; t < NT; t++) { forest->totalBC[v] += eAPT[t]->sV[v].totalBC; eAPT[t]->sV[v].totalBC = 0.0; } } StreamingExtraInfo returnSEI = {0, 0, 0, 0}; returnSEI.sameLevel = samelevel; returnSEI.adjacent = adjacent; returnSEI.movement = movement; return returnSEI; } StreamingExtraInfo deleteVertexStreamingBC(bcForest * forest, struct stinger * sStinger, int64_t src, int64_t * adjacencyArray, int64_t * adjacencySize, int64_t * rootArrayForApproximation, int64_t NK, int64_t NV, int64_t NT, extraArraysPerThread ** eAPT) { StreamingExtraInfo oneSEI, returnsei; returnsei.adjacent = 0; returnsei.movement = 0; returnsei.sameLevel = 0; int64_t d = 0; STINGER_FORALL_EDGES_OF_VTX_BEGIN(sStinger, src) { int64_t dest = STINGER_EDGE_DEST; adjacencyArray[d] = dest; stinger_remove_edge(sStinger, 0, src, dest); stinger_remove_edge(sStinger, 0, dest, src); // Force to be load balancing and coarse-grained implementation. oneSEI = deleteEdgeStreamingBC(forest, sStinger, src, dest, rootArrayForApproximation, NK, NV, NT, eAPT, 1, 1); returnsei.adjacent += oneSEI.adjacent; returnsei.movement += oneSEI.movement; returnsei.sameLevel += oneSEI.sameLevel; } STINGER_FORALL_EDGES_OF_VTX_END(); *adjacencySize = d; return returnsei; } StreamingExtraInfo deleteEdgeStreamingBC(bcForest * forest, struct stinger * sStinger, int64_t oldU, int64_t oldV, int64_t * rootArrayForApproximation, int64_t NK, int64_t NV, int64_t NT, extraArraysPerThread ** eAPT, uint32_t loadBalancing, uint32_t granularity) { omp_set_num_threads(NT); int64_t currRoot = 0; int64_t samelevel = 0, compConn = 0, adjacent = 0, movement = 0; int64_t thread = 0; int64_t workPerVertex[NK][2]; int64_t workIndex = 0; if (loadBalancing == BALANCE) { for (int64_t r = 0; r < NK; r++) { int64_t i = rootArrayForApproximation[r]; bcTree * tree = forest->forest[i]; int64_t diff = tree->vArr[oldU].level - tree->vArr[oldV].level; workPerVertex[workIndex][0] = i; if (diff < 0) { workPerVertex[workIndex++][1] = 2 * tree->vArr[oldV].edgesBelow + tree->vArr[oldV].edgesAbove; } else if (diff > 0) { workPerVertex[workIndex++][1] = 2 * tree->vArr[oldU].edgesBelow + tree->vArr[oldU].edgesAbove; } else { workPerVertex[workIndex++][1] = 0; } } } if (loadBalancing == BALANCE) { qsort((void *)&workPerVertex, workIndex, sizeof(int64_t[2]), compareArrays); } if (granularity == COARSE) { #pragma omp parallel for schedule(dynamic,1) for (int64_t r = 0; r < NK; r++) { int64_t i = workPerVertex[r][0]; if (loadBalancing == 0) { i = rootArrayForApproximation[r]; } int64_t thread = omp_get_thread_num(); extraArraysPerThread * myExtraArrays = eAPT[thread]; bcTree * tree = forest->forest[i]; int64_t extraParents = 0; int64_t childVertex = oldU; int64_t parentVertex = oldV; int64_t diff = tree->vArr[oldU].level - tree->vArr[oldV].level; if (diff == 0) { eAPT[thread]->samelevelCounter++; samelevel++; continue; } if (tree->vArr[oldU].level < tree->vArr[oldV].level) { childVertex = oldV; parentVertex = oldU; } STINGER_FORALL_EDGES_OF_VTX_BEGIN(sStinger, childVertex) { int64_t neighbor = STINGER_EDGE_DEST; if (tree->vArr[neighbor].level + 1 == tree->vArr[childVertex].level) { extraParents++; } } STINGER_FORALL_EDGES_OF_VTX_END(); if (extraParents >= 1) { // Case 2 -- adjacent level deletion. removeEdgeWithoutMovementBrandes(forest, sStinger, i, childVertex, parentVertex, tree->vArr[parentVertex].sigma, myExtraArrays); eAPT[thread]->adjacentCounter++; adjacent++; } else { // Case 3 -- non-adjacent level deletion. moveDownTreeBrandes(forest, sStinger, i, childVertex, parentVertex, myExtraArrays); eAPT[thread]->movementCounter++; movement++; } } } else { for (int64_t r = 0; r < NK; r++) { int64_t i = workPerVertex[r][0]; if (loadBalancing == 0) { i = rootArrayForApproximation[r]; } int64_t thread = omp_get_thread_num(); extraArraysPerThread * myExtraArrays = eAPT[thread]; bcTree * tree = forest->forest[i]; int64_t extraParents = 0; int64_t childVertex = oldU; int64_t parentVertex = oldV; int64_t diff = tree->vArr[oldU].level - tree->vArr[oldV].level; if (diff == 0) { eAPT[thread]->samelevelCounter++; samelevel++; continue; } if (tree->vArr[oldU].level < tree->vArr[oldV].level) { childVertex = oldV; parentVertex = oldU; } STINGER_FORALL_EDGES_OF_VTX_BEGIN(sStinger, childVertex) { int64_t neighbor = STINGER_EDGE_DEST; if (tree->vArr[neighbor].level + 1 == tree->vArr[childVertex].level) { extraParents++; } } STINGER_FORALL_EDGES_OF_VTX_END(); if (extraParents >= 1) { removeEdgeWithoutMovementBrandesFG(forest, sStinger, i, childVertex, parentVertex, tree->vArr[parentVertex].sigma, myExtraArrays, NT); eAPT[thread]->adjacentCounter++; adjacent++; } else { moveDownTreeBrandes(forest, sStinger, i, childVertex, parentVertex, myExtraArrays); eAPT[thread]->movementCounter++; movement++; } } } int64_t tlow = (NV * thread) / NT; int64_t thigh = (NV * (thread + 1)) / NT ; for (int64_t v = tlow; v < NV; v++) { for (int64_t t = 0; t < NT; t++) { forest->totalBC[v] += eAPT[t]->sV[v].totalBC; eAPT[t]->sV[v].totalBC = 0.0; } } StreamingExtraInfo returnSEI = {0, 0, 0, 0}; returnSEI.sameLevel = samelevel; returnSEI.adjacent = adjacent; returnSEI.movement = movement; return returnSEI; }
opencl_krb5pa-sha1_fmt_plug.c
/* * Kerberos 5 "PA ENC TIMESTAMP" by magnum & Dhiru * * Pcap file -> input file: * 1. tshark -r capture.pcapng -T pdml > ~/capture.pdml * 2. krbng2john.py ~/capture.pdml > krb5.in * 3. Run john on krb5.in * * http://www.ietf.org/rfc/rfc4757.txt * http://www.securiteam.com/windowsntfocus/5BP0H0A6KM.html * * Input format is 'user:$krb5pa$etype$user$realm$salt$timestamp+checksum' * * NOTE: Checksum implies last 12 bytes of PA_ENC_TIMESTAMP value in AS-REQ * packet. * * Default Salt: realm + user * * AES-256 encryption & decryption of AS-REQ timestamp in Kerberos v5 * See the following RFC for more details about the crypto & algorithms used: * * RFC3961 - Encryption and Checksum Specifications for Kerberos 5 * RFC3962 - Advanced Encryption Standard (AES) Encryption for Kerberos 5 * * march 09 / kevin devine <wyse101 0x40 gmail.com> * * This software is Copyright (c) 2012 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. * * This software is Copyright (c) 2012 Dhiru Kholia (dhiru at openwall.com) and * released under same terms as above */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_krb5pa_sha1; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_krb5pa_sha1); #else #include <errno.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include "arch.h" #include "misc.h" #include "formats.h" #include "options.h" #include "common.h" #include "unicode.h" #include "config.h" #include "aes.h" #include "common-opencl.h" #define OUTLEN 32 #include "opencl_pbkdf2_hmac_sha1.h" #include "hmac_sha.h" #include "loader.h" #define FORMAT_LABEL "krb5pa-sha1-opencl" #define FORMAT_NAME "Kerberos 5 AS-REQ Pre-Auth etype 17/18" /* aes-cts-hmac-sha1-96 */ #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1001 #define BINARY_SIZE 12 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 1 #define MAX_SALTLEN 52 #define MAX_REALMLEN MAX_SALTLEN #define MAX_USERLEN MAX_SALTLEN #define TIMESTAMP_SIZE 44 #define CHECKSUM_SIZE BINARY_SIZE #define TOTAL_LENGTH (14 + 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) + MAX_REALMLEN + MAX_USERLEN + MAX_SALTLEN) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 /* This handles all sizes */ #define GETPOS(i, index) (((index) % ocl_v_width) * 4 + ((i) & ~3U) * ocl_v_width + (((i) & 3) ^ 3) + ((index) / ocl_v_width) * 64 * ocl_v_width) /* This is faster but can't handle size 3 */ //#define GETPOS(i, index) (((index) & (ocl_v_width - 1)) * 4 + ((i) & ~3U) * ocl_v_width + (((i) & 3) ^ 3) + ((index) / ocl_v_width) * 64 * ocl_v_width) static struct fmt_tests tests[] = { {"$krb5pa$18$user1$EXAMPLE.COM$$2a0e68168d1eac344da458599c3a2b33ff326a061449fcbc242b212504e484d45903c6a16e2d593912f56c93883bf697b325193d62a8be9c", "openwall"}, {"$krb5pa$18$user1$EXAMPLE.COM$$a3918bd0381107feedec8db0022bdf3ac56e534ed54d13c62a7013a47713cfc31ef4e7e572f912fa4164f76b335e588bf29c2d17b11c5caa", "openwall"}, {"$krb5pa$18$l33t$EXAMPLE.COM$$98f732b309a1d7ef2355a974842a32894d911e97150f5d57f248e1c2632fbd3735c5f156532ccae0341e6a2d779ca83a06021fe57dafa464", "openwall"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$64dfeee04be2b2e0423814e0df4d0f960885aca4efffe6cb5694c4d34690406071c4968abd2c153ee42d258c5e09a41269bbcd7799f478d3", "password@123"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$AD.EXAMPLE.COMaduser$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, /* etype 17 hash obtained using MiTM etype downgrade attack */ {"$krb5pa$17$user1$EXAMPLE.COM$$c5461873dc13665771b98ba80be53939e906d90ae1ba79cf2e21f0395e50ee56379fbef4d0298cfccfd6cf8f907329120048fd05e8ae5df4", "openwall"}, {NULL}, }; static cl_mem mem_in, mem_out, mem_salt, mem_state, pinned_in, pinned_out; static cl_kernel pbkdf2_init, pbkdf2_loop, pbkdf2_final; static struct fmt_main *self; static struct custom_salt { int type; int etype; unsigned char realm[64]; unsigned char user[64]; unsigned char salt[64]; /* realm + user */ unsigned char ct[TIMESTAMP_SIZE]; } *cur_salt; static unsigned char constant[16]; static unsigned char ke_input[16]; static unsigned char ki_input[16]; static size_t key_buf_size; static unsigned int *inbuffer; static pbkdf2_salt currentsalt; static pbkdf2_out *output; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static int new_keys; #define ITERATIONS (4096 - 1) #define HASH_LOOPS 105 // Must be made from factors 3, 3, 5, 7, 13 #define STEP 0 #define SEED 128 static const char * warn[] = { "P xfer: ", ", init: ", ", loop: ", ", inter: ", ", final: ", ", res xfer: " }; static int split_events[] = { 2, -1, -1 }; //This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { size_t s; s = autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_init); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_loop)); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_final)); return s; } #if 0 struct fmt_main *me; #endif static void create_clobj(size_t gws, struct fmt_main *self) { gws *= ocl_v_width; key_buf_size = 64 * gws; /// Allocate memory pinned_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, key_buf_size, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating pinned in"); mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, key_buf_size, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem in"); inbuffer = clEnqueueMapBuffer(queue[gpu_id], pinned_in, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, key_buf_size, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory"); mem_state = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, sizeof(pbkdf2_state) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem_state"); mem_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(pbkdf2_salt), &currentsalt, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem setting"); pinned_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR, sizeof(pbkdf2_out) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating pinned out"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, sizeof(pbkdf2_out) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem out"); output = clEnqueueMapBuffer(queue[gpu_id], pinned_out, CL_TRUE, CL_MAP_READ, 0, sizeof(pbkdf2_out) * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 1, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 2, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_loop, 0, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 0, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 2, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); crypt_out = mem_alloc(sizeof(*crypt_out) * gws); } static void release_clobj(void) { if (crypt_out) { HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_in, inbuffer, 0, NULL, NULL), "Error Unmapping mem in"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_out, output, 0, NULL, NULL), "Error Unmapping mem in"); HANDLE_CLERROR(clFinish(queue[gpu_id]), "Error releasing memory mappings"); HANDLE_CLERROR(clReleaseMemObject(pinned_in), "Release pinned_in"); HANDLE_CLERROR(clReleaseMemObject(pinned_out), "Release pinned_out"); HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release pinned_in"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem_out"); HANDLE_CLERROR(clReleaseMemObject(mem_salt), "Release mem_salt"); HANDLE_CLERROR(clReleaseMemObject(mem_state), "Release mem state"); MEM_FREE(crypt_out); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(pbkdf2_init), "Release Kernel"); HANDLE_CLERROR(clReleaseKernel(pbkdf2_loop), "Release Kernel"); HANDLE_CLERROR(clReleaseKernel(pbkdf2_final), "Release Kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } /* n-fold(k-bits): * l = lcm(n,k) * r = l/k * s = k-bits | k-bits rot 13 | k-bits rot 13*2 | ... | k-bits rot 13*(r-1) * compute the 1's complement sum: * n-fold = s[0..n-1]+s[n..2n-1]+s[2n..3n-1]+..+s[(k-1)*n..k*n-1] */ /* representation: msb first, assume n and k are multiples of 8, and * that k>=16. this is the case of all the cryptosystems which are * likely to be used. this function can be replaced if that * assumption ever fails. */ /* input length is in bits */ static void nfold(unsigned int inbits, const unsigned char *in, unsigned int outbits,unsigned char *out) { int a,b,c,lcm; int byte, i, msbit; /* the code below is more readable if I make these bytes * instead of bits */ inbits >>= 3; outbits >>= 3; /* first compute lcm(n,k) */ a = outbits; b = inbits; while (b != 0) { c = b; b = a % b; a = c; } lcm = outbits*inbits/a; /* now do the real work */ memset(out, 0, outbits); byte = 0; /* this will end up cycling through k lcm(k,n)/k times, which * is correct */ for (i = lcm - 1; i >= 0; i--) { /* compute the msbit in k which gets added into this byte */ msbit = (/* first, start with the msbit in the first, unrotated byte */ ((inbits << 3) - 1) /* then, for each byte, shift to the right for each * repetition */ +(((inbits << 3) + 13) * (i / inbits)) /* last, pick out the correct byte within that * shifted repetition */ +((inbits - (i % inbits)) << 3) ) % (inbits << 3); /* pull out the byte value itself */ byte += (((in[((inbits - 1) - (msbit >> 3)) % inbits] << 8)| (in[((inbits) - (msbit>>3)) % inbits])) >>((msbit & 7) + 1)) & 0xff; /* do the addition */ byte += out[i % outbits]; out[i % outbits] = byte & 0xff; /* keep around the carry bit, if any */ byte >>= 8; } /* if there's a carry bit left over, add it back in */ if (byte) { for (i = outbits - 1; i >= 0; i--) { /* do the addition */ byte += out[i]; out[i] = byte & 0xff; /* keep around the carry bit, if any */ byte >>= 8;\ } } } static void init(struct fmt_main *_self) { unsigned char usage[5]; static char valgo[sizeof(ALGORITHM_NAME) + 8] = ""; self = _self; opencl_prepare_dev(gpu_id); /* VLIW5 does better with just 2x vectors due to GPR pressure */ if (!options.v_width && amd_vliw5(device_info[gpu_id])) ocl_v_width = 2; else ocl_v_width = opencl_get_vector_width(gpu_id, sizeof(cl_int)); if (ocl_v_width > 1) { /* Run vectorized kernel */ snprintf(valgo, sizeof(valgo), ALGORITHM_NAME " %ux", ocl_v_width); self->params.algorithm_name = valgo; } // generate 128 bits from 40 bits of "kerberos" string nfold(8 * 8, (unsigned char*)"kerberos", 128, constant); memset(usage,0,sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0xAA; // used to derive Ke nfold(sizeof(usage)*8,usage,sizeof(ke_input)*8,ke_input); memset(usage,0,sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0x55; // used to derive Ki nfold(sizeof(usage)*8,usage,sizeof(ki_input)*8,ki_input); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[128]; snprintf(build_opts, sizeof(build_opts), "-DHASH_LOOPS=%u -DITERATIONS=%u -DOUTLEN=%u " "-DPLAINTEXT_LENGTH=%u -DV_WIDTH=%u", HASH_LOOPS, ITERATIONS, OUTLEN, PLAINTEXT_LENGTH, ocl_v_width); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_kernel.cl", gpu_id, build_opts); pbkdf2_init = clCreateKernel(program[gpu_id], "pbkdf2_init", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); crypt_kernel = pbkdf2_loop = clCreateKernel(program[gpu_id], "pbkdf2_loop", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); pbkdf2_final = clCreateKernel(program[gpu_id], "pbkdf2_final", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); //Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 2 * HASH_LOOPS, split_events, warn, 2, self, create_clobj, release_clobj, ocl_v_width * sizeof(pbkdf2_state), 0, db); //Auto tune execution from shared/included code. autotune_run(self, 4 * ITERATIONS + 4, 0, (cpu(device_info[gpu_id]) ? 1000000000 : 5000000000ULL)); } } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *data = ciphertext; int type, saltlen = 0; // tag is mandatory if (strncmp(ciphertext, "$krb5pa$", 8) != 0) return 0; data += 8; // etype field, 17 or 18 p = strchr(data, '$'); if (!p || p - data != 2) return 0; type = atoi(data); if (type < 17 || type > 18) return 0; data = p + 1; // user field p = strchr(data, '$'); if (!p || p - data > MAX_USERLEN) return 0; saltlen += p - data; data = p + 1; // realm field p = strchr(data, '$'); if (!p || p - data > MAX_REALMLEN) return 0; saltlen += p - data; data = p + 1; // salt field p = strchr(data, '$'); if (!p) return 0; // if salt is empty, realm.user is used instead if (p - data) saltlen = p - data; data = p + 1; // We support a max. total salt length of 52. // We could opt to emit a warning if rejected here. if(saltlen > MAX_SALTLEN) { static int warned = 0; if (!ldr_in_pot) if (!warned++) fprintf(stderr, "%s: One or more hashes rejected due to salt length limitation\n", FORMAT_LABEL); return 0; } // 56 bytes (112 hex chars) encrypted timestamp + checksum if (strlen(data) != 2 * (TIMESTAMP_SIZE + CHECKSUM_SIZE) || strspn(data, HEXCHARS_all) != strlen(data)) return 0; return 1; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int i; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += 8; p = strtokm(ctcopy, "$"); cs.etype = atoi(p); p = strtokm(NULL, "$"); if (p[-1] == '$') cs.user[0] = 0; else { strcpy((char*)cs.user, p); p = strtokm(NULL, "$"); } if (p[-1] == '$') cs.realm[0] = 0; else { strcpy((char*)cs.realm, p); p = strtokm(NULL, "$"); } if (p[-1] == '$') { strcpy((char*)cs.salt, (char*)cs.realm); strcat((char*)cs.salt, (char*)cs.user); } else { strcpy((char*)cs.salt, p); p = strtokm(NULL, "$"); } for (i = 0; i < TIMESTAMP_SIZE; i++) cs.ct[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void clear_keys(void) { memset(inbuffer, 0, key_buf_size); } static void set_key(char *key, int index) { int i; int length = strlen(key); for (i = 0; i < length; i++) ((char*)inbuffer)[GETPOS(i, index)] = key[i]; new_keys = 1; } static char* get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; int i = 0; while (i < PLAINTEXT_LENGTH && (ret[i] = ((char*)inbuffer)[GETPOS(i, index)])) i++; ret[i] = 0; return ret; } static char *split(char *ciphertext, int index, struct fmt_main *pFmt) { static char out[TOTAL_LENGTH + 1]; char in[TOTAL_LENGTH + 1]; char salt[MAX_SALTLEN + 1]; char *data; char *e, *u, *r, *s, *tc; strnzcpy(in, ciphertext, sizeof(in)); tc = strrchr(in, '$'); *tc++ = 0; s = strrchr(in, '$'); *s++ = 0; r = strrchr(in, '$'); *r++ = 0; u = strrchr(in, '$'); *u++ = 0; e = in + 8; /* Default salt is user.realm */ if (!*s) { snprintf(salt, sizeof(salt), "%s%s", r, u); s = salt; } snprintf(out, sizeof(out), "$krb5pa$%s$%s$%s$%s$%s", e, u, r, s, tc); data = out + strlen(out) - 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) - 1; strlwr(data); return out; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1 + TIMESTAMP_SIZE * 2; /* skip to checksum field */ for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; currentsalt.length = strlen((char*)cur_salt->salt); currentsalt.iterations = ITERATIONS; memcpy(currentsalt.salt, cur_salt->salt, currentsalt.length); HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, sizeof(pbkdf2_salt), &currentsalt, 0, NULL, NULL), "Copy setting to gpu"); } static void AES_cts_encrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec, const int encryptp) { unsigned char tmp[AES_BLOCK_SIZE]; unsigned int i; if (encryptp) { while(len > AES_BLOCK_SIZE) { for (i = 0; i < AES_BLOCK_SIZE; i++) tmp[i] = in[i] ^ ivec[i]; AES_encrypt(tmp, out, key); memcpy(ivec, out, AES_BLOCK_SIZE); len -= AES_BLOCK_SIZE; in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; } for (i = 0; i < len; i++) tmp[i] = in[i] ^ ivec[i]; for (; i < AES_BLOCK_SIZE; i++) tmp[i] = 0 ^ ivec[i]; AES_encrypt(tmp, out - AES_BLOCK_SIZE, key); memcpy(out, ivec, len); memcpy(ivec, out - AES_BLOCK_SIZE, AES_BLOCK_SIZE); } else { unsigned char tmp2[AES_BLOCK_SIZE]; unsigned char tmp3[AES_BLOCK_SIZE]; while(len > AES_BLOCK_SIZE * 2) { memcpy(tmp, in, AES_BLOCK_SIZE); AES_decrypt(in, out, key); for (i = 0; i < AES_BLOCK_SIZE; i++) out[i] ^= ivec[i]; memcpy(ivec, tmp, AES_BLOCK_SIZE); len -= AES_BLOCK_SIZE; in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; } len -= AES_BLOCK_SIZE; memcpy(tmp, in, AES_BLOCK_SIZE); /* save last iv */ AES_decrypt(in, tmp2, key); memcpy(tmp3, in + AES_BLOCK_SIZE, len); memcpy(tmp3 + len, tmp2 + len, AES_BLOCK_SIZE - len); /* xor 0 */ for (i = 0; i < len; i++) out[i + AES_BLOCK_SIZE] = tmp2[i] ^ tmp3[i]; AES_decrypt(tmp3, out, key); for (i = 0; i < AES_BLOCK_SIZE; i++) out[i] ^= ivec[i]; memcpy(ivec, tmp, AES_BLOCK_SIZE); } } // keysize = 32 for 256 bits, 16 for 128 bits static void dk(unsigned char key_out[], unsigned char key_in[], size_t key_size, unsigned char ptext[], size_t ptext_size) { unsigned char iv[32]; unsigned char plaintext[32]; AES_KEY ekey; memset(iv,0,sizeof(iv)); memset(plaintext,0,sizeof(plaintext)); memcpy(plaintext,ptext,16); AES_set_encrypt_key(key_in,key_size*8,&ekey); AES_cbc_encrypt(plaintext,key_out,key_size,&ekey,iv,AES_ENCRYPT); } static void krb_decrypt(const unsigned char ciphertext[], size_t ctext_size, unsigned char plaintext[], const unsigned char key[], size_t key_size) { unsigned char iv[32]; AES_KEY ekey; memset(iv,0,sizeof(iv)); AES_set_decrypt_key(key,key_size*8,&ekey); AES_cts_encrypt(ciphertext,plaintext,ctext_size,&ekey,iv,AES_DECRYPT); } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int i; int key_size; size_t scalar_gws; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER_VW(count, local_work_size); scalar_gws = global_work_size * ocl_v_width; if (cur_salt->etype == 17) key_size = 16; else key_size = 32; /// Copy data to gpu if (ocl_autotune_running || new_keys) { BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, key_buf_size, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); new_keys = 0; } /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_init, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run initial kernel"); for (i = 0; i < (ocl_autotune_running ? 1 : ITERATIONS / HASH_LOOPS); i++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_loop, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[2]), "Run loop kernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_final, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[3]), "Run intermediate kernel"); for (i = 0; i < (ocl_autotune_running ? 1 : ITERATIONS / HASH_LOOPS); i++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_loop, 1, NULL, &global_work_size, lws, 0, NULL, NULL), "Run loop kernel (2nd pass)"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_final, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[4]), "Run final kernel (SHA1)"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Failed running final kernel"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, sizeof(pbkdf2_out) * scalar_gws, output, 0, NULL, multi_profilingEvent[5]), "Copy result back"); if (!ocl_autotune_running) { #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < count; i++) { unsigned char base_key[32]; unsigned char Ke[32]; unsigned char plaintext[TIMESTAMP_SIZE]; //pbkdf2((const unsigned char*)saved_key[i], len, (unsigned char *)cur_salt->salt,strlen((char*)cur_salt->salt), 4096, (unsigned int*)tkey); // generate 128 bits from 40 bits of "kerberos" string // This is precomputed in init() //nfold(8 * 8, (unsigned char*)"kerberos", 128, constant); dk(base_key, (unsigned char*)output[i].dk, key_size, constant, 32); /* The "well-known constant" used for the DK function is the key usage number, * expressed as four octets in big-endian order, followed by one octet indicated below. * Kc = DK(base-key, usage | 0x99); * Ke = DK(base-key, usage | 0xAA); * Ki = DK(base-key, usage | 0x55); */ // derive Ke for decryption/encryption // This is precomputed in init() //memset(usage,0,sizeof(usage)); //usage[3] = 0x01; // key number in big-endian format //usage[4] = 0xAA; // used to derive Ke //nfold(sizeof(usage)*8,usage,sizeof(ke_input)*8,ke_input); dk(Ke, base_key, key_size, ke_input, 32); // decrypt the AS-REQ timestamp encrypted with 256-bit AES // here is enough to check the string, further computation below is required // to fully verify the checksum krb_decrypt(cur_salt->ct, TIMESTAMP_SIZE, plaintext, Ke, key_size); // Check a couple bytes from known plain (YYYYMMDDHHMMSSZ) and // bail out if we are out of luck. if (plaintext[22] == '2' && plaintext[23] == '0' && plaintext[36] == 'Z') { unsigned char Ki[32]; unsigned char checksum[20]; // derive Ki used in HMAC-SHA-1 checksum // This is precomputed in init() //memset(usage,0,sizeof(usage)); //usage[3] = 0x01; // key number in big-endian format //usage[4] = 0x55; // used to derive Ki //nfold(sizeof(usage)*8,usage,sizeof(ki_input)*8,ki_input); dk(Ki, base_key, key_size, ki_input, 32); // derive checksum of plaintext (only 96 bits used out of 160) hmac_sha1(Ki, key_size, plaintext, TIMESTAMP_SIZE, checksum, 20); memcpy(crypt_out[i], checksum, BINARY_SIZE); } else { memset(crypt_out[i], 0, BINARY_SIZE); } } } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_opencl_krb5pa_sha1 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, { NULL }, tests }, { init, done, reset, fmt_default_prepare, valid, split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
core_strmm.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_ztrmm.c, normal z -> s, Fri Sep 28 17:38:23 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_trmm * * Performs a triangular matrix-matrix multiply of the form * * \f[B = \alpha [op(A) \times B] \f], if side = PlasmaLeft or * \f[B = \alpha [B \times op(A)] \f], if side = PlasmaRight * * where op( X ) is one of: * * - op(A) = A or * - op(A) = A^T or * - op(A) = A^T * * alpha is a scalar, B is an m-by-n matrix and A is a unit or non-unit, upper * or lower triangular matrix. * ******************************************************************************* * * @param[in] side * Specifies whether op( A ) appears on the left or on the right of B: * - PlasmaLeft: alpha*op( A )*B * - PlasmaRight: alpha*B*op( A ) * * @param[in] uplo * Specifies whether the matrix A is upper triangular or lower * triangular: * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] transa * Specifies whether the matrix A is transposed, not transposed or * conjugate transposed: * - PlasmaNoTrans: A is transposed; * - PlasmaTrans: A is not transposed; * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] diag * Specifies whether or not A is unit triangular: * - PlasmaNonUnit: A is non-unit triangular; * - PlasmaUnit: A is unit triangular. * * @param[in] m * The number of rows of matrix B. * m >= 0. * * @param[in] n * The number of columns of matrix B. * n >= 0. * * @param[in] alpha * The scalar alpha. * * @param[in] A * The triangular matrix A of dimension lda-by-k, where k is m when * side='L' or 'l' and k is n when when side='R' or 'r'. If uplo = * PlasmaUpper, the leading k-by-k upper triangular part of the array * A contains the upper triangular matrix, and the strictly lower * triangular part of A is not referenced. If uplo = PlasmaLower, the * leading k-by-k lower triangular part of the array A contains the * lower triangular matrix, and the strictly upper triangular part of * A is not referenced. If diag = PlasmaUnit, the diagonal elements of * A are also not referenced and are assumed to be 1. * * @param[in] lda * The leading dimension of the array A. When side='L' or 'l', * lda >= max(1,m), when side='R' or 'r' then lda >= max(1,n). * * @param[in,out] B * On entry, the matrix B of dimension ldb-by-n. * On exit, the result of a triangular matrix-matrix multiply * ( alpha*op(A)*B ) or ( alpha*B*op(A) ). * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,m). * ******************************************************************************/ __attribute__((weak)) void plasma_core_strmm( plasma_enum_t side, plasma_enum_t uplo, plasma_enum_t transa, plasma_enum_t diag, int m, int n, float alpha, const float *A, int lda, float *B, int ldb) { cblas_strmm( CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)transa, (CBLAS_DIAG)diag, m, n, (alpha), A, lda, B, ldb); } /******************************************************************************/ void plasma_core_omp_strmm( plasma_enum_t side, plasma_enum_t uplo, plasma_enum_t transa, plasma_enum_t diag, int m, int n, float alpha, const float *A, int lda, float *B, int ldb, plasma_sequence_t *sequence, plasma_request_t *request) { int k = (side == PlasmaLeft) ? m : n; #pragma omp task depend(in:A[0:lda*k]) \ depend(inout:B[0:ldb*n]) { if (sequence->status == PlasmaSuccess) plasma_core_strmm(side, uplo, transa, diag, m, n, alpha, A, lda, B, ldb); } }
scheduled-clause.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int main(int argc, char **argv) { int i, n=200,chunk,a[n],suma=0; if(argc < 3) { fprintf(stderr,"\nFalta iteraciones o chunk \n"); exit(-1); } n = atoi(argv[1]); if (n>200) n=200; chunk = atoi(argv[2]); for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for firstprivate(suma) \ lastprivate(suma) schedule(dynamic,chunk) //No se asignan los chunk previamente, sino que se van asignando //cuando van terminando las hebras. // Se hace una primera asignacion a las hebras disponibles, //en paquetes de tamaño chunk, y la primer que termine se le asigna //otro paquete de tamaño chunk. Así hasta realizarse todas las iteraciones. for (i=0; i<n; i++) { suma = suma + a[i]; printf(" thread %d suma a[%d]=%d suma=%d \n", omp_get_thread_num(),i,a[i],suma); } printf("Fuera de 'parallel for' suma=%d\n",suma); return(0); }
GB_unop__identity_fc32_int8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fc32_int8) // op(A') function: GB (_unop_tran__identity_fc32_int8) // C type: GxB_FC32_t // A type: int8_t // cast: GxB_FC32_t cij = GxB_CMPLXF ((float) (aij), 0) // unaryop: cij = aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FC32 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fc32_int8) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const int8_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int8_t aij = Ax [p] ; GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fc32_int8) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__minv_int64_int64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__minv_int64_int64) // op(A') function: GB (_unop_tran__minv_int64_int64) // C type: int64_t // A type: int64_t // cast: int64_t cij = aij // unaryop: cij = GB_IMINV_SIGNED (aij, 64) #define GB_ATYPE \ int64_t #define GB_CTYPE \ int64_t // 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 = GB_IMINV_SIGNED (x, 64) ; // casting #define GB_CAST(z, aij) \ int64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = aij ; \ Cx [pC] = GB_IMINV_SIGNED (z, 64) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__minv_int64_int64) ( int64_t *Cx, // Cx and Ax may be aliased const int64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t aij = Ax [p] ; int64_t z = aij ; Cx [p] = GB_IMINV_SIGNED (z, 64) ; } } 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 ; int64_t aij = Ax [p] ; int64_t z = aij ; Cx [p] = GB_IMINV_SIGNED (z, 64) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__minv_int64_int64) ( 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
beta_projectors_strain_deriv.h
#ifndef __BETA_PROJECTORS_STRAIN_DERIV_H__ #define __BETA_PROJECTORS_STRAIN_DERIV_H__ #include "beta_projectors_base.h" namespace sirius { class Beta_projectors_strain_deriv : public Beta_projectors_base<9> { private: void generate_pw_coefs_t(std::vector<int> const& igk__) { PROFILE("sirius::Beta_projectors_strain_deriv::generate_pw_coefs_t"); if (!num_beta_t()) { return; } auto& beta_ri0 = ctx_.beta_ri(); auto& beta_ri1 = ctx_.beta_ri_djl(); int lmax = ctx_.unit_cell().lmax(); int lmmax = Utils::lmmax(lmax); mdarray<double, 2> rlm_g(lmmax, num_gkvec_loc()); mdarray<double, 3> rlm_dg(lmmax, 3, num_gkvec_loc()); /* array of real spherical harmonics and derivatives for each G-vector */ #pragma omp parallel for schedule(static) for (int igkloc = 0; igkloc < num_gkvec_loc(); igkloc++) { auto gvc = gkvec_.gkvec_cart(igk__[igkloc]); auto rtp = SHT::spherical_coordinates(gvc); double theta = rtp[1]; double phi = rtp[2]; SHT::spherical_harmonics(lmax, theta, phi, &rlm_g(0, igkloc)); mdarray<double, 2> rlm_dg_tmp(&rlm_dg(0, 0, igkloc), lmmax, 3); SHT::dRlm_dr(lmax, gvc, rlm_dg_tmp); } /* compute d <G+k|beta> / d epsilon_{mu, nu} */ #pragma omp parallel for schedule(static) for (int igkloc = 0; igkloc < num_gkvec_loc(); igkloc++) { auto gvc = gkvec_.gkvec_cart(igk__[igkloc]); /* vs = {r, theta, phi} */ auto gvs = SHT::spherical_coordinates(gvc); /* |G+k|=0 case */ if (gvs[0] < 1e-10) { for (int nu = 0; nu < 3; nu++) { for (int mu = 0; mu < 3; mu++) { double p = (mu == nu) ? 0.5 : 0; for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) { auto& atom_type = ctx_.unit_cell().atom_type(iat); for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) { int l = atom_type.indexb(xi).l; int idxrf = atom_type.indexb(xi).idxrf; if (l == 0) { auto z = fourpi / std::sqrt(ctx_.unit_cell().omega()); auto d1 = beta_ri0.value<int, int>(idxrf, iat, gvs[0]) * (-p * y00); pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) = z * d1; } else { pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) = 0; } } } } } continue; } for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) { auto& atom_type = ctx_.unit_cell().atom_type(iat); auto ri0 = beta_ri0.values(iat, gvs[0]); auto ri1 = beta_ri1.values(iat, gvs[0]); for (int nu = 0; nu < 3; nu++) { for (int mu = 0; mu < 3; mu++) { double p = (mu == nu) ? 0.5 : 0; for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) { int l = atom_type.indexb(xi).l; int lm = atom_type.indexb(xi).lm; int idxrf = atom_type.indexb(xi).idxrf; auto z = std::pow(double_complex(0, -1), l) * fourpi / std::sqrt(ctx_.unit_cell().omega()); auto d1 = ri0(idxrf) * (-gvc[mu] * rlm_dg(lm, nu, igkloc) - p * rlm_g(lm, igkloc)); auto d2 = ri1(idxrf) * rlm_g(lm, igkloc) * (-gvc[mu] * gvc[nu] / gvs[0]); pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) = z * (d1 + d2); } } } } } } //void generate_pw_coefs_t_v2() //{ // PROFILE("sirius::Beta_projectors_strain_deriv::generate_pw_coefs_t_v2"); // auto& bchunk = ctx_.beta_projector_chunks(); // if (!bchunk.num_beta_t()) { // return; // } // Radial_integrals_beta<false> beta_ri0(ctx_.unit_cell(), ctx_.gk_cutoff(), ctx_.settings().nprii_beta_); // Radial_integrals_beta_jl beta_ri1(ctx_.unit_cell(), ctx_.gk_cutoff(), ctx_.settings().nprii_beta_); // vector3d<int> r_m({1, -1, 0}); // vector3d<double> r_f({-2 * std::sqrt(pi / 3), -2 * std::sqrt(pi / 3), 2 * std::sqrt(pi / 3)}); // auto& comm = gkvec_.comm(); // /* zero array */ // for (int i = 0; i < 9; i++) { // pw_coeffs_t_[i].zero(); // } // std::vector<double_complex> zil(lmax_beta_ + 2); // for (int l = 0; l < lmax_beta_ + 2; l++) { // zil[l] = std::pow(double_complex(0, -1), l); // } // Gaunt_coefficients<double> gc(1, lmax_beta_ + 2, lmax_beta_, SHT::gaunt_rlm); // /* compute d <G+k|beta> / d epsilon_{mu, nu} */ // #pragma omp parallel for schedule(static) // for (int igkloc = 0; igkloc < num_gkvec_loc(); igkloc++) { // int igk = gkvec_.gvec_offset(comm.rank()) + igkloc; // auto gvc = gkvec_.gkvec_cart(igk); // /* vs = {r, theta, phi} */ // auto gvs = SHT::spherical_coordinates(gvc); // /* compute real spherical harmonics for G+k vector */ // std::vector<double> gkvec_rlm(Utils::lmmax(lmax_beta_ + 2)); // SHT::spherical_harmonics(lmax_beta_ + 2, gvs[1], gvs[2], &gkvec_rlm[0]); // mdarray<double, 3> tmp(ctx_.unit_cell().max_mt_radial_basis_size(), lmax_beta_ + 3, ctx_.unit_cell().num_atom_types()); // for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) { // for (int l = 0; l <= lmax_beta_ + 2; l++) { // for (int j = 0; j < ctx_.unit_cell().atom_type(iat).mt_radial_basis_size(); j++) { // tmp(j, l, iat) = beta_ri1.value<int, int, int>(j, l, iat, gvs[0]); // } // } // } // for (int nu = 0; nu < 3; nu++) { // for (int mu = 0; mu < 3; mu++) { // double p = (mu == nu) ? 0.5 : 0; // auto z1 = fourpi / std::sqrt(ctx_.unit_cell().omega()); // auto z2 = z1 * gvc[mu] * double_complex(0, 1) * r_f[nu]; // for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) { // auto& atom_type = ctx_.unit_cell().atom_type(iat); // for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) { // int l = atom_type.indexb(xi).l; // int lm = atom_type.indexb(xi).lm; // int idxrf = atom_type.indexb(xi).idxrf; // // double_complex z3(0, 0); // for (int k = 0; k < gc.num_gaunt(Utils::lm_by_l_m(1, r_m[nu]), lm); k++) { // auto& c = gc.gaunt(Utils::lm_by_l_m(1, r_m[nu]), lm, k); // int l3 = c.l3; // z3 += zil[l3] * gkvec_rlm[c.lm3] * c.coef * tmp(idxrf, l3, iat); // } // //pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) += // // gvc[mu] * std::pow(double_complex(0, -1), l3) * z * double_complex(0, 1) * // // gkvec_rlm[c.lm3] * c.coef * tmp(idxrf, l3, iat) * r_f[nu]; // pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) += z3 * z2; // auto d2 = beta_ri0.value<int, int>(idxrf, iat, gvs[0]) * (-p * gkvec_rlm[lm]); // pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) += z1 * d2 * zil[l]; // } // } // } // mu // //for (int mu = 0; mu <= nu; mu++) { // // for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) { // // pw_coeffs_t_[nu + mu * 3](igkloc, atom_type.offset_lo() + xi) = pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi); // // } // //} // } // nu // } //} public: Beta_projectors_strain_deriv(Simulation_context& ctx__, Gvec const& gkvec__, std::vector<int> const& igk__) : Beta_projectors_base<9>(ctx__, gkvec__, igk__) { generate_pw_coefs_t(igk__); //generate_pw_coefs_t_v2(); //if (ctx__.processing_unit() == GPU) { // for (int j = 0; j < 9; j++) { // pw_coeffs_t_[j].copy<memory_t::host, memory_t::device>(); // } //} } }; } #endif
GB_binop__pow_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__pow_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__pow_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__pow_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__pow_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_fp32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__pow_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__pow_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_fp32) // C=scalar+B GB (_bind1st__pow_fp32) // C=scalar+B' GB (_bind1st_tran__pow_fp32) // C=A+scalar GB (_bind2nd__pow_fp32) // C=A'+scalar GB (_bind2nd_tran__pow_fp32) // C type: float // A type: float // B,b type: float // BinaryOp: cij = GB_powf (aij, bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // 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) \ float aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ float bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_powf (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_POW || GxB_NO_FP32 || GxB_NO_POW_FP32) //------------------------------------------------------------------------------ // 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__pow_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__pow_fp32) ( 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__pow_fp32) ( 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 float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) 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__pow_fp32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__pow_fp32) ( 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__pow_fp32) ( 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__pow_fp32) ( 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__pow_fp32) ( 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__pow_fp32) ( 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 float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; float bij = GBX (Bx, p, false) ; Cx [p] = GB_powf (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__pow_fp32) ( 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 ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = GBX (Ax, p, false) ; Cx [p] = GB_powf (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_powf (x, aij) ; \ } GrB_Info GB (_bind1st_tran__pow_fp32) ( 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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_powf (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__pow_fp32) ( 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 float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
p4.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <omp.h> #define ISIZE 1000 #define JSIZE 1000 int main(int argc, char **argv) { double *a = new double[ISIZE*JSIZE]; double *A = new double[ISIZE*JSIZE]; FILE *ff; int nth = 1; if (argc == 2) nth = atoi(argv[1]); omp_set_dynamic(0); omp_set_num_threads(nth); // Initialization for (int i = 0; i < ISIZE; ++i) { for (int j = 0; j < JSIZE; ++j) { a[i*JSIZE+j] = 10 * i + j; } } for (int i = 0; i < ISIZE; ++i) { A[i*JSIZE+JSIZE-2] = 10 * i + JSIZE-2; A[i*JSIZE+JSIZE-1] = 10 * i + JSIZE-1; } double t = omp_get_wtime(); for (int k = 0; k < 1000; ++k){ // Parallelize #pragma omp parallel for collapse(2) for (int j = 0; j < JSIZE - 2; ++j) { for (int i = 0; i < ISIZE; ++i) { A[i*JSIZE+j] = sin(0.00001 * a[i*JSIZE+j+2]); } } } t = omp_get_wtime() - t; printf("Time: %f\n", t); ff = fopen("p4.out", "w"); for (int i = 0; i < ISIZE; ++i) { for (int j = 0; j < JSIZE; ++j) { fprintf(ff, "%f\n", A[i*JSIZE+j]); } fprintf(ff, "\n"); } fclose(ff); delete [] a; delete [] A; return 0; }
BlockMatching_private_initializer.h
#include <algorithm> #include <cmath> #include <iostream> #include <new> #include <stdexcept> template <class T> BlockMatching<T>::BlockMatching(void) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; } template <class T> BlockMatching<T>::BlockMatching(const ImgVector<T>& image_prev, const ImgVector<T>& image_current, const int BlockSize, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_prev"); } else if (image_current.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_current" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_current"); } else if (image_prev.width() != image_current.width()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width of image_prev and image_current not match" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width of image_prev and image_current not match"); } else if (image_prev.height() != image_current.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : height of image_prev and image_current not match" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : height of image_prev and image_current not match"); } else if (BlockSize < 0) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : BlockSize" << std::endl; throw std::out_of_range("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : BlockSize"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = BlockSize; _cells_width = int(ceil(double(_width) / double(_block_size))); _cells_height = int(ceil(double(_height) / double(_block_size))); _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); // Normalize the image image_normalizer(); } template <class T> BlockMatching<T>::BlockMatching(const ImgVector<T>& image_prev, const ImgVector<T>& image_current, const ImgVector<T>& image_next, const int BlockSize, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_prev"); } else if (image_current.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_current" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : ImgVector<T>& image_current"); } else if (image_prev.width() != image_current.width()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width of image_prev and image_current not match" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width of image_prev and image_current not match"); } else if (image_prev.height() != image_current.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : height of image_prev and image_current not match" << std::endl; throw std::invalid_argument("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : height of image_prev and image_current not match"); } else if (BlockSize < 0) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : BlockSize" << std::endl; throw std::out_of_range("BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : BlockSize"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = BlockSize; _cells_width = int(ceil(double(_width) / double(_block_size))); _cells_height = int(ceil(double(_height) / double(_block_size))); _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); _image_next.copy(image_next); // Normalize the image image_normalizer(); } template <class T> BlockMatching<T>::BlockMatching(const ImgVector<T>& image_prev, const ImgVector<size_t>& region_map_prev, const ImgVector<T>& image_current, const ImgVector<size_t>& region_map_current, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_prev"); } else if (image_current.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_current" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_current"); } else if (image_prev.width() != image_current.width() || image_prev.height() != image_current.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width or height of image_prev and image_current not match" << std::endl; throw std::invalid_argument("width or height of image_prev and image_current not match"); } else if (region_map_prev.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<int>& region_map_prev" << std::endl; throw std::invalid_argument("const ImgVector<int>& region_map_prev"); } else if (region_map_current.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<int>& region_map_current" << std::endl; throw std::invalid_argument("const ImgVector<int>& region_map_prev"); } else if (region_map_prev.width() != image_prev.width() || region_map_prev.height() != image_prev.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width or height of region_map_prev and image_prev not match" << std::endl; throw std::invalid_argument("width or height of region_map_prev and image_prev not match"); } else if (region_map_current.width() != image_current.width() || region_map_current.height() != image_current.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width or height of region_map_current and image_current not match" << std::endl; throw std::invalid_argument("width or height of region_map_current and image_current not match"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = 1; _cells_width = _width; _cells_height = _height; _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); _region_map_prev.copy(region_map_prev); _region_map_current.copy(region_map_current); // Normalize the image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Normalize the input images" << std::endl; #endif image_normalizer(); // Extract connected regions from region_map #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Collect connected region from region map" << std::endl; #endif get_connected_regions(&_connected_regions_prev, region_map_prev); get_connected_regions(&_connected_regions_current, region_map_current); // Get color quantized image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Get color quantized image" << std::endl; #endif get_color_quantized_image(&_color_quantized_prev, _image_prev, _connected_regions_prev); get_color_quantized_image(&_color_quantized_current, _image_current, _connected_regions_current); } template <class T> BlockMatching<T>::BlockMatching(const ImgVector<T>& image_prev, const ImgVector<size_t>& region_map_prev, const ImgVector<T>& image_current, const ImgVector<size_t>& region_map_current, const ImgVector<T>& image_next, const ImgVector<size_t>& region_map_next, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_prev"); } else if (image_current.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_current" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_current"); } else if (image_prev.width() != image_current.width() || image_prev.height() != image_current.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width or height of image_prev and image_current not match" << std::endl; throw std::invalid_argument("width or height of image_prev and image_current not match"); } else if (region_map_prev.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<int>& region_map_prev" << std::endl; throw std::invalid_argument("const ImgVector<int>& region_map_prev"); } else if (region_map_current.isNULL()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<int>& region_map_current" << std::endl; throw std::invalid_argument("const ImgVector<int>& region_map_prev"); } else if (region_map_prev.width() != image_prev.width() || region_map_prev.height() != image_prev.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width or height of region_map_prev and image_prev not match" << std::endl; throw std::invalid_argument("width or height of region_map_prev and image_prev not match"); } else if (region_map_current.width() != image_current.width() || region_map_current.height() != image_current.height()) { std::cerr << "BlockMatching<T>::BlockMatching(const ImgVector<T>&, const ImgVector<T>&, const int) : width or height of region_map_current and image_current not match" << std::endl; throw std::invalid_argument("width or height of region_map_current and image_current not match"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = 1; _cells_width = _width; _cells_height = _height; _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); _image_next.copy(image_next); _region_map_prev.copy(region_map_prev); _region_map_current.copy(region_map_current); _region_map_next.copy(region_map_next); // Normalize the image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Normalize the input images" << std::endl; #endif image_normalizer(); // Extract connected regions from region_map #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Collect connected region from region map" << std::endl; #endif get_connected_regions(&_connected_regions_prev, region_map_prev); get_connected_regions(&_connected_regions_current, region_map_current); get_connected_regions(&_connected_regions_next, region_map_next); // Get color quantized image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Get color quantized image" << std::endl; #endif get_color_quantized_image(&_color_quantized_prev, _image_prev, _connected_regions_prev); get_color_quantized_image(&_color_quantized_current, _image_current, _connected_regions_current); get_color_quantized_image(&_color_quantized_next, _image_next, _connected_regions_next); } template <class T> BlockMatching<T>::BlockMatching(const BlockMatching& copy) { _width = copy._width; _height = copy._height; _block_size = copy._block_size; _cells_width = copy._cells_width; _cells_height = copy._cells_height; _subpixel_scale = copy._subpixel_scale; _image_prev.copy(copy._image_prev); _image_current.copy(copy._image_current); _image_next.copy(copy._image_next); _region_map_prev.copy(copy._region_map_prev); _region_map_current.copy(copy._region_map_current); _region_map_next.copy(copy._region_map_next); _color_quantized_prev.copy(copy._color_quantized_prev); _color_quantized_current.copy(copy._color_quantized_current); _color_quantized_next.copy(copy._color_quantized_next); _connected_regions_prev.assign(copy._connected_regions_prev.begin(), copy._connected_regions_prev.end()); _connected_regions_current.assign(copy._connected_regions_current.begin(), copy._connected_regions_current.end()); _connected_regions_next.assign(copy._connected_regions_next.begin(), copy._connected_regions_next.end()); _motion_vector_time.copy(copy._motion_vector_time); _motion_vector_prev.copy(copy._motion_vector_prev); _motion_vector_next.copy(copy._motion_vector_next); } template <class T> BlockMatching<T>::~BlockMatching(void) { } template <class T> void BlockMatching<T>::reset(const ImgVector<T>& image_prev, const ImgVector<T>& image_current, const int BlockSize, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_prev"); } else if (image_prev.width() != image_current.width() || image_prev.height() != image_current.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_prev, const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("width or height of image_prev and image_current not match"); } else if (BlockSize < 0) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const int) : const int BlockSize" << std::endl; throw std::out_of_range("BlockSize"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = BlockSize; _cells_width = int(ceil(double(_width) / double(_block_size))); _cells_height = int(ceil(double(_height) / double(_block_size))); _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); _image_next.clear(); _region_map_prev.clear(); _region_map_current.clear(); _region_map_next.clear(); _connected_regions_prev.clear(); _connected_regions_current.clear(); _connected_regions_next.clear(); _motion_vector_time.clear(); _motion_vector_prev.clear(); _motion_vector_next.clear(); // Normalize the image image_normalizer(); } template <class T> void BlockMatching<T>::reset(const ImgVector<T>& image_prev, const ImgVector<T>& image_current, const ImgVector<T>& image_next, const int BlockSize, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_prev"); } else if (image_prev.width() != image_current.width() || image_prev.height() != image_current.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const int) : const ImgVector<T>& image_prev, const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("width or height of image_prev and image_current not match"); } else if (BlockSize < 0) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const int) : const int BlockSize" << std::endl; throw std::out_of_range("BlockSize"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = BlockSize; _cells_width = int(ceil(double(_width) / double(_block_size))); _cells_height = int(ceil(double(_height) / double(_block_size))); _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); _image_next.copy(image_next); _region_map_prev.clear(); _region_map_current.clear(); _region_map_next.clear(); _connected_regions_prev.clear(); _connected_regions_current.clear(); _connected_regions_next.clear(); _motion_vector_time.clear(); _motion_vector_prev.clear(); _motion_vector_next.clear(); // Normalize the image image_normalizer(); } template <class T> void BlockMatching<T>::reset(const ImgVector<T>& image_prev, const ImgVector<size_t>& region_map_prev, const ImgVector<T>& image_current, const ImgVector<size_t>& region_map_current, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_prev"); } else if (image_prev.width() != image_current.width() || image_prev.height() != image_current.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<T>& image_prev, const ImgVector<T>& image_current" << std::endl; throw std::invalid_argument("width or height of image_prev and image_current not match"); } else if (region_map_prev.width() != image_prev.width() || region_map_prev.height() != image_prev.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<int>& region_map_prev" << std::endl; throw std::invalid_argument("width or height of region_map_prev not match with image_prev"); } else if (region_map_current.width() != image_current.width() || region_map_current.height() != image_current.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<int>& region_map_current" << std::endl; throw std::invalid_argument("width or height of region_map_current not match with image_current"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = 1; _cells_width = _width; _cells_height = _height; _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); _image_next.clear(); _region_map_prev.copy(region_map_prev); _region_map_current.copy(region_map_current); _region_map_next.clear(); _motion_vector_time.clear(); _motion_vector_prev.clear(); _motion_vector_next.clear(); // Normalize the image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Normalize the input images" << std::endl; #endif image_normalizer(); // Extract connected regions from region_map #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Collect connected region from region map" << std::endl; #endif get_connected_regions(&_connected_regions_prev, region_map_prev); get_connected_regions(&_connected_regions_current, region_map_current); _connected_regions_next.clear(); // Get color quantized image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Get color quantized image" << std::endl; #endif get_color_quantized_image(&_color_quantized_prev, _image_prev, _connected_regions_prev); get_color_quantized_image(&_color_quantized_current, _image_current, _connected_regions_current); _color_quantized_next.clear(); } template <class T> void BlockMatching<T>::reset(const ImgVector<T>& image_prev, const ImgVector<size_t>& region_map_prev, const ImgVector<T>& image_current, const ImgVector<size_t>& region_map_current, const ImgVector<T>& image_next, const ImgVector<size_t>& region_map_next, const int Subpixel_Scale) { _width = 0; _height = 0; _block_size = 0; _cells_width = 0; _cells_height = 0; _subpixel_scale = 1; if (image_prev.isNULL()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<T>& image_prev" << std::endl; throw std::invalid_argument("const ImgVector<T>& image_prev"); } else if (image_prev.width() != image_current.width() || image_prev.height() != image_current.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<T>& image_prev, const ImgVector<T>& image_current" << std::endl; throw std::invalid_argument("width or height of image_prev and image_current not match"); } else if (region_map_prev.width() != image_prev.width() || region_map_prev.height() != image_prev.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<int>& region_map_prev" << std::endl; throw std::invalid_argument("width or height of region_map_prev not match with image_prev"); } else if (region_map_current.width() != image_current.width() || region_map_current.height() != image_current.height()) { std::cerr << "void BlockMatching<T>::reset(const ImgVector<T>&, const ImgVector<T>&, const ImgVector<int>&) : const ImgVector<int>& region_map_current" << std::endl; throw std::invalid_argument("width or height of region_map_current not match with image_current"); } _width = image_prev.width(); _height = image_prev.height(); _block_size = 1; _cells_width = _width; _cells_height = _height; _subpixel_scale = Subpixel_Scale; _image_prev.copy(image_prev); _image_current.copy(image_current); _image_next.copy(image_next); _region_map_prev.copy(region_map_prev); _region_map_current.copy(region_map_current); _region_map_next.copy(region_map_next); _motion_vector_time.clear(); _motion_vector_prev.clear(); _motion_vector_next.clear(); // Normalize the image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Normalize the input images" << std::endl; #endif image_normalizer(); // Extract connected regions from region_map #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Collect connected region from region map" << std::endl; #endif get_connected_regions(&_connected_regions_prev, region_map_prev); get_connected_regions(&_connected_regions_current, region_map_current); get_connected_regions(&_connected_regions_next, region_map_next); // Get color quantized image #if defined(OUTPUT_IMG_CLASS) || defined(OUTPUT_IMG_CLASS_BLOCKMATCHING) std::cout << " Block Matching : Get color quantized image" << std::endl; #endif get_color_quantized_image(&_color_quantized_prev, _image_prev, _connected_regions_prev); get_color_quantized_image(&_color_quantized_current, _image_current, _connected_regions_current); get_color_quantized_image(&_color_quantized_next, _image_next, _connected_regions_next); } /* Get connected region list * * If region_map[i] < 0 then it means the pixel is neglected. * So usually region_map include only the integer n > 0. */ template <class T> void BlockMatching<T>::get_connected_regions(std::vector<std::vector<VECTOR_2D<int> > >* connected_regions, const ImgVector<size_t>& region_map) { const VECTOR_2D<int> adjacent[8] = { VECTOR_2D<int>(-1, -1), VECTOR_2D<int>(0, -1), VECTOR_2D<int>(1, -1), VECTOR_2D<int>(-1, 0), VECTOR_2D<int>(1, 0), VECTOR_2D<int>(-1, 1), VECTOR_2D<int>(0, 1), VECTOR_2D<int>(1, 1)}; std::list<std::list<VECTOR_2D<int> > > tmp_list; ImgVector<bool> collected(_width, _height, false); // Clear the vector connected_regions->clear(); for (int y = 0; y < _height; y++) { for (int x = 0; x < _width; x++) { if (collected.get(x, y) == false) { size_t num = region_map.get(x, y); collected.at(x, y) = true; tmp_list.push_back(std::list<VECTOR_2D<int> >(0)); // Add new region pixel list VECTOR_2D<int> r(x, y); tmp_list.back().push_back(r); // Add first element for (std::list<VECTOR_2D<int> >::const_iterator ite = tmp_list.back().begin(); ite != tmp_list.back().end(); ++ite) { for (int k = 0; k < 8; k++) { r.x = ite->x + adjacent[k].x; r.y = ite->y + adjacent[k].y; if (0 <= r.x && r.x < _width && 0 <= r.y && r.y < _height && collected.get(r.x, r.y) == false && region_map.get(r.x, r.y) == num) { collected.at(r.x, r.y) = true; tmp_list.back().push_back(r); } } } } } } connected_regions->resize(tmp_list.size()); // Copy extracted connected region to std::vector _connected_regions std::list<std::list<VECTOR_2D<int> > >::iterator ite = tmp_list.begin(); for (size_t n = 0; n < connected_regions->size(); ++ite, n++) { connected_regions->at(n).assign(ite->begin(), ite->end()); } } // ----- Normalizer ----- template <class T> void BlockMatching<T>::image_normalizer(void) { double max_int = _image_prev.max(); if (max_int > 1.0) { _image_prev /= max_int; } max_int = _image_current.max(); if (max_int > 1.0) { _image_current /= max_int; } max_int = _image_next.max(); if (max_int > 1.0) { _image_next /= max_int; } } template <> void BlockMatching<ImgClass::RGB>::image_normalizer(void); template <> void BlockMatching<ImgClass::Lab>::image_normalizer(void); // ----- Decrease Color ----- template <class T> void BlockMatching<T>::get_color_quantized_image(ImgVector<T>* decreased_color_image, const ImgVector<T>& image, const std::vector<std::vector<VECTOR_2D<int> > >& connected_regions) { decreased_color_image->reset(_width, _height); unsigned int n; #ifdef _OPENMP #pragma omp parallel for schedule(dynamic) #endif for (n = 0; n < connected_regions.size(); n++) { T sum_color = T(); for (const VECTOR_2D<int>& r : connected_regions[n]) { sum_color += image.get(r.x, r.y); } T mean_color = sum_color / double(connected_regions[n].size()); for (const VECTOR_2D<int>& r : connected_regions[n]) { decreased_color_image->at(r.x, r.y) = mean_color; } } }
GB_binop__second_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__second_int16) // A.*B function (eWiseMult): GB (_AemultB_08__second_int16) // A.*B function (eWiseMult): GB (_AemultB_02__second_int16) // A.*B function (eWiseMult): GB (_AemultB_04__second_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__second_int16) // A*D function (colscale): GB (_AxD__second_int16) // D*A function (rowscale): GB (_DxB__second_int16) // C+=B function (dense accum): GB (_Cdense_accumB__second_int16) // C+=b function (dense accum): GB (_Cdense_accumb__second_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_int16) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: int16_t // A type: int16_t // A pattern? 1 // B type: int16_t // B pattern? 0 // BinaryOp: cij = bij #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ ; // 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) \ int16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = y ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 1 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_SECOND || GxB_NO_INT16 || GxB_NO_SECOND_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__second_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__second_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__second_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__second_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__second_int16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__second_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__second_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__second_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__second_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__second_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 //------------------------------------------------------------------------------ #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 int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = bij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = y ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ 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 } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = y ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
DRB011-minusminus-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* The -- operation on numNodes2 is not protected, causing data race. Data race pair: numNodes2@74:7 vs. numNodes2@74:7 */ #include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; int len=100; int numNodes=len, numNodes2=0; int x[100]; // initialize x[] for (i=0; i< len; i++) { if (i%2==0) x[i]=5; else x[i]= -5; } #pragma omp parallel for for (i=numNodes-1 ; i>-1 ; --i) { if (x[i]<=0) { numNodes2-- ; } } printf ("numNodes2 = %d\n", numNodes2); return 0; }
Example_SIMD.6.c
/* * @@name: SIMD.6c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.0 */ #pragma omp declare simd linear(p:1) notinbranch int foo(int *p){ *p = *p + 10; return *p; } int myaddint(int *a, int *b, int n) { #pragma omp simd for (int i=0; i<n; i++){ a[i] = foo(&b[i]); /* foo is not called under a condition */ } return a[n-1]; } #pragma omp declare simd linear(p:1) inbranch float goo(float *p){ *p = *p + 18.5f; return *p; } int myaddfloat(float *x, float *y, int n) { #pragma omp simd for (int i=0; i<n; i++){ x[i] = (x[i] > y[i]) ? goo(&y[i]) : y[i]; /* goo is called under the condition (or within a branch) */ } return x[n-1]; }
rawmd5u_fmt_plug.c
/* * Thick raw-md5-unicode (come-back :) * * This software is Copyright (c) 2011 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. * */ #if FMT_EXTERNS_H extern struct fmt_main fmt_rawmd5uthick; #elif FMT_REGISTERS_H john_register_one(&fmt_rawmd5uthick); #else #include <string.h> #include "arch.h" #ifdef SIMD_COEF_32 #define NBKEYS (SIMD_COEF_32 * SIMD_PARA_MD5) #endif #include "simd-intrinsics.h" #include "md5.h" #include "misc.h" #include "common.h" #include "formats.h" #include "options.h" #include "unicode.h" #include "memory.h" #include "johnswap.h" #include "memdbg.h" #define FORMAT_LABEL "Raw-MD5u" #define FORMAT_NAME "" #define ALGORITHM_NAME "md5(utf16($p)) " MD5_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define CIPHERTEXT_LENGTH 32 #define BINARY_SIZE 16 #define BINARY_ALIGN 4 #define SALT_SIZE 0 #define SALT_ALIGN 1 #ifdef SIMD_COEF_32 #define BLOCK_LOOPS 1 #define PLAINTEXT_LENGTH 27 #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS * BLOCK_LOOPS #define GETPOSW(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i*4)&(0xffffffff-3))*SIMD_COEF_32 + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32*4 ) #else #define PLAINTEXT_LENGTH 125 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #ifdef SIMD_COEF_32 static unsigned char (*saved_key); static unsigned char (*crypt_key); static unsigned int (**buf_ptr); #else static MD5_CTX ctx; static int saved_len; static UTF16 saved_key[PLAINTEXT_LENGTH + 1]; static uint32_t crypt_key[BINARY_SIZE / 4]; #endif /* Note some plaintexts will be replaced in init() if running UTF-8 */ static struct fmt_tests tests[] = { {"16c47151c18ac087cd12b3a70746c790", "test1"}, {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"9c3abef89ff76f8acd80eae37b35f64f", "test2"}, {"849ee1b88b5d887bdb058180a666b450", "test3"}, {"8c4cb7e8b33b56a833cdaa8673f3b425", "test4"}, {"537e738b1ac5551f65106368dc301ece", "thatsworking"}, // repeat first hash in exactly the same form that is used in john.pot {"$dynamic_29$16c47151c18ac087cd12b3a70746c790", "test1"}, {NULL} }; static void set_key_utf8(char *_key, int index); static void set_key_CP(char *_key, int index); static void init(struct fmt_main *self) { #if SIMD_COEF_32 int i; #endif if (options.target_enc == UTF_8) { /* This avoids an if clause for every set_key */ self->methods.set_key = set_key_utf8; #if SIMD_COEF_32 /* kick it up from 27. We will truncate in setkey_utf8() */ self->params.plaintext_length = 3 * PLAINTEXT_LENGTH; #endif tests[1].ciphertext = "94a4e171de16580742c4d141e6607bf7"; tests[1].plaintext = "\xE2\x82\xAC"; // Euro sign tests[2].ciphertext = "03c60810f0e54d16e826aca385d776c8"; tests[2].plaintext = "\xE2\x82\xAC\xE2\x82\xAC"; // 2 x euro tests[3].ciphertext = "2d554433d7cde7ec8d16aaf126c3be6b"; tests[3].plaintext = "\xE2\x82\xAC\xC3\xBC"; // euro and u-umlaut tests[4].ciphertext = "8007d9070b27db7b30433df2cd10abc1"; tests[4].plaintext = "\xC3\xBC\xE2\x82\xAC"; // u-umlaut and euro } else { if (options.target_enc != ASCII && options.target_enc != ISO_8859_1) { /* This avoids an if clause for every set_key */ self->methods.set_key = set_key_CP; } if (CP_to_Unicode[0xfc] == 0x00fc) { tests[1].ciphertext = "ea7ab2b5c07650badab30790d0c9b63e"; tests[1].plaintext = "\xFC"; // German u-umlaut in iso-8859-1 tests[2].ciphertext = "f0a0b9f1dea0e458cec9a284ff434d44"; tests[2].plaintext = "\xFC\xFC"; tests[3].ciphertext = "d25a0b436b768777cc9a343d283dbf5a"; tests[3].plaintext = "\xFC\xFC\xFC"; tests[4].ciphertext = "719917322bf12168f8c55939e4fec8de"; tests[4].plaintext = "\xFC\xFC\xFC\xFC"; } } #if SIMD_COEF_32 saved_key = mem_calloc_align(sizeof(*saved_key), 64*self->params.max_keys_per_crypt, MEM_ALIGN_SIMD); crypt_key = mem_calloc_align(sizeof(*crypt_key), BINARY_SIZE*self->params.max_keys_per_crypt, MEM_ALIGN_SIMD); buf_ptr = mem_calloc_align(sizeof(*buf_ptr), self->params.max_keys_per_crypt, sizeof(*buf_ptr)); for (i=0; i<self->params.max_keys_per_crypt; i++) buf_ptr[i] = (unsigned int*)&saved_key[GETPOSW(0, i)]; #endif } static void done(void) { #ifdef SIMD_COEF_32 MEM_FREE(buf_ptr); MEM_FREE(crypt_key); MEM_FREE(saved_key); #endif } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[32+12+1]; if (!strncmp(ciphertext, "$dynamic_29$", 12)) ciphertext += 12; strcpy(out, "$dynamic_29$"); memcpylwr(&out[12], ciphertext, CIPHERTEXT_LENGTH); out[sizeof(out)-1] = 0; return out; } static int valid(char *ciphertext, struct fmt_main *self) { char *pos; if (!strncmp(ciphertext, "$dynamic_29$", 12)) ciphertext += 12; for (pos = ciphertext; atoi16[ARCH_INDEX(*pos)] != 0x7F; pos++); if (!*pos && pos - ciphertext == CIPHERTEXT_LENGTH) return 1; else return 0; } static void *get_binary(char *ciphertext) { static union { unsigned long dummy; unsigned int i[BINARY_SIZE/sizeof(unsigned int)]; } _out; unsigned int *out = _out.i; unsigned int i; unsigned int temp; ciphertext+=12; for (i=0; i<4; i++) { temp = ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+0])]))<<4; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+1])])); temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+2])]))<<12; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+3])]))<<8; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+4])]))<<20; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+5])]))<<16; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+6])]))<<28; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+7])]))<<24; #if ARCH_LITTLE_ENDIAN==1 || defined(SIMD_COEF_32) out[i]=temp; #else out[i]=JOHNSWAP(temp); #endif } return out; } // ISO-8859-1 to UCS-2, directly into vector key buffer static void set_key(char *_key, int index) { #ifdef SIMD_COEF_32 const unsigned char *key = (unsigned char*)_key; unsigned int *keybuf_word = buf_ptr[index]; unsigned int len, temp2; len = 0; while((temp2 = *key++)) { unsigned int temp; if ((temp = *key++) && len < PLAINTEXT_LENGTH - 1) { temp2 |= (temp << 16); *keybuf_word = temp2; } else { temp2 |= (0x80 << 16); *keybuf_word = temp2; len++; goto key_cleaning; } len += 2; keybuf_word += SIMD_COEF_32; } *keybuf_word = 0x80; key_cleaning: keybuf_word += SIMD_COEF_32; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_32; } ((unsigned int *)saved_key)[14*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32] = len << 4; #else #if ARCH_LITTLE_ENDIAN UTF8 *s = (UTF8*)_key; UTF16 *d = saved_key; while (*s) *d++ = *s++; *d = 0; saved_len = (int)((char*)d - (char*)saved_key); #else UTF8 *s = (UTF8*)_key; UTF8 *d = (UTF8*)saved_key; while (*s) { *d++ = *s++; ++d; } *d = 0; saved_len = (int)((char*)d - (char*)saved_key); #endif #endif } // Legacy codepage to UCS-2, directly into vector key buffer static void set_key_CP(char *_key, int index) { #ifdef SIMD_COEF_32 const unsigned char *key = (unsigned char*)_key; unsigned int *keybuf_word = buf_ptr[index]; unsigned int len, temp2; len = 0; while((temp2 = *key++)) { unsigned int temp; temp2 = CP_to_Unicode[temp2]; if ((temp = *key++) && len < PLAINTEXT_LENGTH - 1) { temp = CP_to_Unicode[temp]; temp2 |= (temp << 16); *keybuf_word = temp2; } else { temp2 |= (0x80 << 16); *keybuf_word = temp2; len++; goto key_cleaning_enc; } len += 2; keybuf_word += SIMD_COEF_32; } *keybuf_word = 0x80; key_cleaning_enc: keybuf_word += SIMD_COEF_32; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_32; } ((unsigned int *)saved_key)[14*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32] = len << 4; #else saved_len = enc_to_utf16((UTF16*)&saved_key, PLAINTEXT_LENGTH + 1, (unsigned char*)_key, strlen(_key)) << 1; if (saved_len < 0) saved_len = strlen16(saved_key); #endif } // UTF-8 to UCS-2, directly into vector key buffer static void set_key_utf8(char *_key, int index) { #ifdef SIMD_COEF_32 const UTF8 *source = (UTF8*)_key; unsigned int *keybuf_word = buf_ptr[index]; UTF32 chl, chh = 0x80; unsigned int len = 0; while (*source) { chl = *source; if (chl >= 0xC0) { unsigned int extraBytesToRead = opt_trailingBytesUTF8[chl & 0x3f]; switch (extraBytesToRead) { case 3: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; case 2: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; case 1: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; case 0: break; default: goto bailout; } chl -= offsetsFromUTF8[extraBytesToRead]; } source++; len++; if (chl > UNI_MAX_BMP) { if (len == PLAINTEXT_LENGTH) { chh = 0x80; *keybuf_word = (chh << 16) | chl; keybuf_word += SIMD_COEF_32; break; } #define halfBase 0x0010000UL #define halfShift 10 #define halfMask 0x3FFUL #define UNI_SUR_HIGH_START (UTF32)0xD800 #define UNI_SUR_LOW_START (UTF32)0xDC00 chl -= halfBase; chh = (UTF16)((chl & halfMask) + UNI_SUR_LOW_START);; chl = (UTF16)((chl >> halfShift) + UNI_SUR_HIGH_START); len++; } else if (*source && len < PLAINTEXT_LENGTH) { chh = *source; if (chh >= 0xC0) { unsigned int extraBytesToRead = opt_trailingBytesUTF8[chh & 0x3f]; switch (extraBytesToRead) { case 3: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; case 2: ++source; if (*source) { chh <<= 6; chh += *source; } else goto bailout; case 1: ++source; if (*source) { chh <<= 6; chh += *source; } else goto bailout; case 0: break; default: goto bailout; } chh -= offsetsFromUTF8[extraBytesToRead]; } source++; len++; } else { chh = 0x80; *keybuf_word = (chh << 16) | chl; keybuf_word += SIMD_COEF_32; break; } *keybuf_word = (chh << 16) | chl; keybuf_word += SIMD_COEF_32; } if (chh != 0x80 || len == 0) { *keybuf_word = 0x80; keybuf_word += SIMD_COEF_32; } bailout: while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_32; } ((unsigned int *)saved_key)[14*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32] = len << 4; #else saved_len = utf8_to_utf16((UTF16*)&saved_key, PLAINTEXT_LENGTH + 1, (unsigned char*)_key, strlen(_key)) << 1; if (saved_len < 0) saved_len = strlen16(saved_key); #endif } static char *get_key(int index) { #ifdef SIMD_COEF_32 // Get the key back from the key buffer, from UCS-2 unsigned int *keybuffer = (unsigned int*)&saved_key[GETPOSW(0, index)]; static UTF16 key[PLAINTEXT_LENGTH + 1 + 1]; // if only +1 we 'can' overflow. Not sure why, but ASan found it. unsigned int md5_size=0; unsigned int i=0; for (; md5_size < PLAINTEXT_LENGTH; i += SIMD_COEF_32, md5_size++) { key[md5_size] = keybuffer[i]; key[md5_size+1] = keybuffer[i] >> 16; if (key[md5_size] == 0x80 && key[md5_size+1] == 0) { key[md5_size] = 0; break; } ++md5_size; if (key[md5_size] == 0x80 && ((keybuffer[i+SIMD_COEF_32]&0xFFFF) == 0 || md5_size == PLAINTEXT_LENGTH)) { key[md5_size] = 0; break; } } #if !ARCH_LITTLE_ENDIAN // NOTE, we really should add utf16be_to_enc(key) to unicode.[ch] (and the // other 7 or so required functions. currently unicode.c ONLY handles // UTF-16LE, but we are left with UTF-16BE due to key loading. alter_endianity_w16(key, md5_size<<1); #endif return (char*)utf16_to_enc(key); #else return (char*)utf16_to_enc(saved_key); #endif } static int cmp_all(void *binary, int count) { #ifdef SIMD_COEF_32 unsigned int x,y=0; for (;y<SIMD_PARA_MD5*BLOCK_LOOPS;y++) for (x=0;x<SIMD_COEF_32;x++) { if ( ((uint32_t*)binary)[0] == ((uint32_t*)crypt_key)[x+y*SIMD_COEF_32*4] ) return 1; } return 0; #else return !memcmp(binary, crypt_key, BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { return (1); } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; if ( ((uint32_t*)binary)[0] != ((uint32_t*)crypt_key)[x+y*SIMD_COEF_32*4] ) return 0; if ( ((uint32_t*)binary)[1] != ((uint32_t*)crypt_key)[x+y*SIMD_COEF_32*4+SIMD_COEF_32] ) return 0; if ( ((uint32_t*)binary)[2] != ((uint32_t*)crypt_key)[x+y*SIMD_COEF_32*4+2*SIMD_COEF_32] ) return 0; if ( ((uint32_t*)binary)[3] != ((uint32_t*)crypt_key)[x+y*SIMD_COEF_32*4+3*SIMD_COEF_32] ) return 0; return 1; #else return !memcmp(binary, crypt_key, BINARY_SIZE); #endif } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; #if defined(SIMD_COEF_32) #if (BLOCK_LOOPS > 1) int i; // This was an experiment. It's not used (unless you bump BLOCK_LOOPS), // cause it does not scale well. We would need to parallelize set_key() #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < BLOCK_LOOPS; i++) SIMDmd5body(&saved_key[i*NBKEYS*64], (unsigned int*)&crypt_key[i*NBKEYS*BINARY_SIZE], NULL, SSEi_MIXED_IN); #else SIMDmd5body(saved_key, (unsigned int*)crypt_key, NULL, SSEi_MIXED_IN); #endif #else MD5_Init( &ctx ); MD5_Update(&ctx, (unsigned char*)saved_key, saved_len); MD5_Final((unsigned char*) crypt_key, &ctx); #endif return count; } #define COMMON_GET_HASH_SIMD32 4 #define COMMON_GET_HASH_VAR crypt_key #include "common-get-hash.h" struct fmt_main fmt_rawmd5uthick = { { 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, #if (BLOCK_LOOPS > 1) && defined(SSE_MD5_PARA) FMT_OMP | #endif FMT_CASE | FMT_8_BIT | FMT_UNICODE | FMT_UTF8 | FMT_SPLIT_UNIFIES_CASE, { NULL }, { NULL }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, fmt_default_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
3d7pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 16; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* 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,4);t1++) { lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8)); ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8)); #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-3,4)),ceild(8*t2-Nz-12,16));t3<=min(min(min(floord(Nt+Ny-4,16),floord(4*t1+Ny+5,16)),floord(8*t2+Ny+4,16)),floord(8*t1-8*t2+Nz+Ny+3,16));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(8*t2-Nz-60,64)),ceild(16*t3-Ny-60,64));t4<=min(min(min(min(floord(Nt+Nx-4,64),floord(4*t1+Nx+5,64)),floord(8*t2+Nx+4,64)),floord(16*t3+Nx+12,64)),floord(8*t1-8*t2+Nz+Nx+3,64));t4++) { for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),16*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),16*t3+14),64*t4+62),8*t1-8*t2+Nz+5);t5++) { for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*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(64*t4,t5+1); ubv=min(64*t4+63,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-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, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
DRB082-declared-in-func-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* A variable is declared inside a function called within a parallel region. The variable should be shared if it uses static storage. Data race pair: q@57:3 vs. q@57:3 */ void foo() { static int q; q += 1; } int main() { #pragma omp parallel { foo(); } return 0; }
getUniqueLabels.h
#pragma once #include<string> #include<sstream> #include<fstream> #include<unordered_map> #include<unordered_set> #include<list> #include<vector> #include<functional> // needed for posix io #include<cstdio> #include <sys/types.h> #include <sys/stat.h> #include<omp.h> using std::string; using std::stringstream; using std::fstream; using std::ios; using std::unordered_map; using std::unordered_set; using std::list; using std::pair; using std::vector; using std::function; using std::runtime_error; /* * This function extracts the first two words of every line * and stores them in res. This is done in parallel. */ void getUniqueLabels( const string& edgeListPath, unordered_set<string>& res) { //get properties of abstract path struct stat st; stat(edgeListPath.c_str(), &st); size_t totalFileSize = st.st_size; vector<size_t> fileStarts; #pragma omp parallel { unsigned int tid = omp_get_thread_num(); unsigned int totalThreadNum = omp_get_num_threads(); size_t bytesPerThread = totalFileSize / totalThreadNum; #pragma omp single { fileStarts = vector<size_t>(totalThreadNum + 1, 0); fileStarts[totalThreadNum] = totalFileSize; } #pragma omp barrier // each thread puts its start position fstream localFile(edgeListPath, ios::in | ios::binary); localFile.seekg(tid * bytesPerThread); string localLine; if(tid > 0){ // jump to next newline getline(localFile, localLine); } fileStarts[tid] = localFile.tellg(); #pragma omp barrier /* UPDATED */ unordered_set<string> localData; // while we are still inside our own section unsigned int numLines = 0; while(localFile.tellg() < fileStarts[tid+1] && localFile){ getline(localFile, localLine); numLines += 1; /* UPDATED */ stringstream ss(localLine); string tmp; ss >> tmp; if(localData.find(tmp) == localData.end()) localData.insert(move(tmp)); ss >> tmp; if(localData.find(tmp) == localData.end()) localData.insert(move(tmp)); } localFile.close(); #pragma omp critical { res.insert(localData.begin(), localData.end()); } } }
gradb_mex.c
#include <inttypes.h> #include <omp.h> #include "mex.h" void gradbf(float *dx, float *dy, float *dz, const float *u, const double *h, const size_t *sz); void gradbd(double *dx, double *dy, double *dz, const double *u, const double *h, const size_t *sz); void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs != 5) || (nlhs > 1)) { mexErrMsgTxt("Usage: gradb_mex(dx, dy, dz, u, h);"); return; } const double *h = (const double *)mxGetData(prhs[4]); const size_t *sz = (const size_t *)mxGetDimensions(prhs[0]); if (mxIsSingle(prhs[0])) { float *dx = (float *)mxGetData(prhs[0]); float *dy = (float *)mxGetData(prhs[1]); float *dz = (float *)mxGetData(prhs[2]); const float *u = (const float *)mxGetData(prhs[3]); gradbf(dx, dy, dz, u, h, sz); } else { double *dx = (double *)mxGetData(prhs[0]); double *dy = (double *)mxGetData(prhs[1]); double *dz = (double *)mxGetData(prhs[2]); const double *u = (const double *)mxGetData(prhs[3]); gradbd(dx, dy, dz, u, h, sz); } if (nlhs == 1) { plhs[0] = mxCreateDoubleScalar(1.0); } return; } void gradbf(float *dx, float *dy, float *dz, const float *u, const double *h, const size_t *sz) { size_t i, j, k; size_t l; const size_t nx = sz[0]; const size_t ny = sz[1]; const size_t nz = sz[2]; const size_t nxny = nx*ny; const size_t nxnynz = nx*ny*nz; const float hx = (float)(1.0/h[0]); const float hy = (float)(1.0/h[1]); const float hz = (float)(1.0/h[2]); /* i = 0, j = 0, k = 0 */ l = 0; dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l+nxny]-u[l]); #pragma omp parallel private(i,j,k,l) if (nxny*nz > 16*16*16) { /* i = 0, k = 0 */ #pragma omp for schedule(static) for(l = nx; l < nxny; l += nx) { dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l+nxny]-u[l]); } /* j = 0, k = 0 */ #pragma omp for schedule(static) for(l = 1; l < nx; ++l) { dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l+nxny]-u[l]); } /* k = 0 */ #pragma omp for schedule(static) collapse(2) for(j = nx; j < nxny; j += nx) { for(i = 1; i < nx; ++i) { l = i + j; dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l+nxny]-u[l]); } } /* interior loop */ #pragma omp for schedule(static) for(k = nxny; k < nxnynz; k += nxny) { /* i = 0, j = 0 */ l = k; dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l]-u[l-nxny]); /* j = 0 */ l = 1 + k; for(i = 1; i < nx; ++i, ++l) { dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l]-u[l-nxny]); } for(j = nx; j < nxny; j += nx) { /* i = 0 */ l = j + k; dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l]-u[l-nxny]); l = 1 + j + k; for(i = 1; i < nx; ++i, ++l) { dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l]-u[l-nxny]); } } } } /* omp parallel */ return; } void gradbd(double *dx, double *dy, double *dz, const double *u, const double *h, const size_t *sz) { size_t i, j, k; size_t l; const size_t nx = sz[0]; const size_t ny = sz[1]; const size_t nz = sz[2]; const size_t nxny = nx*ny; const size_t nxnynz = nx*ny*nz; const double hx = 1.0/h[0]; const double hy = 1.0/h[1]; const double hz = 1.0/h[2]; /* i = 0, j = 0, k = 0 */ l = 0; dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l+nxny]-u[l]); #pragma omp parallel private(i,j,k,l) if (nxny*nz > 16*16*16) { /* i = 0, k = 0 */ #pragma omp for schedule(static) for(l = nx; l < nxny; l += nx) { dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l+nxny]-u[l]); } /* j = 0, k = 0 */ #pragma omp for schedule(static) for(l = 1; l < nx; ++l) { dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l+nxny]-u[l]); } /* k = 0 */ #pragma omp for schedule(static) collapse(2) for(j = nx; j < nxny; j += nx) { for(i = 1; i < nx; ++i) { l = i + j; dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l+nxny]-u[l]); } } /* interior loop */ #pragma omp for schedule(static) for(k = nxny; k < nxnynz; k += nxny) { /* i = 0, j = 0 */ l = k; dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l]-u[l-nxny]); /* j = 0 */ l = 1 + k; for(i = 1; i < nx; ++i, ++l) { dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l+nx]-u[l]); dz[l] = hz*(u[l]-u[l-nxny]); } for(j = nx; j < nxny; j += nx) { /* i = 0 */ l = j + k; dx[l] = hx*(u[l+1]-u[l]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l]-u[l-nxny]); l = 1 + j + k; for(i = 1; i < nx; ++i, ++l) { dx[l] = hx*(u[l]-u[l-1]); dy[l] = hy*(u[l]-u[l-nx]); dz[l] = hz*(u[l]-u[l-nxny]); } } } } /* omp parallel */ return; }
pseudoprojector.c
#include <stdio.h> #include <stdlib.h> #include <complex.h> #include <math.h> #include <omp.h> #include <time.h> #include "pseudoprojector.h" #include "utils.h" void vc_pseudoprojection(pswf_t* wf_ref, pswf_t* wf_proj, int BAND_NUM, double* results) { clock_t start = clock(); kpoint_t** kpts = wf_ref->kpts; kpoint_t** kptspro = wf_proj->kpts; int NUM_KPTS = wf_ref->nwk * wf_ref->nspin; int NUM_BANDS = wf_ref->nband; double* cband = (double*) calloc(NUM_KPTS, sizeof(double)); double* vband = (double*) calloc(NUM_KPTS, sizeof(double)); #pragma omp parallel for for (int b = 0; b < NUM_BANDS; b++) { for (int kpt_num = 0; kpt_num < NUM_KPTS; kpt_num++) { float complex curr_overlap = 0; float complex* C1s = kptspro[kpt_num]->bands[0]->Cs; float complex* C2s = kpts[kpt_num]->bands[b]->Cs; int num_waves = kpts[kpt_num]->bands[b]->num_waves; for (int w = 0; w < num_waves; w++) { curr_overlap += C1s[w] * conj(C2s[w]); } #pragma omp critical { if (kpts[kpt_num]->bands[b]->occ > 0.5) vband[kpt_num] += creal((double) (curr_overlap * conj(curr_overlap))); else cband[kpt_num] += creal((double) (curr_overlap * conj(curr_overlap))); } } } double ctotal = 0.0; double vtotal = 0.0; for (int kpt_num = 0; kpt_num < NUM_KPTS; kpt_num++) { ctotal += cband[kpt_num] * kpts[kpt_num]->weight; vtotal += vband[kpt_num] * kpts[kpt_num]->weight; } printf("%lf\n", creal(kptspro[0]->bands[0]->energy)); printf("c %lf\n", ctotal); printf("v %lf\n", vtotal); free(vband); free(cband); results[0] = vtotal; results[1] = ctotal; clock_t end = clock(); printf("%lf seconds for band projection\n", (double)(end - start) / CLOCKS_PER_SEC); } void pseudoprojection(double complex* projections, pswf_t* wf_ref, pswf_t* wf_proj, int BAND_NUM, int flip_spin) { kpoint_t** kpts = wf_ref->kpts; kpoint_t** kptspro = wf_proj->kpts; int NUM_KPTS = wf_ref->nwk * wf_ref->nspin; int NUM_BANDS = wf_ref->nband; #pragma omp parallel for for (int b = 0; b < NUM_BANDS; b++) { for (int kpt_num = 0; kpt_num < NUM_KPTS; kpt_num++) { int kpt_ind_p = kpt_num; if (wf_ref->nspin == 2 && flip_spin) { if (kpt_ind_p < wf_ref->nwk) { kpt_ind_p += wf_ref->nwk; } else { kpt_ind_p -= wf_ref->nwk; } } float complex curr_overlap = 0; float complex* C1s = kptspro[kpt_num]->bands[BAND_NUM]->Cs; float complex* C2s = kpts[kpt_ind_p]->bands[b]->Cs; int num_waves = kpts[kpt_num]->bands[b]->num_waves; cblas_cdotc_sub(num_waves, C2s, 1, C1s, 1, &curr_overlap); projections[b*NUM_KPTS+kpt_num] = curr_overlap; } } }
GB_unaryop__minv_uint8_bool.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_uint8_bool // op(A') function: GB_tran__minv_uint8_bool // C type: uint8_t // A type: bool // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 8) #define GB_ATYPE \ bool #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 8) ; // casting #define GB_CASTING(z, aij) \ uint8_t z = (uint8_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT8 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint8_bool ( uint8_t *Cx, // Cx and Ax may be aliased bool *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint8_bool ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_int32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int32_fp32) // op(A') function: GB (_unop_tran__identity_int32_fp32) // C type: int32_t // A type: float // cast: int32_t cij = GB_cast_to_int32_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int32_t z = GB_cast_to_int32_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = GB_cast_to_int32_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int32_fp32) ( int32_t *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] ; int32_t z = GB_cast_to_int32_t ((double) (aij)) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; int32_t z = GB_cast_to_int32_t ((double) (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int32_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
rnn_helpers.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #ifdef _WIN32 #pragma warning(disable : 4267) #endif #include <algorithm> #include <functional> #include <future> #include <string> #include <vector> #include "gsl/span" #include "gsl/gsl_algorithm" #include "core/common/common.h" #include "core/common/logging/logging.h" #include "core/framework/allocator.h" #include "core/util/math.h" #include "core/util/math_cpuonly.h" #ifdef USE_EIGEN_THREADPOOL #include <unsupported/Eigen/CXX11/ThreadPool> #else #include "core/common/task_thread_pool.h" #endif namespace onnxruntime { class Tensor; class OpKernelContext; namespace rnn { namespace detail { enum Direction { kForward = 0, kReverse = 1, kBidirectional = 2 }; inline Direction MakeDirection(const std::string& direction) { if (direction == "forward") { return kForward; } else if (direction == "reverse") { return kReverse; } else if (direction == "bidirectional") { return kBidirectional; } else { ORT_THROW("Invalid 'direction' argument of '", direction, "'. Must be one of 'forward', 'reverse', or 'bidirectional'."); } } /** Allocate a unique_ptr using allocator_, and return a span to the allocated memory so usage is safe @param allocator IAllocator to use for the allocation. @param size Allocation size. Number of elements of type TAlloc, or total size if TAlloc is 'void'. @param unique_ptr unique_ptr that will control the lifetime of the allocated memory. @param fill If true, fill the allocated memory with fill_value. @param fill_value Value to use if 'fill' is true. @returns A span to provide bounds checked access to the allocated memory. */ template <typename TAlloc> gsl::span<TAlloc> Allocate(std::shared_ptr<IAllocator> allocator, size_t size, IAllocatorUniquePtr<TAlloc>& unique_ptr, bool fill = false, TAlloc fill_value = TAlloc{}) { unique_ptr = IAllocator::MakeUniquePtr<TAlloc>(allocator, size); auto span = gsl::make_span(unique_ptr.get(), size); if (fill) { // Do't use span.begin() it will cause performance issue and stop compiler to optimize the code std::fill_n(unique_ptr.get(), size, fill_value); } return span; } // validate the common inputs to RNN, LSTM and GRU operators Status ValidateCommonRnnInputs(const Tensor& X, const Tensor& W, const Tensor& R, const Tensor* B, int WRB_dim_1_multipler, // multiplier used with hidden_size for W, R and B inputs const Tensor* sequence_lens, const Tensor* initial_h, int64_t num_directions, int64_t hidden_size); /// Copy an input array repeatedly to an output array /// @param input_begin Beginning of input /// @param input_end End of input /// @param output Output iterator /// @param repetitions Number of times to repeat copy. Assumes output is sufficiently sized. /// @returns Position of output iterator after copy is completed template <typename TInIter, typename TOutIter> TOutIter RepeatVectorToConstructArray(TInIter input_begin, TInIter input_end, TOutIter output, int64_t repetitions) { for (int64_t i = 0; i < repetitions; i++) { output = std::copy(input_begin, input_end, output); } return output; } // reverse an LSTM or GRU sequence which has shape [seq_length, batch_size, hidden_size] // and output to shape [seq_length, num_directions, batch_size, hidden_size] template <typename T> void ReverseSequence(gsl::span<const T> inputs, gsl::span<T> inputs_reverse, gsl::span<const int> sequence_lengths, const int max_sequence_length, const int batch_size, const int input_size, const int num_directions) { for (int i = 0; i < batch_size; i++) { int seq_len = sequence_lengths[i]; #ifdef USE_OPENMP // Parallel execute the loop. #pragma omp parallel for #endif for (int j = 0; j < seq_len; j++) { gsl::span<const T> src = inputs.subspan(j * batch_size * input_size + i * input_size, input_size); gsl::span<T> dest = inputs_reverse.subspan(num_directions * (seq_len - j - 1) * batch_size * input_size + i * input_size, input_size); // Use gsl::copy instead of std::copy() to allow compiler to optimize the code gsl::copy(src, dest); } #ifdef USE_OPENMP // Parallel execute the loop. #pragma omp parallel for #endif for (int j = seq_len; j < max_sequence_length; j++) { gsl::span<const T> src = inputs.subspan(j * batch_size * input_size + i * input_size, input_size); gsl::span<T> dest = inputs_reverse.subspan(num_directions * j * batch_size * input_size + i * input_size, input_size); // Use gsl::copy instead of std::copy() to allow compiler to optimize the code gsl::copy(src, dest); } } } // A has size M x K, B has size N x K (transposed), and C has size M x N // We check that A, B and C are large enough before calling the lower level GEMM implementation template <typename TSpanAIter, typename TSpanBIter, typename TSpanCIter> void ComputeGemm(const int M, const int N, const int K, const float alpha, TSpanAIter A, TSpanAIter A_end, const int lda, TSpanBIter B, TSpanBIter B_end, const int ldb, const float beta, TSpanCIter C, TSpanCIter C_end, const int ldc) { // validate all the inputs // need to use the lda/ldb/ldc strides which should be >= the columns for the span ORT_ENFORCE(lda >= K && ldb >= K && ldc >= N); ORT_ENFORCE(A + (M * lda - (lda - K)) <= A_end); ORT_ENFORCE(B + (N * ldb - (ldb - K)) <= B_end); ORT_ENFORCE(C + (M * ldc - (ldc - N)) <= C_end); ::onnxruntime::math::GemmEx<float, CPUMathUtil>( CblasNoTrans, CblasTrans, M, N, K, alpha, &*A, lda, &*B, ldb, beta, &*C, ldc, &CPUMathUtil::Instance()); } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> const T* SafeRawConstPointer(typename gsl::span<T>::const_iterator cur, typename gsl::span<T>::const_iterator end, size_t size) { ORT_ENFORCE(cur + size <= end); return &*cur; } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> const T* SafeRawConstPointer(gsl::span<T> span, size_t offset, size_t size) { ORT_ENFORCE(offset + size <= size_t(span.size())); return span.data(); } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> T* SafeRawPointer(typename gsl::span<T>::iterator cur, typename gsl::span<T>::iterator end, size_t size) { ORT_ENFORCE(cur + size <= end); return &*cur; } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> T* SafeRawPointer(typename gsl::span<T> span, size_t offset, size_t size) { ORT_ENFORCE(offset + size <= size_t(span.size())); return span.data() + offset; } template <typename TLambda> void ExecuteLambdaInParallel(const std::string& name, TLambda lambda, int max, int step, #ifdef USE_EIGEN_THREADPOOL Eigen::NonBlockingThreadPool& ttp, #else TaskThreadPool& ttp, #endif const ::onnxruntime::logging::Logger& logger) { // #define NOTHREADS to execute the lambdas directly and in order if you need to do that to debug #ifdef NOTHREADS ORT_UNUSED_PARAMETER(ttp); ORT_UNUSED_PARAMETER(logger); for (int i = 0; i < max; i += step) { (void)name; std::bind(lambda, i)(); } #else #ifdef USE_EIGEN_THREADPOOL ORT_UNUSED_PARAMETER(name); ORT_UNUSED_PARAMETER(logger); std::atomic<int> done(0); for (int i = 0; i < max; i += step) { ttp.Schedule([lambda, i, &done]() { lambda(i); ++done; }); } int totalTasks = (int)max / (step > 0 ? step : 1) + (max % step > 0 ? 1 : 0); while (done != totalTasks) { } #else std::vector<std::future<void> > task_results{}; task_results.reserve(static_cast<size_t>(std::ceil(max / step))); for (int i = 0; i < max; i += step) { std::packaged_task<void()> task{std::bind(lambda, i)}; task_results.emplace_back(task.get_future()); ttp.RunTask(std::move(task)); } try { // wait for all and propagate any exceptions for (auto& future : task_results) future.get(); } catch (const std::exception& ex) { LOGS(logger, ERROR) << name << " - exception running tasks: " << ex.what(); throw; } #endif // else part of #ifdef USE_EIGEN_THREADPOOLs #endif // else part of #ifdef NOTHREADS } void DumpMatrixImpl(const std::string& name, const float* src, int row, int col, int offset = 0, int col_width = -1); // Helper class to wrap the processing of the activation funcs and any alpha/beta values. // The alpha/beta values are consumed in the order of the activation funcs. once they run out // defaults will be used as needed. // The Entries property contains the normalized function names and the alpha/beta value to use. class ActivationFuncs { public: struct Entry { const std::string name; const float alpha; const float beta; }; ActivationFuncs() = default; ActivationFuncs(const std::vector<std::string>& funcs, const std::vector<float>& alphas, const std::vector<float>& betas); const std::vector<Entry>& Entries() const { return entries_; } private: std::vector<Entry> entries_; }; namespace deepcpu { using AddBiasIntoFuncPtr = void (*)(const float*, float*, const int); using ClipWithBiasFuncPtr = void (*)(const float, const float*, float*, const int); using ActivationFuncPtr = void (*)(float*, const int, const float, const float); using ActivationFuncBPtr = void (*)(const float*, float*, const int, const float, const float); using LstmMergeGatesFuncPtr = void (*)(const float*, float*, const float*, float*, const int, const float, const float); using GruResetGateFuncPtr = void (*)(const float*, float*, float*, const int, const float, const float); using GruOutputGateFuncPtr = void (*)(float*, const float*, const float*, float*, const int, const float, const float); ActivationFuncPtr ActivationFuncByName(const std::string& func); LstmMergeGatesFuncPtr LstmMergeGatesFuncByName(const std::string& func); GruResetGateFuncPtr GruResetGateFuncByName(const std::string& func); GruOutputGateFuncPtr GruOutputGateFuncByName(const std::string& func); void add_bias_into_ignore(const float* ignored, float* pd, const int c); void add_bias_into(const float* ps, float* pd, const int c); void clip(const float b, float* pd, const int c); void clip_add_bias(const float b, const float* pb, float* pd, const int c); void clip_ignore_bias(const float b, const float* pb, float* pd, const int c); void sigmoid_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void tanh_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void relu_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void sigmoid_exact_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void tanh_exact_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void sigmoid(float* pd, int c, const float alpha, const float beta); void tanh(float* pd, int c, const float alpha, const float beta); void relu(float* pd, int c, const float alpha, const float beta); void sigmoid_exact(float* pd, int c, const float alpha, const float beta); void tanh_exact(float* pd, int c, const float alpha, const float beta); void merge_lstm_gates_to_memory(const float* pprev, const float* pi, const float* pf, const float* pg, float* pcurr, const int c); void gru_reset_gate_tanh(const float* ps1, float* ps2, float* pd, const int c, const float alpha, const float beta); void gru_reset_gate_sigmoid(const float* ps1, float* ps2, float* pd, const int c, const float alpha, const float beta); void gru_reset_gate_relu(const float* ps1, float* ps2, float* pd, const int c, const float alpha, const float beta); void gru_output_gate_tanh(float* ph, const float* pz, const float* ps, float* po, const int c, const float alpha, const float beta); void gru_output_gate_sigmoid(float* ph, const float* pz, const float* ps, float* po, const int c, const float alpha, const float beta); void gru_output_gate_relu(float* ph, const float* pz, const float* ps, float* po, const int c, const float alpha, const float beta); inline void elementwise_product(const float* op1, const float* op2, float* dest, const int size) { for (int i = 0; i < size; i++) dest[i] += op1[i] * op2[i]; } inline void elementwise_sum1(const float* src, float* dest, const int size) { for (int i = 0; i < size; i++) dest[i] += src[i]; } inline void elementwise_sum2(const float* src1, const float* src2, float* dest, const int size) { for (int i = 0; i < size; i++) dest[i] += src1[i] + src2[i]; } } // namespace deepcpu } // namespace detail } // namespace rnn } // namespace onnxruntime
cpu_bound.c
/* * Copyright (c) 2009, 2010, 2011, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. */ #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <omp.h> #include <assert.h> #define PERIOD 2500000000UL #define ITERATIONS 10 #define STACK_SIZE (64 * 1024) struct workcnt { uint64_t cnt; } __attribute__ ((aligned (64))); static inline uint64_t rdtsc(void) { uint64_t eax, edx; __asm volatile ("rdtsc" : "=a" (eax), "=d" (edx)); return (edx << 32) | eax; } int main(int argc, char *argv[]) { static struct workcnt workcnt[32]; int nthreads; if(argc == 2) { nthreads = atoi(argv[1]); bomp_bomp_init(nthreads); omp_set_num_threads(nthreads); } else { assert(!"Specify number of threads"); } uint64_t glast = rdtsc(); for(;;) { // Do some work #pragma omp parallel { uint64_t last = glast; for(;;) { workcnt[omp_get_thread_num()].cnt++; if(rdtsc() >= last + PERIOD) { break; } } } printf("%s: %lu: threads %d (%s), progress ", argv[0], rdtsc(), omp_get_num_threads(), omp_get_dynamic() ? "dynamic" : "static"); for(int n = 0; n < 32; n++) { printf("%lu ", workcnt[n].cnt); } printf("\n"); fflush(stdout); glast += PERIOD; } }
Pragma.h
//===- Pragma.h - Pragma registration and handling --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PragmaHandler and PragmaTable interfaces. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PRAGMA_H #define LLVM_CLANG_LEX_PRAGMA_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include <string> namespace clang { class PragmaNamespace; class Preprocessor; class Token; /** * Describes how the pragma was introduced, e.g., with \#pragma, * _Pragma, or __pragma. */ enum PragmaIntroducerKind { /** * The pragma was introduced via \#pragma. */ PIK_HashPragma, /** * The pragma was introduced via the C99 _Pragma(string-literal). */ PIK__Pragma, /** * The pragma was introduced via the Microsoft * __pragma(token-string). */ PIK___pragma }; /// PragmaHandler - Instances of this interface defined to handle the various /// pragmas that the language front-end uses. Each handler optionally has a /// name (e.g. "pack") and the HandlePragma method is invoked when a pragma with /// that identifier is found. If a handler does not match any of the declared /// pragmas the handler with a null identifier is invoked, if it exists. /// /// Note that the PragmaNamespace class can be used to subdivide pragmas, e.g. /// we treat "\#pragma STDC" and "\#pragma GCC" as namespaces that contain other /// pragmas. class PragmaHandler { std::string Name; public: PragmaHandler() = default; explicit PragmaHandler(StringRef name) : Name(name) {} virtual ~PragmaHandler(); StringRef getName() const { return Name; } virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) = 0; /// getIfNamespace - If this is a namespace, return it. This is equivalent to /// using a dynamic_cast, but doesn't require RTTI. virtual PragmaNamespace *getIfNamespace() { return nullptr; } }; /// EmptyPragmaHandler - A pragma handler which takes no action, which can be /// used to ignore particular pragmas. class EmptyPragmaHandler : public PragmaHandler { public: explicit EmptyPragmaHandler(StringRef Name = StringRef()); void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; /// PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, /// allowing hierarchical pragmas to be defined. Common examples of namespaces /// are "\#pragma GCC", "\#pragma STDC", and "\#pragma omp", but any namespaces /// may be (potentially recursively) defined. class PragmaNamespace : public PragmaHandler { /// Handlers - This is a map of the handlers in this namespace with their name /// as key. llvm::StringMap<PragmaHandler *> Handlers; public: explicit PragmaNamespace(StringRef Name) : PragmaHandler(Name) {} ~PragmaNamespace() override; /// FindHandler - Check to see if there is already a handler for the /// specified name. If not, return the handler for the null name if it /// exists, otherwise return null. If IgnoreNull is true (the default) then /// the null handler isn't returned on failure to match. PragmaHandler *FindHandler(StringRef Name, bool IgnoreNull = true) const; /// AddPragma - Add a pragma to this namespace. void AddPragma(PragmaHandler *Handler); /// RemovePragmaHandler - Remove the given handler from the /// namespace. void RemovePragmaHandler(PragmaHandler *Handler); bool IsEmpty() const { return Handlers.empty(); } void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; PragmaNamespace *getIfNamespace() override { return this; } }; } // namespace clang #endif // LLVM_CLANG_LEX_PRAGMA_H
itunes_fmt_plug.c
/* JtR format to crack encrypted iTunes Backup passwords. * * This software is Copyright (c) 2017, 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. * * All credit goes to Jean-Baptiste Bédrune, Jean Sigwald, DinoSec, philsmd, * and Andrew Neitsch. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_itunes; #elif FMT_REGISTERS_H john_register_one(&fmt_itunes); #else #include <string.h> #include <assert.h> #include <errno.h> #include <openssl/des.h> #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 #endif #endif #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "johnswap.h" #include "pbkdf2_hmac_sha1.h" #include "pbkdf2_hmac_sha256.h" #include "jumbo.h" #include "memdbg.h" #include "itunes_common.h" #define FORMAT_LABEL "itunes-backup" #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 AES " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 AES 32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 0 #define PLAINTEXT_LENGTH 125 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN sizeof(uint64_t) #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT (SSE_GROUP_SZ_SHA1 * SSE_GROUP_SZ_SHA256) #define MAX_KEYS_PER_CRYPT (SSE_GROUP_SZ_SHA1 * SSE_GROUP_SZ_SHA256) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests itunes_tests[] = { // real iTunes 9.x hash {"$itunes_backup$*9*bc707ac0151660426c8114d04caad9d9ee2678a7b7ab05c18ee50cafb2613c31c8978e8b1e9cad2a*10000*266343aaf99102ba7f6af64a3a2d62637793f753**", "123456"}, // artificial hashes generated by hashcat's tools/test.pl script with a low dpic (iterations) value to ease testing {"$itunes_backup$*10*31021f9c5a705c3625af21739d397082d90f7a00718a9307687625abc35fc3e4d78371e95cc708b6*10000*8840233131165307147445064802216857558435*1000*c77a159b325d10efee51a1c05701ef63fb85b599", "855632538858211"}, {"$itunes_backup$*10*b3d3f05b5367345fcb654b9b628e2ed24d8b8726f1f74707a956c776475d6ebfffc962340d9cbbca*10000*6832814730342072666684158073107301064276*1000*46de5e844e0ee1c81d2cca6acefb77789c1a7cd0", "1"}, // real iTunes 9.x hash {"$itunes_backup$*9*06dc04bca4eeea2fbc1bc7356fa758243bead479673640a668db285c8f48c402cc435539d935509e*10000*37d2bd7caefbb24a9729e41a3257ef06188dc01e**", "test123"}, // {"$itunes_backup$*10*deff6d646eb1fa2b6741efee8b70eda84341a838cef2bb10e582669759d7e33c399a0ba2a52cb9ec*10000*f09cfa82cc1695657cb2c347ee127c2523795fda*10000000*66f159e15f3ddbbdd4057f8babef7ad4472fac10", "test123"}, // real hash, this is very very slow! {NULL} }; #if defined (_OPENMP) static int omp_t = 1; #endif static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked, cracked_count; static struct custom_salt *cur_salt; static void init(struct fmt_main *self) { #if defined (_OPENMP) omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt); cracked = mem_calloc(sizeof(*cracked), self->params.max_keys_per_crypt); cracked_count = self->params.max_keys_per_crypt; } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static void itunes_set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; memset(cracked, 0, sizeof(cracked[0])*cracked_count); #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { unsigned char master[MAX_KEYS_PER_CRYPT][32]; int i; if (cur_salt->version == 9) { // iTunes Backup < 10 #ifdef SIMD_COEF_32 int lens[MAX_KEYS_PER_CRYPT]; unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; int loops = MAX_KEYS_PER_CRYPT / SSE_GROUP_SZ_SHA1; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = strlen(saved_key[index+i]); pin[i] = (unsigned char*)saved_key[index+i]; pout[i] = master[i]; } for (i = 0; i < loops; i++) pbkdf2_sha1_sse((const unsigned char**)(pin + i * SSE_GROUP_SZ_SHA1), &lens[i * SSE_GROUP_SZ_SHA1], cur_salt->salt, SALTLEN, cur_salt->iterations, pout + (i * SSE_GROUP_SZ_SHA1), 32, 0); #else for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) pbkdf2_sha1((unsigned char *)saved_key[index+i], strlen(saved_key[index+i]), cur_salt->salt, SALTLEN, cur_salt->iterations, master[i], 32, 0); #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { cracked[index+i] = itunes_common_decrypt(cur_salt, master[i]); } } else { // iTunes Backup 10.x #if defined(SIMD_COEF_64) && defined(SIMD_COEF_32) int lens[MAX_KEYS_PER_CRYPT]; unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; int loops = MAX_KEYS_PER_CRYPT / SSE_GROUP_SZ_SHA256; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = strlen(saved_key[index+i]); pin[i] = (unsigned char*)saved_key[index+i]; pout[i] = master[i]; } for (i = 0; i < loops; i++) pbkdf2_sha256_sse((const unsigned char**)(pin + i * SSE_GROUP_SZ_SHA256), &lens[i * SSE_GROUP_SZ_SHA256], cur_salt->dpsl, SALTLEN, cur_salt->dpic, pout + (i * SSE_GROUP_SZ_SHA256), 32, 0); for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = 32; pin[i] = (unsigned char*)master[i]; pout[i] = master[i]; } loops = MAX_KEYS_PER_CRYPT / SSE_GROUP_SZ_SHA1; for (i = 0; i < loops; i++) pbkdf2_sha1_sse((const unsigned char**)(pin + i * SSE_GROUP_SZ_SHA1), &lens[i * SSE_GROUP_SZ_SHA1], cur_salt->salt, SALTLEN, cur_salt->iterations, pout + (i * SSE_GROUP_SZ_SHA1), 32, 0); #else for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { pbkdf2_sha256((unsigned char *)saved_key[index+i], strlen(saved_key[index+i]), cur_salt->dpsl, SALTLEN, cur_salt->dpic, master[i], 32, 0); pbkdf2_sha1(master[i], 32, cur_salt->salt, SALTLEN, cur_salt->iterations, master[i], 32, 0); } #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { cracked[index+i] = itunes_common_decrypt(cur_salt, master[i]); } } } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (cracked[index]) return 1; return 0; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_itunes = { { 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, { "version", "iteration count", }, { FORMAT_TAG }, itunes_tests }, { init, done, fmt_default_reset, fmt_default_prepare, itunes_common_valid, fmt_default_split, fmt_default_binary, itunes_common_get_salt, { itunes_common_tunable_version, itunes_common_tunable_iterations, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, itunes_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
SpatialAdaptiveAveragePooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/SpatialAdaptiveAveragePooling.c" #else #define START_IND(a,b,c) (int)floor((float)(a * c) / b) #define END_IND(a,b,c) (int)ceil((float)((a + 1) * c) / b) // #define START_IND(a,b,c) a * c / b // #define END_IND(a,b,c) (a + 1) * c / b + ((a + 1) * c % b > 0)?1:0 // 4d tensor B x D x H x W static void THNN_(SpatialAdaptiveAveragePooling_updateOutput_frame)( real *input_p, real *output_p, int64_t sizeD, int64_t isizeH, int64_t isizeW, int64_t osizeH, int64_t osizeW, int64_t istrideD, int64_t istrideH, int64_t istrideW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { /* loop over output */ int64_t oh, ow; for(oh = 0; oh < osizeH; oh++) { int istartH = START_IND(oh, osizeH, isizeH); int iendH = END_IND(oh, osizeH, isizeH); int kH = iendH - istartH; for(ow = 0; ow < osizeW; ow++) { int istartW = START_IND(ow, osizeW, isizeW); int iendW = END_IND(ow, osizeW, isizeW); int kW = iendW - istartW; /* local pointers */ real *ip = input_p + d*istrideD + istartH*istrideH + istartW*istrideW; real *op = output_p + d*osizeH*osizeW + oh*osizeW + ow; /* compute local average: */ real sum = 0; int ih, iw; for(ih = 0; ih < kH; ih++) { for(iw = 0; iw < kW; iw++) { real val = *(ip + ih*istrideH + iw*istrideW); sum += val; } } /* set output to local average */ *op = sum / kW / kH; } } } } void THNN_(SpatialAdaptiveAveragePooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, int osizeW, int osizeH) { int dimD = 0; int dimH = 1; int dimW = 2; int64_t sizeB = 1; int64_t sizeD = 0; int64_t isizeH = 0; int64_t isizeW = 0; int64_t istrideB = 0; int64_t istrideD = 0; int64_t istrideH = 0; int64_t istrideW = 0; real *input_data = nullptr; real *output_data = nullptr; THNN_ARGCHECK(!input->is_empty() && (input->dim() == 3 || input->dim() == 4), 2, input, "non-empty 3D or 4D (batch mode) tensor expected for input, but got: %s"); if (input->dim() == 4) { istrideB = input->stride(0); sizeB = input->size(0); dimD++; dimH++; dimW++; } /* sizes */ sizeD = input->size(dimD); isizeH = input->size(dimH); isizeW = input->size(dimW); /* strides */ istrideD = input->stride(dimD); istrideH = input->stride(dimH); istrideW = input->stride(dimW); /* resize output */ if (input->dim() == 3) { THTensor_(resize3d)(output, sizeD, osizeH, osizeW); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); THNN_(SpatialAdaptiveAveragePooling_updateOutput_frame)(input_data, output_data, sizeD, isizeH, isizeW, osizeH, osizeW, istrideD, istrideH, istrideW); } else { int64_t b; THTensor_(resize4d)(output, sizeB, sizeD, osizeH, osizeW); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(SpatialAdaptiveAveragePooling_updateOutput_frame)(input_data+b*istrideB, output_data+b*sizeD*osizeH*osizeW, sizeD, isizeH, isizeW, osizeH, osizeW, istrideD, istrideH, istrideW); } } } static void THNN_(SpatialAdaptiveAveragePooling_updateGradInput_frame)( real *gradInput_p, real *gradOutput_p, int64_t sizeD, int64_t isizeH, int64_t isizeW, int64_t osizeH, int64_t osizeW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { real *gradInput_p_d = gradInput_p + d*isizeW*isizeH; real *gradOutput_p_d = gradOutput_p + d*osizeW*osizeH; /* calculate average */ int64_t oh, ow; for(oh = 0; oh < osizeH; oh++) { int istartH = START_IND(oh, osizeH, isizeH); int iendH = END_IND(oh, osizeH, isizeH); int kH = iendH - istartH; for(ow = 0; ow < osizeW; ow++) { int istartW = START_IND(ow, osizeW, isizeW); int iendW = END_IND(ow, osizeW, isizeW); int kW = iendW - istartW; real grad_delta = gradOutput_p_d[oh*osizeW +ow] / kH / kW; int ih, iw; for(ih = istartH; ih < iendH; ih++) { for(iw = istartW; iw < iendW; iw++) { /* update gradient */ gradInput_p_d[ih*isizeW + iw] += grad_delta; } } } } } } void THNN_(SpatialAdaptiveAveragePooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput) { int dimD = 0; int dimH = 1; int dimW = 2; int64_t sizeB = 1; int sizeD; int isizeH; int isizeW; int osizeH; int osizeW; real *gradInput_data; real *gradOutput_data; /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); if (input->dim() == 4) { sizeB = input->size(0); dimD++; dimH++; dimW++; } /* sizes */ sizeD = input->size(dimD); isizeH = input->size(dimH); isizeW = input->size(dimW); osizeH = gradOutput->size(dimH); osizeW = gradOutput->size(dimW); /* get raw pointers */ gradInput_data = THTensor_(data)(gradInput); gradOutput_data = THTensor_(data)(gradOutput); /* backprop */ if (input->dim() == 3) { THNN_(SpatialAdaptiveAveragePooling_updateGradInput_frame)(gradInput_data, gradOutput_data, sizeD, isizeH, isizeW, osizeH, osizeW); } else { int64_t b; #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(SpatialAdaptiveAveragePooling_updateGradInput_frame)(gradInput_data+b*sizeD*isizeH*isizeW, gradOutput_data+b*sizeD*osizeH*osizeW, sizeD, isizeH, isizeW, osizeH, osizeW); } } /* cleanup */ THTensor_(free)(gradOutput); } #endif #undef START_IND #undef END_IND
morphology.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M OOO RRRR PPPP H H OOO L OOO GGGG Y Y % % MM MM O O R R P P H H O O L O O G Y Y % % M M M O O RRRR PPPP HHHHH O O L O O G GGG Y % % M M O O R R P H H O O L O O G G Y % % M M OOO R R P H H OOO LLLLL OOO GGG Y % % % % % % MagickCore Morphology Methods % % % % Software Design % % Anthony Thyssen % % January 2010 % % % % % % Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Morpology is the the application of various kernels, of any size and even % shape, to a image in various ways (typically binary, but not always). % % Convolution (weighted sum or average) is just one specific type of % morphology. Just one that is very common for image bluring and sharpening % effects. Not only 2D Gaussian blurring, but also 2-pass 1D Blurring. % % This module provides not only a general morphology function, and the ability % to apply more advanced or iterative morphologies, but also functions for the % generation of many different types of kernel arrays from user supplied % arguments. Prehaps even the generation of a kernel from a small image. */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/cache-view.h" #include "magick/color-private.h" #include "magick/channel.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/monitor-private.h" #include "magick/morphology.h" #include "magick/morphology-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/prepress.h" #include "magick/quantize.h" #include "magick/registry.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/token.h" #include "magick/utility.h" /* Other global definitions used by module. */ static inline double MagickMin(const double x,const double y) { return( x < y ? x : y); } static inline double MagickMax(const double x,const double y) { return( x > y ? x : y); } #define Minimize(assign,value) assign=MagickMin(assign,value) #define Maximize(assign,value) assign=MagickMax(assign,value) /* Integer Factorial Function - for a Binomial kernel */ #if 1 static inline size_t fact(size_t n) { size_t l,f; for(f=1, l=2; l <= n; f=f*l, l++); return(f); } #elif 1 /* glibc floating point alternatives */ #define fact(n) ((size_t)tgamma((double)n+1)) #else #define fact(n) ((size_t)lgamma((double)n+1)) #endif /* Currently these are only internal to this module */ static void CalcKernelMetaData(KernelInfo *), ExpandMirrorKernelInfo(KernelInfo *), ExpandRotateKernelInfo(KernelInfo *, const double), RotateKernelInfo(KernelInfo *, double); /* Quick function to find last kernel in a kernel list */ static inline KernelInfo *LastKernelInfo(KernelInfo *kernel) { while (kernel->next != (KernelInfo *) NULL) kernel=kernel->next; return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelInfo() takes the given string (generally supplied by the % user) and converts it into a Morphology/Convolution Kernel. This allows % users to specify a kernel from a number of pre-defined kernels, or to fully % specify their own kernel for a specific Convolution or Morphology % Operation. % % The kernel so generated can be any rectangular array of floating point % values (doubles) with the 'control point' or 'pixel being affected' % anywhere within that array of values. % % Previously IM was restricted to a square of odd size using the exact % center as origin, this is no longer the case, and any rectangular kernel % with any value being declared the origin. This in turn allows the use of % highly asymmetrical kernels. % % The floating point values in the kernel can also include a special value % known as 'nan' or 'not a number' to indicate that this value is not part % of the kernel array. This allows you to shaped the kernel within its % rectangular area. That is 'nan' values provide a 'mask' for the kernel % shape. However at least one non-nan value must be provided for correct % working of a kernel. % % The returned kernel should be freed using the DestroyKernelInfo() when you % are finished with it. Do not free this memory yourself. % % Input kernel defintion strings can consist of any of three types. % % "name:args[[@><]" % Select from one of the built in kernels, using the name and % geometry arguments supplied. See AcquireKernelBuiltIn() % % "WxH[+X+Y][@><]:num, num, num ..." % a kernel of size W by H, with W*H floating point numbers following. % the 'center' can be optionally be defined at +X+Y (such that +0+0 % is top left corner). If not defined the pixel in the center, for % odd sizes, or to the immediate top or left of center for even sizes % is automatically selected. % % "num, num, num, num, ..." % list of floating point numbers defining an 'old style' odd sized % square kernel. At least 9 values should be provided for a 3x3 % square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc. % Values can be space or comma separated. This is not recommended. % % You can define a 'list of kernels' which can be used by some morphology % operators A list is defined as a semi-colon separated list kernels. % % " kernel ; kernel ; kernel ; " % % Any extra ';' characters, at start, end or between kernel defintions are % simply ignored. % % The special flags will expand a single kernel, into a list of rotated % kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree % cyclic rotations, while a '>' will generate a list of 90-degree rotations. % The '<' also exands using 90-degree rotates, but giving a 180-degree % reflected kernel before the +/- 90-degree rotations, which can be important % for Thinning operations. % % Note that 'name' kernels will start with an alphabetic character while the % new kernel specification has a ':' character in its specification string. % If neither is the case, it is assumed an old style of a simple list of % numbers generating a odd-sized square kernel has been given. % % The format of the AcquireKernal method is: % % KernelInfo *AcquireKernelInfo(const char *kernel_string) % % A description of each parameter follows: % % o kernel_string: the Morphology/Convolution kernel wanted. % */ /* This was separated so that it could be used as a separate ** array input handling function, such as for -color-matrix */ static KernelInfo *ParseKernelArray(const char *kernel_string) { KernelInfo *kernel; char token[MaxTextExtent]; const char *p, *end; register ssize_t i; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ MagickStatusType flags; GeometryInfo args; kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (kernel == (KernelInfo *)NULL) return(kernel); (void) ResetMagickMemory(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = UserDefinedKernel; kernel->next = (KernelInfo *) NULL; kernel->signature = MagickSignature; if (kernel_string == (const char *) NULL) return(kernel); /* find end of this specific kernel definition string */ end = strchr(kernel_string, ';'); if ( end == (char *) NULL ) end = strchr(kernel_string, '\0'); /* clear flags - for Expanding kernel lists thorugh rotations */ flags = NoValue; /* Has a ':' in argument - New user kernel specification FUTURE: this split on ':' could be done by StringToken() */ p = strchr(kernel_string, ':'); if ( p != (char *) NULL && p < end) { /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, kernel_string, (size_t) (p-kernel_string)); token[p-kernel_string] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); /* Size handling and checks of geometry settings */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 1.0; /* then width = 1 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ kernel->width = (size_t)args.rho; kernel->height = (size_t)args.sigma; /* Offset Handling and Checks */ if ( args.xi < 0.0 || args.psi < 0.0 ) return(DestroyKernelInfo(kernel)); kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi : (ssize_t) (kernel->width-1)/2; kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi : (ssize_t) (kernel->height-1)/2; if ( kernel->x >= (ssize_t) kernel->width || kernel->y >= (ssize_t) kernel->height ) return(DestroyKernelInfo(kernel)); p++; /* advance beyond the ':' */ } else { /* ELSE - Old old specification, forming odd-square kernel */ /* count up number of values given */ p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ for (i=0; p < end; i++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); } /* set the size of the kernel - old sized square */ kernel->width = kernel->height= (size_t) sqrt((double) i+1.0); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ } /* Read in the kernel values from rest of input string argument */ kernel->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel->width,kernel->height*sizeof(*kernel->values))); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); kernel->minimum=MagickMaximumValue; kernel->maximum=(-MagickMaximumValue); kernel->negative_range = kernel->positive_range = 0.0; for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); if ( LocaleCompare("nan",token) == 0 || LocaleCompare("-",token) == 0 ) { kernel->values[i] = nan; /* this value is not part of neighbourhood */ } else { kernel->values[i] = StringToDouble(token,(char **) NULL); ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } } /* sanity check -- no more values in kernel definition */ GetMagickToken(p,&p,token); if ( *token != '\0' && *token != ';' && *token != '\'' ) return(DestroyKernelInfo(kernel)); #if 0 /* this was the old method of handling a incomplete kernel */ if ( i < (ssize_t) (kernel->width*kernel->height) ) { Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); for ( ; i < (ssize_t) (kernel->width*kernel->height); i++) kernel->values[i]=0.0; } #else /* Number of values for kernel was not enough - Report Error */ if ( i < (ssize_t) (kernel->width*kernel->height) ) return(DestroyKernelInfo(kernel)); #endif /* check that we recieved at least one real (non-nan) value! */ if (kernel->minimum == MagickMaximumValue) return(DestroyKernelInfo(kernel)); if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */ ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */ else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */ else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */ return(kernel); } static KernelInfo *ParseKernelName(const char *kernel_string) { char token[MaxTextExtent]; const char *p, *end; GeometryInfo args; KernelInfo *kernel; MagickStatusType flags; ssize_t type; /* Parse special 'named' kernel */ GetMagickToken(kernel_string,&p,token); type=ParseCommandOption(MagickKernelOptions,MagickFalse,token); if ( type < 0 || type == UserDefinedKernel ) return((KernelInfo *)NULL); /* not a valid named kernel */ while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';')) p++; end = strchr(p, ';'); /* end of this kernel defintion */ if ( end == (char *) NULL ) end = strchr(p, '\0'); /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, p, (size_t) (end-p)); token[end-p] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif /* special handling of missing values in input string */ switch( type ) { /* Shape Kernel Defaults */ case UnityKernel: if ( (flags & WidthValue) == 0 ) args.rho = 1.0; /* Default scale = 1.0, zero is valid */ break; case SquareKernel: case DiamondKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: if ( (flags & HeightValue) == 0 ) args.sigma = 1.0; /* Default scale = 1.0, zero is valid */ break; case RingKernel: if ( (flags & XValue) == 0 ) args.xi = 1.0; /* Default scale = 1.0, zero is valid */ break; case RectangleKernel: /* Rectangle - set size defaults */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 3; /* then width = 3 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ if ( (flags & XValue) == 0 ) /* center offset if not defined */ args.xi = (double)(((ssize_t)args.rho-1)/2); if ( (flags & YValue) == 0 ) args.psi = (double)(((ssize_t)args.sigma-1)/2); break; /* Distance Kernel Defaults */ case ChebyshevKernel: case ManhattanKernel: case OctagonalKernel: case EuclideanKernel: if ( (flags & HeightValue) == 0 ) /* no distance scale */ args.sigma = 100.0; /* default distance scaling */ else if ( (flags & AspectValue ) != 0 ) /* '!' flag */ args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */ else if ( (flags & PercentValue ) != 0 ) /* '%' flag */ args.sigma *= QuantumRange/100.0; /* percentage of color range */ break; default: break; } kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args); if ( kernel == (KernelInfo *) NULL ) return(kernel); /* global expand to rotated kernel list - only for single kernels */ if ( kernel->next == (KernelInfo *) NULL ) { if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 45.0); else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); } return(kernel); } MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string) { KernelInfo *kernel, *new_kernel; char token[MaxTextExtent]; const char *p; if (kernel_string == (const char *) NULL) return(ParseKernelArray(kernel_string)); p=kernel_string; kernel=NULL; while (GetMagickToken(p,NULL,token), *token != '\0') { /* ignore extra or multiple ';' kernel separators */ if (*token != ';') { /* tokens starting with alpha is a Named kernel */ if (isalpha((int) ((unsigned char) *token)) != 0) new_kernel=ParseKernelName(p); else /* otherwise a user defined kernel array */ new_kernel=ParseKernelArray(p); /* Error handling -- this is not proper error handling! */ if (new_kernel == (KernelInfo *) NULL) { if (kernel != (KernelInfo *) NULL) kernel=DestroyKernelInfo(kernel); return((KernelInfo *) NULL); } /* initialise or append the kernel list */ if (kernel == (KernelInfo *) NULL) kernel=new_kernel; else LastKernelInfo(kernel)->next=new_kernel; } /* look for the next kernel in list */ p=strchr(p,';'); if (p == (char *) NULL) break; p++; } return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l B u i l t I n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelBuiltIn() returned one of the 'named' built-in types of % kernels used for special purposes such as gaussian blurring, skeleton % pruning, and edge distance determination. % % They take a KernelType, and a set of geometry style arguments, which were % typically decoded from a user supplied string, or from a more complex % Morphology Method that was requested. % % The format of the AcquireKernalBuiltIn method is: % % KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, % const GeometryInfo args) % % A description of each parameter follows: % % o type: the pre-defined type of kernel wanted % % o args: arguments defining or modifying the kernel % % Convolution Kernels % % Unity % The a No-Op or Scaling single element kernel. % % Gaussian:{radius},{sigma} % Generate a two-dimensional gaussian kernel, as used by -gaussian. % The sigma for the curve is required. The resulting kernel is % normalized, % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % NOTE: that the 'radius' is optional, but if provided can limit (clip) % the final size of the resulting kernel to a square 2*radius+1 in size. % The radius should be at least 2 times that of the sigma value, or % sever clipping and aliasing may result. If not given or set to 0 the % radius will be determined so as to produce the best minimal error % result, which is usally much larger than is normally needed. % % LoG:{radius},{sigma} % "Laplacian of a Gaussian" or "Mexician Hat" Kernel. % The supposed ideal edge detection, zero-summing kernel. % % An alturnative to this kernel is to use a "DoG" with a sigma ratio of % approx 1.6 (according to wikipedia). % % DoG:{radius},{sigma1},{sigma2} % "Difference of Gaussians" Kernel. % As "Gaussian" but with a gaussian produced by 'sigma2' subtracted % from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1. % The result is a zero-summing kernel. % % Blur:{radius},{sigma}[,{angle}] % Generates a 1 dimensional or linear gaussian blur, at the angle given % (current restricted to orthogonal angles). If a 'radius' is given the % kernel is clipped to a width of 2*radius+1. Kernel can be rotated % by a 90 degree angle. % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % Note that two convolutions with two "Blur" kernels perpendicular to % each other, is equivalent to a far larger "Gaussian" kernel with the % same sigma value, However it is much faster to apply. This is how the % "-blur" operator actually works. % % Comet:{width},{sigma},{angle} % Blur in one direction only, much like how a bright object leaves % a comet like trail. The Kernel is actually half a gaussian curve, % Adding two such blurs in opposite directions produces a Blur Kernel. % Angle can be rotated in multiples of 90 degrees. % % Note that the first argument is the width of the kernel and not the % radius of the kernel. % % Binomial:[{radius}] % Generate a discrete kernel using a 2 dimentional Pascel's Triangle % of values. Used for special forma of image filters % % # Still to be implemented... % # % # Filter2D % # Filter1D % # Set kernel values using a resize filter, and given scale (sigma) % # Cylindrical or Linear. Is this possible with an image? % # % % Named Constant Convolution Kernels % % All these are unscaled, zero-summing kernels by default. As such for % non-HDRI version of ImageMagick some form of normalization, user scaling, % and biasing the results is recommended, to prevent the resulting image % being 'clipped'. % % The 3x3 kernels (most of these) can be circularly rotated in multiples of % 45 degrees to generate the 8 angled varients of each of the kernels. % % Laplacian:{type} % Discrete Lapacian Kernels, (without normalization) % Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood) % Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood) % Type 2 : 3x3 with center:4 edge:1 corner:-2 % Type 3 : 3x3 with center:4 edge:-2 corner:1 % Type 5 : 5x5 laplacian % Type 7 : 7x7 laplacian % Type 15 : 5x5 LoG (sigma approx 1.4) % Type 19 : 9x9 LoG (sigma approx 1.4) % % Sobel:{angle} % Sobel 'Edge' convolution kernel (3x3) % | -1, 0, 1 | % | -2, 0, 2 | % | -1, 0, 1 | % % Roberts:{angle} % Roberts convolution kernel (3x3) % | 0, 0, 0 | % | -1, 1, 0 | % | 0, 0, 0 | % % Prewitt:{angle} % Prewitt Edge convolution kernel (3x3) % | -1, 0, 1 | % | -1, 0, 1 | % | -1, 0, 1 | % % Compass:{angle} % Prewitt's "Compass" convolution kernel (3x3) % | -1, 1, 1 | % | -1,-2, 1 | % | -1, 1, 1 | % % Kirsch:{angle} % Kirsch's "Compass" convolution kernel (3x3) % | -3,-3, 5 | % | -3, 0, 5 | % | -3,-3, 5 | % % FreiChen:{angle} % Frei-Chen Edge Detector is based on a kernel that is similar to % the Sobel Kernel, but is designed to be isotropic. That is it takes % into account the distance of the diagonal in the kernel. % % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | % | 1, 0, -1 | % % FreiChen:{type},{angle} % % Frei-Chen Pre-weighted kernels... % % Type 0: default un-nomalized version shown above. % % Type 1: Orthogonal Kernel (same as type 11 below) % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 2: Diagonal form of Kernel... % | 1, sqrt(2), 0 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 0, -sqrt(2) -1 | % % However this kernel is als at the heart of the FreiChen Edge Detection % Process which uses a set of 9 specially weighted kernel. These 9 % kernels not be normalized, but directly applied to the image. The % results is then added together, to produce the intensity of an edge in % a specific direction. The square root of the pixel value can then be % taken as the cosine of the edge, and at least 2 such runs at 90 degrees % from each other, both the direction and the strength of the edge can be % determined. % % Type 10: All 9 of the following pre-weighted kernels... % % Type 11: | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 12: | 1, sqrt(2), 1 | % | 0, 0, 0 | / 2*sqrt(2) % | 1, sqrt(2), 1 | % % Type 13: | sqrt(2), -1, 0 | % | -1, 0, 1 | / 2*sqrt(2) % | 0, 1, -sqrt(2) | % % Type 14: | 0, 1, -sqrt(2) | % | -1, 0, 1 | / 2*sqrt(2) % | sqrt(2), -1, 0 | % % Type 15: | 0, -1, 0 | % | 1, 0, 1 | / 2 % | 0, -1, 0 | % % Type 16: | 1, 0, -1 | % | 0, 0, 0 | / 2 % | -1, 0, 1 | % % Type 17: | 1, -2, 1 | % | -2, 4, -2 | / 6 % | -1, -2, 1 | % % Type 18: | -2, 1, -2 | % | 1, 4, 1 | / 6 % | -2, 1, -2 | % % Type 19: | 1, 1, 1 | % | 1, 1, 1 | / 3 % | 1, 1, 1 | % % The first 4 are for edge detection, the next 4 are for line detection % and the last is to add a average component to the results. % % Using a special type of '-1' will return all 9 pre-weighted kernels % as a multi-kernel list, so that you can use them directly (without % normalization) with the special "-set option:morphology:compose Plus" % setting to apply the full FreiChen Edge Detection Technique. % % If 'type' is large it will be taken to be an actual rotation angle for % the default FreiChen (type 0) kernel. As such FreiChen:45 will look % like a Sobel:45 but with 'sqrt(2)' instead of '2' values. % % WARNING: The above was layed out as per % http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf % But rotated 90 degrees so direction is from left rather than the top. % I have yet to find any secondary confirmation of the above. The only % other source found was actual source code at % http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf % Neigher paper defineds the kernels in a way that looks locical or % correct when taken as a whole. % % Boolean Kernels % % Diamond:[{radius}[,{scale}]] % Generate a diamond shaped kernel with given radius to the points. % Kernel size will again be radius*2+1 square and defaults to radius 1, % generating a 3x3 kernel that is slightly larger than a square. % % Square:[{radius}[,{scale}]] % Generate a square shaped kernel of size radius*2+1, and defaulting % to a 3x3 (radius 1). % % Octagon:[{radius}[,{scale}]] % Generate octagonal shaped kernel of given radius and constant scale. % Default radius is 3 producing a 7x7 kernel. A radius of 1 will result % in "Diamond" kernel. % % Disk:[{radius}[,{scale}]] % Generate a binary disk, thresholded at the radius given, the radius % may be a float-point value. Final Kernel size is floor(radius)*2+1 % square. A radius of 5.3 is the default. % % NOTE: That a low radii Disk kernels produce the same results as % many of the previously defined kernels, but differ greatly at larger % radii. Here is a table of equivalences... % "Disk:1" => "Diamond", "Octagon:1", or "Cross:1" % "Disk:1.5" => "Square" % "Disk:2" => "Diamond:2" % "Disk:2.5" => "Octagon" % "Disk:2.9" => "Square:2" % "Disk:3.5" => "Octagon:3" % "Disk:4.5" => "Octagon:4" % "Disk:5.4" => "Octagon:5" % "Disk:6.4" => "Octagon:6" % All other Disk shapes are unique to this kernel, but because a "Disk" % is more circular when using a larger radius, using a larger radius is % preferred over iterating the morphological operation. % % Rectangle:{geometry} % Simply generate a rectangle of 1's with the size given. You can also % specify the location of the 'control point', otherwise the closest % pixel to the center of the rectangle is selected. % % Properly centered and odd sized rectangles work the best. % % Symbol Dilation Kernels % % These kernel is not a good general morphological kernel, but is used % more for highlighting and marking any single pixels in an image using, % a "Dilate" method as appropriate. % % For the same reasons iterating these kernels does not produce the % same result as using a larger radius for the symbol. % % Plus:[{radius}[,{scale}]] % Cross:[{radius}[,{scale}]] % Generate a kernel in the shape of a 'plus' or a 'cross' with % a each arm the length of the given radius (default 2). % % NOTE: "plus:1" is equivalent to a "Diamond" kernel. % % Ring:{radius1},{radius2}[,{scale}] % A ring of the values given that falls between the two radii. % Defaults to a ring of approximataly 3 radius in a 7x7 kernel. % This is the 'edge' pixels of the default "Disk" kernel, % More specifically, "Ring" -> "Ring:2.5,3.5,1.0" % % Hit and Miss Kernels % % Peak:radius1,radius2 % Find any peak larger than the pixels the fall between the two radii. % The default ring of pixels is as per "Ring". % Edges % Find flat orthogonal edges of a binary shape % Corners % Find 90 degree corners of a binary shape % Diagonals:type % A special kernel to thin the 'outside' of diagonals % LineEnds:type % Find end points of lines (for pruning a skeletion) % Two types of lines ends (default to both) can be searched for % Type 0: All line ends % Type 1: single kernel for 4-conneected line ends % Type 2: single kernel for simple line ends % LineJunctions % Find three line junctions (within a skeletion) % Type 0: all line junctions % Type 1: Y Junction kernel % Type 2: Diagonal T Junction kernel % Type 3: Orthogonal T Junction kernel % Type 4: Diagonal X Junction kernel % Type 5: Orthogonal + Junction kernel % Ridges:type % Find single pixel ridges or thin lines % Type 1: Fine single pixel thick lines and ridges % Type 2: Find two pixel thick lines and ridges % ConvexHull % Octagonal Thickening Kernel, to generate convex hulls of 45 degrees % Skeleton:type % Traditional skeleton generating kernels. % Type 1: Tradional Skeleton kernel (4 connected skeleton) % Type 2: HIPR2 Skeleton kernel (8 connected skeleton) % Type 3: Thinning skeleton based on a ressearch paper by % Dan S. Bloomberg (Default Type) % ThinSE:type % A huge variety of Thinning Kernels designed to preserve conectivity. % many other kernel sets use these kernels as source definitions. % Type numbers are 41-49, 81-89, 481, and 482 which are based on % the super and sub notations used in the source research paper. % % Distance Measuring Kernels % % Different types of distance measuring methods, which are used with the % a 'Distance' morphology method for generating a gradient based on % distance from an edge of a binary shape, though there is a technique % for handling a anti-aliased shape. % % See the 'Distance' Morphological Method, for information of how it is % applied. % % Chebyshev:[{radius}][x{scale}[%!]] % Chebyshev Distance (also known as Tchebychev or Chessboard distance) % is a value of one to any neighbour, orthogonal or diagonal. One why % of thinking of it is the number of squares a 'King' or 'Queen' in % chess needs to traverse reach any other position on a chess board. % It results in a 'square' like distance function, but one where % diagonals are given a value that is closer than expected. % % Manhattan:[{radius}][x{scale}[%!]] % Manhattan Distance (also known as Rectilinear, City Block, or the Taxi % Cab distance metric), it is the distance needed when you can only % travel in horizontal or vertical directions only. It is the % distance a 'Rook' in chess would have to travel, and results in a % diamond like distances, where diagonals are further than expected. % % Octagonal:[{radius}][x{scale}[%!]] % An interleving of Manhatten and Chebyshev metrics producing an % increasing octagonally shaped distance. Distances matches those of % the "Octagon" shaped kernel of the same radius. The minimum radius % and default is 2, producing a 5x5 kernel. % % Euclidean:[{radius}][x{scale}[%!]] % Euclidean distance is the 'direct' or 'as the crow flys' distance. % However by default the kernel size only has a radius of 1, which % limits the distance to 'Knight' like moves, with only orthogonal and % diagonal measurements being correct. As such for the default kernel % you will get octagonal like distance function. % % However using a larger radius such as "Euclidean:4" you will get a % much smoother distance gradient from the edge of the shape. Especially % if the image is pre-processed to include any anti-aliasing pixels. % Of course a larger kernel is slower to use, and not always needed. % % The first three Distance Measuring Kernels will only generate distances % of exact multiples of {scale} in binary images. As such you can use a % scale of 1 without loosing any information. However you also need some % scaling when handling non-binary anti-aliased shapes. % % The "Euclidean" Distance Kernel however does generate a non-integer % fractional results, and as such scaling is vital even for binary shapes. % */ MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, const GeometryInfo *args) { KernelInfo *kernel; register ssize_t i; register ssize_t u, v; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ /* Generate a new empty kernel if needed */ kernel=(KernelInfo *) NULL; switch(type) { case UndefinedKernel: /* These should not call this function */ case UserDefinedKernel: assert("Should not call this function" != (char *)NULL); break; case LaplacianKernel: /* Named Descrete Convolution Kernels */ case SobelKernel: /* these are defined using other kernels */ case RobertsKernel: case PrewittKernel: case CompassKernel: case KirschKernel: case FreiChenKernel: case EdgesKernel: /* Hit and Miss kernels */ case CornersKernel: case DiagonalsKernel: case LineEndsKernel: case LineJunctionsKernel: case RidgesKernel: case ConvexHullKernel: case SkeletonKernel: case ThinSEKernel: break; /* A pre-generated kernel is not needed */ #if 0 /* set to 1 to do a compile-time check that we haven't missed anything */ case UnityKernel: case GaussianKernel: case DoGKernel: case LoGKernel: case BlurKernel: case CometKernel: case BinomialKernel: case DiamondKernel: case SquareKernel: case RectangleKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: case RingKernel: case PeaksKernel: case ChebyshevKernel: case ManhattanKernel: case OctangonalKernel: case EuclideanKernel: #else default: #endif /* Generate the base Kernel Structure */ kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (kernel == (KernelInfo *) NULL) return(kernel); (void) ResetMagickMemory(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = type; kernel->next = (KernelInfo *) NULL; kernel->signature = MagickSignature; break; } switch(type) { /* Convolution Kernels */ case UnityKernel: { kernel->height = kernel->width = (size_t) 1; kernel->x = kernel->y = (ssize_t) 0; kernel->values=(double *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*kernel->values))); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); kernel->maximum = kernel->values[0] = args->rho; break; } break; case GaussianKernel: case DoGKernel: case LoGKernel: { double sigma = fabs(args->sigma), sigma2 = fabs(args->xi), A, B, R; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else if ( (type != DoGKernel) || (sigma >= sigma2) ) kernel->width = GetOptimalKernelWidth2D(args->rho,sigma); else kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2); kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel->width,kernel->height*sizeof(*kernel->values))); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* WARNING: The following generates a 'sampled gaussian' kernel. * What we really want is a 'discrete gaussian' kernel. * * How to do this is I don't know, but appears to be basied on the * Error Function 'erf()' (intergral of a gaussian) */ if ( type == GaussianKernel || type == DoGKernel ) { /* Calculate a Gaussian, OR positive half of a DoG */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } if ( type == DoGKernel ) { /* Subtract a Negative Gaussian for "Difference of Gaussian" */ if ( sigma2 > MagickEpsilon ) { sigma = sigma2; /* simplify loop expressions */ A = 1.0/(2.0*sigma*sigma); B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0; } if ( type == LoGKernel ) { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { R = ((double)(u*u+v*v))*A; kernel->values[i] = (1-R)*exp(-R)*B; } } else /* special case - generate a unity kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } /* Note the above kernels may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (> 0.1) the central value becomes larger than one, and thus ** producing a very bright kernel. ** ** Normalization will still be needed. */ /* Normalize the 2D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); break; } case BlurKernel: { double sigma = fabs(args->sigma), alpha, beta; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else kernel->width = GetOptimalKernelWidth1D(args->rho,sigma); kernel->height = 1; kernel->x = (ssize_t) (kernel->width-1)/2; kernel->y = 0; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); #if 1 #define KernelRank 3 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix). ** It generates a gaussian 3 times the width, and compresses it into ** the expected range. This produces a closer normalization of the ** resulting kernel, especially for very low sigma values. ** As such while wierd it is prefered. ** ** I am told this method originally came from Photoshop. ** ** A properly normalized curve is generated (apart from edge clipping) ** even though we later normalize the result (for edge clipping) ** to allow the correct generation of a "Difference of Blurs". */ /* initialize */ v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */ (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); /* Calculate a Positive 1D Gaussian */ if ( sigma > MagickEpsilon ) { sigma *= KernelRank; /* simplify loop expressions */ alpha = 1.0/(2.0*sigma*sigma); beta= (double) (1.0/(MagickSQ2PI*sigma )); for ( u=-v; u <= v; u++) { kernel->values[(u+v)/KernelRank] += exp(-((double)(u*u))*alpha)*beta; } } else /* special case - generate a unity kernel */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; #else /* Direct calculation without curve averaging This is equivelent to a KernelRank of 1 */ /* Calculate a Positive Gaussian */ if ( sigma > MagickEpsilon ) { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ beta = 1.0/(MagickSQ2PI*sigma); for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u))*alpha)*beta; } else /* special case - generate a unity kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } #endif /* Note the above kernel may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (< 0.1) the central value becomes larger than one, as a ** result of not generating a actual 'discrete' kernel, and thus ** producing a very bright 'impulse'. ** ** Becuase of these two factors Normalization is required! */ /* Normalize the 1D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); /* rotate the 1D kernel by given angle */ RotateKernelInfo(kernel, args->xi ); break; } case CometKernel: { double sigma = fabs(args->sigma), A; if ( args->rho < 1.0 ) kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1; else kernel->width = (size_t)args->rho; kernel->x = kernel->y = 0; kernel->height = 1; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* A comet blur is half a 1D gaussian curve, so that the object is ** blurred in one direction only. This may not be quite the right ** curve to use so may change in the future. The function must be ** normalised after generation, which also resolves any clipping. ** ** As we are normalizing and not subtracting gaussians, ** there is no need for a divisor in the gaussian formula ** ** It is less comples */ if ( sigma > MagickEpsilon ) { #if 1 #define KernelRank 3 v = (ssize_t) kernel->width*KernelRank; /* start/end points */ (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*sizeof(*kernel->values)); sigma *= KernelRank; /* simplify the loop expression */ A = 1.0/(2.0*sigma*sigma); /* B = 1.0/(MagickSQ2PI*sigma); */ for ( u=0; u < v; u++) { kernel->values[u/KernelRank] += exp(-((double)(u*u))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ } for (i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i]; #else A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */ /* B = 1.0/(MagickSQ2PI*sigma); */ for ( i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i] = exp(-((double)(i*i))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ #endif } else /* special case - generate a unity kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(*kernel->values)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; } kernel->minimum = 0.0; kernel->maximum = kernel->values[0]; kernel->negative_range = 0.0; ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */ RotateKernelInfo(kernel, args->xi); /* Rotate by angle */ break; } case BinomialKernel: { size_t order_f; if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; order_f = fact(kernel->width-1); kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values within diamond area to scale given */ for ( i=0, v=0; v < (ssize_t)kernel->height; v++) { size_t alpha = order_f / ( fact((size_t) v) * fact(kernel->height-v-1) ); for ( u=0; u < (ssize_t)kernel->width; u++, i++) kernel->positive_range += kernel->values[i] = (double) (alpha * order_f / ( fact((size_t) u) * fact(kernel->height-u-1) )); } kernel->minimum = 1.0; kernel->maximum = kernel->values[kernel->x+kernel->y*kernel->width]; kernel->negative_range = 0.0; break; } /* Convolution Kernels - Well Known Named Constant Kernels */ case LaplacianKernel: { switch ( (int) args->rho ) { case 0: default: /* laplacian square filter -- default */ kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1"); break; case 1: /* laplacian diamond filter */ kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0"); break; case 2: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); break; case 3: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1"); break; case 5: /* a 5x5 laplacian */ kernel=ParseKernelArray( "5: -4,-1,0,-1,-4 -1,2,3,2,-1 0,3,4,3,0 -1,2,3,2,-1 -4,-1,0,-1,-4"); break; case 7: /* a 7x7 laplacian */ kernel=ParseKernelArray( "7:-10,-5,-2,-1,-2,-5,-10 -5,0,3,4,3,0,-5 -2,3,6,7,6,3,-2 -1,4,7,8,7,4,-1 -2,3,6,7,6,3,-2 -5,0,3,4,3,0,-5 -10,-5,-2,-1,-2,-5,-10" ); break; case 15: /* a 5x5 LoG (sigma approx 1.4) */ kernel=ParseKernelArray( "5: 0,0,-1,0,0 0,-1,-2,-1,0 -1,-2,16,-2,-1 0,-1,-2,-1,0 0,0,-1,0,0"); break; case 19: /* a 9x9 LoG (sigma approx 1.4) */ /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */ kernel=ParseKernelArray( "9: 0,-1,-1,-2,-2,-2,-1,-1,0 -1,-2,-4,-5,-5,-5,-4,-2,-1 -1,-4,-5,-3,-0,-3,-5,-4,-1 -2,-5,-3,12,24,12,-3,-5,-2 -2,-5,-0,24,40,24,-0,-5,-2 -2,-5,-3,12,24,12,-3,-5,-2 -1,-4,-5,-3,-0,-3,-5,-4,-1 -1,-2,-4,-5,-5,-5,-4,-2,-1 0,-1,-1,-2,-2,-2,-1,-1,0"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; break; } case SobelKernel: { /* Simple Sobel Kernel */ kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case RobertsKernel: { kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case PrewittKernel: { kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case CompassKernel: { kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case KirschKernel: { kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case FreiChenKernel: /* Direction is set to be left to right positive */ /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */ /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */ { switch ( (int) args->rho ) { default: case 0: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +MagickSQ2; kernel->values[5] = -MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ break; case 2: kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = kernel->values[3]= +MagickSQ2; kernel->values[5] = kernel->values[7]= -MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 10: kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19"); if (kernel == (KernelInfo *) NULL) return(kernel); break; case 1: case 11: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +MagickSQ2; kernel->values[5] = -MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 12: kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = +MagickSQ2; kernel->values[7] = +MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 13: kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[0] = +MagickSQ2; kernel->values[8] = -MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 14: kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[2] = -MagickSQ2; kernel->values[6] = +MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 15: kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 16: kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 17: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 18: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 19: kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/3.0, NoValue); break; } if ( fabs(args->sigma) >= MagickEpsilon ) /* Rotate by correctly supplied 'angle' */ RotateKernelInfo(kernel, args->sigma); else if ( args->rho > 30.0 || args->rho < -30.0 ) /* Rotate by out of bounds 'type' */ RotateKernelInfo(kernel, args->rho); break; } /* Boolean or Shaped Kernels */ case DiamondKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values within diamond area to scale given */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case SquareKernel: case RectangleKernel: { double scale; if ( type == SquareKernel ) { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = (size_t) (2*args->rho+1); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; scale = args->sigma; } else { /* NOTE: user defaults set in "AcquireKernelInfo()" */ if ( args->rho < 1.0 || args->sigma < 1.0 ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->width = (size_t)args->rho; kernel->height = (size_t)args->sigma; if ( args->xi < 0.0 || args->xi > (double)kernel->width || args->psi < 0.0 || args->psi > (double)kernel->height ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->x = (ssize_t) args->xi; kernel->y = (ssize_t) args->psi; scale = 1.0; } kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values to scale given */ u=(ssize_t) (kernel->width*kernel->height); for ( i=0; i < u; i++) kernel->values[i] = scale; kernel->minimum = kernel->maximum = scale; /* a flat shape */ kernel->positive_range = scale*u; break; } case OctagonKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= ((long)kernel->x + (long)(kernel->x/2)) ) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case DiskKernel: { ssize_t limit = (ssize_t)(args->rho*args->rho); if (args->rho < 0.4) /* default radius approx 4.3 */ kernel->width = kernel->height = 9L, limit = 18L; else kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ((u*u+v*v) <= limit) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case PlusKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } case CrossKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == v || u == -v) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } /* HitAndMiss Kernels */ case RingKernel: case PeaksKernel: { ssize_t limit1, limit2, scale; if (args->rho < args->sigma) { kernel->width = ((size_t)args->sigma)*2+1; limit1 = (ssize_t)(args->rho*args->rho); limit2 = (ssize_t)(args->sigma*args->sigma); } else { kernel->width = ((size_t)args->rho)*2+1; limit1 = (ssize_t)(args->sigma*args->sigma); limit2 = (ssize_t)(args->rho*args->rho); } if ( limit2 <= 0 ) kernel->width = 7L, limit1 = 7L, limit2 = 11L; kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */ scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi); for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { ssize_t radius=u*u+v*v; if (limit1 < radius && radius <= limit2) kernel->positive_range += kernel->values[i] = (double) scale; else kernel->values[i] = nan; } kernel->minimum = kernel->maximum = (double) scale; if ( type == PeaksKernel ) { /* set the central point in the middle */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; kernel->maximum = 1.0; } break; } case EdgesKernel: { kernel=AcquireKernelInfo("ThinSE:482"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */ break; } case CornersKernel: { kernel=AcquireKernelInfo("ThinSE:87"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */ break; } case DiagonalsKernel: { switch ( (int) args->rho ) { case 0: default: { KernelInfo *new_kernel; kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; ExpandMirrorKernelInfo(kernel); return(kernel); } case 1: kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); break; case 2: kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineEndsKernel: { /* Kernels for finding the end of thin lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all end of lines */ return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>")); case 1: /* kernel for 4-connected line ends - no rotation */ kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-"); break; case 2: /* kernel to add for 8-connected lines - no rotation */ kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1"); break; case 3: /* kernel to add for orthogonal line ends - does not find corners */ kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0"); break; case 4: /* traditional line end - fails on last T end */ kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineJunctionsKernel: { /* kernels for finding the junctions of multiple lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all line junctions */ return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>")); case 1: /* Y Junction */ kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-"); break; case 2: /* Diagonal T Junctions */ kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1"); break; case 3: /* Orthogonal T Junctions */ kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-"); break; case 4: /* Diagonal X Junctions */ kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1"); break; case 5: /* Orthogonal X Junctions - minimal diamond kernel */ kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case RidgesKernel: { /* Ridges - Ridge finding kernels */ KernelInfo *new_kernel; switch ( (int) args->rho ) { case 1: default: kernel=ParseKernelArray("3x1:0,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */ break; case 2: kernel=ParseKernelArray("4x1:0,1,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */ /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */ /* Unfortunatally we can not yet rotate a non-square kernel */ /* But then we can't flip a non-symetrical kernel either */ new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; break; } break; } case ConvexHullKernel: { KernelInfo *new_kernel; /* first set of 8 kernels */ kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* append the mirror versions too - no flip function yet */ new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; ExpandRotateKernelInfo(new_kernel, 90.0); LastKernelInfo(kernel)->next = new_kernel; break; } case SkeletonKernel: { switch ( (int) args->rho ) { case 1: default: /* Traditional Skeleton... ** A cyclically rotated single kernel */ kernel=AcquireKernelInfo("ThinSE:482"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */ break; case 2: /* HIPR Variation of the cyclic skeleton ** Corners of the traditional method made more forgiving, ** but the retain the same cyclic order. */ kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;"); if (kernel == (KernelInfo *) NULL) return(kernel); if (kernel->next == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); kernel->type = type; kernel->next->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */ break; case 3: /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf */ kernel=AcquireKernelInfo( "ThinSE:41; ThinSE:42; ThinSE:43"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->next->type = type; kernel->next->next->type = type; ExpandMirrorKernelInfo(kernel); /* 12 kernels total */ break; } break; } case ThinSEKernel: { /* Special kernels for general thinning, while preserving connections ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf ** And ** http://tpgit.github.com/Leptonica/ccthin_8c_source.html ** ** Note kernels do not specify the origin pixel, allowing them ** to be used for both thickening and thinning operations. */ switch ( (int) args->rho ) { /* SE for 4-connected thinning */ case 41: /* SE_4_1 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1"); break; case 42: /* SE_4_2 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-"); break; case 43: /* SE_4_3 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1"); break; case 44: /* SE_4_4 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-"); break; case 45: /* SE_4_5 */ kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-"); break; case 46: /* SE_4_6 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1"); break; case 47: /* SE_4_7 */ kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-"); break; case 48: /* SE_4_8 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1"); break; case 49: /* SE_4_9 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1"); break; /* SE for 8-connected thinning - negatives of the above */ case 81: /* SE_8_0 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-"); break; case 82: /* SE_8_2 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-"); break; case 83: /* SE_8_3 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-"); break; case 84: /* SE_8_4 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-"); break; case 85: /* SE_8_5 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-"); break; case 86: /* SE_8_6 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1"); break; case 87: /* SE_8_7 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-"); break; case 88: /* SE_8_8 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-"); break; case 89: /* SE_8_9 */ kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-"); break; /* Special combined SE kernels */ case 423: /* SE_4_2 , SE_4_3 Combined Kernel */ kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-"); break; case 823: /* SE_8_2 , SE_8_3 Combined Kernel */ kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-"); break; case 481: /* SE_48_1 - General Connected Corner Kernel */ kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-"); break; default: case 482: /* SE_48_2 - General Edge Kernel */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } /* Distance Measuring Kernels */ case ChebyshevKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*MagickMax(fabs((double)u),fabs((double)v)) ); kernel->maximum = kernel->values[0]; break; } case ManhattanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*(labs((long) u)+labs((long) v)) ); kernel->maximum = kernel->values[0]; break; } case OctagonalKernel: { if (args->rho < 2.0) kernel->width = kernel->height = 5; /* default/minimum radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { double r1 = MagickMax(fabs((double)u),fabs((double)v)), r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5); kernel->positive_range += kernel->values[i] = args->sigma*MagickMax(r1,r2); } kernel->maximum = kernel->values[0]; break; } case EuclideanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*sqrt((double)(u*u+v*v)) ); kernel->maximum = kernel->values[0]; break; } default: { /* No-Op Kernel - Basically just a single pixel on its own */ kernel=ParseKernelArray("1:1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = UndefinedKernel; break; } break; } return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneKernelInfo() creates a new clone of the given Kernel List so that its % can be modified without effecting the original. The cloned kernel should % be destroyed using DestoryKernelInfo() when no longer needed. % % The format of the CloneKernelInfo method is: % % KernelInfo *CloneKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be cloned % */ MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel) { register ssize_t i; KernelInfo *new_kernel; assert(kernel != (KernelInfo *) NULL); new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (new_kernel == (KernelInfo *) NULL) return(new_kernel); *new_kernel=(*kernel); /* copy values in structure */ /* replace the values with a copy of the values */ new_kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (new_kernel->values == (double *) NULL) return(DestroyKernelInfo(new_kernel)); for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) new_kernel->values[i]=kernel->values[i]; /* Also clone the next kernel in the kernel list */ if ( kernel->next != (KernelInfo *) NULL ) { new_kernel->next = CloneKernelInfo(kernel->next); if ( new_kernel->next == (KernelInfo *) NULL ) return(DestroyKernelInfo(new_kernel)); } return(new_kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyKernelInfo() frees the memory used by a Convolution/Morphology % kernel. % % The format of the DestroyKernelInfo method is: % % KernelInfo *DestroyKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be destroyed % */ MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel) { assert(kernel != (KernelInfo *) NULL); if (kernel->next != (KernelInfo *) NULL) kernel->next=DestroyKernelInfo(kernel->next); kernel->values=(double *) RelinquishAlignedMemory(kernel->values); kernel=(KernelInfo *) RelinquishMagickMemory(kernel); return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d M i r r o r K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandMirrorKernelInfo() takes a single kernel, and expands it into a % sequence of 90-degree rotated kernels but providing a reflected 180 % rotatation, before the -/+ 90-degree rotations. % % This special rotation order produces a better, more symetrical thinning of % objects. % % The format of the ExpandMirrorKernelInfo method is: % % void ExpandMirrorKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ #if 0 static void FlopKernelInfo(KernelInfo *kernel) { /* Do a Flop by reversing each row. */ size_t y; register ssize_t x,r; register double *k,t; for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width) for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--) t=k[x], k[x]=k[r], k[r]=t; kernel->x = kernel->width - kernel->x - 1; angle = fmod(angle+180.0, 360.0); } #endif static void ExpandMirrorKernelInfo(KernelInfo *kernel) { KernelInfo *clone, *last; last = kernel; clone = CloneKernelInfo(last); RotateKernelInfo(clone, 180); /* flip */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); RotateKernelInfo(clone, 90); /* transpose */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); RotateKernelInfo(clone, 180); /* flop */ LastKernelInfo(last)->next = clone; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating % incrementally by the angle given, until the kernel repeats. % % WARNING: 45 degree rotations only works for 3x3 kernels. % While 90 degree roatations only works for linear and square kernels % % The format of the ExpandRotateKernelInfo method is: % % void ExpandRotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ /* Internal Routine - Return true if two kernels are the same */ static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1, const KernelInfo *kernel2) { register size_t i; /* check size and origin location */ if ( kernel1->width != kernel2->width || kernel1->height != kernel2->height || kernel1->x != kernel2->x || kernel1->y != kernel2->y ) return MagickFalse; /* check actual kernel values */ for (i=0; i < (kernel1->width*kernel1->height); i++) { /* Test for Nan equivalence */ if ( IsNaN(kernel1->values[i]) && !IsNaN(kernel2->values[i]) ) return MagickFalse; if ( IsNaN(kernel2->values[i]) && !IsNaN(kernel1->values[i]) ) return MagickFalse; /* Test actual values are equivalent */ if ( fabs(kernel1->values[i] - kernel2->values[i]) >= MagickEpsilon ) return MagickFalse; } return MagickTrue; } static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle) { KernelInfo *clone, *last; last = kernel; DisableMSCWarning(4127) while(1) { RestoreMSCWarning clone = CloneKernelInfo(last); RotateKernelInfo(clone, angle); if ( SameKernelInfo(kernel, clone) != MagickFalse ) break; LastKernelInfo(last)->next = clone; last = clone; } clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a l c M e t a K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only, % using the kernel values. This should only ne used if it is not possible to % calculate that meta-data in some easier way. % % It is important that the meta-data is correct before ScaleKernelInfo() is % used to perform kernel normalization. % % The format of the CalcKernelMetaData method is: % % void CalcKernelMetaData(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % WARNING: Minimum and Maximum values are assumed to include zero, even if % zero is not part of the kernel (as in Gaussian Derived kernels). This % however is not true for flat-shaped morphological kernels. % % WARNING: Only the specific kernel pointed to is modified, not a list of % multiple kernels. % % This is an internal function and not expected to be useful outside this % module. This could change however. */ static void CalcKernelMetaData(KernelInfo *kernel) { register size_t i; kernel->minimum = kernel->maximum = 0.0; kernel->negative_range = kernel->positive_range = 0.0; for (i=0; i < (kernel->width*kernel->height); i++) { if ( fabs(kernel->values[i]) < MagickEpsilon ) kernel->values[i] = 0.0; ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y A p p l y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyApply() applies a morphological method, multiple times using % a list of multiple kernels. This is the method that should be called by % other 'operators' that internally use morphology operations as part of % their processing. % % It is basically equivalent to as MorphologyImage() (see below) but % without any user controls. This allows internel programs to use this % function, to actually perform a specific task without possible interference % by any API user supplied settings. % % It is MorphologyImage() task to extract any such user controls, and % pass them to this function for processing. % % More specifically all given kernels should already be scaled, normalised, % and blended appropriatally before being parred to this routine. The % appropriate bias, and compose (typically 'UndefinedComposeOp') given. % % The format of the MorphologyApply method is: % % Image *MorphologyApply(const Image *image,MorphologyMethod method, % const ChannelType channel, const ssize_t iterations, % const KernelInfo *kernel, const CompositeMethod compose, % const double bias, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the source image % % o method: the morphology method to be applied. % % o channel: the channels to which the operations are applied % The channel 'sync' flag determines if 'alpha weighting' is % applied for convolution style operations. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o channel: the channel type. % % o kernel: An array of double representing the morphology kernel. % % o compose: How to handle or merge multi-kernel results. % If 'UndefinedCompositeOp' use default for the Morphology method. % If 'NoCompositeOp' force image to be re-iterated by each kernel. % Otherwise merge the results using the compose method given. % % o bias: Convolution Output Bias. % % o exception: return any errors or warnings in this structure. % */ /* Apply a Morphology Primative to an image using the given kernel. ** Two pre-created images must be provided, and no image is created. ** It returns the number of pixels that changed between the images ** for result convergence determination. */ static ssize_t MorphologyPrimitive(const Image *image, Image *result_image, const MorphologyMethod method, const ChannelType channel, const KernelInfo *kernel,const double bias,ExceptionInfo *exception) { #define MorphologyTag "Morphology/Image" CacheView *p_view, *q_view; register ssize_t i; size_t *changes, changed, virt_width; ssize_t y, offx, offy; MagickBooleanType status; MagickOffsetType progress; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(result_image != (Image *) NULL); assert(result_image->signature == MagickSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=MagickTrue; progress=0; p_view=AcquireVirtualCacheView(image,exception); q_view=AcquireAuthenticCacheView(result_image,exception); virt_width=image->columns+kernel->width-1; /* Some methods (including convolve) needs use a reflected kernel. * Adjust 'origin' offsets to loop though kernel as a reflection. */ offx = kernel->x; offy = kernel->y; switch(method) { case ConvolveMorphology: case DilateMorphology: case DilateIntensityMorphology: case IterativeDistanceMorphology: /* kernel needs to used with reflection about origin */ offx = (ssize_t) kernel->width-offx-1; offy = (ssize_t) kernel->height-offy-1; break; case ErodeMorphology: case ErodeIntensityMorphology: case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: /* kernel is used as is, without reflection */ break; default: assert("Not a Primitive Morphology Method" != (char *) NULL); break; } changed=0; changes=(size_t *) AcquireQuantumMemory(GetOpenMPMaximumThreads(), sizeof(*changes)); if (changes == (size_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++) changes[i]=0; if ( method == ConvolveMorphology && kernel->width == 1 ) { /* Special handling (for speed) of vertical (blur) kernels. ** This performs its handling in columns rather than in rows. ** This is only done for convolve as it is the only method that ** generates very large 1-D vertical kernels (such as a 'BlurKernel') ** ** Timing tests (on single CPU laptop) ** Using a vertical 1-d Blue with normal row-by-row (below) ** time convert logo: -morphology Convolve Blur:0x10+90 null: ** 0.807u ** Using this column method ** time convert logo: -morphology Convolve Blur:0x10+90 null: ** 0.620u ** ** Anthony Thyssen, 14 June 2010 */ register ssize_t x; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,result_image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t y; ssize_t r; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(p_view,x,-offy,1,image->rows+kernel->height-1, exception); q=GetCacheViewAuthenticPixels(q_view,x,0,1,result_image->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } p_indexes=GetCacheViewVirtualIndexQueue(p_view); q_indexes=GetCacheViewAuthenticIndexQueue(q_view); /* offset to origin in 'p'. while 'q' points to it directly */ r = offy; for (y=0; y < (ssize_t) image->rows; y++) { DoublePixelPacket result; register ssize_t v; register const double *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; /* Copy input image to the output image for unused channels * This removes need for 'cloning' a new image every iteration */ *q = p[r]; if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+y,GetPixelIndex(p_indexes+r)); /* Set the bias of the weighted average output */ result.red = result.green = result.blue = result.opacity = result.index = bias; /* Weighted Average of pixels using reflected kernel ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. */ k = &kernel->values[ kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; if ( ((channel & SyncChannels) == 0 ) || (image->matte == MagickFalse) ) { /* No 'Sync' involved. ** Convolution is simple greyscale channel operation */ for (v=0; v < (ssize_t) kernel->height; v++) { if ( IsNaN(*k) ) continue; result.red += (*k)*GetPixelRed(k_pixels); result.green += (*k)*GetPixelGreen(k_pixels); result.blue += (*k)*GetPixelBlue(k_pixels); result.opacity += (*k)*GetPixelOpacity(k_pixels); if ( image->colorspace == CMYKColorspace) result.index += (*k)*(*k_indexes); k--; k_pixels++; k_indexes++; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,ClampToQuantum(result.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(q_indexes+y,ClampToQuantum(result.index)); } else { /* Channel 'Sync' Flag, and Alpha Channel enabled. ** Weight the color channels with Alpha Channel so that ** transparent pixels are not part of the results. */ double gamma; /* divisor, sum of color alpha weighting */ MagickRealType alpha; /* alpha weighting for colors : alpha */ size_t count; /* alpha valus collected, number kernel values */ count=0; gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { if ( IsNaN(*k) ) continue; alpha=QuantumScale*(QuantumRange-GetPixelOpacity(k_pixels)); count++; /* number of alpha values collected */ alpha*=(*k); /* include kernel weighting now */ gamma += alpha; /* normalize alpha weights only */ result.red += alpha*GetPixelRed(k_pixels); result.green += alpha*GetPixelGreen(k_pixels); result.blue += alpha*GetPixelBlue(k_pixels); result.opacity += (*k)*GetPixelOpacity(k_pixels); if ( image->colorspace == CMYKColorspace) result.index += alpha*(*k_indexes); k--; k_pixels++; k_indexes++; } /* Sync'ed channels, all channels are modified */ gamma=PerceptibleReciprocal(gamma); gamma*=(double) kernel->height/count; SetPixelRed(q,ClampToQuantum(gamma*result.red)); SetPixelGreen(q,ClampToQuantum(gamma*result.green)); SetPixelBlue(q,ClampToQuantum(gamma*result.blue)); SetPixelOpacity(q,ClampToQuantum(result.opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+y,ClampToQuantum(gamma*result.index)); } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q)) || ( p[r].green != GetPixelGreen(q)) || ( p[r].blue != GetPixelBlue(q)) || ( p[r].opacity != GetPixelOpacity(q)) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+y) ) ) changes[id]++; p++; q++; } /* y */ if ( SyncCacheViewAuthenticPixels(q_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MorphologyPrimitive) #endif proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } /* x */ result_image->type=image->type; q_view=DestroyCacheView(q_view); p_view=DestroyCacheView(p_view); for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++) changed+=changes[i]; changes=(size_t *) RelinquishMagickMemory(changes); return(status ? (ssize_t) changed : 0); } /* ** Normal handling of horizontal or rectangular kernels (row by row) */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,result_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t x; size_t r; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(p_view, -offx, y-offy, virt_width, kernel->height, exception); q=GetCacheViewAuthenticPixels(q_view,0,y,result_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } p_indexes=GetCacheViewVirtualIndexQueue(p_view); q_indexes=GetCacheViewAuthenticIndexQueue(q_view); /* offset to origin in 'p'. while 'q' points to it directly */ r = virt_width*offy + offx; for (x=0; x < (ssize_t) image->columns; x++) { ssize_t v; register ssize_t u; register const double *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; DoublePixelPacket result, min, max; /* Copy input image to the output image for unused channels * This removes need for 'cloning' a new image every iteration */ *q = p[r]; if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,GetPixelIndex(p_indexes+r)); /* Defaults */ min.red = min.green = min.blue = min.opacity = min.index = (double) QuantumRange; max.red = max.green = max.blue = max.opacity = max.index = 0.0; /* default result is the original pixel value */ result.red = (double) p[r].red; result.green = (double) p[r].green; result.blue = (double) p[r].blue; result.opacity = QuantumRange - (double) p[r].opacity; result.index = 0.0; if ( image->colorspace == CMYKColorspace) result.index = (double) GetPixelIndex(p_indexes+r); switch (method) { case ConvolveMorphology: /* Set the bias of the weighted average output */ result.red = result.green = result.blue = result.opacity = result.index = bias; break; case DilateIntensityMorphology: case ErodeIntensityMorphology: /* use a boolean flag indicating when first match found */ result.red = 0.0; /* result is not used otherwise */ break; default: break; } switch ( method ) { case ConvolveMorphology: /* Weighted Average of pixels using reflected kernel ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. ** ** Correlation is actually the same as this but without reflecting ** the kernel, and thus 'lower-level' that Convolution. However ** as Convolution is the more common method used, and it does not ** really cost us much in terms of processing to use a reflected ** kernel, so it is Convolution that is implemented. ** ** Correlation will have its kernel reflected before calling ** this function to do a Convolve. ** ** For more details of Correlation vs Convolution see ** http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; if ( ((channel & SyncChannels) == 0 ) || (image->matte == MagickFalse) ) { /* No 'Sync' involved. ** Convolution is simple greyscale channel operation */ for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) ) continue; result.red += (*k)*k_pixels[u].red; result.green += (*k)*k_pixels[u].green; result.blue += (*k)*k_pixels[u].blue; result.opacity += (*k)*k_pixels[u].opacity; if ( image->colorspace == CMYKColorspace) result.index += (*k)*GetPixelIndex(k_indexes+u); } k_pixels += virt_width; k_indexes += virt_width; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum((MagickRealType) result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum((MagickRealType) result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum((MagickRealType) result.blue)); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,ClampToQuantum((MagickRealType) result.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); } else { /* Channel 'Sync' Flag, and Alpha Channel enabled. ** Weight the color channels with Alpha Channel so that ** transparent pixels are not part of the results. */ double alpha, /* alpha weighting for colors : alpha */ gamma; /* divisor, sum of color alpha weighting */ size_t count; /* alpha valus collected, number kernel values */ count=0; gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) ) continue; alpha=QuantumScale*(QuantumRange-k_pixels[u].opacity); count++; /* number of alpha values collected */ alpha*=(*k); /* include kernel weighting now */ gamma += alpha; /* normalize alpha weights only */ result.red += alpha*k_pixels[u].red; result.green += alpha*k_pixels[u].green; result.blue += alpha*k_pixels[u].blue; result.opacity += (*k)*k_pixels[u].opacity; if ( image->colorspace == CMYKColorspace) result.index+=alpha*GetPixelIndex(k_indexes+u); } k_pixels += virt_width; k_indexes += virt_width; } /* Sync'ed channels, all channels are modified */ gamma=PerceptibleReciprocal(gamma); gamma*=(double) kernel->height*kernel->width/count; SetPixelRed(q,ClampToQuantum((MagickRealType) (gamma*result.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (gamma*result.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (gamma*result.blue))); SetPixelOpacity(q,ClampToQuantum(result.opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum((MagickRealType) (gamma* result.index))); } break; case ErodeMorphology: /* Minimum Value within kernel neighbourhood ** ** NOTE that the kernel is not reflected for this operation! ** ** NOTE: in normal Greyscale Morphology, the kernel value should ** be added to the real value, this is currently not done, due to ** the nature of the boolean kernels being used. */ k = kernel->values; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k++) { if ( IsNaN(*k) || (*k) < 0.5 ) continue; Minimize(min.red, (double) k_pixels[u].red); Minimize(min.green, (double) k_pixels[u].green); Minimize(min.blue, (double) k_pixels[u].blue); Minimize(min.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(min.index,(double) GetPixelIndex(k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } break; case DilateMorphology: /* Maximum Value within kernel neighbourhood ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. ** ** NOTE: in normal Greyscale Morphology, the kernel value should ** be added to the real value, this is currently not done, due to ** the nature of the boolean kernels being used. ** */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) || (*k) < 0.5 ) continue; Maximize(max.red, (double) k_pixels[u].red); Maximize(max.green, (double) k_pixels[u].green); Maximize(max.blue, (double) k_pixels[u].blue); Maximize(max.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Maximize(max.index, (double) GetPixelIndex( k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } break; case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: /* Minimum of Foreground Pixel minus Maxumum of Background Pixels ** ** NOTE that the kernel is not reflected for this operation, ** and consists of both foreground and background pixel ** neighbourhoods, 0.0 for background, and 1.0 for foreground ** with either Nan or 0.5 values for don't care. ** ** Note that this will never produce a meaningless negative ** result. Such results can cause Thinning/Thicken to not work ** correctly when used against a greyscale image. */ k = kernel->values; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k++) { if ( IsNaN(*k) ) continue; if ( (*k) > 0.7 ) { /* minimim of foreground pixels */ Minimize(min.red, (double) k_pixels[u].red); Minimize(min.green, (double) k_pixels[u].green); Minimize(min.blue, (double) k_pixels[u].blue); Minimize(min.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(min.index,(double) GetPixelIndex( k_indexes+u)); } else if ( (*k) < 0.3 ) { /* maximum of background pixels */ Maximize(max.red, (double) k_pixels[u].red); Maximize(max.green, (double) k_pixels[u].green); Maximize(max.blue, (double) k_pixels[u].blue); Maximize(max.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Maximize(max.index, (double) GetPixelIndex( k_indexes+u)); } } k_pixels += virt_width; k_indexes += virt_width; } /* Pattern Match if difference is positive */ min.red -= max.red; Maximize( min.red, 0.0 ); min.green -= max.green; Maximize( min.green, 0.0 ); min.blue -= max.blue; Maximize( min.blue, 0.0 ); min.opacity -= max.opacity; Maximize( min.opacity, 0.0 ); min.index -= max.index; Maximize( min.index, 0.0 ); break; case ErodeIntensityMorphology: /* Select Pixel with Minimum Intensity within kernel neighbourhood ** ** WARNING: the intensity test fails for CMYK and does not ** take into account the moderating effect of the alpha channel ** on the intensity. ** ** NOTE that the kernel is not reflected for this operation! */ k = kernel->values; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k++) { if ( IsNaN(*k) || (*k) < 0.5 ) continue; if ( result.red == 0.0 || GetPixelIntensity(image,&(k_pixels[u])) < GetPixelIntensity(result_image,q) ) { /* copy the whole pixel - no channel selection */ *q = k_pixels[u]; if ( result.red > 0.0 ) changes[id]++; result.red = 1.0; } } k_pixels += virt_width; k_indexes += virt_width; } break; case DilateIntensityMorphology: /* Select Pixel with Maximum Intensity within kernel neighbourhood ** ** WARNING: the intensity test fails for CMYK and does not ** take into account the moderating effect of the alpha channel ** on the intensity (yet). ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) || (*k) < 0.5 ) continue; /* boolean kernel */ if ( result.red == 0.0 || GetPixelIntensity(image,&(k_pixels[u])) > GetPixelIntensity(result_image,q) ) { /* copy the whole pixel - no channel selection */ *q = k_pixels[u]; if ( result.red > 0.0 ) changes[id]++; result.red = 1.0; } } k_pixels += virt_width; k_indexes += virt_width; } break; case IterativeDistanceMorphology: /* Work out an iterative distance from black edge of a white image ** shape. Essentually white values are decreased to the smallest ** 'distance from edge' it can find. ** ** It works by adding kernel values to the neighbourhood, and and ** select the minimum value found. The kernel is rotated before ** use, so kernel distances match resulting distances, when a user ** provided asymmetric kernel is applied. ** ** ** This code is almost identical to True GrayScale Morphology But ** not quite. ** ** GreyDilate Kernel values added, maximum value found Kernel is ** rotated before use. ** ** GrayErode: Kernel values subtracted and minimum value found No ** kernel rotation used. ** ** Note the the Iterative Distance method is essentially a ** GrayErode, but with negative kernel values, and kernel ** rotation applied. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index,(*k)+GetPixelIndex( k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } break; case UndefinedMorphology: default: break; /* Do nothing */ } /* Final mathematics of results (combine with original image?) ** ** NOTE: Difference Morphology operators Edge* and *Hat could also ** be done here but works better with iteration as a image difference ** in the controlling function (below). Thicken and Thinning however ** should be done here so thay can be iterated correctly. */ switch ( method ) { case HitAndMissMorphology: case ErodeMorphology: result = min; /* minimum of neighbourhood */ break; case DilateMorphology: result = max; /* maximum of neighbourhood */ break; case ThinningMorphology: /* subtract pattern match from original */ result.red -= min.red; result.green -= min.green; result.blue -= min.blue; result.opacity -= min.opacity; result.index -= min.index; break; case ThickenMorphology: /* Add the pattern matchs to the original */ result.red += min.red; result.green += min.green; result.blue += min.blue; result.opacity += min.opacity; result.index += min.index; break; default: /* result directly calculated or assigned */ break; } /* Assign the resulting pixel values - Clamping Result */ switch ( method ) { case UndefinedMorphology: case ConvolveMorphology: case DilateIntensityMorphology: case ErodeIntensityMorphology: break; /* full pixel was directly assigned - not a channel method */ default: if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if ((channel & OpacityChannel) != 0 && image->matte != MagickFalse ) SetPixelAlpha(q,ClampToQuantum(result.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); break; } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q) ) || ( p[r].green != GetPixelGreen(q) ) || ( p[r].blue != GetPixelBlue(q) ) || ( p[r].opacity != GetPixelOpacity(q) ) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+x) ) ) changes[id]++; p++; q++; } /* x */ if ( SyncCacheViewAuthenticPixels(q_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MorphologyPrimitive) #endif proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } /* y */ q_view=DestroyCacheView(q_view); p_view=DestroyCacheView(p_view); for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++) changed+=changes[i]; changes=(size_t *) RelinquishMagickMemory(changes); return(status ? (ssize_t)changed : -1); } /* This is almost identical to the MorphologyPrimative() function above, ** but will apply the primitive directly to the actual image using two ** passes, once in each direction, with the results of the previous (and ** current) row being re-used. ** ** That is after each row is 'Sync'ed' into the image, the next row will ** make use of those values as part of the calculation of the next row. ** It then repeats, but going in the oppisite (bottom-up) direction. ** ** Because of this 're-use of results' this function can not make use ** of multi-threaded, parellel processing. */ static ssize_t MorphologyPrimitiveDirect(Image *image, const MorphologyMethod method, const ChannelType channel, const KernelInfo *kernel,ExceptionInfo *exception) { CacheView *auth_view, *virt_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y, offx, offy; size_t changed, virt_width; status=MagickTrue; changed=0; progress=0; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Some methods (including convolve) needs use a reflected kernel. * Adjust 'origin' offsets to loop though kernel as a reflection. */ offx = kernel->x; offy = kernel->y; switch(method) { case DistanceMorphology: case VoronoiMorphology: /* kernel needs to used with reflection about origin */ offx = (ssize_t) kernel->width-offx-1; offy = (ssize_t) kernel->height-offy-1; break; #if 0 case ?????Morphology: /* kernel is used as is, without reflection */ break; #endif default: assert("Not a PrimativeDirect Morphology Method" != (char *) NULL); break; } /* DO NOT THREAD THIS CODE! */ /* two views into same image (virtual, and actual) */ virt_view=AcquireVirtualCacheView(image,exception); auth_view=AcquireAuthenticCacheView(image,exception); virt_width=image->columns+kernel->width-1; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t x; ssize_t r; /* NOTE read virtual pixels, and authentic pixels, from the same image! ** we read using virtual to get virtual pixel handling, but write back ** into the same image. ** ** Only top half of kernel is processed as we do a single pass downward ** through the image iterating the distance function as we go. */ if (status == MagickFalse) break; p=GetCacheViewVirtualPixels(virt_view, -offx, y-offy, virt_width, (size_t) offy+1, exception); q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) status=MagickFalse; if (status == MagickFalse) break; p_indexes=GetCacheViewVirtualIndexQueue(virt_view); q_indexes=GetCacheViewAuthenticIndexQueue(auth_view); /* offset to origin in 'p'. while 'q' points to it directly */ r = (ssize_t) virt_width*offy + offx; for (x=0; x < (ssize_t) image->columns; x++) { ssize_t v; register ssize_t u; register const double *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; MagickPixelPacket result; /* Starting Defaults */ GetMagickPixelPacket(image,&result); SetMagickPixelPacket(image,q,q_indexes,&result); if ( method != VoronoiMorphology ) result.opacity = QuantumRange - result.opacity; switch ( method ) { case DistanceMorphology: /* Add kernel Value and select the minimum value found. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v <= (ssize_t) offy; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index, (*k)+GetPixelIndex(k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=0; u < (ssize_t) offx; u++, k--) { if ( x+u-offx < 0 ) continue; /* off the edge! */ if ( IsNaN(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index, (*k)+GetPixelIndex(k_indexes+u)); } break; case VoronoiMorphology: /* Apply Distance to 'Matte' channel, while coping the color ** values of the closest pixel. ** ** This is experimental, and realy the 'alpha' component should ** be completely separate 'masking' channel so that alpha can ** also be used as part of the results. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v <= (ssize_t) offy; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=0; u < (ssize_t) offx; u++, k--) { if ( x+u-offx < 0 ) continue; /* off the edge! */ if ( IsNaN(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } break; default: /* result directly calculated or assigned */ break; } /* Assign the resulting pixel values - Clamping Result */ switch ( method ) { case VoronoiMorphology: SetPixelPacket(image,&result,q,q_indexes); break; default: if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelAlpha(q,ClampToQuantum(result.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); break; } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q) ) || ( p[r].green != GetPixelGreen(q) ) || ( p[r].blue != GetPixelBlue(q) ) || ( p[r].opacity != GetPixelOpacity(q) ) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+x) ) ) changed++; /* The pixel was changed in some way! */ p++; /* increment pixel buffers */ q++; } /* x */ if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) if ( SetImageProgress(image,MorphologyTag,progress++,image->rows) == MagickFalse ) status=MagickFalse; } /* y */ /* Do the reversed pass through the image */ for (y=(ssize_t)image->rows-1; y >= 0; y--) { register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t x; ssize_t r; if (status == MagickFalse) break; /* NOTE read virtual pixels, and authentic pixels, from the same image! ** we read using virtual to get virtual pixel handling, but write back ** into the same image. ** ** Only the bottom half of the kernel will be processes as we ** up the image. */ p=GetCacheViewVirtualPixels(virt_view, -offx, y, virt_width, (size_t) kernel->y+1, exception); q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) status=MagickFalse; if (status == MagickFalse) break; p_indexes=GetCacheViewVirtualIndexQueue(virt_view); q_indexes=GetCacheViewAuthenticIndexQueue(auth_view); /* adjust positions to end of row */ p += image->columns-1; q += image->columns-1; /* offset to origin in 'p'. while 'q' points to it directly */ r = offx; for (x=(ssize_t)image->columns-1; x >= 0; x--) { ssize_t v; register ssize_t u; register const double *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; MagickPixelPacket result; /* Default - previously modified pixel */ GetMagickPixelPacket(image,&result); SetMagickPixelPacket(image,q,q_indexes,&result); if ( method != VoronoiMorphology ) result.opacity = QuantumRange - result.opacity; switch ( method ) { case DistanceMorphology: /* Add kernel Value and select the minimum value found. */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=offy; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index,(*k)+GetPixelIndex(k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) { if ( (x+u-offx) >= (ssize_t)image->columns ) continue; if ( IsNaN(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index, (*k)+GetPixelIndex(k_indexes+u)); } break; case VoronoiMorphology: /* Apply Distance to 'Matte' channel, coping the closest color. ** ** This is experimental, and realy the 'alpha' component should ** be completely separate 'masking' channel. */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=offy; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNaN(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) { if ( (x+u-offx) >= (ssize_t)image->columns ) continue; if ( IsNaN(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } break; default: /* result directly calculated or assigned */ break; } /* Assign the resulting pixel values - Clamping Result */ switch ( method ) { case VoronoiMorphology: SetPixelPacket(image,&result,q,q_indexes); break; default: if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelAlpha(q,ClampToQuantum(result.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); break; } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q) ) || ( p[r].green != GetPixelGreen(q) ) || ( p[r].blue != GetPixelBlue(q) ) || ( p[r].opacity != GetPixelOpacity(q) ) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+x) ) ) changed++; /* The pixel was changed in some way! */ p--; /* go backward through pixel buffers */ q--; } /* x */ if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) if ( SetImageProgress(image,MorphologyTag,progress++,image->rows) == MagickFalse ) status=MagickFalse; } /* y */ auth_view=DestroyCacheView(auth_view); virt_view=DestroyCacheView(virt_view); return(status ? (ssize_t) changed : -1); } /* Apply a Morphology by calling one of the above low level primitive ** application functions. This function handles any iteration loops, ** composition or re-iteration of results, and compound morphology methods ** that is based on multiple low-level (staged) morphology methods. ** ** Basically this provides the complex grue between the requested morphology ** method and raw low-level implementation (above). */ MagickExport Image *MorphologyApply(const Image *image, const ChannelType channel,const MorphologyMethod method, const ssize_t iterations, const KernelInfo *kernel, const CompositeOperator compose, const double bias, ExceptionInfo *exception) { CompositeOperator curr_compose; Image *curr_image, /* Image we are working with or iterating */ *work_image, /* secondary image for primitive iteration */ *save_image, /* saved image - for 'edge' method only */ *rslt_image; /* resultant image - after multi-kernel handling */ KernelInfo *reflected_kernel, /* A reflected copy of the kernel (if needed) */ *norm_kernel, /* the current normal un-reflected kernel */ *rflt_kernel, /* the current reflected kernel (if needed) */ *this_kernel; /* the kernel being applied */ MorphologyMethod primitive; /* the current morphology primitive being applied */ CompositeOperator rslt_compose; /* multi-kernel compose method for results to use */ MagickBooleanType special, /* do we use a direct modify function? */ verbose; /* verbose output of results */ size_t method_loop, /* Loop 1: number of compound method iterations (norm 1) */ method_limit, /* maximum number of compound method iterations */ kernel_number, /* Loop 2: the kernel number being applied */ stage_loop, /* Loop 3: primitive loop for compound morphology */ stage_limit, /* how many primitives are in this compound */ kernel_loop, /* Loop 4: iterate the kernel over image */ kernel_limit, /* number of times to iterate kernel */ count, /* total count of primitive steps applied */ kernel_changed, /* total count of changed using iterated kernel */ method_changed; /* total count of changed over method iteration */ ssize_t changed; /* number pixels changed by last primitive operation */ char v_info[MaxTextExtent]; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); count = 0; /* number of low-level morphology primitives performed */ if ( iterations == 0 ) return((Image *)NULL); /* null operation - nothing to do! */ kernel_limit = (size_t) iterations; if ( iterations < 0 ) /* negative interations = infinite (well alomst) */ kernel_limit = image->columns>image->rows ? image->columns : image->rows; verbose = IsMagickTrue(GetImageArtifact(image,"debug")); /* initialise for cleanup */ curr_image = (Image *) image; curr_compose = image->compose; (void) curr_compose; work_image = save_image = rslt_image = (Image *) NULL; reflected_kernel = (KernelInfo *) NULL; /* Initialize specific methods * + which loop should use the given iteratations * + how many primitives make up the compound morphology * + multi-kernel compose method to use (by default) */ method_limit = 1; /* just do method once, unless otherwise set */ stage_limit = 1; /* assume method is not a compound */ special = MagickFalse; /* assume it is NOT a direct modify primitive */ rslt_compose = compose; /* and we are composing multi-kernels as given */ switch( method ) { case SmoothMorphology: /* 4 primitive compound morphology */ stage_limit = 4; break; case OpenMorphology: /* 2 primitive compound morphology */ case OpenIntensityMorphology: case TopHatMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case EdgeMorphology: stage_limit = 2; break; case HitAndMissMorphology: rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */ /* FALL THUR */ case ThinningMorphology: case ThickenMorphology: method_limit = kernel_limit; /* iterate the whole method */ kernel_limit = 1; /* do not do kernel iteration */ break; case DistanceMorphology: case VoronoiMorphology: special = MagickTrue; /* use special direct primative */ break; default: break; } /* Apply special methods with special requirments ** For example, single run only, or post-processing requirements */ if ( special != MagickFalse ) { rslt_image=CloneImage(image,0,0,MagickTrue,exception); if (rslt_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(rslt_image,DirectClass) == MagickFalse) { InheritException(exception,&rslt_image->exception); goto error_cleanup; } changed = MorphologyPrimitiveDirect(rslt_image, method, channel, kernel, exception); if ( verbose != MagickFalse ) (void) (void) FormatLocaleFile(stderr, "%s:%.20g.%.20g #%.20g => Changed %.20g\n", CommandOptionToMnemonic(MagickMorphologyOptions, method), 1.0,0.0,1.0, (double) changed); if ( changed < 0 ) goto error_cleanup; if ( method == VoronoiMorphology ) { /* Preserve the alpha channel of input image - but turned off */ (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel); (void) CompositeImageChannel(rslt_image, DefaultChannels, CopyOpacityCompositeOp, image, 0, 0); (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel); } goto exit_cleanup; } /* Handle user (caller) specified multi-kernel composition method */ if ( compose != UndefinedCompositeOp ) rslt_compose = compose; /* override default composition for method */ if ( rslt_compose == UndefinedCompositeOp ) rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */ /* Some methods require a reflected kernel to use with primitives. * Create the reflected kernel for those methods. */ switch ( method ) { case CorrelateMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case SmoothMorphology: reflected_kernel = CloneKernelInfo(kernel); if (reflected_kernel == (KernelInfo *) NULL) goto error_cleanup; RotateKernelInfo(reflected_kernel,180); break; default: break; } /* Loops around more primitive morpholgy methods ** erose, dilate, open, close, smooth, edge, etc... */ /* Loop 1: iterate the compound method */ method_loop = 0; method_changed = 1; while ( method_loop < method_limit && method_changed > 0 ) { method_loop++; method_changed = 0; /* Loop 2: iterate over each kernel in a multi-kernel list */ norm_kernel = (KernelInfo *) kernel; this_kernel = (KernelInfo *) kernel; rflt_kernel = reflected_kernel; kernel_number = 0; while ( norm_kernel != NULL ) { /* Loop 3: Compound Morphology Staging - Select Primative to apply */ stage_loop = 0; /* the compound morphology stage number */ while ( stage_loop < stage_limit ) { stage_loop++; /* The stage of the compound morphology */ /* Select primitive morphology for this stage of compound method */ this_kernel = norm_kernel; /* default use unreflected kernel */ primitive = method; /* Assume method is a primitive */ switch( method ) { case ErodeMorphology: /* just erode */ case EdgeInMorphology: /* erode and image difference */ primitive = ErodeMorphology; break; case DilateMorphology: /* just dilate */ case EdgeOutMorphology: /* dilate and image difference */ primitive = DilateMorphology; break; case OpenMorphology: /* erode then dialate */ case TopHatMorphology: /* open and image difference */ primitive = ErodeMorphology; if ( stage_loop == 2 ) primitive = DilateMorphology; break; case OpenIntensityMorphology: primitive = ErodeIntensityMorphology; if ( stage_loop == 2 ) primitive = DilateIntensityMorphology; break; case CloseMorphology: /* dilate, then erode */ case BottomHatMorphology: /* close and image difference */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; if ( stage_loop == 2 ) primitive = ErodeMorphology; break; case CloseIntensityMorphology: this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateIntensityMorphology; if ( stage_loop == 2 ) primitive = ErodeIntensityMorphology; break; case SmoothMorphology: /* open, close */ switch ( stage_loop ) { case 1: /* start an open method, which starts with Erode */ primitive = ErodeMorphology; break; case 2: /* now Dilate the Erode */ primitive = DilateMorphology; break; case 3: /* Reflect kernel a close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; break; case 4: /* Finish the Close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ErodeMorphology; break; } break; case EdgeMorphology: /* dilate and erode difference */ primitive = DilateMorphology; if ( stage_loop == 2 ) { save_image = curr_image; /* save the image difference */ curr_image = (Image *) image; primitive = ErodeMorphology; } break; case CorrelateMorphology: /* A Correlation is a Convolution with a reflected kernel. ** However a Convolution is a weighted sum using a reflected ** kernel. It may seem stange to convert a Correlation into a ** Convolution as the Correlation is the simplier method, but ** Convolution is much more commonly used, and it makes sense to ** implement it directly so as to avoid the need to duplicate the ** kernel when it is not required (which is typically the ** default). */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ConvolveMorphology; break; default: break; } assert( this_kernel != (KernelInfo *) NULL ); /* Extra information for debugging compound operations */ if ( verbose != MagickFalse ) { if ( stage_limit > 1 ) (void) FormatLocaleString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions,method),(double) method_loop,(double) stage_loop); else if ( primitive != method ) (void) FormatLocaleString(v_info, MaxTextExtent, "%s:%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions, method),(double) method_loop); else v_info[0] = '\0'; } /* Loop 4: Iterate the kernel with primitive */ kernel_loop = 0; kernel_changed = 0; changed = 1; while ( kernel_loop < kernel_limit && changed > 0 ) { kernel_loop++; /* the iteration of this kernel */ /* Create a clone as the destination image, if not yet defined */ if ( work_image == (Image *) NULL ) { work_image=CloneImage(image,0,0,MagickTrue,exception); if (work_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(work_image,DirectClass) == MagickFalse) { InheritException(exception,&work_image->exception); goto error_cleanup; } /* work_image->type=image->type; ??? */ } /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */ count++; changed = MorphologyPrimitive(curr_image, work_image, primitive, channel, this_kernel, bias, exception); if ( verbose != MagickFalse ) { if ( kernel_loop > 1 ) (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */ (void) (void) FormatLocaleFile(stderr, "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g", v_info,CommandOptionToMnemonic(MagickMorphologyOptions, primitive),(this_kernel == rflt_kernel ) ? "*" : "", (double) (method_loop+kernel_loop-1),(double) kernel_number, (double) count,(double) changed); } if ( changed < 0 ) goto error_cleanup; kernel_changed += changed; method_changed += changed; /* prepare next loop */ { Image *tmp = work_image; /* swap images for iteration */ work_image = curr_image; curr_image = tmp; } if ( work_image == image ) work_image = (Image *) NULL; /* replace input 'image' */ } /* End Loop 4: Iterate the kernel with primitive */ if ( verbose != MagickFalse && kernel_changed != (size_t)changed ) (void) FormatLocaleFile(stderr, " Total %.20g",(double) kernel_changed); if ( verbose != MagickFalse && stage_loop < stage_limit ) (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */ #if 0 (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image); (void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image); (void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image); (void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image); (void) FormatLocaleFile(stderr, " union=0x%lx\n", (unsigned long)rslt_image); #endif } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */ /* Final Post-processing for some Compound Methods ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** Turn off SVG composition 'alpha blending'. */ switch( method ) { case EdgeOutMorphology: case EdgeInMorphology: case TopHatMorphology: case BottomHatMorphology: if ( verbose != MagickFalse ) (void) FormatLocaleFile(stderr, "\n%s: Difference with original image", CommandOptionToMnemonic(MagickMorphologyOptions, method) ); (void) CompositeImageChannel(curr_image, (ChannelType) (channel & ~SyncChannels), DifferenceCompositeOp, image, 0, 0); break; case EdgeMorphology: if ( verbose != MagickFalse ) (void) FormatLocaleFile(stderr, "\n%s: Difference of Dilate and Erode", CommandOptionToMnemonic(MagickMorphologyOptions, method) ); (void) CompositeImageChannel(curr_image, (ChannelType) (channel & ~SyncChannels), DifferenceCompositeOp, save_image, 0, 0); save_image = DestroyImage(save_image); /* finished with save image */ break; default: break; } /* multi-kernel handling: re-iterate, or compose results */ if ( kernel->next == (KernelInfo *) NULL ) rslt_image = curr_image; /* just return the resulting image */ else if ( rslt_compose == NoCompositeOp ) { if ( verbose != MagickFalse ) { if ( this_kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(stderr, " (re-iterate)"); else (void) FormatLocaleFile(stderr, " (done)"); } rslt_image = curr_image; /* return result, and re-iterate */ } else if ( rslt_image == (Image *) NULL) { if ( verbose != MagickFalse ) (void) FormatLocaleFile(stderr, " (save for compose)"); rslt_image = curr_image; curr_image = (Image *) image; /* continue with original image */ } else { /* Add the new 'current' result to the composition ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** IE: Turn off SVG composition 'alpha blending'. */ if ( verbose != MagickFalse ) (void) FormatLocaleFile(stderr, " (compose \"%s\")", CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) ); (void) CompositeImageChannel(rslt_image, (ChannelType) (channel & ~SyncChannels), rslt_compose, curr_image, 0, 0); curr_image = DestroyImage(curr_image); curr_image = (Image *) image; /* continue with original image */ } if ( verbose != MagickFalse ) (void) FormatLocaleFile(stderr, "\n"); /* loop to the next kernel in a multi-kernel list */ norm_kernel = norm_kernel->next; if ( rflt_kernel != (KernelInfo *) NULL ) rflt_kernel = rflt_kernel->next; kernel_number++; } /* End Loop 2: Loop over each kernel */ } /* End Loop 1: compound method interation */ goto exit_cleanup; /* Yes goto's are bad, but it makes cleanup lot more efficient */ error_cleanup: if ( curr_image == rslt_image ) curr_image = (Image *) NULL; if ( rslt_image != (Image *) NULL ) rslt_image = DestroyImage(rslt_image); exit_cleanup: if ( curr_image == rslt_image || curr_image == image ) curr_image = (Image *) NULL; if ( curr_image != (Image *) NULL ) curr_image = DestroyImage(curr_image); if ( work_image != (Image *) NULL ) work_image = DestroyImage(work_image); if ( save_image != (Image *) NULL ) save_image = DestroyImage(save_image); if ( reflected_kernel != (KernelInfo *) NULL ) reflected_kernel = DestroyKernelInfo(reflected_kernel); return(rslt_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyImageChannel() applies a user supplied kernel to the image % according to the given mophology method. % % This function applies any and all user defined settings before calling % the above internal function MorphologyApply(). % % User defined settings include... % * Output Bias for Convolution and correlation ("-bias" or "-define convolve:bias=??") % * Kernel Scale/normalize settings ("-set 'option:convolve:scale'") % This can also includes the addition of a scaled unity kernel. % * Show Kernel being applied ("-set option:showkernel 1") % % The format of the MorphologyImage method is: % % Image *MorphologyImage(const Image *image,MorphologyMethod method, % const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception) % % Image *MorphologyImageChannel(const Image *image, const ChannelType % channel,MorphologyMethod method,const ssize_t iterations, % KernelInfo *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the morphology method to be applied. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o channel: the channel type. % % o kernel: An array of double representing the morphology kernel. % Warning: kernel may be normalized for the Convolve method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphologyImage(const Image *image, const MorphologyMethod method,const ssize_t iterations, const KernelInfo *kernel,ExceptionInfo *exception) { Image *morphology_image; morphology_image=MorphologyImageChannel(image,DefaultChannels,method, iterations,kernel,exception); return(morphology_image); } MagickExport Image *MorphologyImageChannel(const Image *image, const ChannelType channel,const MorphologyMethod method, const ssize_t iterations,const KernelInfo *kernel,ExceptionInfo *exception) { KernelInfo *curr_kernel; CompositeOperator compose; double bias; Image *morphology_image; /* Apply Convolve/Correlate Normalization and Scaling Factors. * This is done BEFORE the ShowKernelInfo() function is called so that * users can see the results of the 'option:convolve:scale' option. */ curr_kernel = (KernelInfo *) kernel; bias=image->bias; if ((method == ConvolveMorphology) || (method == CorrelateMorphology)) { const char *artifact; artifact = GetImageArtifact(image,"convolve:bias"); if (artifact != (const char *) NULL) bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0); artifact = GetImageArtifact(image,"convolve:scale"); if ( artifact != (const char *)NULL ) { if ( curr_kernel == kernel ) curr_kernel = CloneKernelInfo(kernel); if (curr_kernel == (KernelInfo *) NULL) { curr_kernel=DestroyKernelInfo(curr_kernel); return((Image *) NULL); } ScaleGeometryKernelInfo(curr_kernel, artifact); } } /* display the (normalized) kernel via stderr */ if ( IsMagickTrue(GetImageArtifact(image,"showkernel")) || IsMagickTrue(GetImageArtifact(image,"convolve:showkernel")) || IsMagickTrue(GetImageArtifact(image,"morphology:showkernel")) ) ShowKernelInfo(curr_kernel); /* Override the default handling of multi-kernel morphology results * If 'Undefined' use the default method * If 'None' (default for 'Convolve') re-iterate previous result * Otherwise merge resulting images using compose method given. * Default for 'HitAndMiss' is 'Lighten'. */ { const char *artifact; compose = UndefinedCompositeOp; /* use default for method */ artifact = GetImageArtifact(image,"morphology:compose"); if ( artifact != (const char *) NULL) compose = (CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,artifact); } /* Apply the Morphology */ morphology_image = MorphologyApply(image, channel, method, iterations, curr_kernel, compose, bias, exception); /* Cleanup and Exit */ if ( curr_kernel != kernel ) curr_kernel=DestroyKernelInfo(curr_kernel); return(morphology_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotateKernelInfo() rotates the kernel by the angle given. % % Currently it is restricted to 90 degree angles, of either 1D kernels % or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels. % It will ignore usless rotations for specific 'named' built-in kernels. % % The format of the RotateKernelInfo method is: % % void RotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is currently internal to this module only, but can be exported % to other modules if needed. */ static void RotateKernelInfo(KernelInfo *kernel, double angle) { /* angle the lower kernels first */ if ( kernel->next != (KernelInfo *) NULL) RotateKernelInfo(kernel->next, angle); /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical ** ** TODO: expand beyond simple 90 degree rotates, flips and flops */ /* Modulus the angle */ angle = fmod(angle, 360.0); if ( angle < 0 ) angle += 360.0; if ( 337.5 < angle || angle <= 22.5 ) return; /* Near zero angle - no change! - At least not at this time */ /* Handle special cases */ switch (kernel->type) { /* These built-in kernels are cylindrical kernels, rotating is useless */ case GaussianKernel: case DoGKernel: case LoGKernel: case DiskKernel: case PeaksKernel: case LaplacianKernel: case ChebyshevKernel: case ManhattanKernel: case EuclideanKernel: return; /* These may be rotatable at non-90 angles in the future */ /* but simply rotating them in multiples of 90 degrees is useless */ case SquareKernel: case DiamondKernel: case PlusKernel: case CrossKernel: return; /* These only allows a +/-90 degree rotation (by transpose) */ /* A 180 degree rotation is useless */ case BlurKernel: if ( 135.0 < angle && angle <= 225.0 ) return; if ( 225.0 < angle && angle <= 315.0 ) angle -= 180; break; default: break; } /* Attempt rotations by 45 degrees -- 3x3 kernels only */ if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 ) { if ( kernel->width == 3 && kernel->height == 3 ) { /* Rotate a 3x3 square by 45 degree angle */ double t = kernel->values[0]; kernel->values[0] = kernel->values[3]; kernel->values[3] = kernel->values[6]; kernel->values[6] = kernel->values[7]; kernel->values[7] = kernel->values[8]; kernel->values[8] = kernel->values[5]; kernel->values[5] = kernel->values[2]; kernel->values[2] = kernel->values[1]; kernel->values[1] = t; /* rotate non-centered origin */ if ( kernel->x != 1 || kernel->y != 1 ) { ssize_t x,y; x = (ssize_t) kernel->x-1; y = (ssize_t) kernel->y-1; if ( x == y ) x = 0; else if ( x == 0 ) x = -y; else if ( x == -y ) y = 0; else if ( y == 0 ) y = x; kernel->x = (ssize_t) x+1; kernel->y = (ssize_t) y+1; } angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */ kernel->angle = fmod(kernel->angle+45.0, 360.0); } else perror("Unable to rotate non-3x3 kernel by 45 degrees"); } if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 ) { if ( kernel->width == 1 || kernel->height == 1 ) { /* Do a transpose of a 1 dimensional kernel, ** which results in a fast 90 degree rotation of some type. */ ssize_t t; t = (ssize_t) kernel->width; kernel->width = kernel->height; kernel->height = (size_t) t; t = kernel->x; kernel->x = kernel->y; kernel->y = t; if ( kernel->width == 1 ) { angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else { angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */ kernel->angle = fmod(kernel->angle+270.0, 360.0); } } else if ( kernel->width == kernel->height ) { /* Rotate a square array of values by 90 degrees */ { register size_t i,j,x,y; register double *k,t; k=kernel->values; for( i=0, x=kernel->width-1; i<=x; i++, x--) for( j=0, y=kernel->height-1; j<y; j++, y--) { t = k[i+j*kernel->width]; k[i+j*kernel->width] = k[j+x*kernel->width]; k[j+x*kernel->width] = k[x+y*kernel->width]; k[x+y*kernel->width] = k[y+i*kernel->width]; k[y+i*kernel->width] = t; } } /* rotate the origin - relative to center of array */ { register ssize_t x,y; x = (ssize_t) (kernel->x*2-kernel->width+1); y = (ssize_t) (kernel->y*2-kernel->height+1); kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2; kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2; } angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else perror("Unable to rotate a non-square, non-linear kernel 90 degrees"); } if ( 135.0 < angle && angle <= 225.0 ) { /* For a 180 degree rotation - also know as a reflection * This is actually a very very common operation! * Basically all that is needed is a reversal of the kernel data! * And a reflection of the origon */ double t; register double *k; size_t i, j; k=kernel->values; for ( i=0, j=kernel->width*kernel->height-1; i<j; i++, j--) t=k[i], k[i]=k[j], k[j]=t; kernel->x = (ssize_t) kernel->width - kernel->x - 1; kernel->y = (ssize_t) kernel->height - kernel->y - 1; angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */ kernel->angle = fmod(kernel->angle+180.0, 360.0); } /* At this point angle should at least between -45 (315) and +45 degrees * In the future some form of non-orthogonal angled rotates could be * performed here, posibily with a linear kernel restriction. */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e G e o m e t r y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleGeometryKernelInfo() takes a geometry argument string, typically % provided as a "-set option:convolve:scale {geometry}" user setting, % and modifies the kernel according to the parsed arguments of that setting. % % The first argument (and any normalization flags) are passed to % ScaleKernelInfo() to scale/normalize the kernel. The second argument % is then passed to UnityAddKernelInfo() to add a scled unity kernel % into the scaled/normalized kernel. % % The format of the ScaleGeometryKernelInfo method is: % % void ScaleGeometryKernelInfo(KernelInfo *kernel, % const double scaling_factor,const MagickStatusType normalize_flags) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % o geometry: % The geometry string to parse, typically from the user provided % "-set option:convolve:scale {geometry}" setting. % */ MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel, const char *geometry) { GeometryFlags flags; GeometryInfo args; SetGeometryInfo(&args); flags = (GeometryFlags) ParseGeometry(geometry, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/ args.rho *= 0.01, args.sigma *= 0.01; if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */ args.rho = 1.0; if ( (flags & SigmaValue) == 0 ) args.sigma = 0.0; /* Scale/Normalize the input kernel */ ScaleKernelInfo(kernel, args.rho, flags); /* Add Unity Kernel, for blending with original */ if ( (flags & SigmaValue) != 0 ) UnityAddKernelInfo(kernel, args.sigma); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleKernelInfo() scales the given kernel list by the given amount, with or % without normalization of the sum of the kernel values (as per given flags). % % By default (no flags given) the values within the kernel is scaled % directly using given scaling factor without change. % % If either of the two 'normalize_flags' are given the kernel will first be % normalized and then further scaled by the scaling factor value given. % % Kernel normalization ('normalize_flags' given) is designed to ensure that % any use of the kernel scaling factor with 'Convolve' or 'Correlate' % morphology methods will fall into -1.0 to +1.0 range. Note that for % non-HDRI versions of IM this may cause images to have any negative results % clipped, unless some 'bias' is used. % % More specifically. Kernels which only contain positive values (such as a % 'Gaussian' kernel) will be scaled so that those values sum to +1.0, % ensuring a 0.0 to +1.0 output range for non-HDRI images. % % For Kernels that contain some negative values, (such as 'Sharpen' kernels) % the kernel will be scaled by the absolute of the sum of kernel values, so % that it will generally fall within the +/- 1.0 range. % % For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel % will be scaled by just the sum of the postive values, so that its output % range will again fall into the +/- 1.0 range. % % For special kernels designed for locating shapes using 'Correlate', (often % only containing +1 and -1 values, representing foreground/brackground % matching) a special normalization method is provided to scale the positive % values separately to those of the negative values, so the kernel will be % forced to become a zero-sum kernel better suited to such searches. % % WARNING: Correct normalization of the kernel assumes that the '*_range' % attributes within the kernel structure have been correctly set during the % kernels creation. % % NOTE: The values used for 'normalize_flags' have been selected specifically % to match the use of geometry options, so that '!' means NormalizeValue, '^' % means CorrelateNormalizeValue. All other GeometryFlags values are ignored. % % The format of the ScaleKernelInfo method is: % % void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor, % const MagickStatusType normalize_flags ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scaling_factor: % multiply all values (after normalization) by this factor if not % zero. If the kernel is normalized regardless of any flags. % % o normalize_flags: % GeometryFlags defining normalization method to use. % specifically: NormalizeValue, CorrelateNormalizeValue, % and/or PercentValue % */ MagickExport void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,const GeometryFlags normalize_flags) { register ssize_t i; register double pos_scale, neg_scale; /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags); /* Normalization of Kernel */ pos_scale = 1.0; if ( (normalize_flags&NormalizeValue) != 0 ) { if ( fabs(kernel->positive_range + kernel->negative_range) >= MagickEpsilon ) /* non-zero-summing kernel (generally positive) */ pos_scale = fabs(kernel->positive_range + kernel->negative_range); else /* zero-summing kernel */ pos_scale = kernel->positive_range; } /* Force kernel into a normalized zero-summing kernel */ if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) { pos_scale = ( fabs(kernel->positive_range) >= MagickEpsilon ) ? kernel->positive_range : 1.0; neg_scale = ( fabs(kernel->negative_range) >= MagickEpsilon ) ? -kernel->negative_range : 1.0; } else neg_scale = pos_scale; /* finialize scaling_factor for positive and negative components */ pos_scale = scaling_factor/pos_scale; neg_scale = scaling_factor/neg_scale; for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) if ( ! IsNaN(kernel->values[i]) ) kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale; /* convolution output range */ kernel->positive_range *= pos_scale; kernel->negative_range *= neg_scale; /* maximum and minimum values in kernel */ kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale; kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale; /* swap kernel settings if user's scaling factor is negative */ if ( scaling_factor < MagickEpsilon ) { double t; t = kernel->positive_range; kernel->positive_range = kernel->negative_range; kernel->negative_range = t; t = kernel->maximum; kernel->maximum = kernel->minimum; kernel->minimum = 1; } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h o w K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShowKernelInfo() outputs the details of the given kernel defination to % standard error, generally due to a users 'showkernel' option request. % % The format of the ShowKernel method is: % % void ShowKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickExport void ShowKernelInfo(const KernelInfo *kernel) { const KernelInfo *k; size_t c, i, u, v; for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) { (void) FormatLocaleFile(stderr, "Kernel"); if ( kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c ); (void) FormatLocaleFile(stderr, " \"%s", CommandOptionToMnemonic(MagickKernelOptions, k->type) ); if ( fabs(k->angle) >= MagickEpsilon ) (void) FormatLocaleFile(stderr, "@%lg", k->angle); (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long) k->width,(unsigned long) k->height,(long) k->x,(long) k->y); (void) FormatLocaleFile(stderr, " with values from %.*lg to %.*lg\n", GetMagickPrecision(), k->minimum, GetMagickPrecision(), k->maximum); (void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg", GetMagickPrecision(), k->negative_range, GetMagickPrecision(), k->positive_range); if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon ) (void) FormatLocaleFile(stderr, " (Zero-Summing)\n"); else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon ) (void) FormatLocaleFile(stderr, " (Normalized)\n"); else (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n", GetMagickPrecision(), k->positive_range+k->negative_range); for (i=v=0; v < k->height; v++) { (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v ); for (u=0; u < k->width; u++, i++) if ( IsNaN(k->values[i]) ) (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan"); else (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3, GetMagickPrecision(), k->values[i]); (void) FormatLocaleFile(stderr,"\n"); } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n i t y A d d K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel % to the given pre-scaled and normalized Kernel. This in effect adds that % amount of the original image into the resulting convolution kernel. This % value is usually provided by the user as a percentage value in the % 'convolve:scale' setting. % % The resulting effect is to convert the defined kernels into blended % soft-blurs, unsharp kernels or into sharpening kernels. % % The format of the UnityAdditionKernelInfo method is: % % void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scale: % scaling factor for the unity kernel to be added to % the given kernel. % */ MagickExport void UnityAddKernelInfo(KernelInfo *kernel, const double scale) { /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) UnityAddKernelInfo(kernel->next, scale); /* Add the scaled unity kernel to the existing kernel */ kernel->values[kernel->x+kernel->y*kernel->width] += scale; CalcKernelMetaData(kernel); /* recalculate the meta-data */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Z e r o K e r n e l N a n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroKernelNans() replaces any special 'nan' value that may be present in % the kernel with a zero value. This is typically done when the kernel will % be used in special hardware (GPU) convolution processors, to simply % matters. % % The format of the ZeroKernelNans method is: % % void ZeroKernelNans (KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickExport void ZeroKernelNans(KernelInfo *kernel) { register size_t i; /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) ZeroKernelNans(kernel->next); for (i=0; i < (kernel->width*kernel->height); i++) if ( IsNaN(kernel->values[i]) ) kernel->values[i] = 0.0; return; }
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 8; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4)); ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(0,ceild(16*t2-Nz+5,8)),t1),2*t1-2*t2+1);t3<=min(min(min(floord(4*Nt+Ny-9,8),floord(8*t1+Ny+7,8)),floord(16*t2+Ny+3,8)),floord(16*t1-16*t2+Nz+Ny+5,8));t3++) { for (t4=max(max(max(0,ceild(t1-127,128)),ceild(16*t2-Nz-1011,1024)),ceild(8*t3-Ny-1011,1024));t4<=min(min(min(min(floord(4*Nt+Nx-9,1024),floord(8*t1+Nx+7,1024)),floord(16*t2+Nx+3,1024)),floord(8*t3+Nx-5,1024)),floord(16*t1-16*t2+Nz+Nx+5,1024));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),2*t3),Nt-1),2*t1+3),4*t2+2),256*t4+254);t5++) { for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(1024*t4,4*t5+4); ubv=min(1024*t4+1023,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
__clang_cuda_complex_builtins.h
/*===-- __clang_cuda_complex_builtins - CUDA impls of runtime complex fns ---=== * * 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 * *===-----------------------------------------------------------------------=== */ #ifndef __CLANG_CUDA_COMPLEX_BUILTINS #define __CLANG_CUDA_COMPLEX_BUILTINS // This header defines __muldc3, __mulsc3, __divdc3, and __divsc3. These are // libgcc functions that clang assumes are available when compiling c99 complex // operations. (These implementations come from libc++, and have been modified // to work with CUDA and OpenMP target offloading [in C and C++ mode].) #pragma push_macro("__DEVICE__") #ifdef __OPENMP_NVPTX__ #pragma omp declare target #define __DEVICE__ __attribute__((noinline, nothrow, cold, weak)) #else #define __DEVICE__ __device__ inline #endif // To make the algorithms available for C and C++ in CUDA and OpenMP we select // different but equivalent function versions. TODO: For OpenMP we currently // select the native builtins as the overload support for templates is lacking. #if !defined(__OPENMP_NVPTX__) #define _ISNANd std::isnan #define _ISNANf std::isnan #define _ISINFd std::isinf #define _ISINFf std::isinf #define _ISFINITEd std::isfinite #define _ISFINITEf std::isfinite #define _COPYSIGNd std::copysign #define _COPYSIGNf std::copysign #define _SCALBNd std::scalbn #define _SCALBNf std::scalbn #define _ABSd std::abs #define _ABSf std::abs #define _LOGBd std::logb #define _LOGBf std::logb #else #define _ISNANd __nv_isnand #define _ISNANf __nv_isnanf #define _ISINFd __nv_isinfd #define _ISINFf __nv_isinff #define _ISFINITEd __nv_isfinited #define _ISFINITEf __nv_finitef #define _COPYSIGNd __nv_copysign #define _COPYSIGNf __nv_copysignf #define _SCALBNd __nv_scalbn #define _SCALBNf __nv_scalbnf #define _ABSd __nv_fabs #define _ABSf __nv_fabsf #define _LOGBd __nv_logb #define _LOGBf __nv_logbf #endif #if defined(__cplusplus) extern "C" { #endif __DEVICE__ double _Complex __muldc3(double __a, double __b, double __c, double __d) { double __ac = __a * __c; double __bd = __b * __d; double __ad = __a * __d; double __bc = __b * __c; double _Complex z; __real__(z) = __ac - __bd; __imag__(z) = __ad + __bc; if (_ISNANd(__real__(z)) && _ISNANd(__imag__(z))) { int __recalc = 0; if (_ISINFd(__a) || _ISINFd(__b)) { __a = _COPYSIGNd(_ISINFd(__a) ? 1 : 0, __a); __b = _COPYSIGNd(_ISINFd(__b) ? 1 : 0, __b); if (_ISNANd(__c)) __c = _COPYSIGNd(0, __c); if (_ISNANd(__d)) __d = _COPYSIGNd(0, __d); __recalc = 1; } if (_ISINFd(__c) || _ISINFd(__d)) { __c = _COPYSIGNd(_ISINFd(__c) ? 1 : 0, __c); __d = _COPYSIGNd(_ISINFd(__d) ? 1 : 0, __d); if (_ISNANd(__a)) __a = _COPYSIGNd(0, __a); if (_ISNANd(__b)) __b = _COPYSIGNd(0, __b); __recalc = 1; } if (!__recalc && (_ISINFd(__ac) || _ISINFd(__bd) || _ISINFd(__ad) || _ISINFd(__bc))) { if (_ISNANd(__a)) __a = _COPYSIGNd(0, __a); if (_ISNANd(__b)) __b = _COPYSIGNd(0, __b); if (_ISNANd(__c)) __c = _COPYSIGNd(0, __c); if (_ISNANd(__d)) __d = _COPYSIGNd(0, __d); __recalc = 1; } if (__recalc) { // Can't use std::numeric_limits<double>::infinity() -- that doesn't have // a device overload (and isn't constexpr before C++11, naturally). __real__(z) = __builtin_huge_val() * (__a * __c - __b * __d); __imag__(z) = __builtin_huge_val() * (__a * __d + __b * __c); } } return z; } __DEVICE__ float _Complex __mulsc3(float __a, float __b, float __c, float __d) { float __ac = __a * __c; float __bd = __b * __d; float __ad = __a * __d; float __bc = __b * __c; float _Complex z; __real__(z) = __ac - __bd; __imag__(z) = __ad + __bc; if (_ISNANf(__real__(z)) && _ISNANf(__imag__(z))) { int __recalc = 0; if (_ISINFf(__a) || _ISINFf(__b)) { __a = _COPYSIGNf(_ISINFf(__a) ? 1 : 0, __a); __b = _COPYSIGNf(_ISINFf(__b) ? 1 : 0, __b); if (_ISNANf(__c)) __c = _COPYSIGNf(0, __c); if (_ISNANf(__d)) __d = _COPYSIGNf(0, __d); __recalc = 1; } if (_ISINFf(__c) || _ISINFf(__d)) { __c = _COPYSIGNf(_ISINFf(__c) ? 1 : 0, __c); __d = _COPYSIGNf(_ISINFf(__d) ? 1 : 0, __d); if (_ISNANf(__a)) __a = _COPYSIGNf(0, __a); if (_ISNANf(__b)) __b = _COPYSIGNf(0, __b); __recalc = 1; } if (!__recalc && (_ISINFf(__ac) || _ISINFf(__bd) || _ISINFf(__ad) || _ISINFf(__bc))) { if (_ISNANf(__a)) __a = _COPYSIGNf(0, __a); if (_ISNANf(__b)) __b = _COPYSIGNf(0, __b); if (_ISNANf(__c)) __c = _COPYSIGNf(0, __c); if (_ISNANf(__d)) __d = _COPYSIGNf(0, __d); __recalc = 1; } if (__recalc) { __real__(z) = __builtin_huge_valf() * (__a * __c - __b * __d); __imag__(z) = __builtin_huge_valf() * (__a * __d + __b * __c); } } return z; } __DEVICE__ double _Complex __divdc3(double __a, double __b, double __c, double __d) { int __ilogbw = 0; // Can't use std::max, because that's defined in <algorithm>, and we don't // want to pull that in for every compile. The CUDA headers define // ::max(float, float) and ::max(double, double), which is sufficient for us. double __logbw = _LOGBd(max(_ABSd(__c), _ABSd(__d))); if (_ISFINITEd(__logbw)) { __ilogbw = (int)__logbw; __c = _SCALBNd(__c, -__ilogbw); __d = _SCALBNd(__d, -__ilogbw); } double __denom = __c * __c + __d * __d; double _Complex z; __real__(z) = _SCALBNd((__a * __c + __b * __d) / __denom, -__ilogbw); __imag__(z) = _SCALBNd((__b * __c - __a * __d) / __denom, -__ilogbw); if (_ISNANd(__real__(z)) && _ISNANd(__imag__(z))) { if ((__denom == 0.0) && (!_ISNANd(__a) || !_ISNANd(__b))) { __real__(z) = _COPYSIGNd(__builtin_huge_val(), __c) * __a; __imag__(z) = _COPYSIGNd(__builtin_huge_val(), __c) * __b; } else if ((_ISINFd(__a) || _ISINFd(__b)) && _ISFINITEd(__c) && _ISFINITEd(__d)) { __a = _COPYSIGNd(_ISINFd(__a) ? 1.0 : 0.0, __a); __b = _COPYSIGNd(_ISINFd(__b) ? 1.0 : 0.0, __b); __real__(z) = __builtin_huge_val() * (__a * __c + __b * __d); __imag__(z) = __builtin_huge_val() * (__b * __c - __a * __d); } else if (_ISINFd(__logbw) && __logbw > 0.0 && _ISFINITEd(__a) && _ISFINITEd(__b)) { __c = _COPYSIGNd(_ISINFd(__c) ? 1.0 : 0.0, __c); __d = _COPYSIGNd(_ISINFd(__d) ? 1.0 : 0.0, __d); __real__(z) = 0.0 * (__a * __c + __b * __d); __imag__(z) = 0.0 * (__b * __c - __a * __d); } } return z; } __DEVICE__ float _Complex __divsc3(float __a, float __b, float __c, float __d) { int __ilogbw = 0; float __logbw = _LOGBf(max(_ABSf(__c), _ABSf(__d))); if (_ISFINITEf(__logbw)) { __ilogbw = (int)__logbw; __c = _SCALBNf(__c, -__ilogbw); __d = _SCALBNf(__d, -__ilogbw); } float __denom = __c * __c + __d * __d; float _Complex z; __real__(z) = _SCALBNf((__a * __c + __b * __d) / __denom, -__ilogbw); __imag__(z) = _SCALBNf((__b * __c - __a * __d) / __denom, -__ilogbw); if (_ISNANf(__real__(z)) && _ISNANf(__imag__(z))) { if ((__denom == 0) && (!_ISNANf(__a) || !_ISNANf(__b))) { __real__(z) = _COPYSIGNf(__builtin_huge_valf(), __c) * __a; __imag__(z) = _COPYSIGNf(__builtin_huge_valf(), __c) * __b; } else if ((_ISINFf(__a) || _ISINFf(__b)) && _ISFINITEf(__c) && _ISFINITEf(__d)) { __a = _COPYSIGNf(_ISINFf(__a) ? 1 : 0, __a); __b = _COPYSIGNf(_ISINFf(__b) ? 1 : 0, __b); __real__(z) = __builtin_huge_valf() * (__a * __c + __b * __d); __imag__(z) = __builtin_huge_valf() * (__b * __c - __a * __d); } else if (_ISINFf(__logbw) && __logbw > 0 && _ISFINITEf(__a) && _ISFINITEf(__b)) { __c = _COPYSIGNf(_ISINFf(__c) ? 1 : 0, __c); __d = _COPYSIGNf(_ISINFf(__d) ? 1 : 0, __d); __real__(z) = 0 * (__a * __c + __b * __d); __imag__(z) = 0 * (__b * __c - __a * __d); } } return z; } #if defined(__cplusplus) } // extern "C" #endif #undef _ISNANd #undef _ISNANf #undef _ISINFd #undef _ISINFf #undef _COPYSIGNd #undef _COPYSIGNf #undef _ISFINITEd #undef _ISFINITEf #undef _SCALBNd #undef _SCALBNf #undef _ABSd #undef _ABSf #undef _LOGBd #undef _LOGBf #ifdef __OPENMP_NVPTX__ #pragma omp end declare target #endif #pragma pop_macro("__DEVICE__") #endif // __CLANG_CUDA_COMPLEX_BUILTINS
pwsafe_fmt_plug.c
/* Password Safe and Password Gorilla cracker patch for JtR. Hacked together * during May of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>. * * Optimization patch during January of 2013 by Brian Wallace <brian.wallace9809 at gmail.com>. * * This software is Copyright (c) 2012-2013 * Dhiru Kholia <dhiru.kholia at gmail.com> and Brian Wallace <brian.wallace9809 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. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_pwsafe; #elif FMT_REGISTERS_H john_register_one(&fmt_pwsafe); #else #include <string.h> #include <assert.h> #include <errno.h> #include "arch.h" //#undef SIMD_COEF_32 #include "sha2.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "johnswap.h" #include "simd-intrinsics.h" #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 // tuned on core i7 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "pwsafe" #define FORMAT_NAME "Password Safe" #define FORMAT_TAG "$pwsafe$*" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "SHA256 " SHA256_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 32 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN sizeof(uint32_t) #define SALT_ALIGN sizeof(int) #ifdef SIMD_COEF_32 #define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (3-((i)&3)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32*4 ) #define MIN_KEYS_PER_CRYPT (SIMD_COEF_32*SIMD_PARA_SHA256) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_32*SIMD_PARA_SHA256) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests pwsafe_tests[] = { {"$pwsafe$*3*fefc1172093344c9d5577b25f5b4b6e5d2942c94f9fc24c21733e28ae6527521*2048*88cbaf7d8668c1a98263f5dce7cb39c3304c49a3e0d76a7ea475dc02ab2f97a7", "12345678"}, {"$pwsafe$*3*581cd1135b9b993ccb0f6b01c1fcfacd799c69960496c96286f94fe1400c1b25*2048*4ab3c2d3af251e94eb2f753fdf30fb9da074bec6bac0fa9d9d152b95fc5795c6", "openwall"}, {"$pwsafe$*3*34ba0066d0fc594c126b60b9db98b6024e1cf585901b81b5b005ce386f173d4c*2048*cc86f1a5d930ff19b3602770a86586b5d9dea7bb657012aca875aa2a7dc71dc0", "12345678901234567890123"}, {"$pwsafe$*3*a42431191707895fb8d1121a3a6e255e33892d8eecb50fc616adab6185b5affb*2048*0f71d12df2b7c5394ae90771f6475a7ad0437007a8eeb5d9b58e35d8fd57c827", "123456789012345678901234567"}, {"$pwsafe$*3*c380dee0dbb536f5454f78603b020be76b33e294e9c2a0e047f43b9c61669fc8*2048*e88ed54a85e419d555be219d200563ae3ba864e24442826f412867fc0403917d", "this is an 87 character password to test the max bound of pwsafe-opencl................"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static struct custom_salt { int version; unsigned int iterations; unsigned char salt[32]; } *cur_salt; 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(sizeof(*saved_key), self->params.max_keys_per_crypt); crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { // format $pwsafe$version*salt*iterations*hash char *p; char *ctcopy; char *keeptr; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += FORMAT_TAG_LEN; /* skip over "$pwsafe$*" */ if ((p = strtokm(ctcopy, "*")) == NULL) /* version */ goto err; if (!isdec(p)) goto err; if (!atoi(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt */ goto err; if (strlen(p) < 64) goto err; if (strspn(p, HEXCHARS_lc) != 64) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iterations */ goto err; if (!isdec(p)) goto err; if (!atoi(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* hash */ goto err; if (strlen(p) != 64) goto err; if (strspn(p, HEXCHARS_lc) != 64) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int i; static struct custom_salt cs; ctcopy += FORMAT_TAG_LEN; /* skip over "$pwsafe$*" */ p = strtokm(ctcopy, "*"); cs.version = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.iterations = (unsigned int)atoi(p); MEM_FREE(keeptr); return (void *)&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; p = strrchr(ciphertext, '*') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } #ifndef SIMD_COEF_32 #define rotl(x,y) ( x<<y | x>>(32-y) ) #define rotr(x,y) ( x>>y | x<<(32-y) ) #define CHOICE(x,y,z) ( z ^ (x & ( y ^ z)) ) #define MAJORITY(x,y,z) ( (x & y) | (z & (x | y)) ) #define ROTXOR1(x) (rotr(x,2) ^ rotr(x,13) ^ rotr(x,22)) #define ROTXOR2(x) (rotr(x,6) ^ rotr(x,11) ^ rotr(x,25)) #define ROTXOR3(x) (rotr(x,7) ^ rotr(x,18) ^ (x>>3)) #define ROTXOR4(x) (rotr(x,17) ^ rotr(x,19) ^ (x>>10)) #if ARCH_LITTLE_ENDIAN #define bytereverse(x) ( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) ) #else #define bytereverse(x) (x) #endif static void pwsafe_sha256_iterate(unsigned int * state, unsigned int iterations) { unsigned int word00,word01,word02,word03,word04,word05,word06,word07; unsigned int word08,word09,word10,word11,word12,word13,word14,word15; unsigned int temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7; iterations++; word00 = state[0]; word01 = state[1]; word02 = state[2]; word03 = state[3]; word04 = state[4]; word05 = state[5]; word06 = state[6]; word07 = state[7]; while(iterations) { iterations--; temp0 = 0x6a09e667UL; temp1 = 0xbb67ae85UL; temp2 = 0x3c6ef372UL; temp3 = 0xa54ff53aUL; temp4 = 0x510e527fUL; temp5 = 0x9b05688cUL; temp6 = 0x1f83d9abUL; temp7 = 0x5be0cd19UL; temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0x428a2f98 + (word00); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0x71374491 + (word01); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0xb5c0fbcf + (word02); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0xe9b5dba5 + (word03); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0x3956c25b + (word04); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0x59f111f1 + (word05); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0x923f82a4 + (word06); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0xab1c5ed5 + (word07); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0xd807aa98 + ( (word08 = 0x80000000U) ); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0x12835b01 + ( (word09 = 0) ); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0x243185be + ( (word10 = 0) ); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0x550c7dc3 + ( (word11 = 0) ); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0x72be5d74 + ( (word12 = 0) ); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0x80deb1fe + ( (word13 = 0) ); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0x9bdc06a7 + ( (word14 = 0) ); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0xc19bf174 + ( (word15 = 256) ); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0xe49b69c1 + ( (word00 += ROTXOR4( word14 ) + word09 + ROTXOR3( word01 ) ) ); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0xefbe4786 + ( (word01 += ROTXOR4( word15 ) + word10 + ROTXOR3( word02 ) ) ); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0x0fc19dc6 + ( (word02 += ROTXOR4( word00 ) + word11 + ROTXOR3( word03 ) ) ); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0x240ca1cc + ( (word03 += ROTXOR4( word01 ) + word12 + ROTXOR3( word04 ) ) ); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0x2de92c6f + ( (word04 += ROTXOR4( word02 ) + word13 + ROTXOR3( word05 ) ) ); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0x4a7484aa + ( (word05 += ROTXOR4( word03 ) + word14 + ROTXOR3( word06 ) ) ); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0x5cb0a9dc + ( (word06 += ROTXOR4( word04 ) + word15 + ROTXOR3( word07 ) ) ); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0x76f988da + ( (word07 += ROTXOR4( word05 ) + word00 + ROTXOR3( word08 ) ) ); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0x983e5152 + ( (word08 += ROTXOR4( word06 ) + word01 + ROTXOR3( word09 ) ) ); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0xa831c66d + ( (word09 += ROTXOR4( word07 ) + word02 + ROTXOR3( word10 ) ) ); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0xb00327c8 + ( (word10 += ROTXOR4( word08 ) + word03 + ROTXOR3( word11 ) ) ); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0xbf597fc7 + ( (word11 += ROTXOR4( word09 ) + word04 + ROTXOR3( word12 ) ) ); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0xc6e00bf3 + ( (word12 += ROTXOR4( word10 ) + word05 + ROTXOR3( word13 ) ) ); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0xd5a79147 + ( (word13 += ROTXOR4( word11 ) + word06 + ROTXOR3( word14 ) ) ); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0x06ca6351 + ( (word14 += ROTXOR4( word12 ) + word07 + ROTXOR3( word15 ) ) ); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0x14292967 + ( (word15 += ROTXOR4( word13 ) + word08 + ROTXOR3( word00 ) ) ); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0x27b70a85 + ( (word00 += ROTXOR4( word14 ) + word09 + ROTXOR3( word01 ) ) ); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0x2e1b2138 + ( (word01 += ROTXOR4( word15 ) + word10 + ROTXOR3( word02 ) ) ); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0x4d2c6dfc + ( (word02 += ROTXOR4( word00 ) + word11 + ROTXOR3( word03 ) ) ); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0x53380d13 + ( (word03 += ROTXOR4( word01 ) + word12 + ROTXOR3( word04 ) ) ); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0x650a7354 + ( (word04 += ROTXOR4( word02 ) + word13 + ROTXOR3( word05 ) ) ); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0x766a0abb + ( (word05 += ROTXOR4( word03 ) + word14 + ROTXOR3( word06 ) ) ); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0x81c2c92e + ( (word06 += ROTXOR4( word04 ) + word15 + ROTXOR3( word07 ) ) ); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0x92722c85 + ( (word07 += ROTXOR4( word05 ) + word00 + ROTXOR3( word08 ) ) ); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0xa2bfe8a1 + ( (word08 += ROTXOR4( word06 ) + word01 + ROTXOR3( word09 ) ) ); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0xa81a664b + ( (word09 += ROTXOR4( word07 ) + word02 + ROTXOR3( word10 ) ) ); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0xc24b8b70 + ( (word10 += ROTXOR4( word08 ) + word03 + ROTXOR3( word11 ) ) ); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0xc76c51a3 + ( (word11 += ROTXOR4( word09 ) + word04 + ROTXOR3( word12 ) ) ); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0xd192e819 + ( (word12 += ROTXOR4( word10 ) + word05 + ROTXOR3( word13 ) ) ); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0xd6990624 + ( (word13 += ROTXOR4( word11 ) + word06 + ROTXOR3( word14 ) ) ); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0xf40e3585 + ( (word14 += ROTXOR4( word12 ) + word07 + ROTXOR3( word15 ) ) ); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0x106aa070 + ( (word15 += ROTXOR4( word13 ) + word08 + ROTXOR3( word00 ) ) ); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0x19a4c116 + ( (word00 += ROTXOR4( word14 ) + word09 + ROTXOR3( word01 ) ) ); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0x1e376c08 + ( (word01 += ROTXOR4( word15 ) + word10 + ROTXOR3( word02 ) ) ); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0x2748774c + ( (word02 += ROTXOR4( word00 ) + word11 + ROTXOR3( word03 ) ) ); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0x34b0bcb5 + ( (word03 += ROTXOR4( word01 ) + word12 + ROTXOR3( word04 ) ) ); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0x391c0cb3 + ( (word04 += ROTXOR4( word02 ) + word13 + ROTXOR3( word05 ) ) ); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0x4ed8aa4a + ( (word05 += ROTXOR4( word03 ) + word14 + ROTXOR3( word06 ) ) ); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0x5b9cca4f + ( (word06 += ROTXOR4( word04 ) + word15 + ROTXOR3( word07 ) ) ); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0x682e6ff3 + ( (word07 += ROTXOR4( word05 ) + word00 + ROTXOR3( word08 ) ) ); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); temp7 += ROTXOR2( temp4 ) + CHOICE( temp4, temp5, temp6 ) + 0x748f82ee + ( (word08 += ROTXOR4( word06 ) + word01 + ROTXOR3( word09 ) ) ); temp3 += temp7; temp7 += ROTXOR1( temp0 ) + MAJORITY( temp0, temp1, temp2 ); temp6 += ROTXOR2( temp3 ) + CHOICE( temp3, temp4, temp5 ) + 0x78a5636f + ( (word09 += ROTXOR4( word07 ) + word02 + ROTXOR3( word10 ) ) ); temp2 += temp6; temp6 += ROTXOR1( temp7 ) + MAJORITY( temp7, temp0, temp1 ); temp5 += ROTXOR2( temp2 ) + CHOICE( temp2, temp3, temp4 ) + 0x84c87814 + ( (word10 += ROTXOR4( word08 ) + word03 + ROTXOR3( word11 ) ) ); temp1 += temp5; temp5 += ROTXOR1( temp6 ) + MAJORITY( temp6, temp7, temp0 ); temp4 += ROTXOR2( temp1 ) + CHOICE( temp1, temp2, temp3 ) + 0x8cc70208 + ( (word11 += ROTXOR4( word09 ) + word04 + ROTXOR3( word12 ) ) ); temp0 += temp4; temp4 += ROTXOR1( temp5 ) + MAJORITY( temp5, temp6, temp7 ); temp3 += ROTXOR2( temp0 ) + CHOICE( temp0, temp1, temp2 ) + 0x90befffa + ( (word12 += ROTXOR4( word10 ) + word05 + ROTXOR3( word13 ) ) ); temp7 += temp3; temp3 += ROTXOR1( temp4 ) + MAJORITY( temp4, temp5, temp6 ); temp2 += ROTXOR2( temp7 ) + CHOICE( temp7, temp0, temp1 ) + 0xa4506ceb + ( (word13 += ROTXOR4( word11 ) + word06 + ROTXOR3( word14 ) ) ); temp6 += temp2; temp2 += ROTXOR1( temp3 ) + MAJORITY( temp3, temp4, temp5 ); temp1 += ROTXOR2( temp6 ) + CHOICE( temp6, temp7, temp0 ) + 0xbef9a3f7 + ( (word14 += ROTXOR4( word12 ) + word07 + ROTXOR3( word15 ) ) ); temp5 += temp1; temp1 += ROTXOR1( temp2 ) + MAJORITY( temp2, temp3, temp4 ); temp0 += ROTXOR2( temp5 ) + CHOICE( temp5, temp6, temp7 ) + 0xc67178f2 + ( (word15 += ROTXOR4( word13 ) + word08 + ROTXOR3( word00 ) ) ); temp4 += temp0; temp0 += ROTXOR1( temp1 ) + MAJORITY( temp1, temp2, temp3 ); word00 = 0x6a09e667UL + temp0; word01 = 0xbb67ae85UL + temp1; word02 = 0x3c6ef372UL + temp2; word03 = 0xa54ff53aUL + temp3; word04 = 0x510e527fUL + temp4; word05 = 0x9b05688cUL + temp5; word06 = 0x1f83d9abUL + temp6; word07 = 0x5be0cd19UL + temp7; } state[0] = bytereverse(word00); state[1] = bytereverse(word01); state[2] = bytereverse(word02); state[3] = bytereverse(word03); state[4] = bytereverse(word04); state[5] = bytereverse(word05); state[6] = bytereverse(word06); state[7] = bytereverse(word07); } #endif static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index+=MAX_KEYS_PER_CRYPT) { SHA256_CTX ctx; #ifdef SIMD_COEF_32 unsigned int i; unsigned char _IBuf[64*MAX_KEYS_PER_CRYPT+MEM_ALIGN_CACHE], *keys, tmpBuf[32]; uint32_t *keys32, j; keys = (unsigned char*)mem_align(_IBuf, MEM_ALIGN_CACHE); keys32 = (uint32_t*)keys; memset(keys, 0, 64*MAX_KEYS_PER_CRYPT); for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { SHA256_Init(&ctx); SHA256_Update(&ctx, saved_key[index+i], strlen(saved_key[index+i])); SHA256_Update(&ctx, cur_salt->salt, 32); SHA256_Final(tmpBuf, &ctx); for (j = 0; j < 32; ++j) keys[GETPOS(j, i)] = tmpBuf[j]; keys[GETPOS(j, i)] = 0x80; // 32 bytes of crypt data (0x100 bits). keys[GETPOS(62, i)] = 0x01; } for (i = 0; i < cur_salt->iterations; i++) { SIMDSHA256body(keys, keys32, NULL, SSEi_MIXED_IN|SSEi_OUTPUT_AS_INP_FMT); } // Last one with FLAT_OUT SIMDSHA256body(keys, crypt_out[index], NULL, SSEi_MIXED_IN|SSEi_OUTPUT_AS_INP_FMT|SSEi_FLAT_OUT); #else SHA256_Init(&ctx); SHA256_Update(&ctx, saved_key[index], strlen(saved_key[index])); SHA256_Update(&ctx, cur_salt->salt, 32); SHA256_Final((unsigned char*)crypt_out[index], &ctx); #if 1 // This complex crap only boosted speed on my quad-HT from 5016 to 5285. // A ton of complex code for VERY little gain. The SIMD change gave us // a 4x improvement with very little change. This pwsafe_sha256_iterate // does get 5% gain, but 400% is so much better, lol. I put the other // code in to be able to dump data out easier, getting dump_stuff() // data in flat, to be able to help get the SIMD code working. #ifdef COMMON_DIGEST_FOR_OPENSSL pwsafe_sha256_iterate(ctx.hash, cur_salt->iterations); memcpy(crypt_out[index], ctx.hash, 32); #else pwsafe_sha256_iterate(ctx.h, cur_salt->iterations); memcpy(crypt_out[index], ctx.h, 32); #endif #else { int i; for (i = 0; i <= cur_salt->iterations; ++i) { SHA256_Init(&ctx); SHA256_Update(&ctx, (unsigned char*)crypt_out[index], 32); SHA256_Final((unsigned char*)crypt_out[index], &ctx); } } #endif #endif } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void pwsafe_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 unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->iterations; } struct fmt_main fmt_pwsafe = { { 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, { "iteration count", }, { FORMAT_TAG }, pwsafe_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { iteration_count, }, 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, pwsafe_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 */
oskar_dftw_o2c_2d_omp.c
/* * Copyright (c) 2013, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford 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 "math/oskar_dftw_o2c_2d_omp.h" #include <math.h> #ifdef __cplusplus extern "C" { #endif #if 0 /* Single precision. */ void oskar_dftw_o2c_2d_omp_f(const int n_in, const float wavenumber, const float* x_in, const float* y_in, const float2* weights_in, const int n_out, const float* x_out, const float* y_out, float2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; float xp_out, yp_out; float2 out, out_c, out_cnt, out_new; /* Clear output value. */ out.x = 0.0f; out.y = 0.0f; out_c.x = 0.0f; out_c.y = 0.0f; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { float signal_x, signal_y; /* Calculate the phase for the output position. */ { float a; a = xp_out * x_in[i] + yp_out * y_in[i]; signal_x = cos(a); signal_y = sin(a); } /* Perform complex multiply-accumulate using Kahan summation. */ { float2 w, r; w = weights_in[i]; r.x = signal_x * w.x - signal_y * w.y; r.y = signal_x * w.y + signal_y * w.x; out_cnt.x = r.x - out_c.x; out_new.x = out.x + out_cnt.x; out_c.x = (out_new.x - out.x) - out_cnt.x; out.x = out_new.x; out_cnt.y = r.y - out_c.y; out_new.y = out.y + out_cnt.y; out_c.y = (out_new.y - out.y) - out_cnt.y; out.y = out_new.y; } } /* Store the output point. */ output[i_out] = out; } } #endif /* Single precision. */ void oskar_dftw_o2c_2d_omp_f(const int n_in, const float wavenumber, const float* x_in, const float* y_in, const float2* weights_in, const int n_out, const float* x_out, const float* y_out, float2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; float xp_out, yp_out; float2 out; /* Clear output value. */ out.x = 0.0f; out.y = 0.0f; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { float signal_x, signal_y; /* Calculate the phase for the output position. */ { float a; a = xp_out * x_in[i] + yp_out * y_in[i]; signal_x = cosf(a); signal_y = sinf(a); } /* Perform complex multiply-accumulate. */ { float2 w; w = weights_in[i]; out.x += signal_x * w.x; out.x -= signal_y * w.y; out.y += signal_y * w.x; out.y += signal_x * w.y; } } /* Store the output point. */ output[i_out] = out; } } /* Double precision. */ void oskar_dftw_o2c_2d_omp_d(const int n_in, const double wavenumber, const double* x_in, const double* y_in, const double2* weights_in, const int n_out, const double* x_out, const double* y_out, double2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; double xp_out, yp_out; double2 out; /* Clear output value. */ out.x = 0.0; out.y = 0.0; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { double signal_x, signal_y; /* Calculate the phase for the output position. */ { double a; a = xp_out * x_in[i] + yp_out * y_in[i]; signal_x = cos(a); signal_y = sin(a); } /* Perform complex multiply-accumulate. */ { double2 w; w = weights_in[i]; out.x += signal_x * w.x; out.x -= signal_y * w.y; out.y += signal_y * w.x; out.y += signal_x * w.y; } } /* Store the output point. */ output[i_out] = out; } } #ifdef __cplusplus } #endif
GB_binop__isgt_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__isgt_uint32) // A.*B function (eWiseMult): GB (_AemultB_01__isgt_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__isgt_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__isgt_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isgt_uint32) // A*D function (colscale): GB (_AxD__isgt_uint32) // D*A function (rowscale): GB (_DxB__isgt_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__isgt_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__isgt_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isgt_uint32) // C=scalar+B GB (_bind1st__isgt_uint32) // C=scalar+B' GB (_bind1st_tran__isgt_uint32) // C=A+scalar GB (_bind2nd__isgt_uint32) // C=A'+scalar GB (_bind2nd_tran__isgt_uint32) // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,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_ISGT || GxB_NO_UINT32 || GxB_NO_ISGT_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__isgt_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isgt_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isgt_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isgt_uint32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isgt_uint32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isgt_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__isgt_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isgt_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__isgt_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isgt_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isgt_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_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__isgt_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = 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) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB (_bind1st_tran__isgt_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij > y) ; \ } GrB_Info GB (_bind2nd_tran__isgt_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
test_vadd_2.c
#include <stdio.h> #include <stdlib.h> #include <assert.h> #ifdef _OPENMP #include <omp.h> #endif #define RESTRICT double vdiff(int n, const float * RESTRICT a, const float * RESTRICT b) { double d = 0.0; for(int i = 0; i < n; i++) { d += (a[i] - b[i]); } return d; } void vadd0(int n, float * RESTRICT a, float * RESTRICT b, float * RESTRICT c) { for(int i = 0; i < n; i++) c[i] = a[i] + b[i]; } void vadd1(int n, float * RESTRICT a, float * RESTRICT b, float * RESTRICT c) { #if defined(_OPENMP) && (_OPENMP >= 201307) #pragma omp parallel for simd #elif defined(_OPENMP) #warning No OpenMP simd support! #pragma omp parallel for #else #warning No OpenMP support! #endif for(int i = 0; i < n; i++) c[i] = a[i] + b[i]; } void vadd2(int n, float * RESTRICT a, float * RESTRICT b, float * RESTRICT c) { #if defined(_OPENMP) && (_OPENMP >= 201307) //#pragma omp target teams distribute map(to:n,a[0:n],b[0:n]) map(from:c[0:n]) #pragma omp target map(to:n,a[0:n],b[0:n]) map(from:c[0:n]) #pragma omp parallel for simd #else #warning No OpenMP target/simd support! #pragma omp parallel for #endif for(int i = 0; i < n; i++) c[i] = a[i] + b[i]; } int main(int argc, char * argv[]) { int n = (argc > 1 ) ? atoi(argv[1]) : 1000; float * x = calloc(n,sizeof(float)); assert(x !=NULL); float * y = calloc(n,sizeof(float)); assert(y !=NULL); float * z0 = calloc(n,sizeof(float)); assert(z0!=NULL); float * z1 = calloc(n,sizeof(float)); assert(z1!=NULL); float * z2 = calloc(n,sizeof(float)); assert(z2!=NULL); #if 0 && defined(_OPENMP) && (_OPENMP >= 201307) int nthrd = omp_get_max_threads(); int ndevs = omp_get_num_devices(); printf("OpenMP threads = %d devices = %d\n", nthrd, ndevs); #endif for (int i=0; i<n; i++) { x[i] = (float)i; } for (int i=0; i<n; i++) { y[i] = (float)i; } for (int iter=0; iter<10; iter++) { double t0 = omp_get_wtime(); vadd0(n,x,y,z0); double t1 = omp_get_wtime(); vadd1(n,x,y,z1); double t2 = omp_get_wtime(); vadd2(n,x,y,z2); double t3 = omp_get_wtime(); printf("%20s time = %lf \n", "for", t1-t0); printf("%20s time = %lf (error=%lf) \n", "OpenMP for", t2-t1, vdiff(n,z0,z1)); printf("%20s time = %lf (error=%lf) \n", "OpenMP offload for", t3-t2, vdiff(n,z0,z2)); /* prevent compiler from optimizing away anything */ double junk = t0+t1+t2+t3; for (int i=0; i<n; i++) { junk += z0[i] + z1[i] + z2[i]; } printf("junk=%lf\n", junk); } free(z2); free(z1); free(z0); free(y); free(x); printf("Success\n"); return 0; }
sections_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify %s void foo(); // expected-error@+1 {{unexpected OpenMP directive '#pragma omp sections'}} #pragma omp sections // expected-error@+1 {{unexpected OpenMP directive '#pragma omp sections'}} #pragma omp sections foo void test_no_clause() { int i; #pragma omp sections { foo(); } // expected-error@+2 {{the statement for '#pragma omp sections' must be a compound statement}} #pragma omp sections ++i; #pragma omp sections { foo(); foo(); // expected-error {{statement in 'omp sections' directive must be enclosed into a section region}} } } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp parallel #pragma omp sections { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } #pragma omp section if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L3; else if (i == 8) { L3: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; goto L3; // expected-error {{use of undeclared label 'L3'}} } void test_invalid_clause() { int i; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp sections' are ignored}} #pragma omp sections foo bar { foo(); // expected-error@+1 {{unexpected OpenMP clause 'nowait' in directive '#pragma omp section'}} #pragma omp section nowait ; } } void test_non_identifiers() { int i, x; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp sections' are ignored}} #pragma omp sections; { foo(); } #pragma omp parallel // expected-error@+2 {{unexpected OpenMP clause 'linear' in directive '#pragma omp sections'}} // expected-warning@+1 {{extra tokens at the end of '#pragma omp sections' are ignored}} #pragma omp sections linear(x); { foo(); } #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp sections' are ignored}} #pragma omp sections private(x); { foo(); } #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp sections' are ignored}} #pragma omp sections, private(x); { foo(); } } void test_private() { int i; #pragma omp parallel // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp sections private( { foo(); } #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp sections private(, { foo(); } #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp sections private(, ) { foo(); } #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp sections private() { foo(); } #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp sections private(int) { foo(); } #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp sections private(0) { foo(); } int x, y, z; #pragma omp parallel #pragma omp sections private(x) { foo(); } #pragma omp parallel #pragma omp sections private(x, y) { foo(); } #pragma omp parallel #pragma omp sections private(x, y, z) { foo(); } } void test_lastprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp sections lastprivate( { foo(); } #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp sections lastprivate(, { foo(); } #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp sections lastprivate(, ) { foo(); } #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp sections lastprivate() { foo(); } #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp sections lastprivate(int) { foo(); } #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp sections lastprivate(0) { foo(); } int x, y, z; #pragma omp parallel #pragma omp sections lastprivate(x) { foo(); } #pragma omp parallel #pragma omp sections lastprivate(x, y) { foo(); } #pragma omp parallel #pragma omp sections lastprivate(x, y, z) { foo(); } } void test_firstprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp sections firstprivate( { foo(); } #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp sections firstprivate(, { foo(); } #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp sections firstprivate(, ) { foo(); } #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp sections firstprivate() { foo(); } #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp sections firstprivate(int) { foo(); } #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp sections firstprivate(0) { foo(); } int x, y, z; #pragma omp parallel #pragma omp sections lastprivate(x) firstprivate(x) { foo(); } #pragma omp parallel #pragma omp sections lastprivate(x, y) firstprivate(x, y) { foo(); } #pragma omp parallel #pragma omp sections lastprivate(x, y, z) firstprivate(x, y, z) { foo(); } } void test_nowait() { #pragma omp parallel #pragma omp sections nowait nowait // expected-error {{directive '#pragma omp sections' cannot contain more than one 'nowait' clause}} { ; } }
GB_binop__rminus_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__rminus_uint64 // A.*B function (eWiseMult): GB_AemultB__rminus_uint64 // A*D function (colscale): GB_AxD__rminus_uint64 // D*A function (rowscale): GB_DxB__rminus_uint64 // C+=B function (dense accum): GB_Cdense_accumB__rminus_uint64 // C+=b function (dense accum): GB_Cdense_accumb__rminus_uint64 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rminus_uint64 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rminus_uint64 // C=scalar+B GB_bind1st__rminus_uint64 // C=scalar+B' GB_bind1st_tran__rminus_uint64 // C=A+scalar GB_bind2nd__rminus_uint64 // C=A'+scalar GB_bind2nd_tran__rminus_uint64 // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (y - x) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RMINUS || GxB_NO_UINT64 || GxB_NO_RMINUS_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__rminus_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__rminus_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__rminus_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__rminus_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__rminus_uint64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__rminus_uint64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__rminus_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__rminus_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__rminus_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t bij = Bx [p] ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__rminus_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; Cx [p] = (y - aij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB_bind1st_tran__rminus_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB_bind2nd_tran__rminus_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
header-brisbane.h
//-------------------------------------------------------------------------// // // // This benchmark is a serial C version of the NPB SP code. This C // // version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the serial Fortran versions in // // "NPB3.3-SER" 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 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 // //-------------------------------------------------------------------------// //--------------------------------------------------------------------- // The following include file is generated automatically by the // "setparams" utility. It defines // problem_size: 12, 64, 102, 162 (for class T, A, B, C) // dt_default: default time step for this problem size if no // config file // niter_default: default number of iterations for this problem size //--------------------------------------------------------------------- #include <brisbane/brisbane.h> #include "npbparams.h" #include "type.h" #include <stdio.h> /* common /global/ */ #pragma omp declare target extern int grid_points[3], nx2, ny2, nz2; #pragma omp end declare target extern int timeron; /* common /constants/ */ extern double tx1, tx3, ty1, ty3, tz1, tz3, ce[5][13], dxmax, dymax, dzmax, xxcon1, yycon1, zzcon1, dnxm1, dnym1, dnzm1, c1345, conz1, c3, c4, c5, c4dssp, c5dssp, dtdssp, c3c4tx3, c3c4ty3, c3c4tz3, con16; #pragma omp declare target extern double tx2, ty2, tz2, dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4, dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt, dxmax, dymax, dzmax, xxcon2, xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1, dx4tx1, dx5tx1, yycon2, yycon3, yycon4, yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1, dz2tz1, dz3tz1, dz4tz1, dz5tz1, c1c2, c1c5, c3c4, c1, c2, dttx1, bt, dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1, c2dtty1, c2dttz1, comz1, comz4, comz5, comz6, c2iv, con43; #pragma omp end declare target #define IMAX PROBLEM_SIZE #define JMAX PROBLEM_SIZE #define KMAX PROBLEM_SIZE #define IMAXP (IMAX/2*2) #define JMAXP (JMAX/2*2) //--------------------------------------------------------------------- // To improve cache performance, grid dimensions padded by 1 // for even number sizes only //--------------------------------------------------------------------- /* common /fields/ */ #pragma omp declare target extern double u [5][KMAX][JMAXP+1][IMAXP+1]; extern double us [KMAX][JMAXP+1][IMAXP+1]; extern double vs [KMAX][JMAXP+1][IMAXP+1]; extern double ws [KMAX][JMAXP+1][IMAXP+1]; extern double qs [KMAX][JMAXP+1][IMAXP+1]; extern double rho_i [KMAX][JMAXP+1][IMAXP+1]; extern double speed [KMAX][JMAXP+1][IMAXP+1]; extern double square [KMAX][JMAXP+1][IMAXP+1]; extern double rhs [5][KMAX][JMAXP+1][IMAXP+1]; extern double forcing[5][KMAX][JMAXP+1][IMAXP+1]; #pragma omp end declare target extern brisbane_mem mem_u; extern brisbane_mem mem_us; extern brisbane_mem mem_vs; extern brisbane_mem mem_ws; extern brisbane_mem mem_qs; extern brisbane_mem mem_rho_i; extern brisbane_mem mem_speed; extern brisbane_mem mem_square; extern brisbane_mem mem_rhs; extern brisbane_mem mem_forcing; /* common /work_1d/ */ extern double cv [PROBLEM_SIZE]; extern double rhon[PROBLEM_SIZE]; extern double rhos[PROBLEM_SIZE]; extern double rhoq[PROBLEM_SIZE]; extern double cuf [PROBLEM_SIZE]; extern double q [PROBLEM_SIZE]; extern double ue [PROBLEM_SIZE][5]; extern double buf[PROBLEM_SIZE][5]; /* common /work_lhs/ */ extern double lhs [IMAXP+1][IMAXP+1][5]; extern double lhsp[IMAXP+1][IMAXP+1][5]; extern double lhsm[IMAXP+1][IMAXP+1][5]; //----------------------------------------------------------------------- // Timer constants //----------------------------------------------------------------------- #define t_total 1 #define t_rhsx 2 #define t_rhsy 3 #define t_rhsz 4 #define t_rhs 5 #define t_xsolve 6 #define t_ysolve 7 #define t_zsolve 8 #define t_rdis1 9 #define t_rdis2 10 #define t_txinvr 11 #define t_pinvr 12 #define t_ninvr 13 #define t_tzetar 14 #define t_add 15 #define t_last 15 //----------------------------------------------------------------------- void initialize(); void lhsinit(int ni, int nj); void lhsinitj(int nj, int ni); void exact_solution(double xi, double eta, double zeta, double dtemp[5]); void exact_rhs(); void set_constants(); void adi(); void compute_rhs(); void x_solve(); void ninvr(); void y_solve(); void pinvr(); void z_solve(); void tzetar(); void add(); void txinvr(); void error_norm(double rms[5]); void rhs_norm(double rms[5]); void verify(int no_time_steps, char *Class, int *verified);
weightedNorm2Many.c
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus 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. */ extern "C" void FUNC(weightedNorm2Many)(const dlong & Nblocks, const dlong & N, const dlong & Nfields, const dlong & offset, const dfloat * __restrict__ cpu_w, const dfloat * __restrict__ cpu_a, dfloat * __restrict__ cpu_wa){ dfloat wa2 = 0; #ifdef __NEKRS__OMP__ #pragma omp parallel for collapse(2) reduction(+:wa2) #endif for(int fld=0;fld<Nfields;fld++) { for(int i=0;i<N;++i){ const dlong id = i + fld*offset; const dfloat ai = cpu_a[id]; const dfloat wi = cpu_w[i]; wa2 += ai*ai*wi; } } cpu_wa[0] = wa2; }
linAlgWeightedInnerProd.c
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus 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. */ extern "C" void weightedInnerProd( const dlong & Nblocks, const dlong & N, const dfloat * __restrict__ cpu_w, const dfloat * __restrict__ cpu_a, const dfloat * __restrict__ cpu_b, dfloat * __restrict__ cpu_wab){ dfloat wab = 0; #pragma omp parallel for reduction(+:wab) for(int i=0;i<N;++i){ const dfloat ai = cpu_a[i]; const dfloat bi = cpu_b[i]; const dfloat wi = cpu_w[i]; wab += ai*bi*wi; } cpu_wab[0] = wab; } extern "C" void weightedInnerProdMany( const dlong & Nblocks, const dlong & N, const dlong & Nfields, const dlong & offset, const dfloat * __restrict__ cpu_w, const dfloat * __restrict__ cpu_a, const dfloat * __restrict__ cpu_b, dfloat * __restrict__ cpu_wab){ dfloat wab = 0; #pragma omp parallel for collapse(2) reduction(+:wab) for(int fld=0;fld<Nfields;fld++) { for(int i=0;i<N;++i){ const dlong id = i + fld*offset; const dfloat ai = cpu_a[id]; const dfloat bi = cpu_b[id]; const dfloat wi = cpu_w[i]; wab += ai*bi*wi; } } cpu_wab[0] = wab; }
GB_convert_bitmap_worker.c
//------------------------------------------------------------------------------ // GB_convert_bitmap_worker: construct triplets or CSC/CSR from bitmap //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If A is iso and Ax_new is not NULL, the iso scalar is expanded into the // non-iso array Ax_new. Otherwise, if Ax_new and Ax are NULL then no values // are extracted. // TODO allow this function to do typecasting. Create 169 different versions // for all 13x13 versions. Use this as part of Method 24, C=A assignment. // Can also use typecasting for GB_Matrix_diag. #include "GB.h" #include "GB_partition.h" GrB_Info GB_convert_bitmap_worker // extract CSC/CSR or triplets from bitmap ( // outputs: int64_t *restrict Ap, // vector pointers for CSC/CSR form int64_t *restrict Ai, // indices for CSC/CSR or triplet form int64_t *restrict Aj, // vector indices for triplet form GB_void *restrict Ax_new, // values for CSC/CSR or triplet form int64_t *anvec_nonempty, // # of non-empty vectors // inputs: not modified const GrB_Matrix A, // matrix to extract; not modified GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (GB_IS_BITMAP (A)) ; ASSERT (Ap != NULL) ; // must be provided on input, size avdim+1 int64_t *restrict W = NULL ; size_t W_size = 0 ; const int64_t avdim = A->vdim ; const int64_t avlen = A->vlen ; const size_t asize = A->type->size ; //-------------------------------------------------------------------------- // count the entries in each vector //-------------------------------------------------------------------------- const int8_t *restrict Ab = A->b ; GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (avlen*avdim, chunk, nthreads_max) ; bool by_vector = (nthreads <= avdim) ; if (by_vector) { //---------------------------------------------------------------------- // compute all vectors in parallel (no workspace) //---------------------------------------------------------------------- int64_t j ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (j = 0 ; j < avdim ; j++) { // ajnz = nnz (A (:,j)) int64_t ajnz = 0 ; int64_t pA_start = j * avlen ; for (int64_t i = 0 ; i < avlen ; i++) { // see if A(i,j) is present in the bitmap int64_t p = i + pA_start ; ajnz += Ab [p] ; ASSERT (Ab [p] == 0 || Ab [p] == 1) ; } Ap [j] = ajnz ; } } else { //---------------------------------------------------------------------- // compute blocks of rows in parallel //---------------------------------------------------------------------- // allocate one row of W per thread, each row of length avdim W = GB_MALLOC_WORK (nthreads * avdim, int64_t, &W_size) ; if (W == NULL) { // out of memory return (GrB_OUT_OF_MEMORY) ; } int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (taskid = 0 ; taskid < nthreads ; taskid++) { int64_t *restrict Wtask = W + taskid * avdim ; int64_t istart, iend ; GB_PARTITION (istart, iend, avlen, taskid, nthreads) ; for (int64_t j = 0 ; j < avdim ; j++) { // ajnz = nnz (A (istart:iend-1,j)) int64_t ajnz = 0 ; int64_t pA_start = j * avlen ; for (int64_t i = istart ; i < iend ; i++) { // see if A(i,j) is present in the bitmap int64_t p = i + pA_start ; ajnz += Ab [p] ; ASSERT (Ab [p] == 0 || Ab [p] == 1) ; } Wtask [j] = ajnz ; } } // cumulative sum to compute nnz(A(:,j)) for each vector j int64_t j ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (j = 0 ; j < avdim ; j++) { int64_t ajnz = 0 ; for (int taskid = 0 ; taskid < nthreads ; taskid++) { int64_t *restrict Wtask = W + taskid * avdim ; int64_t c = Wtask [j] ; Wtask [j] = ajnz ; ajnz += c ; } Ap [j] = ajnz ; } } //-------------------------------------------------------------------------- // cumulative sum of Ap //-------------------------------------------------------------------------- int nth = GB_nthreads (avdim, chunk, nthreads_max) ; GB_cumsum (Ap, avdim, anvec_nonempty, nth, Context) ; int64_t anz = Ap [avdim] ; ASSERT (anz == A->nvals) ; //-------------------------------------------------------------------------- // gather the pattern and values from the bitmap //-------------------------------------------------------------------------- // TODO: add type-specific versions for built-in types const GB_void *restrict Ax = (GB_void *) (A->x) ; const bool A_iso = A->iso ; const bool numeric = (Ax_new != NULL && Ax != NULL) ; if (by_vector) { //---------------------------------------------------------------------- // construct all vectors in parallel (no workspace) //---------------------------------------------------------------------- int64_t j ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (j = 0 ; j < avdim ; j++) { // gather from the bitmap into the new A (:,j) int64_t pnew = Ap [j] ; int64_t pA_start = j * avlen ; for (int64_t i = 0 ; i < avlen ; i++) { int64_t p = i + pA_start ; if (Ab [p]) { // A(i,j) is in the bitmap if (Ai != NULL) Ai [pnew] = i ; if (Aj != NULL) Aj [pnew] = j ; if (numeric) { // Ax_new [pnew] = Ax [p]) memcpy (Ax_new +(pnew)*asize, Ax +(A_iso ? 0:(p)*asize), asize) ; } pnew++ ; } } ASSERT (pnew == Ap [j+1]) ; } } else { //---------------------------------------------------------------------- // compute blocks of rows in parallel //---------------------------------------------------------------------- int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (taskid = 0 ; taskid < nthreads ; taskid++) { int64_t *restrict Wtask = W + taskid * avdim ; int64_t istart, iend ; GB_PARTITION (istart, iend, avlen, taskid, nthreads) ; for (int64_t j = 0 ; j < avdim ; j++) { // gather from the bitmap into the new A (:,j) int64_t pnew = Ap [j] + Wtask [j] ; int64_t pA_start = j * avlen ; for (int64_t i = istart ; i < iend ; i++) { // see if A(i,j) is present in the bitmap int64_t p = i + pA_start ; if (Ab [p]) { // A(i,j) is in the bitmap if (Ai != NULL) Ai [pnew] = i ; if (Aj != NULL) Aj [pnew] = j ; if (numeric) { // Ax_new [pnew] = Ax [p] ; memcpy (Ax_new +(pnew)*asize, Ax +(A_iso ? 0:(p)*asize), asize) ; } pnew++ ; } } } } } //-------------------------------------------------------------------------- // free workspace return result //-------------------------------------------------------------------------- GB_FREE_WORK (&W, W_size) ; return (GrB_SUCCESS) ; }
libsais.c
/*-- This file is a part of libsais, a library for linear time suffix array and burrows wheeler transform construction. Copyright (c) 2021-2022 Ilya Grebnov <ilya.grebnov@gmail.com> 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. Please see the file LICENSE for full copyright information. --*/ #include "libsais.h" #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <limits.h> #if defined(_OPENMP) #include <omp.h> #else #define UNUSED(_x) (void)(_x) #endif typedef int32_t sa_sint_t; typedef uint32_t sa_uint_t; typedef ptrdiff_t fast_sint_t; typedef size_t fast_uint_t; #define SAINT_BIT (32) #define SAINT_MAX INT32_MAX #define SAINT_MIN INT32_MIN #define ALPHABET_SIZE (1 << CHAR_BIT) #define UNBWT_FASTBITS (17) #define SUFFIX_GROUP_BIT (SAINT_BIT - 1) #define SUFFIX_GROUP_MARKER (((sa_sint_t)1) << (SUFFIX_GROUP_BIT - 1)) #define BUCKETS_INDEX2(_c, _s) (((_c) << 1) + (_s)) #define BUCKETS_INDEX4(_c, _s) (((_c) << 2) + (_s)) #define LIBSAIS_PER_THREAD_CACHE_SIZE (24576) typedef struct LIBSAIS_THREAD_CACHE { sa_sint_t symbol; sa_sint_t index; } LIBSAIS_THREAD_CACHE; typedef union LIBSAIS_THREAD_STATE { struct { fast_sint_t position; fast_sint_t count; fast_sint_t m; fast_sint_t last_lms_suffix; sa_sint_t * buckets; LIBSAIS_THREAD_CACHE * cache; } state; uint8_t padding[64]; } LIBSAIS_THREAD_STATE; typedef struct LIBSAIS_CONTEXT { sa_sint_t * buckets; LIBSAIS_THREAD_STATE * thread_state; fast_sint_t threads; } LIBSAIS_CONTEXT; typedef struct LIBSAIS_UNBWT_CONTEXT { sa_uint_t * bucket2; uint16_t * fastbits; sa_uint_t * buckets; fast_sint_t threads; } LIBSAIS_UNBWT_CONTEXT; #if defined(__GNUC__) || defined(__clang__) #define RESTRICT __restrict__ #elif defined(_MSC_VER) || defined(__INTEL_COMPILER) #define RESTRICT __restrict #else #error Your compiler, configuration or platform is not supported. #endif #if defined(__has_builtin) #if __has_builtin(__builtin_prefetch) #define HAS_BUILTIN_PREFECTCH #endif #elif defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 2)) || (__GNUC__ >= 4) #define HAS_BUILTIN_PREFECTCH #endif #if defined(__has_builtin) #if __has_builtin(__builtin_bswap16) #define HAS_BUILTIN_BSWAP16 #endif #elif defined(__GNUC__) && ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ >= 5) #define HAS_BUILTIN_BSWAP16 #endif #if defined(HAS_BUILTIN_PREFECTCH) #define libsais_prefetch(address) __builtin_prefetch((const void *)(address), 0, 0) #define libsais_prefetchw(address) __builtin_prefetch((const void *)(address), 1, 0) #elif defined (_M_IX86) || defined (_M_AMD64) #include <intrin.h> #define libsais_prefetch(address) _mm_prefetch((const void *)(address), _MM_HINT_NTA) #define libsais_prefetchw(address) _m_prefetchw((const void *)(address)) #elif defined (_M_ARM) #include <intrin.h> #define libsais_prefetch(address) __prefetch((const void *)(address)) #define libsais_prefetchw(address) __prefetchw((const void *)(address)) #elif defined (_M_ARM64) #include <intrin.h> #define libsais_prefetch(address) __prefetch2((const void *)(address), 1) #define libsais_prefetchw(address) __prefetch2((const void *)(address), 17) #else #error Your compiler, configuration or platform is not supported. #endif #if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) #if defined(_LITTLE_ENDIAN) \ || (defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && BYTE_ORDER == LITTLE_ENDIAN) \ || (defined(_BYTE_ORDER) && defined(_LITTLE_ENDIAN) && _BYTE_ORDER == _LITTLE_ENDIAN) \ || (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN) \ || (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) #define __LITTLE_ENDIAN__ #elif defined(_BIG_ENDIAN) \ || (defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN) \ || (defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && _BYTE_ORDER == _BIG_ENDIAN) \ || (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN) \ || (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) #define __BIG_ENDIAN__ #elif defined(_WIN32) #define __LITTLE_ENDIAN__ #endif #endif #if defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) #if defined(HAS_BUILTIN_BSWAP16) #define libsais_bswap16(x) (__builtin_bswap16(x)) #elif defined(_MSC_VER) && !defined(__INTEL_COMPILER) #define libsais_bswap16(x) (_byteswap_ushort(x)) #else #define libsais_bswap16(x) ((uint16_t)(x >> 8) | (uint16_t)(x << 8)) #endif #elif !defined(__LITTLE_ENDIAN__) && defined(__BIG_ENDIAN__) #define libsais_bswap16(x) (x) #else #error Your compiler, configuration or platform is not supported. #endif static void * libsais_align_up(const void * address, size_t alignment) { return (void *)((((ptrdiff_t)address) + ((ptrdiff_t)alignment) - 1) & (-((ptrdiff_t)alignment))); } static void * libsais_alloc_aligned(size_t size, size_t alignment) { void * address = malloc(size + sizeof(short) + alignment - 1); if (address != NULL) { void * aligned_address = libsais_align_up((void *)((ptrdiff_t)address + (ptrdiff_t)(sizeof(short))), alignment); ((short *)aligned_address)[-1] = (short)((ptrdiff_t)aligned_address - (ptrdiff_t)address); return aligned_address; } return NULL; } static void libsais_free_aligned(void * aligned_address) { if (aligned_address != NULL) { free((void *)((ptrdiff_t)aligned_address - ((short *)aligned_address)[-1])); } } static LIBSAIS_THREAD_STATE * libsais_alloc_thread_state(sa_sint_t threads) { LIBSAIS_THREAD_STATE * RESTRICT thread_state = (LIBSAIS_THREAD_STATE *)libsais_alloc_aligned((size_t)threads * sizeof(LIBSAIS_THREAD_STATE), 4096); sa_sint_t * RESTRICT thread_buckets = (sa_sint_t *)libsais_alloc_aligned((size_t)threads * 4 * ALPHABET_SIZE * sizeof(sa_sint_t), 4096); LIBSAIS_THREAD_CACHE * RESTRICT thread_cache = (LIBSAIS_THREAD_CACHE *)libsais_alloc_aligned((size_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE * sizeof(LIBSAIS_THREAD_CACHE), 4096); if (thread_state != NULL && thread_buckets != NULL && thread_cache != NULL) { fast_sint_t t; for (t = 0; t < threads; ++t) { thread_state[t].state.buckets = thread_buckets; thread_buckets += 4 * ALPHABET_SIZE; thread_state[t].state.cache = thread_cache; thread_cache += LIBSAIS_PER_THREAD_CACHE_SIZE; } return thread_state; } libsais_free_aligned(thread_cache); libsais_free_aligned(thread_buckets); libsais_free_aligned(thread_state); return NULL; } static void libsais_free_thread_state(LIBSAIS_THREAD_STATE * thread_state) { if (thread_state != NULL) { libsais_free_aligned(thread_state[0].state.cache); libsais_free_aligned(thread_state[0].state.buckets); libsais_free_aligned(thread_state); } } static LIBSAIS_CONTEXT * libsais_create_ctx_main(sa_sint_t threads) { LIBSAIS_CONTEXT * RESTRICT ctx = (LIBSAIS_CONTEXT *)libsais_alloc_aligned(sizeof(LIBSAIS_CONTEXT), 64); sa_sint_t * RESTRICT buckets = (sa_sint_t *)libsais_alloc_aligned(8 * ALPHABET_SIZE * sizeof(sa_sint_t), 4096); LIBSAIS_THREAD_STATE * RESTRICT thread_state = threads > 1 ? libsais_alloc_thread_state(threads) : NULL; if (ctx != NULL && buckets != NULL && (thread_state != NULL || threads == 1)) { ctx->buckets = buckets; ctx->threads = threads; ctx->thread_state = thread_state; return ctx; } libsais_free_thread_state(thread_state); libsais_free_aligned(buckets); libsais_free_aligned(ctx); return NULL; } static void libsais_free_ctx_main(LIBSAIS_CONTEXT * ctx) { if (ctx != NULL) { libsais_free_thread_state(ctx->thread_state); libsais_free_aligned(ctx->buckets); libsais_free_aligned(ctx); } } #if defined(_OPENMP) static sa_sint_t libsais_count_negative_marked_suffixes(sa_sint_t * RESTRICT SA, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { sa_sint_t count = 0; fast_sint_t i; for (i = omp_block_start; i < omp_block_start + omp_block_size; ++i) { count += (SA[i] < 0); } return count; } static sa_sint_t libsais_count_zero_marked_suffixes(sa_sint_t * RESTRICT SA, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { sa_sint_t count = 0; fast_sint_t i; for (i = omp_block_start; i < omp_block_start + omp_block_size; ++i) { count += (SA[i] == 0); } return count; } static void libsais_place_cached_suffixes(sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&cache[i + 2 * prefetch_distance]); libsais_prefetchw(&SA[cache[i + prefetch_distance + 0].symbol]); libsais_prefetchw(&SA[cache[i + prefetch_distance + 1].symbol]); libsais_prefetchw(&SA[cache[i + prefetch_distance + 2].symbol]); libsais_prefetchw(&SA[cache[i + prefetch_distance + 3].symbol]); SA[cache[i + 0].symbol] = cache[i + 0].index; SA[cache[i + 1].symbol] = cache[i + 1].index; SA[cache[i + 2].symbol] = cache[i + 2].index; SA[cache[i + 3].symbol] = cache[i + 3].index; } for (j += prefetch_distance + 3; i < j; i += 1) { SA[cache[i].symbol] = cache[i].index; } } static void libsais_compact_and_place_cached_suffixes(sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j, l; for (i = omp_block_start, j = omp_block_start + omp_block_size - 3, l = omp_block_start; i < j; i += 4) { libsais_prefetchw(&cache[i + prefetch_distance]); cache[l] = cache[i + 0]; l += cache[l].symbol >= 0; cache[l] = cache[i + 1]; l += cache[l].symbol >= 0; cache[l] = cache[i + 2]; l += cache[l].symbol >= 0; cache[l] = cache[i + 3]; l += cache[l].symbol >= 0; } for (j += 3; i < j; i += 1) { cache[l] = cache[i]; l += cache[l].symbol >= 0; } libsais_place_cached_suffixes(SA, cache, omp_block_start, l - omp_block_start); } static void libsais_accumulate_counts_s32_2(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s]; } } static void libsais_accumulate_counts_s32_3(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; sa_sint_t * RESTRICT bucket02 = bucket01 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s] + bucket02[s]; } } static void libsais_accumulate_counts_s32_4(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; sa_sint_t * RESTRICT bucket02 = bucket01 - bucket_stride; sa_sint_t * RESTRICT bucket03 = bucket02 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s] + bucket02[s] + bucket03[s]; } } static void libsais_accumulate_counts_s32_5(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; sa_sint_t * RESTRICT bucket02 = bucket01 - bucket_stride; sa_sint_t * RESTRICT bucket03 = bucket02 - bucket_stride; sa_sint_t * RESTRICT bucket04 = bucket03 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s] + bucket02[s] + bucket03[s] + bucket04[s]; } } static void libsais_accumulate_counts_s32_6(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; sa_sint_t * RESTRICT bucket02 = bucket01 - bucket_stride; sa_sint_t * RESTRICT bucket03 = bucket02 - bucket_stride; sa_sint_t * RESTRICT bucket04 = bucket03 - bucket_stride; sa_sint_t * RESTRICT bucket05 = bucket04 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s] + bucket02[s] + bucket03[s] + bucket04[s] + bucket05[s]; } } static void libsais_accumulate_counts_s32_7(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; sa_sint_t * RESTRICT bucket02 = bucket01 - bucket_stride; sa_sint_t * RESTRICT bucket03 = bucket02 - bucket_stride; sa_sint_t * RESTRICT bucket04 = bucket03 - bucket_stride; sa_sint_t * RESTRICT bucket05 = bucket04 - bucket_stride; sa_sint_t * RESTRICT bucket06 = bucket05 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s] + bucket02[s] + bucket03[s] + bucket04[s] + bucket05[s] + bucket06[s]; } } static void libsais_accumulate_counts_s32_8(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; sa_sint_t * RESTRICT bucket02 = bucket01 - bucket_stride; sa_sint_t * RESTRICT bucket03 = bucket02 - bucket_stride; sa_sint_t * RESTRICT bucket04 = bucket03 - bucket_stride; sa_sint_t * RESTRICT bucket05 = bucket04 - bucket_stride; sa_sint_t * RESTRICT bucket06 = bucket05 - bucket_stride; sa_sint_t * RESTRICT bucket07 = bucket06 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s] + bucket02[s] + bucket03[s] + bucket04[s] + bucket05[s] + bucket06[s] + bucket07[s]; } } static void libsais_accumulate_counts_s32_9(sa_sint_t * RESTRICT bucket00, fast_sint_t bucket_size, fast_sint_t bucket_stride) { sa_sint_t * RESTRICT bucket01 = bucket00 - bucket_stride; sa_sint_t * RESTRICT bucket02 = bucket01 - bucket_stride; sa_sint_t * RESTRICT bucket03 = bucket02 - bucket_stride; sa_sint_t * RESTRICT bucket04 = bucket03 - bucket_stride; sa_sint_t * RESTRICT bucket05 = bucket04 - bucket_stride; sa_sint_t * RESTRICT bucket06 = bucket05 - bucket_stride; sa_sint_t * RESTRICT bucket07 = bucket06 - bucket_stride; sa_sint_t * RESTRICT bucket08 = bucket07 - bucket_stride; fast_sint_t s; for (s = 0; s < bucket_size; s += 1) { bucket00[s] = bucket00[s] + bucket01[s] + bucket02[s] + bucket03[s] + bucket04[s] + bucket05[s] + bucket06[s] + bucket07[s] + bucket08[s]; } } static void libsais_accumulate_counts_s32(sa_sint_t * RESTRICT buckets, fast_sint_t bucket_size, fast_sint_t bucket_stride, fast_sint_t num_buckets) { while (num_buckets >= 9) { libsais_accumulate_counts_s32_9(buckets - (num_buckets - 9) * bucket_stride, bucket_size, bucket_stride); num_buckets -= 8; } switch (num_buckets) { case 1: break; case 2: libsais_accumulate_counts_s32_2(buckets, bucket_size, bucket_stride); break; case 3: libsais_accumulate_counts_s32_3(buckets, bucket_size, bucket_stride); break; case 4: libsais_accumulate_counts_s32_4(buckets, bucket_size, bucket_stride); break; case 5: libsais_accumulate_counts_s32_5(buckets, bucket_size, bucket_stride); break; case 6: libsais_accumulate_counts_s32_6(buckets, bucket_size, bucket_stride); break; case 7: libsais_accumulate_counts_s32_7(buckets, bucket_size, bucket_stride); break; case 8: libsais_accumulate_counts_s32_8(buckets, bucket_size, bucket_stride); break; } } #endif static void libsais_gather_lms_suffixes_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, fast_sint_t m, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { if (omp_block_size > 0) { const fast_sint_t prefetch_distance = 128; fast_sint_t i, j = omp_block_start + omp_block_size, c0 = T[omp_block_start + omp_block_size - 1], c1 = -1; while (j < n && (c1 = T[j]) == c0) { ++j; } fast_uint_t s = c0 >= c1; for (i = omp_block_start + omp_block_size - 2, j = omp_block_start + 3; i >= j; i -= 4) { libsais_prefetch(&T[i - prefetch_distance]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 0); m -= ((s & 3) == 1); c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 1); m -= ((s & 3) == 1); c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 2); m -= ((s & 3) == 1); } for (j -= 3; i >= j; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); } SA[m] = (sa_sint_t)(i + 1); } } static void libsais_gather_lms_suffixes_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536 && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { libsais_gather_lms_suffixes_8u(T, SA, n, (fast_sint_t)n - 1, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { fast_sint_t t, m = 0; for (t = omp_num_threads - 1; t > omp_thread_num; --t) { m += thread_state[t].state.m; } libsais_gather_lms_suffixes_8u(T, SA, n, (fast_sint_t)n - 1 - m, omp_block_start, omp_block_size); #pragma omp barrier if (thread_state[omp_thread_num].state.m > 0) { SA[(fast_sint_t)n - 1 - m] = (sa_sint_t)thread_state[omp_thread_num].state.last_lms_suffix; } } #endif } } static sa_sint_t libsais_gather_lms_suffixes_32s(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n) { const fast_sint_t prefetch_distance = 32; sa_sint_t i = n - 2; sa_sint_t m = n - 1; fast_uint_t s = 1; fast_sint_t c0 = T[n - 1]; fast_sint_t c1 = 0; for (; i >= 3; i -= 4) { libsais_prefetch(&T[i - prefetch_distance]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = i + 1; m -= ((s & 3) == 1); c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = i - 0; m -= ((s & 3) == 1); c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = i - 1; m -= ((s & 3) == 1); c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = i - 2; m -= ((s & 3) == 1); } for (; i >= 0; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = i + 1; m -= ((s & 3) == 1); } return n - 1 - m; } static sa_sint_t libsais_gather_compacted_lms_suffixes_32s(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n) { const fast_sint_t prefetch_distance = 32; sa_sint_t i = n - 2; sa_sint_t m = n - 1; fast_uint_t s = 1; fast_sint_t c0 = T[n - 1]; fast_sint_t c1 = 0; for (; i >= 3; i -= 4) { libsais_prefetch(&T[i - prefetch_distance]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = i + 1; m -= ((fast_sint_t)(s & 3) == (c0 >= 0)); c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = i - 0; m -= ((fast_sint_t)(s & 3) == (c1 >= 0)); c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = i - 1; m -= ((fast_sint_t)(s & 3) == (c0 >= 0)); c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = i - 2; m -= ((fast_sint_t)(s & 3) == (c1 >= 0)); } for (; i >= 0; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = i + 1; m -= ((fast_sint_t)(s & 3) == (c1 >= 0)); } return n - 1 - m; } #if defined(_OPENMP) static void libsais_count_lms_suffixes_32s_4k(const sa_sint_t * RESTRICT T, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, 4 * (size_t)k * sizeof(sa_sint_t)); sa_sint_t i = n - 2; fast_uint_t s = 1; fast_sint_t c0 = T[n - 1]; fast_sint_t c1 = 0; for (; i >= prefetch_distance + 3; i -= 4) { libsais_prefetch(&T[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 0], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 1], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 2], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 3], 0)]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; } for (; i >= 0; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; } buckets[BUCKETS_INDEX4((fast_uint_t)c0, (s << 1) & 3)]++; } #endif static void libsais_count_lms_suffixes_32s_2k(const sa_sint_t * RESTRICT T, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, 2 * (size_t)k * sizeof(sa_sint_t)); sa_sint_t i = n - 2; fast_uint_t s = 1; fast_sint_t c0 = T[n - 1]; fast_sint_t c1 = 0; for (; i >= prefetch_distance + 3; i -= 4) { libsais_prefetch(&T[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 0], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 1], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 2], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 3], 0)]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } for (; i >= 0; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } buckets[BUCKETS_INDEX2((fast_uint_t)c0, 0)]++; } #if defined(_OPENMP) static void libsais_count_compacted_lms_suffixes_32s_2k(const sa_sint_t * RESTRICT T, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, 2 * (size_t)k * sizeof(sa_sint_t)); sa_sint_t i = n - 2; fast_uint_t s = 1; fast_sint_t c0 = T[n - 1]; fast_sint_t c1 = 0; for (; i >= prefetch_distance + 3; i -= 4) { libsais_prefetch(&T[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 0] & SAINT_MAX, 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 1] & SAINT_MAX, 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 2] & SAINT_MAX, 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 3] & SAINT_MAX, 0)]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); c0 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); c1 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); c0 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); c1 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } for (; i >= 0; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); c1 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } c0 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c0, 0)]++; } #endif static sa_sint_t libsais_count_and_gather_lms_suffixes_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { memset(buckets, 0, 4 * ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t m = omp_block_start + omp_block_size - 1; if (omp_block_size > 0) { const fast_sint_t prefetch_distance = 128; fast_sint_t i, j = m + 1, c0 = T[m], c1 = -1; while (j < n && (c1 = T[j]) == c0) { ++j; } fast_uint_t s = c0 >= c1; for (i = m - 1, j = omp_block_start + 3; i >= j; i -= 4) { libsais_prefetch(&T[i - prefetch_distance]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 0); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 2); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; } for (j -= 3; i >= j; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; } c1 = (i >= 0) ? T[i] : -1; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; } return (sa_sint_t)(omp_block_start + omp_block_size - 1 - m); } static sa_sint_t libsais_count_and_gather_lms_suffixes_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t m = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536 && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { m = libsais_count_and_gather_lms_suffixes_8u(T, SA, n, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.position = omp_block_start + omp_block_size; thread_state[omp_thread_num].state.m = libsais_count_and_gather_lms_suffixes_8u(T, SA, n, thread_state[omp_thread_num].state.buckets, omp_block_start, omp_block_size); if (thread_state[omp_thread_num].state.m > 0) { thread_state[omp_thread_num].state.last_lms_suffix = SA[thread_state[omp_thread_num].state.position - 1]; } } #pragma omp barrier #pragma omp master { memset(buckets, 0, 4 * ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t t; for (t = omp_num_threads - 1; t >= 0; --t) { m += (sa_sint_t)thread_state[t].state.m; if (t != omp_num_threads - 1 && thread_state[t].state.m > 0) { memcpy(&SA[n - m], &SA[thread_state[t].state.position - thread_state[t].state.m], (size_t)thread_state[t].state.m * sizeof(sa_sint_t)); } { sa_sint_t * RESTRICT temp_bucket = thread_state[t].state.buckets; fast_sint_t s; for (s = 0; s < 4 * ALPHABET_SIZE; s += 1) { sa_sint_t A = buckets[s], B = temp_bucket[s]; buckets[s] = A + B; temp_bucket[s] = A; } } } } } #endif } return m; } static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_4k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { memset(buckets, 0, 4 * (size_t)k * sizeof(sa_sint_t)); fast_sint_t m = omp_block_start + omp_block_size - 1; if (omp_block_size > 0) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j = m + 1, c0 = T[m], c1 = -1; while (j < n && (c1 = T[j]) == c0) { ++j; } fast_uint_t s = c0 >= c1; for (i = m - 1, j = omp_block_start + prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetch(&T[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 0], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 1], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 2], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX4(T[i - prefetch_distance - 3], 0)]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 0); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 2); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; } for (j -= prefetch_distance + 3; i >= j; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]++; } c1 = (i >= 0) ? T[i] : -1; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX4((fast_uint_t)c0, s & 3)]++; } return (sa_sint_t)(omp_block_start + omp_block_size - 1 - m); } static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_2k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { memset(buckets, 0, 2 * (size_t)k * sizeof(sa_sint_t)); fast_sint_t m = omp_block_start + omp_block_size - 1; if (omp_block_size > 0) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j = m + 1, c0 = T[m], c1 = -1; while (j < n && (c1 = T[j]) == c0) { ++j; } fast_uint_t s = c0 >= c1; for (i = m - 1, j = omp_block_start + prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetch(&T[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 0], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 1], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 2], 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 3], 0)]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 0); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 2); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } for (j -= prefetch_distance + 3; i >= j; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } c1 = (i >= 0) ? T[i] : -1; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((s & 3) == 1); buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; } return (sa_sint_t)(omp_block_start + omp_block_size - 1 - m); } static sa_sint_t libsais_count_and_gather_compacted_lms_suffixes_32s_2k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { memset(buckets, 0, 2 * (size_t)k * sizeof(sa_sint_t)); fast_sint_t m = omp_block_start + omp_block_size - 1; if (omp_block_size > 0) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j = m + 1, c0 = T[m], c1 = -1; while (j < n && (c1 = T[j]) == c0) { ++j; } fast_uint_t s = c0 >= c1; for (i = m - 1, j = omp_block_start + prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetch(&T[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 0] & SAINT_MAX, 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 1] & SAINT_MAX, 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 2] & SAINT_MAX, 0)]); libsais_prefetchw(&buckets[BUCKETS_INDEX2(T[i - prefetch_distance - 3] & SAINT_MAX, 0)]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((fast_sint_t)(s & 3) == (c0 >= 0)); c0 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 0); m -= ((fast_sint_t)(s & 3) == (c1 >= 0)); c1 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 1); m -= ((fast_sint_t)(s & 3) == (c0 >= 0)); c0 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i - 2); m -= ((fast_sint_t)(s & 3) == (c1 >= 0)); c1 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } for (j -= prefetch_distance + 3; i >= j; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((fast_sint_t)(s & 3) == (c1 >= 0)); c1 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c1, (s & 3) == 1)]++; } c1 = (i >= 0) ? T[i] : -1; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); SA[m] = (sa_sint_t)(i + 1); m -= ((fast_sint_t)(s & 3) == (c0 >= 0)); c0 &= SAINT_MAX; buckets[BUCKETS_INDEX2((fast_uint_t)c0, (s & 3) == 1)]++; } return (sa_sint_t)(omp_block_start + omp_block_size - 1 - m); } #if defined(_OPENMP) static fast_sint_t libsais_get_bucket_stride(fast_sint_t free_space, fast_sint_t bucket_size, fast_sint_t num_buckets) { fast_sint_t bucket_size_1024 = (bucket_size + 1023) & (-1024); if (free_space / (num_buckets - 1) >= bucket_size_1024) { return bucket_size_1024; } fast_sint_t bucket_size_16 = (bucket_size + 15) & (-16); if (free_space / (num_buckets - 1) >= bucket_size_16) { return bucket_size_16; } return bucket_size; } static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_4k_fs_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t m = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { m = libsais_count_and_gather_lms_suffixes_32s_4k(T, SA, n, k, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { fast_sint_t bucket_size = 4 * (fast_sint_t)k; fast_sint_t bucket_stride = libsais_get_bucket_stride(buckets - &SA[n], bucket_size, omp_num_threads); { thread_state[omp_thread_num].state.position = omp_block_start + omp_block_size; thread_state[omp_thread_num].state.count = libsais_count_and_gather_lms_suffixes_32s_4k(T, SA, n, k, buckets - (omp_thread_num * bucket_stride), omp_block_start, omp_block_size); } #pragma omp barrier if (omp_thread_num == omp_num_threads - 1) { fast_sint_t t; for (t = omp_num_threads - 1; t >= 0; --t) { m += (sa_sint_t)thread_state[t].state.count; if (t != omp_num_threads - 1 && thread_state[t].state.count > 0) { memcpy(&SA[n - m], &SA[thread_state[t].state.position - thread_state[t].state.count], (size_t)thread_state[t].state.count * sizeof(sa_sint_t)); } } } else { omp_num_threads = omp_num_threads - 1; omp_block_stride = (bucket_size / omp_num_threads) & (-16); omp_block_start = omp_thread_num * omp_block_stride; omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : bucket_size - omp_block_start; libsais_accumulate_counts_s32(buckets + omp_block_start, omp_block_size, bucket_stride, omp_num_threads + 1); } } #endif } return m; } static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_2k_fs_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t m = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { m = libsais_count_and_gather_lms_suffixes_32s_2k(T, SA, n, k, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { fast_sint_t bucket_size = 2 * (fast_sint_t)k; fast_sint_t bucket_stride = libsais_get_bucket_stride(buckets - &SA[n], bucket_size, omp_num_threads); { thread_state[omp_thread_num].state.position = omp_block_start + omp_block_size; thread_state[omp_thread_num].state.count = libsais_count_and_gather_lms_suffixes_32s_2k(T, SA, n, k, buckets - (omp_thread_num * bucket_stride), omp_block_start, omp_block_size); } #pragma omp barrier if (omp_thread_num == omp_num_threads - 1) { fast_sint_t t; for (t = omp_num_threads - 1; t >= 0; --t) { m += (sa_sint_t)thread_state[t].state.count; if (t != omp_num_threads - 1 && thread_state[t].state.count > 0) { memcpy(&SA[n - m], &SA[thread_state[t].state.position - thread_state[t].state.count], (size_t)thread_state[t].state.count * sizeof(sa_sint_t)); } } } else { omp_num_threads = omp_num_threads - 1; omp_block_stride = (bucket_size / omp_num_threads) & (-16); omp_block_start = omp_thread_num * omp_block_stride; omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : bucket_size - omp_block_start; libsais_accumulate_counts_s32(buckets + omp_block_start, omp_block_size, bucket_stride, omp_num_threads + 1); } } #endif } return m; } static void libsais_count_and_gather_compacted_lms_suffixes_32s_2k_fs_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { libsais_count_and_gather_compacted_lms_suffixes_32s_2k(T, SA, n, k, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { fast_sint_t bucket_size = 2 * (fast_sint_t)k; fast_sint_t bucket_stride = libsais_get_bucket_stride(buckets - &SA[n + n], bucket_size, omp_num_threads); { thread_state[omp_thread_num].state.position = omp_block_start + omp_block_size; thread_state[omp_thread_num].state.count = libsais_count_and_gather_compacted_lms_suffixes_32s_2k(T, SA + n, n, k, buckets - (omp_thread_num * bucket_stride), omp_block_start, omp_block_size); } #pragma omp barrier { fast_sint_t t, m = 0; for (t = omp_num_threads - 1; t >= omp_thread_num; --t) { m += (sa_sint_t)thread_state[t].state.count; } if (thread_state[omp_thread_num].state.count > 0) { memcpy(&SA[n - m], &SA[n + thread_state[omp_thread_num].state.position - thread_state[omp_thread_num].state.count], (size_t)thread_state[omp_thread_num].state.count * sizeof(sa_sint_t)); } } { omp_block_stride = (bucket_size / omp_num_threads) & (-16); omp_block_start = omp_thread_num * omp_block_stride; omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : bucket_size - omp_block_start; libsais_accumulate_counts_s32(buckets + omp_block_start, omp_block_size, bucket_stride, omp_num_threads); } } #endif } } #endif static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_4k_nofs_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads) { sa_sint_t m = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(2) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); fast_sint_t omp_num_threads = 1; #endif if (omp_num_threads == 1) { m = libsais_count_and_gather_lms_suffixes_32s_4k(T, SA, n, k, buckets, 0, n); } #if defined(_OPENMP) else if (omp_thread_num == 0) { libsais_count_lms_suffixes_32s_4k(T, n, k, buckets); } else { m = libsais_gather_lms_suffixes_32s(T, SA, n); } #endif } return m; } static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_2k_nofs_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads) { sa_sint_t m = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(2) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); fast_sint_t omp_num_threads = 1; #endif if (omp_num_threads == 1) { m = libsais_count_and_gather_lms_suffixes_32s_2k(T, SA, n, k, buckets, 0, n); } #if defined(_OPENMP) else if (omp_thread_num == 0) { libsais_count_lms_suffixes_32s_2k(T, n, k, buckets); } else { m = libsais_gather_lms_suffixes_32s(T, SA, n); } #endif } return m; } static sa_sint_t libsais_count_and_gather_compacted_lms_suffixes_32s_2k_nofs_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads) { sa_sint_t m = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(2) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); fast_sint_t omp_num_threads = 1; #endif if (omp_num_threads == 1) { m = libsais_count_and_gather_compacted_lms_suffixes_32s_2k(T, SA, n, k, buckets, 0, n); } #if defined(_OPENMP) else if (omp_thread_num == 0) { libsais_count_compacted_lms_suffixes_32s_2k(T, n, k, buckets); } else { m = libsais_gather_compacted_lms_suffixes_32s(T, SA, n); } #endif } return m; } static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_4k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t m; #if defined(_OPENMP) sa_sint_t max_threads = (sa_sint_t)((buckets - &SA[n]) / ((4 * (fast_sint_t)k + 15) & (-16))); if (max_threads > threads) { max_threads = threads; } if (max_threads > 1 && n >= 65536 && n / k >= 2) { if (max_threads > n / 16 / k) { max_threads = n / 16 / k; } m = libsais_count_and_gather_lms_suffixes_32s_4k_fs_omp(T, SA, n, k, buckets, max_threads > 2 ? max_threads : 2, thread_state); } else #else UNUSED(thread_state); #endif { m = libsais_count_and_gather_lms_suffixes_32s_4k_nofs_omp(T, SA, n, k, buckets, threads); } return m; } static sa_sint_t libsais_count_and_gather_lms_suffixes_32s_2k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t m; #if defined(_OPENMP) sa_sint_t max_threads = (sa_sint_t)((buckets - &SA[n]) / ((2 * (fast_sint_t)k + 15) & (-16))); if (max_threads > threads) { max_threads = threads; } if (max_threads > 1 && n >= 65536 && n / k >= 2) { if (max_threads > n / 8 / k) { max_threads = n / 8 / k; } m = libsais_count_and_gather_lms_suffixes_32s_2k_fs_omp(T, SA, n, k, buckets, max_threads > 2 ? max_threads : 2, thread_state); } else #else UNUSED(thread_state); #endif { m = libsais_count_and_gather_lms_suffixes_32s_2k_nofs_omp(T, SA, n, k, buckets, threads); } return m; } static void libsais_count_and_gather_compacted_lms_suffixes_32s_2k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) sa_sint_t max_threads = (sa_sint_t)((buckets - &SA[n + n]) / ((2 * (fast_sint_t)k + 15) & (-16))); if (max_threads > threads) { max_threads = threads; } if (max_threads > 1 && n >= 65536 && n / k >= 2) { if (max_threads > n / 8 / k) { max_threads = n / 8 / k; } libsais_count_and_gather_compacted_lms_suffixes_32s_2k_fs_omp(T, SA, n, k, buckets, max_threads > 2 ? max_threads : 2, thread_state); } else #else UNUSED(thread_state); #endif { libsais_count_and_gather_compacted_lms_suffixes_32s_2k_nofs_omp(T, SA, n, k, buckets, threads); } } static void libsais_count_suffixes_32s(const sa_sint_t * RESTRICT T, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, (size_t)k * sizeof(sa_sint_t)); fast_sint_t i, j; for (i = 0, j = (fast_sint_t)n - 7; i < j; i += 8) { libsais_prefetch(&T[i + prefetch_distance]); buckets[T[i + 0]]++; buckets[T[i + 1]]++; buckets[T[i + 2]]++; buckets[T[i + 3]]++; buckets[T[i + 4]]++; buckets[T[i + 5]]++; buckets[T[i + 6]]++; buckets[T[i + 7]]++; } for (j += 7; i < j; i += 1) { buckets[T[i]]++; } } static void libsais_initialize_buckets_start_and_end_8u(sa_sint_t * RESTRICT buckets, sa_sint_t * RESTRICT freq) { sa_sint_t * RESTRICT bucket_start = &buckets[6 * ALPHABET_SIZE]; sa_sint_t * RESTRICT bucket_end = &buckets[7 * ALPHABET_SIZE]; if (freq != NULL) { fast_sint_t i, j; sa_sint_t sum = 0; for (i = BUCKETS_INDEX4(0, 0), j = 0; i <= BUCKETS_INDEX4(ALPHABET_SIZE - 1, 0); i += BUCKETS_INDEX4(1, 0), j += 1) { bucket_start[j] = sum; sum += (freq[j] = buckets[i + BUCKETS_INDEX4(0, 0)] + buckets[i + BUCKETS_INDEX4(0, 1)] + buckets[i + BUCKETS_INDEX4(0, 2)] + buckets[i + BUCKETS_INDEX4(0, 3)]); bucket_end[j] = sum; } } else { fast_sint_t i, j; sa_sint_t sum = 0; for (i = BUCKETS_INDEX4(0, 0), j = 0; i <= BUCKETS_INDEX4(ALPHABET_SIZE - 1, 0); i += BUCKETS_INDEX4(1, 0), j += 1) { bucket_start[j] = sum; sum += buckets[i + BUCKETS_INDEX4(0, 0)] + buckets[i + BUCKETS_INDEX4(0, 1)] + buckets[i + BUCKETS_INDEX4(0, 2)] + buckets[i + BUCKETS_INDEX4(0, 3)]; bucket_end[j] = sum; } } } static void libsais_initialize_buckets_start_and_end_32s_6k(sa_sint_t k, sa_sint_t * RESTRICT buckets) { sa_sint_t * RESTRICT bucket_start = &buckets[4 * k]; sa_sint_t * RESTRICT bucket_end = &buckets[5 * k]; fast_sint_t i, j; sa_sint_t sum = 0; for (i = BUCKETS_INDEX4(0, 0), j = 0; i <= BUCKETS_INDEX4((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX4(1, 0), j += 1) { bucket_start[j] = sum; sum += buckets[i + BUCKETS_INDEX4(0, 0)] + buckets[i + BUCKETS_INDEX4(0, 1)] + buckets[i + BUCKETS_INDEX4(0, 2)] + buckets[i + BUCKETS_INDEX4(0, 3)]; bucket_end[j] = sum; } } static void libsais_initialize_buckets_start_and_end_32s_4k(sa_sint_t k, sa_sint_t * RESTRICT buckets) { sa_sint_t * RESTRICT bucket_start = &buckets[2 * k]; sa_sint_t * RESTRICT bucket_end = &buckets[3 * k]; fast_sint_t i, j; sa_sint_t sum = 0; for (i = BUCKETS_INDEX2(0, 0), j = 0; i <= BUCKETS_INDEX2((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX2(1, 0), j += 1) { bucket_start[j] = sum; sum += buckets[i + BUCKETS_INDEX2(0, 0)] + buckets[i + BUCKETS_INDEX2(0, 1)]; bucket_end[j] = sum; } } static void libsais_initialize_buckets_end_32s_2k(sa_sint_t k, sa_sint_t * RESTRICT buckets) { fast_sint_t i; sa_sint_t sum0 = 0; for (i = BUCKETS_INDEX2(0, 0); i <= BUCKETS_INDEX2((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX2(1, 0)) { sum0 += buckets[i + BUCKETS_INDEX2(0, 0)] + buckets[i + BUCKETS_INDEX2(0, 1)]; buckets[i + BUCKETS_INDEX2(0, 0)] = sum0; } } static void libsais_initialize_buckets_start_and_end_32s_2k(sa_sint_t k, sa_sint_t * RESTRICT buckets) { fast_sint_t i, j; for (i = BUCKETS_INDEX2(0, 0), j = 0; i <= BUCKETS_INDEX2((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX2(1, 0), j += 1) { buckets[j] = buckets[i]; } buckets[k] = 0; memcpy(&buckets[k + 1], buckets, ((size_t)k - 1) * sizeof(sa_sint_t)); } static void libsais_initialize_buckets_start_32s_1k(sa_sint_t k, sa_sint_t * RESTRICT buckets) { fast_sint_t i; sa_sint_t sum = 0; for (i = 0; i <= (fast_sint_t)k - 1; i += 1) { sa_sint_t tmp = buckets[i]; buckets[i] = sum; sum += tmp; } } static void libsais_initialize_buckets_end_32s_1k(sa_sint_t k, sa_sint_t * RESTRICT buckets) { fast_sint_t i; sa_sint_t sum = 0; for (i = 0; i <= (fast_sint_t)k - 1; i += 1) { sum += buckets[i]; buckets[i] = sum; } } static sa_sint_t libsais_initialize_buckets_for_lms_suffixes_radix_sort_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix) { { fast_uint_t s = 0; fast_sint_t c0 = T[first_lms_suffix]; fast_sint_t c1 = 0; for (; --first_lms_suffix >= 0; ) { c1 = c0; c0 = T[first_lms_suffix]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]--; } buckets[BUCKETS_INDEX4((fast_uint_t)c0, (s << 1) & 3)]--; } { sa_sint_t * RESTRICT temp_bucket = &buckets[4 * ALPHABET_SIZE]; fast_sint_t i, j; sa_sint_t sum = 0; for (i = BUCKETS_INDEX4(0, 0), j = BUCKETS_INDEX2(0, 0); i <= BUCKETS_INDEX4(ALPHABET_SIZE - 1, 0); i += BUCKETS_INDEX4(1, 0), j += BUCKETS_INDEX2(1, 0)) { temp_bucket[j + BUCKETS_INDEX2(0, 1)] = sum; sum += buckets[i + BUCKETS_INDEX4(0, 1)] + buckets[i + BUCKETS_INDEX4(0, 3)]; temp_bucket[j] = sum; } return sum; } } static void libsais_initialize_buckets_for_lms_suffixes_radix_sort_32s_2k(const sa_sint_t * RESTRICT T, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix) { buckets[BUCKETS_INDEX2(T[first_lms_suffix], 0)]++; buckets[BUCKETS_INDEX2(T[first_lms_suffix], 1)]--; fast_sint_t i; sa_sint_t sum0 = 0, sum1 = 0; for (i = BUCKETS_INDEX2(0, 0); i <= BUCKETS_INDEX2((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX2(1, 0)) { sum0 += buckets[i + BUCKETS_INDEX2(0, 0)] + buckets[i + BUCKETS_INDEX2(0, 1)]; sum1 += buckets[i + BUCKETS_INDEX2(0, 1)]; buckets[i + BUCKETS_INDEX2(0, 0)] = sum0; buckets[i + BUCKETS_INDEX2(0, 1)] = sum1; } } static sa_sint_t libsais_initialize_buckets_for_lms_suffixes_radix_sort_32s_6k(const sa_sint_t * RESTRICT T, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix) { { fast_uint_t s = 0; fast_sint_t c0 = T[first_lms_suffix]; fast_sint_t c1 = 0; for (; --first_lms_suffix >= 0; ) { c1 = c0; c0 = T[first_lms_suffix]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); buckets[BUCKETS_INDEX4((fast_uint_t)c1, s & 3)]--; } buckets[BUCKETS_INDEX4((fast_uint_t)c0, (s << 1) & 3)]--; } { sa_sint_t * RESTRICT temp_bucket = &buckets[4 * k]; fast_sint_t i, j; sa_sint_t sum = 0; for (i = BUCKETS_INDEX4(0, 0), j = 0; i <= BUCKETS_INDEX4((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX4(1, 0), j += 1) { sum += buckets[i + BUCKETS_INDEX4(0, 1)] + buckets[i + BUCKETS_INDEX4(0, 3)]; temp_bucket[j] = sum; } return sum; } } static void libsais_initialize_buckets_for_radix_and_partial_sorting_32s_4k(const sa_sint_t * RESTRICT T, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix) { sa_sint_t * RESTRICT bucket_start = &buckets[2 * k]; sa_sint_t * RESTRICT bucket_end = &buckets[3 * k]; buckets[BUCKETS_INDEX2(T[first_lms_suffix], 0)]++; buckets[BUCKETS_INDEX2(T[first_lms_suffix], 1)]--; fast_sint_t i, j; sa_sint_t sum0 = 0, sum1 = 0; for (i = BUCKETS_INDEX2(0, 0), j = 0; i <= BUCKETS_INDEX2((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX2(1, 0), j += 1) { bucket_start[j] = sum1; sum0 += buckets[i + BUCKETS_INDEX2(0, 1)]; sum1 += buckets[i + BUCKETS_INDEX2(0, 0)] + buckets[i + BUCKETS_INDEX2(0, 1)]; buckets[i + BUCKETS_INDEX2(0, 1)] = sum0; bucket_end[j] = sum1; } } static void libsais_radix_sort_lms_suffixes_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetch(&SA[i - 2 * prefetch_distance]); libsais_prefetch(&T[SA[i - prefetch_distance - 0]]); libsais_prefetch(&T[SA[i - prefetch_distance - 1]]); libsais_prefetch(&T[SA[i - prefetch_distance - 2]]); libsais_prefetch(&T[SA[i - prefetch_distance - 3]]); sa_sint_t p0 = SA[i - 0]; SA[--induction_bucket[BUCKETS_INDEX2(T[p0], 0)]] = p0; sa_sint_t p1 = SA[i - 1]; SA[--induction_bucket[BUCKETS_INDEX2(T[p1], 0)]] = p1; sa_sint_t p2 = SA[i - 2]; SA[--induction_bucket[BUCKETS_INDEX2(T[p2], 0)]] = p2; sa_sint_t p3 = SA[i - 3]; SA[--induction_bucket[BUCKETS_INDEX2(T[p3], 0)]] = p3; } for (j -= prefetch_distance + 3; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[--induction_bucket[BUCKETS_INDEX2(T[p], 0)]] = p; } } static void libsais_radix_sort_lms_suffixes_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536 && m >= 65536 && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_num_threads = 1; #endif if (omp_num_threads == 1) { libsais_radix_sort_lms_suffixes_8u(T, SA, &buckets[4 * ALPHABET_SIZE], (fast_sint_t)n - (fast_sint_t)m + 1, (fast_sint_t)m - 1); } #if defined(_OPENMP) else { { sa_sint_t * RESTRICT src_bucket = &buckets[4 * ALPHABET_SIZE]; sa_sint_t * RESTRICT dst_bucket = thread_state[omp_thread_num].state.buckets; fast_sint_t i, j; for (i = BUCKETS_INDEX2(0, 0), j = BUCKETS_INDEX4(0, 1); i <= BUCKETS_INDEX2(ALPHABET_SIZE - 1, 0); i += BUCKETS_INDEX2(1, 0), j += BUCKETS_INDEX4(1, 0)) { dst_bucket[i] = src_bucket[i] - dst_bucket[j]; } } { fast_sint_t t, omp_block_start = 0, omp_block_size = thread_state[omp_thread_num].state.m; for (t = omp_num_threads - 1; t >= omp_thread_num; --t) omp_block_start += thread_state[t].state.m; if (omp_block_start == (fast_sint_t)m && omp_block_size > 0) { omp_block_start -= 1; omp_block_size -= 1; } libsais_radix_sort_lms_suffixes_8u(T, SA, thread_state[omp_thread_num].state.buckets, (fast_sint_t)n - omp_block_start, omp_block_size); } } #endif } } static void libsais_radix_sort_lms_suffixes_32s_6k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + 2 * prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetch(&SA[i - 3 * prefetch_distance]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 0]]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 1]]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 2]]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 3]]); libsais_prefetchw(&induction_bucket[T[SA[i - prefetch_distance - 0]]]); libsais_prefetchw(&induction_bucket[T[SA[i - prefetch_distance - 1]]]); libsais_prefetchw(&induction_bucket[T[SA[i - prefetch_distance - 2]]]); libsais_prefetchw(&induction_bucket[T[SA[i - prefetch_distance - 3]]]); sa_sint_t p0 = SA[i - 0]; SA[--induction_bucket[T[p0]]] = p0; sa_sint_t p1 = SA[i - 1]; SA[--induction_bucket[T[p1]]] = p1; sa_sint_t p2 = SA[i - 2]; SA[--induction_bucket[T[p2]]] = p2; sa_sint_t p3 = SA[i - 3]; SA[--induction_bucket[T[p3]]] = p3; } for (j -= 2 * prefetch_distance + 3; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[--induction_bucket[T[p]]] = p; } } static void libsais_radix_sort_lms_suffixes_32s_2k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + 2 * prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetch(&SA[i - 3 * prefetch_distance]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 0]]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 1]]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 2]]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 3]]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(T[SA[i - prefetch_distance - 0]], 0)]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(T[SA[i - prefetch_distance - 1]], 0)]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(T[SA[i - prefetch_distance - 2]], 0)]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(T[SA[i - prefetch_distance - 3]], 0)]); sa_sint_t p0 = SA[i - 0]; SA[--induction_bucket[BUCKETS_INDEX2(T[p0], 0)]] = p0; sa_sint_t p1 = SA[i - 1]; SA[--induction_bucket[BUCKETS_INDEX2(T[p1], 0)]] = p1; sa_sint_t p2 = SA[i - 2]; SA[--induction_bucket[BUCKETS_INDEX2(T[p2], 0)]] = p2; sa_sint_t p3 = SA[i - 3]; SA[--induction_bucket[BUCKETS_INDEX2(T[p3], 0)]] = p3; } for (j -= 2 * prefetch_distance + 3; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[--induction_bucket[BUCKETS_INDEX2(T[p], 0)]] = p; } } #if defined(_OPENMP) static void libsais_radix_sort_lms_suffixes_32s_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetch(&T[SA[i + prefetch_distance + 0]]); libsais_prefetch(&T[SA[i + prefetch_distance + 1]]); libsais_prefetch(&T[SA[i + prefetch_distance + 2]]); libsais_prefetch(&T[SA[i + prefetch_distance + 3]]); libsais_prefetchw(&cache[i + prefetch_distance]); cache[i + 0].symbol = T[cache[i + 0].index = SA[i + 0]]; cache[i + 1].symbol = T[cache[i + 1].index = SA[i + 1]]; cache[i + 2].symbol = T[cache[i + 2].index = SA[i + 2]]; cache[i + 3].symbol = T[cache[i + 3].index = SA[i + 3]]; } for (j += prefetch_distance + 3; i < j; i += 1) { cache[i].symbol = T[cache[i].index = SA[i]]; } } static void libsais_radix_sort_lms_suffixes_32s_6k_block_sort(sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetchw(&cache[i - 2 * prefetch_distance]); libsais_prefetchw(&induction_bucket[cache[i - prefetch_distance - 0].symbol]); libsais_prefetchw(&induction_bucket[cache[i - prefetch_distance - 1].symbol]); libsais_prefetchw(&induction_bucket[cache[i - prefetch_distance - 2].symbol]); libsais_prefetchw(&induction_bucket[cache[i - prefetch_distance - 3].symbol]); cache[i - 0].symbol = --induction_bucket[cache[i - 0].symbol]; cache[i - 1].symbol = --induction_bucket[cache[i - 1].symbol]; cache[i - 2].symbol = --induction_bucket[cache[i - 2].symbol]; cache[i - 3].symbol = --induction_bucket[cache[i - 3].symbol]; } for (j -= prefetch_distance + 3; i >= j; i -= 1) { cache[i].symbol = --induction_bucket[cache[i].symbol]; } } static void libsais_radix_sort_lms_suffixes_32s_2k_block_sort(sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 3; i >= j; i -= 4) { libsais_prefetchw(&cache[i - 2 * prefetch_distance]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(cache[i - prefetch_distance - 0].symbol, 0)]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(cache[i - prefetch_distance - 1].symbol, 0)]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(cache[i - prefetch_distance - 2].symbol, 0)]); libsais_prefetchw(&induction_bucket[BUCKETS_INDEX2(cache[i - prefetch_distance - 3].symbol, 0)]); cache[i - 0].symbol = --induction_bucket[BUCKETS_INDEX2(cache[i - 0].symbol, 0)]; cache[i - 1].symbol = --induction_bucket[BUCKETS_INDEX2(cache[i - 1].symbol, 0)]; cache[i - 2].symbol = --induction_bucket[BUCKETS_INDEX2(cache[i - 2].symbol, 0)]; cache[i - 3].symbol = --induction_bucket[BUCKETS_INDEX2(cache[i - 3].symbol, 0)]; } for (j -= prefetch_distance + 3; i >= j; i -= 1) { cache[i].symbol = --induction_bucket[BUCKETS_INDEX2(cache[i].symbol, 0)]; } } static void libsais_radix_sort_lms_suffixes_32s_6k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_radix_sort_lms_suffixes_32s_6k(T, SA, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_radix_sort_lms_suffixes_32s_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { libsais_radix_sort_lms_suffixes_32s_6k_block_sort(induction_bucket, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } } static void libsais_radix_sort_lms_suffixes_32s_2k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_radix_sort_lms_suffixes_32s_2k(T, SA, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_radix_sort_lms_suffixes_32s_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { libsais_radix_sort_lms_suffixes_32s_2k_block_sort(induction_bucket, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } } #endif static void libsais_radix_sort_lms_suffixes_32s_6k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (threads == 1 || m < 65536) { libsais_radix_sort_lms_suffixes_32s_6k(T, SA, induction_bucket, (fast_sint_t)n - (fast_sint_t)m + 1, (fast_sint_t)m - 1); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = 0; block_start < (fast_sint_t)m - 1; block_start = block_end) { block_end = block_start + (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end >= m) { block_end = (fast_sint_t)m - 1; } libsais_radix_sort_lms_suffixes_32s_6k_block_omp(T, SA, induction_bucket, thread_state[0].state.cache, (fast_sint_t)n - block_end, block_end - block_start, threads); } } #else UNUSED(thread_state); #endif } static void libsais_radix_sort_lms_suffixes_32s_2k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (threads == 1 || m < 65536) { libsais_radix_sort_lms_suffixes_32s_2k(T, SA, induction_bucket, (fast_sint_t)n - (fast_sint_t)m + 1, (fast_sint_t)m - 1); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = 0; block_start < (fast_sint_t)m - 1; block_start = block_end) { block_end = block_start + (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end >= m) { block_end = (fast_sint_t)m - 1; } libsais_radix_sort_lms_suffixes_32s_2k_block_omp(T, SA, induction_bucket, thread_state[0].state.cache, (fast_sint_t)n - block_end, block_end - block_start, threads); } } #else UNUSED(thread_state); #endif } static sa_sint_t libsais_radix_sort_lms_suffixes_32s_1k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets) { const fast_sint_t prefetch_distance = 32; sa_sint_t i = n - 2; sa_sint_t m = 0; fast_uint_t s = 1; fast_sint_t c0 = T[n - 1]; fast_sint_t c1 = 0; fast_sint_t c2 = 0; for (; i >= prefetch_distance + 3; i -= 4) { libsais_prefetch(&T[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[T[i - prefetch_distance - 0]]); libsais_prefetchw(&buckets[T[i - prefetch_distance - 1]]); libsais_prefetchw(&buckets[T[i - prefetch_distance - 2]]); libsais_prefetchw(&buckets[T[i - prefetch_distance - 3]]); c1 = T[i - 0]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); if ((s & 3) == 1) { SA[--buckets[c2 = c0]] = i + 1; m++; } c0 = T[i - 1]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); if ((s & 3) == 1) { SA[--buckets[c2 = c1]] = i - 0; m++; } c1 = T[i - 2]; s = (s << 1) + (fast_uint_t)(c1 > (c0 - (fast_sint_t)(s & 1))); if ((s & 3) == 1) { SA[--buckets[c2 = c0]] = i - 1; m++; } c0 = T[i - 3]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); if ((s & 3) == 1) { SA[--buckets[c2 = c1]] = i - 2; m++; } } for (; i >= 0; i -= 1) { c1 = c0; c0 = T[i]; s = (s << 1) + (fast_uint_t)(c0 > (c1 - (fast_sint_t)(s & 1))); if ((s & 3) == 1) { SA[--buckets[c2 = c1]] = i + 1; m++; } } if (m > 1) { SA[buckets[c2]] = 0; } return m; } static void libsais_radix_sort_set_markers_32s_6k(sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&induction_bucket[i + 2 * prefetch_distance]); libsais_prefetchw(&SA[induction_bucket[i + prefetch_distance + 0]]); libsais_prefetchw(&SA[induction_bucket[i + prefetch_distance + 1]]); libsais_prefetchw(&SA[induction_bucket[i + prefetch_distance + 2]]); libsais_prefetchw(&SA[induction_bucket[i + prefetch_distance + 3]]); SA[induction_bucket[i + 0]] |= SAINT_MIN; SA[induction_bucket[i + 1]] |= SAINT_MIN; SA[induction_bucket[i + 2]] |= SAINT_MIN; SA[induction_bucket[i + 3]] |= SAINT_MIN; } for (j += prefetch_distance + 3; i < j; i += 1) { SA[induction_bucket[i]] |= SAINT_MIN; } } static void libsais_radix_sort_set_markers_32s_4k(sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&induction_bucket[BUCKETS_INDEX2(i + 2 * prefetch_distance, 0)]); libsais_prefetchw(&SA[induction_bucket[BUCKETS_INDEX2(i + prefetch_distance + 0, 0)]]); libsais_prefetchw(&SA[induction_bucket[BUCKETS_INDEX2(i + prefetch_distance + 1, 0)]]); libsais_prefetchw(&SA[induction_bucket[BUCKETS_INDEX2(i + prefetch_distance + 2, 0)]]); libsais_prefetchw(&SA[induction_bucket[BUCKETS_INDEX2(i + prefetch_distance + 3, 0)]]); SA[induction_bucket[BUCKETS_INDEX2(i + 0, 0)]] |= SUFFIX_GROUP_MARKER; SA[induction_bucket[BUCKETS_INDEX2(i + 1, 0)]] |= SUFFIX_GROUP_MARKER; SA[induction_bucket[BUCKETS_INDEX2(i + 2, 0)]] |= SUFFIX_GROUP_MARKER; SA[induction_bucket[BUCKETS_INDEX2(i + 3, 0)]] |= SUFFIX_GROUP_MARKER; } for (j += prefetch_distance + 3; i < j; i += 1) { SA[induction_bucket[BUCKETS_INDEX2(i, 0)]] |= SUFFIX_GROUP_MARKER; } } static void libsais_radix_sort_set_markers_32s_6k_omp(sa_sint_t * RESTRICT SA, sa_sint_t k, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && k >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); fast_sint_t omp_block_stride = (((fast_sint_t)k - 1) / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : (fast_sint_t)k - 1 - omp_block_start; #else UNUSED(threads); fast_sint_t omp_block_start = 0; fast_sint_t omp_block_size = (fast_sint_t)k - 1; #endif libsais_radix_sort_set_markers_32s_6k(SA, induction_bucket, omp_block_start, omp_block_size); } } static void libsais_radix_sort_set_markers_32s_4k_omp(sa_sint_t * RESTRICT SA, sa_sint_t k, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && k >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); fast_sint_t omp_block_stride = (((fast_sint_t)k - 1) / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : (fast_sint_t)k - 1 - omp_block_start; #else UNUSED(threads); fast_sint_t omp_block_start = 0; fast_sint_t omp_block_size = (fast_sint_t)k - 1; #endif libsais_radix_sort_set_markers_32s_4k(SA, induction_bucket, omp_block_start, omp_block_size); } } static void libsais_initialize_buckets_for_partial_sorting_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix, sa_sint_t left_suffixes_count) { sa_sint_t * RESTRICT temp_bucket = &buckets[4 * ALPHABET_SIZE]; buckets[BUCKETS_INDEX4((fast_uint_t)T[first_lms_suffix], 1)]++; fast_sint_t i, j; sa_sint_t sum0 = left_suffixes_count + 1, sum1 = 0; for (i = BUCKETS_INDEX4(0, 0), j = BUCKETS_INDEX2(0, 0); i <= BUCKETS_INDEX4(ALPHABET_SIZE - 1, 0); i += BUCKETS_INDEX4(1, 0), j += BUCKETS_INDEX2(1, 0)) { temp_bucket[j + BUCKETS_INDEX2(0, 0)] = sum0; sum0 += buckets[i + BUCKETS_INDEX4(0, 0)] + buckets[i + BUCKETS_INDEX4(0, 2)]; sum1 += buckets[i + BUCKETS_INDEX4(0, 1)]; buckets[j + BUCKETS_INDEX2(0, 0)] = sum0; buckets[j + BUCKETS_INDEX2(0, 1)] = sum1; } } static void libsais_initialize_buckets_for_partial_sorting_32s_6k(const sa_sint_t * RESTRICT T, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix, sa_sint_t left_suffixes_count) { sa_sint_t * RESTRICT temp_bucket = &buckets[4 * k]; fast_sint_t i, j; sa_sint_t sum0 = left_suffixes_count + 1, sum1 = 0, sum2 = 0; for (first_lms_suffix = T[first_lms_suffix], i = BUCKETS_INDEX4(0, 0), j = BUCKETS_INDEX2(0, 0); i <= BUCKETS_INDEX4((fast_sint_t)first_lms_suffix - 1, 0); i += BUCKETS_INDEX4(1, 0), j += BUCKETS_INDEX2(1, 0)) { sa_sint_t SS = buckets[i + BUCKETS_INDEX4(0, 0)]; sa_sint_t LS = buckets[i + BUCKETS_INDEX4(0, 1)]; sa_sint_t SL = buckets[i + BUCKETS_INDEX4(0, 2)]; sa_sint_t LL = buckets[i + BUCKETS_INDEX4(0, 3)]; buckets[i + BUCKETS_INDEX4(0, 0)] = sum0; buckets[i + BUCKETS_INDEX4(0, 1)] = sum2; buckets[i + BUCKETS_INDEX4(0, 2)] = 0; buckets[i + BUCKETS_INDEX4(0, 3)] = 0; sum0 += SS + SL; sum1 += LS; sum2 += LS + LL; temp_bucket[j + BUCKETS_INDEX2(0, 0)] = sum0; temp_bucket[j + BUCKETS_INDEX2(0, 1)] = sum1; } for (sum1 += 1; i <= BUCKETS_INDEX4((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX4(1, 0), j += BUCKETS_INDEX2(1, 0)) { sa_sint_t SS = buckets[i + BUCKETS_INDEX4(0, 0)]; sa_sint_t LS = buckets[i + BUCKETS_INDEX4(0, 1)]; sa_sint_t SL = buckets[i + BUCKETS_INDEX4(0, 2)]; sa_sint_t LL = buckets[i + BUCKETS_INDEX4(0, 3)]; buckets[i + BUCKETS_INDEX4(0, 0)] = sum0; buckets[i + BUCKETS_INDEX4(0, 1)] = sum2; buckets[i + BUCKETS_INDEX4(0, 2)] = 0; buckets[i + BUCKETS_INDEX4(0, 3)] = 0; sum0 += SS + SL; sum1 += LS; sum2 += LS + LL; temp_bucket[j + BUCKETS_INDEX2(0, 0)] = sum0; temp_bucket[j + BUCKETS_INDEX2(0, 1)] = sum1; } } static sa_sint_t libsais_partial_sorting_scan_left_to_right_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[4 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 2); sa_sint_t p0 = SA[i + 0]; d += (p0 < 0); p0 &= SAINT_MAX; sa_sint_t v0 = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] >= T[p0 - 1]); SA[induction_bucket[v0]++] = (p0 - 1) | ((sa_sint_t)(distinct_names[v0] != d) << (SAINT_BIT - 1)); distinct_names[v0] = d; sa_sint_t p1 = SA[i + 1]; d += (p1 < 0); p1 &= SAINT_MAX; sa_sint_t v1 = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] >= T[p1 - 1]); SA[induction_bucket[v1]++] = (p1 - 1) | ((sa_sint_t)(distinct_names[v1] != d) << (SAINT_BIT - 1)); distinct_names[v1] = d; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = BUCKETS_INDEX2(T[p - 1], T[p - 2] >= T[p - 1]); SA[induction_bucket[v]++] = (p - 1) | ((sa_sint_t)(distinct_names[v] != d) << (SAINT_BIT - 1)); distinct_names[v] = d; } return d; } #if defined(_OPENMP) static void libsais_partial_sorting_scan_left_to_right_8u_block_prepare(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size, LIBSAIS_THREAD_STATE * RESTRICT state) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; memset(buckets, 0, 4 * ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t i, j, count = 0; sa_sint_t d = 1; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 2); sa_sint_t p0 = cache[count].index = SA[i + 0]; d += (p0 < 0); p0 &= SAINT_MAX; sa_sint_t v0 = cache[count++].symbol = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] >= T[p0 - 1]); induction_bucket[v0]++; distinct_names[v0] = d; sa_sint_t p1 = cache[count].index = SA[i + 1]; d += (p1 < 0); p1 &= SAINT_MAX; sa_sint_t v1 = cache[count++].symbol = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] >= T[p1 - 1]); induction_bucket[v1]++; distinct_names[v1] = d; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = cache[count].index = SA[i]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = cache[count++].symbol = BUCKETS_INDEX2(T[p - 1], T[p - 2] >= T[p - 1]); induction_bucket[v]++; distinct_names[v] = d; } state[0].state.position = (fast_sint_t)d - 1; state[0].state.count = count; } static void libsais_partial_sorting_scan_left_to_right_8u_block_place(sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t count, sa_sint_t d) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; fast_sint_t i, j; for (i = 0, j = count - 1; i < j; i += 2) { libsais_prefetch(&cache[i + prefetch_distance]); sa_sint_t p0 = cache[i + 0].index; d += (p0 < 0); sa_sint_t v0 = cache[i + 0].symbol; SA[induction_bucket[v0]++] = (p0 - 1) | ((sa_sint_t)(distinct_names[v0] != d) << (SAINT_BIT - 1)); distinct_names[v0] = d; sa_sint_t p1 = cache[i + 1].index; d += (p1 < 0); sa_sint_t v1 = cache[i + 1].symbol; SA[induction_bucket[v1]++] = (p1 - 1) | ((sa_sint_t)(distinct_names[v1] != d) << (SAINT_BIT - 1)); distinct_names[v1] = d; } for (j += 1; i < j; i += 1) { sa_sint_t p = cache[i].index; d += (p < 0); sa_sint_t v = cache[i].symbol; SA[induction_bucket[v]++] = (p - 1) | ((sa_sint_t)(distinct_names[v] != d) << (SAINT_BIT - 1)); distinct_names[v] = d; } } static sa_sint_t libsais_partial_sorting_scan_left_to_right_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { d = libsais_partial_sorting_scan_left_to_right_8u(T, SA, buckets, d, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_left_to_right_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size, &thread_state[omp_thread_num]); } #pragma omp barrier #pragma omp master { sa_sint_t * RESTRICT induction_bucket = &buckets[4 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; fast_sint_t t; for (t = 0; t < omp_num_threads; ++t) { sa_sint_t * RESTRICT temp_induction_bucket = &thread_state[t].state.buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT temp_distinct_names = &thread_state[t].state.buckets[2 * ALPHABET_SIZE]; fast_sint_t c; for (c = 0; c < 2 * ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_induction_bucket[c]; induction_bucket[c] = A + B; temp_induction_bucket[c] = A; } for (d -= 1, c = 0; c < 2 * ALPHABET_SIZE; c += 1) { sa_sint_t A = distinct_names[c], B = temp_distinct_names[c], D = B + d; distinct_names[c] = B > 0 ? D : A; temp_distinct_names[c] = A; } d += 1 + (sa_sint_t)thread_state[t].state.position; thread_state[t].state.position = (fast_sint_t)d - thread_state[t].state.position; } } #pragma omp barrier { libsais_partial_sorting_scan_left_to_right_8u_block_place(SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count, (sa_sint_t)thread_state[omp_thread_num].state.position); } } #endif } return d; } #endif static sa_sint_t libsais_partial_sorting_scan_left_to_right_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t left_suffixes_count, sa_sint_t d, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t * RESTRICT induction_bucket = &buckets[4 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; SA[induction_bucket[BUCKETS_INDEX2(T[n - 1], T[n - 2] >= T[n - 1])]++] = (n - 1) | SAINT_MIN; distinct_names[BUCKETS_INDEX2(T[n - 1], T[n - 2] >= T[n - 1])] = ++d; if (threads == 1 || left_suffixes_count < 65536) { d = libsais_partial_sorting_scan_left_to_right_8u(T, SA, buckets, d, 0, left_suffixes_count); } #if defined(_OPENMP) else { fast_sint_t block_start; for (block_start = 0; block_start < left_suffixes_count; ) { if (SA[block_start] == 0) { block_start++; } else { fast_sint_t block_max_end = block_start + ((fast_sint_t)threads) * (LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads); if (block_max_end > left_suffixes_count) { block_max_end = left_suffixes_count;} fast_sint_t block_end = block_start + 1; while (block_end < block_max_end && SA[block_end] != 0) { block_end++; } fast_sint_t block_size = block_end - block_start; if (block_size < 32) { for (; block_start < block_end; block_start += 1) { sa_sint_t p = SA[block_start]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = BUCKETS_INDEX2(T[p - 1], T[p - 2] >= T[p - 1]); SA[induction_bucket[v]++] = (p - 1) | ((sa_sint_t)(distinct_names[v] != d) << (SAINT_BIT - 1)); distinct_names[v] = d; } } else { d = libsais_partial_sorting_scan_left_to_right_8u_block_omp(T, SA, buckets, d, block_start, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif return d; } static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_6k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - 2 * prefetch_distance - 1; i < j; i += 2) { libsais_prefetch(&SA[i + 3 * prefetch_distance]); libsais_prefetch(&T[SA[i + 2 * prefetch_distance + 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + 2 * prefetch_distance + 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i + 2 * prefetch_distance + 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + 2 * prefetch_distance + 1] & SAINT_MAX] - 2); sa_sint_t p0 = SA[i + prefetch_distance + 0] & SAINT_MAX; sa_sint_t v0 = BUCKETS_INDEX4(T[p0 - (p0 > 0)], 0); libsais_prefetchw(&buckets[v0]); sa_sint_t p1 = SA[i + prefetch_distance + 1] & SAINT_MAX; sa_sint_t v1 = BUCKETS_INDEX4(T[p1 - (p1 > 0)], 0); libsais_prefetchw(&buckets[v1]); sa_sint_t p2 = SA[i + 0]; d += (p2 < 0); p2 &= SAINT_MAX; sa_sint_t v2 = BUCKETS_INDEX4(T[p2 - 1], T[p2 - 2] >= T[p2 - 1]); SA[buckets[v2]++] = (p2 - 1) | ((sa_sint_t)(buckets[2 + v2] != d) << (SAINT_BIT - 1)); buckets[2 + v2] = d; sa_sint_t p3 = SA[i + 1]; d += (p3 < 0); p3 &= SAINT_MAX; sa_sint_t v3 = BUCKETS_INDEX4(T[p3 - 1], T[p3 - 2] >= T[p3 - 1]); SA[buckets[v3]++] = (p3 - 1) | ((sa_sint_t)(buckets[2 + v3] != d) << (SAINT_BIT - 1)); buckets[2 + v3] = d; } for (j += 2 * prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = BUCKETS_INDEX4(T[p - 1], T[p - 2] >= T[p - 1]); SA[buckets[v]++] = (p - 1) | ((sa_sint_t)(buckets[2 + v] != d) << (SAINT_BIT - 1)); buckets[2 + v] = d; } return d; } static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_4k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[2 * k]; sa_sint_t * RESTRICT distinct_names = &buckets[0 * k]; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - 2 * prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 3 * prefetch_distance]); sa_sint_t s0 = SA[i + 2 * prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + 2 * prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t s2 = SA[i + 1 * prefetch_distance + 0]; if (s2 > 0) { const fast_sint_t Ts2 = T[(s2 & ~SUFFIX_GROUP_MARKER) - 1]; libsais_prefetchw(&induction_bucket[Ts2]); libsais_prefetchw(&distinct_names[BUCKETS_INDEX2(Ts2, 0)]); } sa_sint_t s3 = SA[i + 1 * prefetch_distance + 1]; if (s3 > 0) { const fast_sint_t Ts3 = T[(s3 & ~SUFFIX_GROUP_MARKER) - 1]; libsais_prefetchw(&induction_bucket[Ts3]); libsais_prefetchw(&distinct_names[BUCKETS_INDEX2(Ts3, 0)]); } sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 & SAINT_MAX; if (p0 > 0) { SA[i + 0] = 0; d += (p0 >> (SUFFIX_GROUP_BIT - 1)); p0 &= ~SUFFIX_GROUP_MARKER; sa_sint_t v0 = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] < T[p0 - 1]); SA[induction_bucket[T[p0 - 1]]++] = (p0 - 1) | ((sa_sint_t)(T[p0 - 2] < T[p0 - 1]) << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v0] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v0] = d; } sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 & SAINT_MAX; if (p1 > 0) { SA[i + 1] = 0; d += (p1 >> (SUFFIX_GROUP_BIT - 1)); p1 &= ~SUFFIX_GROUP_MARKER; sa_sint_t v1 = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] < T[p1 - 1]); SA[induction_bucket[T[p1 - 1]]++] = (p1 - 1) | ((sa_sint_t)(T[p1 - 2] < T[p1 - 1]) << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v1] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v1] = d; } } for (j += 2 * prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { SA[i] = 0; d += (p >> (SUFFIX_GROUP_BIT - 1)); p &= ~SUFFIX_GROUP_MARKER; sa_sint_t v = BUCKETS_INDEX2(T[p - 1], T[p - 2] < T[p - 1]); SA[induction_bucket[T[p - 1]]++] = (p - 1) | ((sa_sint_t)(T[p - 2] < T[p - 1]) << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v] = d; } } return d; } static void libsais_partial_sorting_scan_left_to_right_32s_1k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - 2 * prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 3 * prefetch_distance]); sa_sint_t s0 = SA[i + 2 * prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + 2 * prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t s2 = SA[i + 1 * prefetch_distance + 0]; if (s2 > 0) { libsais_prefetchw(&induction_bucket[T[s2 - 1]]); libsais_prefetch(&T[s2] - 2); } sa_sint_t s3 = SA[i + 1 * prefetch_distance + 1]; if (s3 > 0) { libsais_prefetchw(&induction_bucket[T[s3 - 1]]); libsais_prefetch(&T[s3] - 2); } sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 & SAINT_MAX; if (p0 > 0) { SA[i + 0] = 0; SA[induction_bucket[T[p0 - 1]]++] = (p0 - 1) | ((sa_sint_t)(T[p0 - 2] < T[p0 - 1]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 & SAINT_MAX; if (p1 > 0) { SA[i + 1] = 0; SA[induction_bucket[T[p1 - 1]]++] = (p1 - 1) | ((sa_sint_t)(T[p1 - 2] < T[p1 - 1]) << (SAINT_BIT - 1)); } } for (j += 2 * prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { SA[i] = 0; SA[induction_bucket[T[p - 1]]++] = (p - 1) | ((sa_sint_t)(T[p - 2] < T[p - 1]) << (SAINT_BIT - 1)); } } } #if defined(_OPENMP) static void libsais_partial_sorting_scan_left_to_right_32s_6k_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 2); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t p0 = cache[i + 0].index = SA[i + 0]; sa_sint_t symbol0 = 0; p0 &= SAINT_MAX; if (p0 != 0) { symbol0 = BUCKETS_INDEX4(T[p0 - 1], T[p0 - 2] >= T[p0 - 1]); } cache[i + 0].symbol = symbol0; sa_sint_t p1 = cache[i + 1].index = SA[i + 1]; sa_sint_t symbol1 = 0; p1 &= SAINT_MAX; if (p1 != 0) { symbol1 = BUCKETS_INDEX4(T[p1 - 1], T[p1 - 2] >= T[p1 - 1]); } cache[i + 1].symbol = symbol1; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = cache[i].index = SA[i]; sa_sint_t symbol = 0; p &= SAINT_MAX; if (p != 0) { symbol = BUCKETS_INDEX4(T[p - 1], T[p - 2] >= T[p - 1]); } cache[i].symbol = symbol; } } static void libsais_partial_sorting_scan_left_to_right_32s_4k_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t symbol0 = SAINT_MIN, p0 = SA[i + 0]; if (p0 > 0) { cache[i + 0].index = p0; p0 &= ~SUFFIX_GROUP_MARKER; symbol0 = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] < T[p0 - 1]); p0 = 0; } cache[i + 0].symbol = symbol0; SA[i + 0] = p0 & SAINT_MAX; sa_sint_t symbol1 = SAINT_MIN, p1 = SA[i + 1]; if (p1 > 0) { cache[i + 1].index = p1; p1 &= ~SUFFIX_GROUP_MARKER; symbol1 = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] < T[p1 - 1]); p1 = 0; } cache[i + 1].symbol = symbol1; SA[i + 1] = p1 & SAINT_MAX; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t symbol = SAINT_MIN, p = SA[i]; if (p > 0) { cache[i].index = p; p &= ~SUFFIX_GROUP_MARKER; symbol = BUCKETS_INDEX2(T[p - 1], T[p - 2] < T[p - 1]); p = 0; } cache[i].symbol = symbol; SA[i] = p & SAINT_MAX; } } static void libsais_partial_sorting_scan_left_to_right_32s_1k_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t symbol0 = SAINT_MIN, p0 = SA[i + 0]; if (p0 > 0) { cache[i + 0].index = (p0 - 1) | ((sa_sint_t)(T[p0 - 2] < T[p0 - 1]) << (SAINT_BIT - 1)); symbol0 = T[p0 - 1]; p0 = 0; } cache[i + 0].symbol = symbol0; SA[i + 0] = p0 & SAINT_MAX; sa_sint_t symbol1 = SAINT_MIN, p1 = SA[i + 1]; if (p1 > 0) { cache[i + 1].index = (p1 - 1) | ((sa_sint_t)(T[p1 - 2] < T[p1 - 1]) << (SAINT_BIT - 1)); symbol1 = T[p1 - 1]; p1 = 0; } cache[i + 1].symbol = symbol1; SA[i + 1] = p1 & SAINT_MAX; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t symbol = SAINT_MIN, p = SA[i]; if (p > 0) { cache[i].index = (p - 1) | ((sa_sint_t)(T[p - 2] < T[p - 1]) << (SAINT_BIT - 1)); symbol = T[p - 1]; p = 0; } cache[i].symbol = symbol; SA[i] = p & SAINT_MAX; } } static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_6k_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j, omp_block_end = omp_block_start + omp_block_size; for (i = omp_block_start, j = omp_block_end - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&cache[i + 2 * prefetch_distance]); libsais_prefetchw(&buckets[cache[i + prefetch_distance + 0].symbol]); libsais_prefetchw(&buckets[cache[i + prefetch_distance + 1].symbol]); sa_sint_t v0 = cache[i + 0].symbol, p0 = cache[i + 0].index; d += (p0 < 0); cache[i + 0].symbol = buckets[v0]++; cache[i + 0].index = (p0 - 1) | ((sa_sint_t)(buckets[2 + v0] != d) << (SAINT_BIT - 1)); buckets[2 + v0] = d; if (cache[i + 0].symbol < omp_block_end) { sa_sint_t s = cache[i + 0].symbol, q = (cache[s].index = cache[i + 0].index) & SAINT_MAX; cache[s].symbol = BUCKETS_INDEX4(T[q - 1], T[q - 2] >= T[q - 1]); } sa_sint_t v1 = cache[i + 1].symbol, p1 = cache[i + 1].index; d += (p1 < 0); cache[i + 1].symbol = buckets[v1]++; cache[i + 1].index = (p1 - 1) | ((sa_sint_t)(buckets[2 + v1] != d) << (SAINT_BIT - 1)); buckets[2 + v1] = d; if (cache[i + 1].symbol < omp_block_end) { sa_sint_t s = cache[i + 1].symbol, q = (cache[s].index = cache[i + 1].index) & SAINT_MAX; cache[s].symbol = BUCKETS_INDEX4(T[q - 1], T[q - 2] >= T[q - 1]); } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t v = cache[i].symbol, p = cache[i].index; d += (p < 0); cache[i].symbol = buckets[v]++; cache[i].index = (p - 1) | ((sa_sint_t)(buckets[2 + v] != d) << (SAINT_BIT - 1)); buckets[2 + v] = d; if (cache[i].symbol < omp_block_end) { sa_sint_t s = cache[i].symbol, q = (cache[s].index = cache[i].index) & SAINT_MAX; cache[s].symbol = BUCKETS_INDEX4(T[q - 1], T[q - 2] >= T[q - 1]); } } return d; } static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_4k_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[2 * k]; sa_sint_t * RESTRICT distinct_names = &buckets[0 * k]; fast_sint_t i, j, omp_block_end = omp_block_start + omp_block_size; for (i = omp_block_start, j = omp_block_end - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&cache[i + 2 * prefetch_distance]); sa_sint_t s0 = cache[i + prefetch_distance + 0].symbol; const sa_sint_t * Is0 = &induction_bucket[s0 >> 1]; libsais_prefetchw(s0 >= 0 ? Is0 : NULL); const sa_sint_t * Ds0 = &distinct_names[s0]; libsais_prefetchw(s0 >= 0 ? Ds0 : NULL); sa_sint_t s1 = cache[i + prefetch_distance + 1].symbol; const sa_sint_t * Is1 = &induction_bucket[s1 >> 1]; libsais_prefetchw(s1 >= 0 ? Is1 : NULL); const sa_sint_t * Ds1 = &distinct_names[s1]; libsais_prefetchw(s1 >= 0 ? Ds1 : NULL); sa_sint_t v0 = cache[i + 0].symbol; if (v0 >= 0) { sa_sint_t p0 = cache[i + 0].index; d += (p0 >> (SUFFIX_GROUP_BIT - 1)); cache[i + 0].symbol = induction_bucket[v0 >> 1]++; cache[i + 0].index = (p0 - 1) | (v0 << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v0] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v0] = d; if (cache[i + 0].symbol < omp_block_end) { sa_sint_t ni = cache[i + 0].symbol, np = cache[i + 0].index; if (np > 0) { cache[ni].index = np; np &= ~SUFFIX_GROUP_MARKER; cache[ni].symbol = BUCKETS_INDEX2(T[np - 1], T[np - 2] < T[np - 1]); np = 0; } cache[i + 0].index = np & SAINT_MAX; } } sa_sint_t v1 = cache[i + 1].symbol; if (v1 >= 0) { sa_sint_t p1 = cache[i + 1].index; d += (p1 >> (SUFFIX_GROUP_BIT - 1)); cache[i + 1].symbol = induction_bucket[v1 >> 1]++; cache[i + 1].index = (p1 - 1) | (v1 << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v1] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v1] = d; if (cache[i + 1].symbol < omp_block_end) { sa_sint_t ni = cache[i + 1].symbol, np = cache[i + 1].index; if (np > 0) { cache[ni].index = np; np &= ~SUFFIX_GROUP_MARKER; cache[ni].symbol = BUCKETS_INDEX2(T[np - 1], T[np - 2] < T[np - 1]); np = 0; } cache[i + 1].index = np & SAINT_MAX; } } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t v = cache[i].symbol; if (v >= 0) { sa_sint_t p = cache[i].index; d += (p >> (SUFFIX_GROUP_BIT - 1)); cache[i].symbol = induction_bucket[v >> 1]++; cache[i].index = (p - 1) | (v << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v] = d; if (cache[i].symbol < omp_block_end) { sa_sint_t ni = cache[i].symbol, np = cache[i].index; if (np > 0) { cache[ni].index = np; np &= ~SUFFIX_GROUP_MARKER; cache[ni].symbol = BUCKETS_INDEX2(T[np - 1], T[np - 2] < T[np - 1]); np = 0; } cache[i].index = np & SAINT_MAX; } } } return d; } static void libsais_partial_sorting_scan_left_to_right_32s_1k_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j, omp_block_end = omp_block_start + omp_block_size; for (i = omp_block_start, j = omp_block_end - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&cache[i + 2 * prefetch_distance]); sa_sint_t s0 = cache[i + prefetch_distance + 0].symbol; const sa_sint_t * Is0 = &induction_bucket[s0]; libsais_prefetchw(s0 >= 0 ? Is0 : NULL); sa_sint_t s1 = cache[i + prefetch_distance + 1].symbol; const sa_sint_t * Is1 = &induction_bucket[s1]; libsais_prefetchw(s1 >= 0 ? Is1 : NULL); sa_sint_t v0 = cache[i + 0].symbol; if (v0 >= 0) { cache[i + 0].symbol = induction_bucket[v0]++; if (cache[i + 0].symbol < omp_block_end) { sa_sint_t ni = cache[i + 0].symbol, np = cache[i + 0].index; if (np > 0) { cache[ni].index = (np - 1) | ((sa_sint_t)(T[np - 2] < T[np - 1]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np - 1]; np = 0; } cache[i + 0].index = np & SAINT_MAX; } } sa_sint_t v1 = cache[i + 1].symbol; if (v1 >= 0) { cache[i + 1].symbol = induction_bucket[v1]++; if (cache[i + 1].symbol < omp_block_end) { sa_sint_t ni = cache[i + 1].symbol, np = cache[i + 1].index; if (np > 0) { cache[ni].index = (np - 1) | ((sa_sint_t)(T[np - 2] < T[np - 1]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np - 1]; np = 0; } cache[i + 1].index = np & SAINT_MAX; } } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t v = cache[i].symbol; if (v >= 0) { cache[i].symbol = induction_bucket[v]++; if (cache[i].symbol < omp_block_end) { sa_sint_t ni = cache[i].symbol, np = cache[i].index; if (np > 0) { cache[ni].index = (np - 1) | ((sa_sint_t)(T[np - 2] < T[np - 1]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np - 1]; np = 0; } cache[i].index = np & SAINT_MAX; } } } } static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_6k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { d = libsais_partial_sorting_scan_left_to_right_32s_6k(T, SA, buckets, d, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_left_to_right_32s_6k_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { d = libsais_partial_sorting_scan_left_to_right_32s_6k_block_sort(T, buckets, d, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } return d; } static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_4k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { d = libsais_partial_sorting_scan_left_to_right_32s_4k(T, SA, k, buckets, d, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_left_to_right_32s_4k_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { d = libsais_partial_sorting_scan_left_to_right_32s_4k_block_sort(T, k, buckets, d, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_compact_and_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } return d; } static void libsais_partial_sorting_scan_left_to_right_32s_1k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_partial_sorting_scan_left_to_right_32s_1k(T, SA, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_left_to_right_32s_1k_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { libsais_partial_sorting_scan_left_to_right_32s_1k_block_sort(T, buckets, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_compact_and_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } } #endif static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_6k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t left_suffixes_count, sa_sint_t d, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { SA[buckets[BUCKETS_INDEX4(T[n - 1], T[n - 2] >= T[n - 1])]++] = (n - 1) | SAINT_MIN; buckets[2 + BUCKETS_INDEX4(T[n - 1], T[n - 2] >= T[n - 1])] = ++d; if (threads == 1 || left_suffixes_count < 65536) { d = libsais_partial_sorting_scan_left_to_right_32s_6k(T, SA, buckets, d, 0, left_suffixes_count); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = 0; block_start < left_suffixes_count; block_start = block_end) { block_end = block_start + (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end > left_suffixes_count) { block_end = left_suffixes_count; } d = libsais_partial_sorting_scan_left_to_right_32s_6k_block_omp(T, SA, buckets, d, thread_state[0].state.cache, block_start, block_end - block_start, threads); } } #else UNUSED(thread_state); #endif return d; } static sa_sint_t libsais_partial_sorting_scan_left_to_right_32s_4k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t * RESTRICT induction_bucket = &buckets[2 * k]; sa_sint_t * RESTRICT distinct_names = &buckets[0 * k]; SA[induction_bucket[T[n - 1]]++] = (n - 1) | ((sa_sint_t)(T[n - 2] < T[n - 1]) << (SAINT_BIT - 1)) | SUFFIX_GROUP_MARKER; distinct_names[BUCKETS_INDEX2(T[n - 1], T[n - 2] < T[n - 1])] = ++d; if (threads == 1 || n < 65536) { d = libsais_partial_sorting_scan_left_to_right_32s_4k(T, SA, k, buckets, d, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = 0; block_start < n; block_start = block_end) { block_end = block_start + (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end > n) { block_end = n; } d = libsais_partial_sorting_scan_left_to_right_32s_4k_block_omp(T, SA, k, buckets, d, thread_state[0].state.cache, block_start, block_end - block_start, threads); } } #else UNUSED(thread_state); #endif return d; } static void libsais_partial_sorting_scan_left_to_right_32s_1k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { SA[buckets[T[n - 1]]++] = (n - 1) | ((sa_sint_t)(T[n - 2] < T[n - 1]) << (SAINT_BIT - 1)); if (threads == 1 || n < 65536) { libsais_partial_sorting_scan_left_to_right_32s_1k(T, SA, buckets, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = 0; block_start < n; block_start = block_end) { block_end = block_start + (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end > n) { block_end = n; } libsais_partial_sorting_scan_left_to_right_32s_1k_block_omp(T, SA, buckets, thread_state[0].state.cache, block_start, block_end - block_start, threads); } } #else UNUSED(thread_state); #endif } static void libsais_partial_sorting_shift_markers_8u_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, const sa_sint_t * RESTRICT buckets, sa_sint_t threads) { const fast_sint_t prefetch_distance = 32; const sa_sint_t * RESTRICT temp_bucket = &buckets[4 * ALPHABET_SIZE]; fast_sint_t c; #if defined(_OPENMP) #pragma omp parallel for schedule(static, 1) num_threads(threads) if(threads > 1 && n >= 65536) #else UNUSED(threads); UNUSED(n); #endif for (c = BUCKETS_INDEX2(ALPHABET_SIZE - 1, 0); c >= BUCKETS_INDEX2(1, 0); c -= BUCKETS_INDEX2(1, 0)) { fast_sint_t i, j; sa_sint_t s = SAINT_MIN; for (i = (fast_sint_t)temp_bucket[c] - 1, j = (fast_sint_t)buckets[c - BUCKETS_INDEX2(1, 0)] + 3; i >= j; i -= 4) { libsais_prefetchw(&SA[i - prefetch_distance]); sa_sint_t p0 = SA[i - 0], q0 = (p0 & SAINT_MIN) ^ s; s = s ^ q0; SA[i - 0] = p0 ^ q0; sa_sint_t p1 = SA[i - 1], q1 = (p1 & SAINT_MIN) ^ s; s = s ^ q1; SA[i - 1] = p1 ^ q1; sa_sint_t p2 = SA[i - 2], q2 = (p2 & SAINT_MIN) ^ s; s = s ^ q2; SA[i - 2] = p2 ^ q2; sa_sint_t p3 = SA[i - 3], q3 = (p3 & SAINT_MIN) ^ s; s = s ^ q3; SA[i - 3] = p3 ^ q3; } for (j -= 3; i >= j; i -= 1) { sa_sint_t p = SA[i], q = (p & SAINT_MIN) ^ s; s = s ^ q; SA[i] = p ^ q; } } } static void libsais_partial_sorting_shift_markers_32s_6k_omp(sa_sint_t * RESTRICT SA, sa_sint_t k, const sa_sint_t * RESTRICT buckets, sa_sint_t threads) { const fast_sint_t prefetch_distance = 32; const sa_sint_t * RESTRICT temp_bucket = &buckets[4 * k]; fast_sint_t c; #if defined(_OPENMP) #pragma omp parallel for schedule(static, 1) num_threads(threads) if(threads > 1 && k >= 65536) #else UNUSED(threads); #endif for (c = (fast_sint_t)k - 1; c >= 1; c -= 1) { fast_sint_t i, j; sa_sint_t s = SAINT_MIN; for (i = (fast_sint_t)buckets[BUCKETS_INDEX4(c, 0)] - 1, j = (fast_sint_t)temp_bucket[BUCKETS_INDEX2(c - 1, 0)] + 3; i >= j; i -= 4) { libsais_prefetchw(&SA[i - prefetch_distance]); sa_sint_t p0 = SA[i - 0], q0 = (p0 & SAINT_MIN) ^ s; s = s ^ q0; SA[i - 0] = p0 ^ q0; sa_sint_t p1 = SA[i - 1], q1 = (p1 & SAINT_MIN) ^ s; s = s ^ q1; SA[i - 1] = p1 ^ q1; sa_sint_t p2 = SA[i - 2], q2 = (p2 & SAINT_MIN) ^ s; s = s ^ q2; SA[i - 2] = p2 ^ q2; sa_sint_t p3 = SA[i - 3], q3 = (p3 & SAINT_MIN) ^ s; s = s ^ q3; SA[i - 3] = p3 ^ q3; } for (j -= 3; i >= j; i -= 1) { sa_sint_t p = SA[i], q = (p & SAINT_MIN) ^ s; s = s ^ q; SA[i] = p ^ q; } } } static void libsais_partial_sorting_shift_markers_32s_4k(sa_sint_t * RESTRICT SA, sa_sint_t n) { const fast_sint_t prefetch_distance = 32; fast_sint_t i; sa_sint_t s = SUFFIX_GROUP_MARKER; for (i = (fast_sint_t)n - 1; i >= 3; i -= 4) { libsais_prefetchw(&SA[i - prefetch_distance]); sa_sint_t p0 = SA[i - 0], q0 = ((p0 & SUFFIX_GROUP_MARKER) ^ s) & ((sa_sint_t)(p0 > 0) << ((SUFFIX_GROUP_BIT - 1))); s = s ^ q0; SA[i - 0] = p0 ^ q0; sa_sint_t p1 = SA[i - 1], q1 = ((p1 & SUFFIX_GROUP_MARKER) ^ s) & ((sa_sint_t)(p1 > 0) << ((SUFFIX_GROUP_BIT - 1))); s = s ^ q1; SA[i - 1] = p1 ^ q1; sa_sint_t p2 = SA[i - 2], q2 = ((p2 & SUFFIX_GROUP_MARKER) ^ s) & ((sa_sint_t)(p2 > 0) << ((SUFFIX_GROUP_BIT - 1))); s = s ^ q2; SA[i - 2] = p2 ^ q2; sa_sint_t p3 = SA[i - 3], q3 = ((p3 & SUFFIX_GROUP_MARKER) ^ s) & ((sa_sint_t)(p3 > 0) << ((SUFFIX_GROUP_BIT - 1))); s = s ^ q3; SA[i - 3] = p3 ^ q3; } for (; i >= 0; i -= 1) { sa_sint_t p = SA[i], q = ((p & SUFFIX_GROUP_MARKER) ^ s) & ((sa_sint_t)(p > 0) << ((SUFFIX_GROUP_BIT - 1))); s = s ^ q; SA[i] = p ^ q; } } static void libsais_partial_sorting_shift_buckets_32s_6k(sa_sint_t k, sa_sint_t * RESTRICT buckets) { sa_sint_t * RESTRICT temp_bucket = &buckets[4 * k]; fast_sint_t i; for (i = BUCKETS_INDEX2(0, 0); i <= BUCKETS_INDEX2((fast_sint_t)k - 1, 0); i += BUCKETS_INDEX2(1, 0)) { buckets[2 * i + BUCKETS_INDEX4(0, 0)] = temp_bucket[i + BUCKETS_INDEX2(0, 0)]; buckets[2 * i + BUCKETS_INDEX4(0, 1)] = temp_bucket[i + BUCKETS_INDEX2(0, 1)]; } } static sa_sint_t libsais_partial_sorting_scan_right_to_left_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetch(&SA[i - 2 * prefetch_distance]); libsais_prefetch(&T[SA[i - prefetch_distance - 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i - prefetch_distance - 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i - prefetch_distance - 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i - prefetch_distance - 1] & SAINT_MAX] - 2); sa_sint_t p0 = SA[i - 0]; d += (p0 < 0); p0 &= SAINT_MAX; sa_sint_t v0 = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] > T[p0 - 1]); SA[--induction_bucket[v0]] = (p0 - 1) | ((sa_sint_t)(distinct_names[v0] != d) << (SAINT_BIT - 1)); distinct_names[v0] = d; sa_sint_t p1 = SA[i - 1]; d += (p1 < 0); p1 &= SAINT_MAX; sa_sint_t v1 = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] > T[p1 - 1]); SA[--induction_bucket[v1]] = (p1 - 1) | ((sa_sint_t)(distinct_names[v1] != d) << (SAINT_BIT - 1)); distinct_names[v1] = d; } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = BUCKETS_INDEX2(T[p - 1], T[p - 2] > T[p - 1]); SA[--induction_bucket[v]] = (p - 1) | ((sa_sint_t)(distinct_names[v] != d) << (SAINT_BIT - 1)); distinct_names[v] = d; } return d; } #if defined(_OPENMP) static void libsais_partial_sorting_scan_right_to_left_8u_block_prepare(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size, LIBSAIS_THREAD_STATE * RESTRICT state) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; memset(buckets, 0, 4 * ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t i, j, count = 0; sa_sint_t d = 1; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetch(&SA[i - 2 * prefetch_distance]); libsais_prefetch(&T[SA[i - prefetch_distance - 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i - prefetch_distance - 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i - prefetch_distance - 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i - prefetch_distance - 1] & SAINT_MAX] - 2); sa_sint_t p0 = cache[count].index = SA[i - 0]; d += (p0 < 0); p0 &= SAINT_MAX; sa_sint_t v0 = cache[count++].symbol = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] > T[p0 - 1]); induction_bucket[v0]++; distinct_names[v0] = d; sa_sint_t p1 = cache[count].index = SA[i - 1]; d += (p1 < 0); p1 &= SAINT_MAX; sa_sint_t v1 = cache[count++].symbol = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] > T[p1 - 1]); induction_bucket[v1]++; distinct_names[v1] = d; } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = cache[count].index = SA[i]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = cache[count++].symbol = BUCKETS_INDEX2(T[p - 1], T[p - 2] > T[p - 1]); induction_bucket[v]++; distinct_names[v] = d; } state[0].state.position = (fast_sint_t)d - 1; state[0].state.count = count; } static void libsais_partial_sorting_scan_right_to_left_8u_block_place(sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t count, sa_sint_t d) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; fast_sint_t i, j; for (i = 0, j = count - 1; i < j; i += 2) { libsais_prefetch(&cache[i + prefetch_distance]); sa_sint_t p0 = cache[i + 0].index; d += (p0 < 0); sa_sint_t v0 = cache[i + 0].symbol; SA[--induction_bucket[v0]] = (p0 - 1) | ((sa_sint_t)(distinct_names[v0] != d) << (SAINT_BIT - 1)); distinct_names[v0] = d; sa_sint_t p1 = cache[i + 1].index; d += (p1 < 0); sa_sint_t v1 = cache[i + 1].symbol; SA[--induction_bucket[v1]] = (p1 - 1) | ((sa_sint_t)(distinct_names[v1] != d) << (SAINT_BIT - 1)); distinct_names[v1] = d; } for (j += 1; i < j; i += 1) { sa_sint_t p = cache[i].index; d += (p < 0); sa_sint_t v = cache[i].symbol; SA[--induction_bucket[v]] = (p - 1) | ((sa_sint_t)(distinct_names[v] != d) << (SAINT_BIT - 1)); distinct_names[v] = d; } } static sa_sint_t libsais_partial_sorting_scan_right_to_left_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { d = libsais_partial_sorting_scan_right_to_left_8u(T, SA, buckets, d, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_right_to_left_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size, &thread_state[omp_thread_num]); } #pragma omp barrier #pragma omp master { sa_sint_t * RESTRICT induction_bucket = &buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; fast_sint_t t; for (t = omp_num_threads - 1; t >= 0; --t) { sa_sint_t * RESTRICT temp_induction_bucket = &thread_state[t].state.buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT temp_distinct_names = &thread_state[t].state.buckets[2 * ALPHABET_SIZE]; fast_sint_t c; for (c = 0; c < 2 * ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_induction_bucket[c]; induction_bucket[c] = A - B; temp_induction_bucket[c] = A; } for (d -= 1, c = 0; c < 2 * ALPHABET_SIZE; c += 1) { sa_sint_t A = distinct_names[c], B = temp_distinct_names[c], D = B + d; distinct_names[c] = B > 0 ? D : A; temp_distinct_names[c] = A; } d += 1 + (sa_sint_t)thread_state[t].state.position; thread_state[t].state.position = (fast_sint_t)d - thread_state[t].state.position; } } #pragma omp barrier { libsais_partial_sorting_scan_right_to_left_8u_block_place(SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count, (sa_sint_t)thread_state[omp_thread_num].state.position); } } #endif } return d; } #endif static void libsais_partial_sorting_scan_right_to_left_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix, sa_sint_t left_suffixes_count, sa_sint_t d, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { fast_sint_t scan_start = (fast_sint_t)left_suffixes_count + 1; fast_sint_t scan_end = (fast_sint_t)n - (fast_sint_t)first_lms_suffix; if (threads == 1 || (scan_end - scan_start) < 65536) { libsais_partial_sorting_scan_right_to_left_8u(T, SA, buckets, d, scan_start, scan_end - scan_start); } #if defined(_OPENMP) else { sa_sint_t * RESTRICT induction_bucket = &buckets[0 * ALPHABET_SIZE]; sa_sint_t * RESTRICT distinct_names = &buckets[2 * ALPHABET_SIZE]; fast_sint_t block_start; for (block_start = scan_end - 1; block_start >= scan_start; ) { if (SA[block_start] == 0) { block_start--; } else { fast_sint_t block_max_end = block_start - ((fast_sint_t)threads) * (LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads); if (block_max_end < scan_start) { block_max_end = scan_start - 1; } fast_sint_t block_end = block_start - 1; while (block_end > block_max_end && SA[block_end] != 0) { block_end--; } fast_sint_t block_size = block_start - block_end; if (block_size < 32) { for (; block_start > block_end; block_start -= 1) { sa_sint_t p = SA[block_start]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = BUCKETS_INDEX2(T[p - 1], T[p - 2] > T[p - 1]); SA[--induction_bucket[v]] = (p - 1) | ((sa_sint_t)(distinct_names[v] != d) << (SAINT_BIT - 1)); distinct_names[v] = d; } } else { d = libsais_partial_sorting_scan_right_to_left_8u_block_omp(T, SA, buckets, d, block_end + 1, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif } static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_6k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + 2 * prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetch(&SA[i - 3 * prefetch_distance]); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i - 2 * prefetch_distance - 1] & SAINT_MAX] - 2); sa_sint_t p0 = SA[i - prefetch_distance - 0] & SAINT_MAX; sa_sint_t v0 = BUCKETS_INDEX4(T[p0 - (p0 > 0)], 0); libsais_prefetchw(&buckets[v0]); sa_sint_t p1 = SA[i - prefetch_distance - 1] & SAINT_MAX; sa_sint_t v1 = BUCKETS_INDEX4(T[p1 - (p1 > 0)], 0); libsais_prefetchw(&buckets[v1]); sa_sint_t p2 = SA[i - 0]; d += (p2 < 0); p2 &= SAINT_MAX; sa_sint_t v2 = BUCKETS_INDEX4(T[p2 - 1], T[p2 - 2] > T[p2 - 1]); SA[--buckets[v2]] = (p2 - 1) | ((sa_sint_t)(buckets[2 + v2] != d) << (SAINT_BIT - 1)); buckets[2 + v2] = d; sa_sint_t p3 = SA[i - 1]; d += (p3 < 0); p3 &= SAINT_MAX; sa_sint_t v3 = BUCKETS_INDEX4(T[p3 - 1], T[p3 - 2] > T[p3 - 1]); SA[--buckets[v3]] = (p3 - 1) | ((sa_sint_t)(buckets[2 + v3] != d) << (SAINT_BIT - 1)); buckets[2 + v3] = d; } for (j -= 2 * prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; d += (p < 0); p &= SAINT_MAX; sa_sint_t v = BUCKETS_INDEX4(T[p - 1], T[p - 2] > T[p - 1]); SA[--buckets[v]] = (p - 1) | ((sa_sint_t)(buckets[2 + v] != d) << (SAINT_BIT - 1)); buckets[2 + v] = d; } return d; } static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_4k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[3 * k]; sa_sint_t * RESTRICT distinct_names = &buckets[0 * k]; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + 2 * prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 3 * prefetch_distance]); sa_sint_t s0 = SA[i - 2 * prefetch_distance - 0]; const sa_sint_t * Ts0 = &T[s0 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - 2 * prefetch_distance - 1]; const sa_sint_t * Ts1 = &T[s1 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t s2 = SA[i - 1 * prefetch_distance - 0]; if (s2 > 0) { const fast_sint_t Ts2 = T[(s2 & ~SUFFIX_GROUP_MARKER) - 1]; libsais_prefetchw(&induction_bucket[Ts2]); libsais_prefetchw(&distinct_names[BUCKETS_INDEX2(Ts2, 0)]); } sa_sint_t s3 = SA[i - 1 * prefetch_distance - 1]; if (s3 > 0) { const fast_sint_t Ts3 = T[(s3 & ~SUFFIX_GROUP_MARKER) - 1]; libsais_prefetchw(&induction_bucket[Ts3]); libsais_prefetchw(&distinct_names[BUCKETS_INDEX2(Ts3, 0)]); } sa_sint_t p0 = SA[i - 0]; if (p0 > 0) { SA[i - 0] = 0; d += (p0 >> (SUFFIX_GROUP_BIT - 1)); p0 &= ~SUFFIX_GROUP_MARKER; sa_sint_t v0 = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] > T[p0 - 1]); SA[--induction_bucket[T[p0 - 1]]] = (p0 - 1) | ((sa_sint_t)(T[p0 - 2] > T[p0 - 1]) << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v0] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v0] = d; } sa_sint_t p1 = SA[i - 1]; if (p1 > 0) { SA[i - 1] = 0; d += (p1 >> (SUFFIX_GROUP_BIT - 1)); p1 &= ~SUFFIX_GROUP_MARKER; sa_sint_t v1 = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] > T[p1 - 1]); SA[--induction_bucket[T[p1 - 1]]] = (p1 - 1) | ((sa_sint_t)(T[p1 - 2] > T[p1 - 1]) << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v1] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v1] = d; } } for (j -= 2 * prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; if (p > 0) { SA[i] = 0; d += (p >> (SUFFIX_GROUP_BIT - 1)); p &= ~SUFFIX_GROUP_MARKER; sa_sint_t v = BUCKETS_INDEX2(T[p - 1], T[p - 2] > T[p - 1]); SA[--induction_bucket[T[p - 1]]] = (p - 1) | ((sa_sint_t)(T[p - 2] > T[p - 1]) << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v] = d; } } return d; } static void libsais_partial_sorting_scan_right_to_left_32s_1k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + 2 * prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 3 * prefetch_distance]); sa_sint_t s0 = SA[i - 2 * prefetch_distance - 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - 2 * prefetch_distance - 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t s2 = SA[i - 1 * prefetch_distance - 0]; if (s2 > 0) { libsais_prefetchw(&induction_bucket[T[s2 - 1]]); libsais_prefetch(&T[s2] - 2); } sa_sint_t s3 = SA[i - 1 * prefetch_distance - 1]; if (s3 > 0) { libsais_prefetchw(&induction_bucket[T[s3 - 1]]); libsais_prefetch(&T[s3] - 2); } sa_sint_t p0 = SA[i - 0]; if (p0 > 0) { SA[i - 0] = 0; SA[--induction_bucket[T[p0 - 1]]] = (p0 - 1) | ((sa_sint_t)(T[p0 - 2] > T[p0 - 1]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i - 1]; if (p1 > 0) { SA[i - 1] = 0; SA[--induction_bucket[T[p1 - 1]]] = (p1 - 1) | ((sa_sint_t)(T[p1 - 2] > T[p1 - 1]) << (SAINT_BIT - 1)); } } for (j -= 2 * prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; if (p > 0) { SA[i] = 0; SA[--induction_bucket[T[p - 1]]] = (p - 1) | ((sa_sint_t)(T[p - 2] > T[p - 1]) << (SAINT_BIT - 1)); } } } #if defined(_OPENMP) static void libsais_partial_sorting_scan_right_to_left_32s_6k_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 0] & SAINT_MAX] - 2); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 1); libsais_prefetch(&T[SA[i + prefetch_distance + 1] & SAINT_MAX] - 2); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t p0 = cache[i + 0].index = SA[i + 0]; sa_sint_t symbol0 = 0; p0 &= SAINT_MAX; if (p0 != 0) { symbol0 = BUCKETS_INDEX4(T[p0 - 1], T[p0 - 2] > T[p0 - 1]); } cache[i + 0].symbol = symbol0; sa_sint_t p1 = cache[i + 1].index = SA[i + 1]; sa_sint_t symbol1 = 0; p1 &= SAINT_MAX; if (p1 != 0) { symbol1 = BUCKETS_INDEX4(T[p1 - 1], T[p1 - 2] > T[p1 - 1]); } cache[i + 1].symbol = symbol1; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = cache[i].index = SA[i]; sa_sint_t symbol = 0; p &= SAINT_MAX; if (p != 0) { symbol = BUCKETS_INDEX4(T[p - 1], T[p - 2] > T[p - 1]); } cache[i].symbol = symbol; } } static void libsais_partial_sorting_scan_right_to_left_32s_4k_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1 & ~SUFFIX_GROUP_MARKER] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t symbol0 = SAINT_MIN, p0 = SA[i + 0]; if (p0 > 0) { SA[i + 0] = 0; cache[i + 0].index = p0; p0 &= ~SUFFIX_GROUP_MARKER; symbol0 = BUCKETS_INDEX2(T[p0 - 1], T[p0 - 2] > T[p0 - 1]); } cache[i + 0].symbol = symbol0; sa_sint_t symbol1 = SAINT_MIN, p1 = SA[i + 1]; if (p1 > 0) { SA[i + 1] = 0; cache[i + 1].index = p1; p1 &= ~SUFFIX_GROUP_MARKER; symbol1 = BUCKETS_INDEX2(T[p1 - 1], T[p1 - 2] > T[p1 - 1]); } cache[i + 1].symbol = symbol1; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t symbol = SAINT_MIN, p = SA[i]; if (p > 0) { SA[i] = 0; cache[i].index = p; p &= ~SUFFIX_GROUP_MARKER; symbol = BUCKETS_INDEX2(T[p - 1], T[p - 2] > T[p - 1]); } cache[i].symbol = symbol; } } static void libsais_partial_sorting_scan_right_to_left_32s_1k_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t symbol0 = SAINT_MIN, p0 = SA[i + 0]; if (p0 > 0) { SA[i + 0] = 0; cache[i + 0].index = (p0 - 1) | ((sa_sint_t)(T[p0 - 2] > T[p0 - 1]) << (SAINT_BIT - 1)); symbol0 = T[p0 - 1]; } cache[i + 0].symbol = symbol0; sa_sint_t symbol1 = SAINT_MIN, p1 = SA[i + 1]; if (p1 > 0) { SA[i + 1] = 0; cache[i + 1].index = (p1 - 1) | ((sa_sint_t)(T[p1 - 2] > T[p1 - 1]) << (SAINT_BIT - 1)); symbol1 = T[p1 - 1]; } cache[i + 1].symbol = symbol1; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t symbol = SAINT_MIN, p = SA[i]; if (p > 0) { SA[i] = 0; cache[i].index = (p - 1) | ((sa_sint_t)(T[p - 2] > T[p - 1]) << (SAINT_BIT - 1)); symbol = T[p - 1]; } cache[i].symbol = symbol; } } static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_6k_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&cache[i - 2 * prefetch_distance]); libsais_prefetchw(&buckets[cache[i - prefetch_distance - 0].symbol]); libsais_prefetchw(&buckets[cache[i - prefetch_distance - 1].symbol]); sa_sint_t v0 = cache[i - 0].symbol, p0 = cache[i - 0].index; d += (p0 < 0); cache[i - 0].symbol = --buckets[v0]; cache[i - 0].index = (p0 - 1) | ((sa_sint_t)(buckets[2 + v0] != d) << (SAINT_BIT - 1)); buckets[2 + v0] = d; if (cache[i - 0].symbol >= omp_block_start) { sa_sint_t s = cache[i - 0].symbol, q = (cache[s].index = cache[i - 0].index) & SAINT_MAX; cache[s].symbol = BUCKETS_INDEX4(T[q - 1], T[q - 2] > T[q - 1]); } sa_sint_t v1 = cache[i - 1].symbol, p1 = cache[i - 1].index; d += (p1 < 0); cache[i - 1].symbol = --buckets[v1]; cache[i - 1].index = (p1 - 1) | ((sa_sint_t)(buckets[2 + v1] != d) << (SAINT_BIT - 1)); buckets[2 + v1] = d; if (cache[i - 1].symbol >= omp_block_start) { sa_sint_t s = cache[i - 1].symbol, q = (cache[s].index = cache[i - 1].index) & SAINT_MAX; cache[s].symbol = BUCKETS_INDEX4(T[q - 1], T[q - 2] > T[q - 1]); } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t v = cache[i].symbol, p = cache[i].index; d += (p < 0); cache[i].symbol = --buckets[v]; cache[i].index = (p - 1) | ((sa_sint_t)(buckets[2 + v] != d) << (SAINT_BIT - 1)); buckets[2 + v] = d; if (cache[i].symbol >= omp_block_start) { sa_sint_t s = cache[i].symbol, q = (cache[s].index = cache[i].index) & SAINT_MAX; cache[s].symbol = BUCKETS_INDEX4(T[q - 1], T[q - 2] > T[q - 1]); } } return d; } static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_4k_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT induction_bucket = &buckets[3 * k]; sa_sint_t * RESTRICT distinct_names = &buckets[0 * k]; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&cache[i - 2 * prefetch_distance]); sa_sint_t s0 = cache[i - prefetch_distance - 0].symbol; const sa_sint_t * Is0 = &induction_bucket[s0 >> 1]; libsais_prefetchw(s0 >= 0 ? Is0 : NULL); const sa_sint_t * Ds0 = &distinct_names[s0]; libsais_prefetchw(s0 >= 0 ? Ds0 : NULL); sa_sint_t s1 = cache[i - prefetch_distance - 1].symbol; const sa_sint_t * Is1 = &induction_bucket[s1 >> 1]; libsais_prefetchw(s1 >= 0 ? Is1 : NULL); const sa_sint_t * Ds1 = &distinct_names[s1]; libsais_prefetchw(s1 >= 0 ? Ds1 : NULL); sa_sint_t v0 = cache[i - 0].symbol; if (v0 >= 0) { sa_sint_t p0 = cache[i - 0].index; d += (p0 >> (SUFFIX_GROUP_BIT - 1)); cache[i - 0].symbol = --induction_bucket[v0 >> 1]; cache[i - 0].index = (p0 - 1) | (v0 << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v0] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v0] = d; if (cache[i - 0].symbol >= omp_block_start) { sa_sint_t ni = cache[i - 0].symbol, np = cache[i - 0].index; if (np > 0) { cache[i - 0].index = 0; cache[ni].index = np; np &= ~SUFFIX_GROUP_MARKER; cache[ni].symbol = BUCKETS_INDEX2(T[np - 1], T[np - 2] > T[np - 1]); } } } sa_sint_t v1 = cache[i - 1].symbol; if (v1 >= 0) { sa_sint_t p1 = cache[i - 1].index; d += (p1 >> (SUFFIX_GROUP_BIT - 1)); cache[i - 1].symbol = --induction_bucket[v1 >> 1]; cache[i - 1].index = (p1 - 1) | (v1 << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v1] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v1] = d; if (cache[i - 1].symbol >= omp_block_start) { sa_sint_t ni = cache[i - 1].symbol, np = cache[i - 1].index; if (np > 0) { cache[i - 1].index = 0; cache[ni].index = np; np &= ~SUFFIX_GROUP_MARKER; cache[ni].symbol = BUCKETS_INDEX2(T[np - 1], T[np - 2] > T[np - 1]); } } } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t v = cache[i].symbol; if (v >= 0) { sa_sint_t p = cache[i].index; d += (p >> (SUFFIX_GROUP_BIT - 1)); cache[i].symbol = --induction_bucket[v >> 1]; cache[i].index = (p - 1) | (v << (SAINT_BIT - 1)) | ((sa_sint_t)(distinct_names[v] != d) << (SUFFIX_GROUP_BIT - 1)); distinct_names[v] = d; if (cache[i].symbol >= omp_block_start) { sa_sint_t ni = cache[i].symbol, np = cache[i].index; if (np > 0) { cache[i].index = 0; cache[ni].index = np; np &= ~SUFFIX_GROUP_MARKER; cache[ni].symbol = BUCKETS_INDEX2(T[np - 1], T[np - 2] > T[np - 1]); } } } } return d; } static void libsais_partial_sorting_scan_right_to_left_32s_1k_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&cache[i - 2 * prefetch_distance]); sa_sint_t s0 = cache[i - prefetch_distance - 0].symbol; const sa_sint_t * Is0 = &induction_bucket[s0]; libsais_prefetchw(s0 >= 0 ? Is0 : NULL); sa_sint_t s1 = cache[i - prefetch_distance - 1].symbol; const sa_sint_t * Is1 = &induction_bucket[s1]; libsais_prefetchw(s1 >= 0 ? Is1 : NULL); sa_sint_t v0 = cache[i - 0].symbol; if (v0 >= 0) { cache[i - 0].symbol = --induction_bucket[v0]; if (cache[i - 0].symbol >= omp_block_start) { sa_sint_t ni = cache[i - 0].symbol, np = cache[i - 0].index; if (np > 0) { cache[i - 0].index = 0; cache[ni].index = (np - 1) | ((sa_sint_t)(T[np - 2] > T[np - 1]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np - 1]; } } } sa_sint_t v1 = cache[i - 1].symbol; if (v1 >= 0) { cache[i - 1].symbol = --induction_bucket[v1]; if (cache[i - 1].symbol >= omp_block_start) { sa_sint_t ni = cache[i - 1].symbol, np = cache[i - 1].index; if (np > 0) { cache[i - 1].index = 0; cache[ni].index = (np - 1) | ((sa_sint_t)(T[np - 2] > T[np - 1]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np - 1]; }} } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t v = cache[i].symbol; if (v >= 0) { cache[i].symbol = --induction_bucket[v]; if (cache[i].symbol >= omp_block_start) { sa_sint_t ni = cache[i].symbol, np = cache[i].index; if (np > 0) { cache[i].index = 0; cache[ni].index = (np - 1) | ((sa_sint_t)(T[np - 2] > T[np - 1]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np - 1]; } } } } } static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_6k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { d = libsais_partial_sorting_scan_right_to_left_32s_6k(T, SA, buckets, d, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_right_to_left_32s_6k_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { d = libsais_partial_sorting_scan_right_to_left_32s_6k_block_sort(T, buckets, d, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } return d; } static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_4k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { d = libsais_partial_sorting_scan_right_to_left_32s_4k(T, SA, k, buckets, d, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_right_to_left_32s_4k_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { d = libsais_partial_sorting_scan_right_to_left_32s_4k_block_sort(T, k, buckets, d, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_compact_and_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } return d; } static void libsais_partial_sorting_scan_right_to_left_32s_1k_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_partial_sorting_scan_right_to_left_32s_1k(T, SA, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_partial_sorting_scan_right_to_left_32s_1k_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { libsais_partial_sorting_scan_right_to_left_32s_1k_block_sort(T, buckets, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_compact_and_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } } #endif static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_6k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix, sa_sint_t left_suffixes_count, sa_sint_t d, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { fast_sint_t scan_start = (fast_sint_t)left_suffixes_count + 1; fast_sint_t scan_end = (fast_sint_t)n - (fast_sint_t)first_lms_suffix; if (threads == 1 || (scan_end - scan_start) < 65536) { d = libsais_partial_sorting_scan_right_to_left_32s_6k(T, SA, buckets, d, scan_start, scan_end - scan_start); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = scan_end - 1; block_start >= scan_start; block_start = block_end) { block_end = block_start - (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end < scan_start) { block_end = scan_start - 1; } d = libsais_partial_sorting_scan_right_to_left_32s_6k_block_omp(T, SA, buckets, d, thread_state[0].state.cache, block_end + 1, block_start - block_end, threads); } } #else UNUSED(thread_state); #endif return d; } static sa_sint_t libsais_partial_sorting_scan_right_to_left_32s_4k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t d, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (threads == 1 || n < 65536) { d = libsais_partial_sorting_scan_right_to_left_32s_4k(T, SA, k, buckets, d, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = (fast_sint_t)n - 1; block_start >= 0; block_start = block_end) { block_end = block_start - (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end < 0) { block_end = -1; } d = libsais_partial_sorting_scan_right_to_left_32s_4k_block_omp(T, SA, k, buckets, d, thread_state[0].state.cache, block_end + 1, block_start - block_end, threads); } } #else UNUSED(thread_state); #endif return d; } static void libsais_partial_sorting_scan_right_to_left_32s_1k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (threads == 1 || n < 65536) { libsais_partial_sorting_scan_right_to_left_32s_1k(T, SA, buckets, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = (fast_sint_t)n - 1; block_start >= 0; block_start = block_end) { block_end = block_start - (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end < 0) { block_end = -1; } libsais_partial_sorting_scan_right_to_left_32s_1k_block_omp(T, SA, buckets, thread_state[0].state.cache, block_end + 1, block_start - block_end, threads); } } #else UNUSED(thread_state); #endif } static fast_sint_t libsais_partial_sorting_gather_lms_suffixes_32s_4k(sa_sint_t * RESTRICT SA, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j, l; for (i = omp_block_start, j = omp_block_start + omp_block_size - 3, l = omp_block_start; i < j; i += 4) { libsais_prefetch(&SA[i + prefetch_distance]); sa_sint_t s0 = SA[i + 0]; SA[l] = (s0 - SUFFIX_GROUP_MARKER) & (~SUFFIX_GROUP_MARKER); l += (s0 < 0); sa_sint_t s1 = SA[i + 1]; SA[l] = (s1 - SUFFIX_GROUP_MARKER) & (~SUFFIX_GROUP_MARKER); l += (s1 < 0); sa_sint_t s2 = SA[i + 2]; SA[l] = (s2 - SUFFIX_GROUP_MARKER) & (~SUFFIX_GROUP_MARKER); l += (s2 < 0); sa_sint_t s3 = SA[i + 3]; SA[l] = (s3 - SUFFIX_GROUP_MARKER) & (~SUFFIX_GROUP_MARKER); l += (s3 < 0); } for (j += 3; i < j; i += 1) { sa_sint_t s = SA[i]; SA[l] = (s - SUFFIX_GROUP_MARKER) & (~SUFFIX_GROUP_MARKER); l += (s < 0); } return l; } static fast_sint_t libsais_partial_sorting_gather_lms_suffixes_32s_1k(sa_sint_t * RESTRICT SA, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j, l; for (i = omp_block_start, j = omp_block_start + omp_block_size - 3, l = omp_block_start; i < j; i += 4) { libsais_prefetch(&SA[i + prefetch_distance]); sa_sint_t s0 = SA[i + 0]; SA[l] = s0 & SAINT_MAX; l += (s0 < 0); sa_sint_t s1 = SA[i + 1]; SA[l] = s1 & SAINT_MAX; l += (s1 < 0); sa_sint_t s2 = SA[i + 2]; SA[l] = s2 & SAINT_MAX; l += (s2 < 0); sa_sint_t s3 = SA[i + 3]; SA[l] = s3 & SAINT_MAX; l += (s3 < 0); } for (j += 3; i < j; i += 1) { sa_sint_t s = SA[i]; SA[l] = s & SAINT_MAX; l += (s < 0); } return l; } static void libsais_partial_sorting_gather_lms_suffixes_32s_4k_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { libsais_partial_sorting_gather_lms_suffixes_32s_4k(SA, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.position = omp_block_start; thread_state[omp_thread_num].state.count = libsais_partial_sorting_gather_lms_suffixes_32s_4k(SA, omp_block_start, omp_block_size) - omp_block_start; } #pragma omp barrier #pragma omp master { fast_sint_t t, position = 0; for (t = 0; t < omp_num_threads; ++t) { if (t > 0 && thread_state[t].state.count > 0) { memmove(&SA[position], &SA[thread_state[t].state.position], (size_t)thread_state[t].state.count * sizeof(sa_sint_t)); } position += thread_state[t].state.count; } } } #endif } } static void libsais_partial_sorting_gather_lms_suffixes_32s_1k_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { libsais_partial_sorting_gather_lms_suffixes_32s_1k(SA, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.position = omp_block_start; thread_state[omp_thread_num].state.count = libsais_partial_sorting_gather_lms_suffixes_32s_1k(SA, omp_block_start, omp_block_size) - omp_block_start; } #pragma omp barrier #pragma omp master { fast_sint_t t, position = 0; for (t = 0; t < omp_num_threads; ++t) { if (t > 0 && thread_state[t].state.count > 0) { memmove(&SA[position], &SA[thread_state[t].state.position], (size_t)thread_state[t].state.count * sizeof(sa_sint_t)); } position += thread_state[t].state.count; } } } #endif } } static void libsais_induce_partial_order_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix, sa_sint_t left_suffixes_count, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { memset(&buckets[2 * ALPHABET_SIZE], 0, 2 * ALPHABET_SIZE * sizeof(sa_sint_t)); sa_sint_t d = libsais_partial_sorting_scan_left_to_right_8u_omp(T, SA, n, buckets, left_suffixes_count, 0, threads, thread_state); libsais_partial_sorting_shift_markers_8u_omp(SA, n, buckets, threads); libsais_partial_sorting_scan_right_to_left_8u_omp(T, SA, n, buckets, first_lms_suffix, left_suffixes_count, d, threads, thread_state); } static void libsais_induce_partial_order_32s_6k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t first_lms_suffix, sa_sint_t left_suffixes_count, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t d = libsais_partial_sorting_scan_left_to_right_32s_6k_omp(T, SA, n, buckets, left_suffixes_count, 0, threads, thread_state); libsais_partial_sorting_shift_markers_32s_6k_omp(SA, k, buckets, threads); libsais_partial_sorting_shift_buckets_32s_6k(k, buckets); libsais_partial_sorting_scan_right_to_left_32s_6k_omp(T, SA, n, buckets, first_lms_suffix, left_suffixes_count, d, threads, thread_state); } static void libsais_induce_partial_order_32s_4k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { memset(buckets, 0, 2 * (size_t)k * sizeof(sa_sint_t)); sa_sint_t d = libsais_partial_sorting_scan_left_to_right_32s_4k_omp(T, SA, n, k, buckets, 0, threads, thread_state); libsais_partial_sorting_shift_markers_32s_4k(SA, n); libsais_partial_sorting_scan_right_to_left_32s_4k_omp(T, SA, n, k, buckets, d, threads, thread_state); libsais_partial_sorting_gather_lms_suffixes_32s_4k_omp(SA, n, threads, thread_state); } static void libsais_induce_partial_order_32s_2k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { libsais_partial_sorting_scan_left_to_right_32s_1k_omp(T, SA, n, &buckets[1 * k], threads, thread_state); libsais_partial_sorting_scan_right_to_left_32s_1k_omp(T, SA, n, &buckets[0 * k], threads, thread_state); libsais_partial_sorting_gather_lms_suffixes_32s_1k_omp(SA, n, threads, thread_state); } static void libsais_induce_partial_order_32s_1k_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { libsais_count_suffixes_32s(T, n, k, buckets); libsais_initialize_buckets_start_32s_1k(k, buckets); libsais_partial_sorting_scan_left_to_right_32s_1k_omp(T, SA, n, buckets, threads, thread_state); libsais_count_suffixes_32s(T, n, k, buckets); libsais_initialize_buckets_end_32s_1k(k, buckets); libsais_partial_sorting_scan_right_to_left_32s_1k_omp(T, SA, n, buckets, threads, thread_state); libsais_partial_sorting_gather_lms_suffixes_32s_1k_omp(SA, n, threads, thread_state); } static sa_sint_t libsais_renumber_lms_suffixes_8u(sa_sint_t * RESTRICT SA, sa_sint_t m, sa_sint_t name, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT SAm = &SA[m]; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 0] & SAINT_MAX) >> 1]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 1] & SAINT_MAX) >> 1]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 2] & SAINT_MAX) >> 1]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 3] & SAINT_MAX) >> 1]); sa_sint_t p0 = SA[i + 0]; SAm[(p0 & SAINT_MAX) >> 1] = name | SAINT_MIN; name += p0 < 0; sa_sint_t p1 = SA[i + 1]; SAm[(p1 & SAINT_MAX) >> 1] = name | SAINT_MIN; name += p1 < 0; sa_sint_t p2 = SA[i + 2]; SAm[(p2 & SAINT_MAX) >> 1] = name | SAINT_MIN; name += p2 < 0; sa_sint_t p3 = SA[i + 3]; SAm[(p3 & SAINT_MAX) >> 1] = name | SAINT_MIN; name += p3 < 0; } for (j += prefetch_distance + 3; i < j; i += 1) { sa_sint_t p = SA[i]; SAm[(p & SAINT_MAX) >> 1] = name | SAINT_MIN; name += p < 0; } return name; } static fast_sint_t libsais_gather_marked_suffixes_8u(sa_sint_t * RESTRICT SA, sa_sint_t m, fast_sint_t l, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; l -= 1; fast_sint_t i, j; for (i = (fast_sint_t)m + omp_block_start + omp_block_size - 1, j = (fast_sint_t)m + omp_block_start + 3; i >= j; i -= 4) { libsais_prefetch(&SA[i - prefetch_distance]); sa_sint_t s0 = SA[i - 0]; SA[l] = s0 & SAINT_MAX; l -= s0 < 0; sa_sint_t s1 = SA[i - 1]; SA[l] = s1 & SAINT_MAX; l -= s1 < 0; sa_sint_t s2 = SA[i - 2]; SA[l] = s2 & SAINT_MAX; l -= s2 < 0; sa_sint_t s3 = SA[i - 3]; SA[l] = s3 & SAINT_MAX; l -= s3 < 0; } for (j -= 3; i >= j; i -= 1) { sa_sint_t s = SA[i]; SA[l] = s & SAINT_MAX; l -= s < 0; } l += 1; return l; } static sa_sint_t libsais_renumber_lms_suffixes_8u_omp(sa_sint_t * RESTRICT SA, sa_sint_t m, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t name = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && m >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (m / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : m - omp_block_start; if (omp_num_threads == 1) { name = libsais_renumber_lms_suffixes_8u(SA, m, 0, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_count_negative_marked_suffixes(SA, omp_block_start, omp_block_size); } #pragma omp barrier { fast_sint_t t, count = 0; for (t = 0; t < omp_thread_num; ++t) { count += thread_state[t].state.count; } if (omp_thread_num == omp_num_threads - 1) { name = (sa_sint_t)(count + thread_state[omp_thread_num].state.count); } libsais_renumber_lms_suffixes_8u(SA, m, (sa_sint_t)count, omp_block_start, omp_block_size); } } #endif } return name; } static void libsais_gather_marked_lms_suffixes_8u_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t fs, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 131072) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (((fast_sint_t)n >> 1) / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : ((fast_sint_t)n >> 1) - omp_block_start; if (omp_num_threads == 1) { libsais_gather_marked_suffixes_8u(SA, m, (fast_sint_t)n + (fast_sint_t)fs, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { if (omp_thread_num < omp_num_threads - 1) { thread_state[omp_thread_num].state.position = libsais_gather_marked_suffixes_8u(SA, m, (fast_sint_t)m + omp_block_start + omp_block_size, omp_block_start, omp_block_size); thread_state[omp_thread_num].state.count = (fast_sint_t)m + omp_block_start + omp_block_size - thread_state[omp_thread_num].state.position; } else { thread_state[omp_thread_num].state.position = libsais_gather_marked_suffixes_8u(SA, m, (fast_sint_t)n + (fast_sint_t)fs, omp_block_start, omp_block_size); thread_state[omp_thread_num].state.count = (fast_sint_t)n + (fast_sint_t)fs - thread_state[omp_thread_num].state.position; } } #pragma omp barrier #pragma omp master { fast_sint_t t, position = (fast_sint_t)n + (fast_sint_t)fs; for (t = omp_num_threads - 1; t >= 0; --t) { position -= thread_state[t].state.count; if (t != omp_num_threads - 1 && thread_state[t].state.count > 0) { memmove(&SA[position], &SA[thread_state[t].state.position], (size_t)thread_state[t].state.count * sizeof(sa_sint_t)); } } } } #endif } } static sa_sint_t libsais_renumber_and_gather_lms_suffixes_8u_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t fs, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { memset(&SA[m], 0, ((size_t)n >> 1) * sizeof(sa_sint_t)); sa_sint_t name = libsais_renumber_lms_suffixes_8u_omp(SA, m, threads, thread_state); if (name < m) { libsais_gather_marked_lms_suffixes_8u_omp(SA, n, m, fs, threads, thread_state); } else { fast_sint_t i; for (i = 0; i < m; i += 1) { SA[i] &= SAINT_MAX; } } return name; } static sa_sint_t libsais_renumber_distinct_lms_suffixes_32s_4k(sa_sint_t * RESTRICT SA, sa_sint_t m, sa_sint_t name, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT SAm = &SA[m]; fast_sint_t i, j; sa_sint_t p0, p1, p2, p3 = 0; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 0] & SAINT_MAX) >> 1]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 1] & SAINT_MAX) >> 1]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 2] & SAINT_MAX) >> 1]); libsais_prefetchw(&SAm[(SA[i + prefetch_distance + 3] & SAINT_MAX) >> 1]); p0 = SA[i + 0]; SAm[(SA[i + 0] = p0 & SAINT_MAX) >> 1] = name | (p0 & p3 & SAINT_MIN); name += p0 < 0; p1 = SA[i + 1]; SAm[(SA[i + 1] = p1 & SAINT_MAX) >> 1] = name | (p1 & p0 & SAINT_MIN); name += p1 < 0; p2 = SA[i + 2]; SAm[(SA[i + 2] = p2 & SAINT_MAX) >> 1] = name | (p2 & p1 & SAINT_MIN); name += p2 < 0; p3 = SA[i + 3]; SAm[(SA[i + 3] = p3 & SAINT_MAX) >> 1] = name | (p3 & p2 & SAINT_MIN); name += p3 < 0; } for (j += prefetch_distance + 3; i < j; i += 1) { p2 = p3; p3 = SA[i]; SAm[(SA[i] = p3 & SAINT_MAX) >> 1] = name | (p3 & p2 & SAINT_MIN); name += p3 < 0; } return name; } static void libsais_mark_distinct_lms_suffixes_32s(sa_sint_t * RESTRICT SA, sa_sint_t m, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; sa_sint_t p0, p1, p2, p3 = 0; for (i = (fast_sint_t)m + omp_block_start, j = (fast_sint_t)m + omp_block_start + omp_block_size - 3; i < j; i += 4) { libsais_prefetchw(&SA[i + prefetch_distance]); p0 = SA[i + 0]; SA[i + 0] = p0 & (p3 | SAINT_MAX); p0 = (p0 == 0) ? p3 : p0; p1 = SA[i + 1]; SA[i + 1] = p1 & (p0 | SAINT_MAX); p1 = (p1 == 0) ? p0 : p1; p2 = SA[i + 2]; SA[i + 2] = p2 & (p1 | SAINT_MAX); p2 = (p2 == 0) ? p1 : p2; p3 = SA[i + 3]; SA[i + 3] = p3 & (p2 | SAINT_MAX); p3 = (p3 == 0) ? p2 : p3; } for (j += 3; i < j; i += 1) { p2 = p3; p3 = SA[i]; SA[i] = p3 & (p2 | SAINT_MAX); p3 = (p3 == 0) ? p2 : p3; } } static void libsais_clamp_lms_suffixes_length_32s(sa_sint_t * RESTRICT SA, sa_sint_t m, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT SAm = &SA[m]; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - 3; i < j; i += 4) { libsais_prefetchw(&SAm[i + prefetch_distance]); SAm[i + 0] = (SAm[i + 0] < 0 ? SAm[i + 0] : 0) & SAINT_MAX; SAm[i + 1] = (SAm[i + 1] < 0 ? SAm[i + 1] : 0) & SAINT_MAX; SAm[i + 2] = (SAm[i + 2] < 0 ? SAm[i + 2] : 0) & SAINT_MAX; SAm[i + 3] = (SAm[i + 3] < 0 ? SAm[i + 3] : 0) & SAINT_MAX; } for (j += 3; i < j; i += 1) { SAm[i] = (SAm[i] < 0 ? SAm[i] : 0) & SAINT_MAX; } } static sa_sint_t libsais_renumber_distinct_lms_suffixes_32s_4k_omp(sa_sint_t * RESTRICT SA, sa_sint_t m, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t name = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && m >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (m / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : m - omp_block_start; if (omp_num_threads == 1) { name = libsais_renumber_distinct_lms_suffixes_32s_4k(SA, m, 1, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_count_negative_marked_suffixes(SA, omp_block_start, omp_block_size); } #pragma omp barrier { fast_sint_t t, count = 1; for (t = 0; t < omp_thread_num; ++t) { count += thread_state[t].state.count; } if (omp_thread_num == omp_num_threads - 1) { name = (sa_sint_t)(count + thread_state[omp_thread_num].state.count); } libsais_renumber_distinct_lms_suffixes_32s_4k(SA, m, (sa_sint_t)count, omp_block_start, omp_block_size); } } #endif } return name - 1; } static void libsais_mark_distinct_lms_suffixes_32s_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 131072) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); fast_sint_t omp_block_stride = (((fast_sint_t)n >> 1) / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : ((fast_sint_t)n >> 1) - omp_block_start; #else UNUSED(threads); fast_sint_t omp_block_start = 0; fast_sint_t omp_block_size = (fast_sint_t)n >> 1; #endif libsais_mark_distinct_lms_suffixes_32s(SA, m, omp_block_start, omp_block_size); } } static void libsais_clamp_lms_suffixes_length_32s_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 131072) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); fast_sint_t omp_block_stride = (((fast_sint_t)n >> 1) / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : ((fast_sint_t)n >> 1) - omp_block_start; #else UNUSED(threads); fast_sint_t omp_block_start = 0; fast_sint_t omp_block_size = (fast_sint_t)n >> 1; #endif libsais_clamp_lms_suffixes_length_32s(SA, m, omp_block_start, omp_block_size); } } static sa_sint_t libsais_renumber_and_mark_distinct_lms_suffixes_32s_4k_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { memset(&SA[m], 0, ((size_t)n >> 1) * sizeof(sa_sint_t)); sa_sint_t name = libsais_renumber_distinct_lms_suffixes_32s_4k_omp(SA, m, threads, thread_state); if (name < m) { libsais_mark_distinct_lms_suffixes_32s_omp(SA, n, m, threads); } return name; } static sa_sint_t libsais_renumber_and_mark_distinct_lms_suffixes_32s_1k_omp(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t threads) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT SAm = &SA[m]; { libsais_gather_lms_suffixes_32s(T, SA, n); memset(&SA[m], 0, ((size_t)n - (size_t)m - (size_t)m) * sizeof(sa_sint_t)); fast_sint_t i, j; for (i = (fast_sint_t)n - (fast_sint_t)m, j = (fast_sint_t)n - 1 - prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + prefetch_distance + 0]) >> 1]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + prefetch_distance + 1]) >> 1]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + prefetch_distance + 2]) >> 1]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + prefetch_distance + 3]) >> 1]); SAm[((sa_uint_t)SA[i + 0]) >> 1] = SA[i + 1] - SA[i + 0] + 1 + SAINT_MIN; SAm[((sa_uint_t)SA[i + 1]) >> 1] = SA[i + 2] - SA[i + 1] + 1 + SAINT_MIN; SAm[((sa_uint_t)SA[i + 2]) >> 1] = SA[i + 3] - SA[i + 2] + 1 + SAINT_MIN; SAm[((sa_uint_t)SA[i + 3]) >> 1] = SA[i + 4] - SA[i + 3] + 1 + SAINT_MIN; } for (j += prefetch_distance + 3; i < j; i += 1) { SAm[((sa_uint_t)SA[i]) >> 1] = SA[i + 1] - SA[i] + 1 + SAINT_MIN; } SAm[((sa_uint_t)SA[n - 1]) >> 1] = 1 + SAINT_MIN; } { libsais_clamp_lms_suffixes_length_32s_omp(SA, n, m, threads); } sa_sint_t name = 1; { fast_sint_t i, j, p = SA[0], plen = SAm[p >> 1]; sa_sint_t pdiff = SAINT_MIN; for (i = 1, j = m - prefetch_distance - 1; i < j; i += 2) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + prefetch_distance + 0]) >> 1]); libsais_prefetch(&T[((sa_uint_t)SA[i + prefetch_distance + 0])]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + prefetch_distance + 1]) >> 1]); libsais_prefetch(&T[((sa_uint_t)SA[i + prefetch_distance + 1])]); fast_sint_t q = SA[i + 0], qlen = SAm[q >> 1]; sa_sint_t qdiff = SAINT_MIN; if (plen == qlen) { fast_sint_t l = 0; do { if (T[p + l] != T[q + l]) { break; } } while (++l < qlen); qdiff = (sa_sint_t)(l - qlen) & SAINT_MIN; } SAm[p >> 1] = name | (pdiff & qdiff); name += (qdiff < 0); p = SA[i + 1]; plen = SAm[p >> 1]; pdiff = SAINT_MIN; if (qlen == plen) { fast_sint_t l = 0; do { if (T[q + l] != T[p + l]) { break; } } while (++l < plen); pdiff = (sa_sint_t)(l - plen) & SAINT_MIN; } SAm[q >> 1] = name | (qdiff & pdiff); name += (pdiff < 0); } for (j += prefetch_distance + 1; i < j; i += 1) { fast_sint_t q = SA[i], qlen = SAm[q >> 1]; sa_sint_t qdiff = SAINT_MIN; if (plen == qlen) { fast_sint_t l = 0; do { if (T[p + l] != T[q + l]) { break; } } while (++l < plen); qdiff = (sa_sint_t)(l - plen) & SAINT_MIN; } SAm[p >> 1] = name | (pdiff & qdiff); name += (qdiff < 0); p = q; plen = qlen; pdiff = qdiff; } SAm[p >> 1] = name | pdiff; name++; } if (name <= m) { libsais_mark_distinct_lms_suffixes_32s_omp(SA, n, m, threads); } return name - 1; } static void libsais_reconstruct_lms_suffixes(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; const sa_sint_t * RESTRICT SAnm = &SA[n - m]; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); libsais_prefetch(&SAnm[SA[i + prefetch_distance + 0]]); libsais_prefetch(&SAnm[SA[i + prefetch_distance + 1]]); libsais_prefetch(&SAnm[SA[i + prefetch_distance + 2]]); libsais_prefetch(&SAnm[SA[i + prefetch_distance + 3]]); SA[i + 0] = SAnm[SA[i + 0]]; SA[i + 1] = SAnm[SA[i + 1]]; SA[i + 2] = SAnm[SA[i + 2]]; SA[i + 3] = SAnm[SA[i + 3]]; } for (j += prefetch_distance + 3; i < j; i += 1) { SA[i] = SAnm[SA[i]]; } } static void libsais_reconstruct_lms_suffixes_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && m >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); fast_sint_t omp_block_stride = (m / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : m - omp_block_start; #else UNUSED(threads); fast_sint_t omp_block_start = 0; fast_sint_t omp_block_size = m; #endif libsais_reconstruct_lms_suffixes(SA, n, m, omp_block_start, omp_block_size); } } static void libsais_place_lms_suffixes_interval_8u(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, const sa_sint_t * RESTRICT buckets) { const sa_sint_t * RESTRICT bucket_end = &buckets[7 * ALPHABET_SIZE]; fast_sint_t c, j = n; for (c = ALPHABET_SIZE - 2; c >= 0; --c) { fast_sint_t l = (fast_sint_t)buckets[BUCKETS_INDEX2(c, 1) + BUCKETS_INDEX2(1, 0)] - (fast_sint_t)buckets[BUCKETS_INDEX2(c, 1)]; if (l > 0) { fast_sint_t i = bucket_end[c]; if (j - i > 0) { memset(&SA[i], 0, (size_t)(j - i) * sizeof(sa_sint_t)); } memmove(&SA[j = (i - l)], &SA[m -= (sa_sint_t)l], (size_t)l * sizeof(sa_sint_t)); } } memset(&SA[0], 0, (size_t)j * sizeof(sa_sint_t)); } static void libsais_place_lms_suffixes_interval_32s_4k(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t m, const sa_sint_t * RESTRICT buckets) { const sa_sint_t * RESTRICT bucket_end = &buckets[3 * k]; fast_sint_t c, j = n; for (c = (fast_sint_t)k - 2; c >= 0; --c) { fast_sint_t l = (fast_sint_t)buckets[BUCKETS_INDEX2(c, 1) + BUCKETS_INDEX2(1, 0)] - (fast_sint_t)buckets[BUCKETS_INDEX2(c, 1)]; if (l > 0) { fast_sint_t i = bucket_end[c]; if (j - i > 0) { memset(&SA[i], 0, (size_t)(j - i) * sizeof(sa_sint_t)); } memmove(&SA[j = (i - l)], &SA[m -= (sa_sint_t)l], (size_t)l * sizeof(sa_sint_t)); } } memset(&SA[0], 0, (size_t)j * sizeof(sa_sint_t)); } static void libsais_place_lms_suffixes_interval_32s_2k(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t m, const sa_sint_t * RESTRICT buckets) { fast_sint_t j = n; if (k > 1) { fast_sint_t c; for (c = BUCKETS_INDEX2((fast_sint_t)k - 2, 0); c >= BUCKETS_INDEX2(0, 0); c -= BUCKETS_INDEX2(1, 0)) { fast_sint_t l = (fast_sint_t)buckets[c + BUCKETS_INDEX2(1, 1)] - (fast_sint_t)buckets[c + BUCKETS_INDEX2(0, 1)]; if (l > 0) { fast_sint_t i = buckets[c]; if (j - i > 0) { memset(&SA[i], 0, (size_t)(j - i) * sizeof(sa_sint_t)); } memmove(&SA[j = (i - l)], &SA[m -= (sa_sint_t)l], (size_t)l * sizeof(sa_sint_t)); } } } memset(&SA[0], 0, (size_t)j * sizeof(sa_sint_t)); } static void libsais_place_lms_suffixes_interval_32s_1k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t k, sa_sint_t m, sa_sint_t * RESTRICT buckets) { const fast_sint_t prefetch_distance = 32; sa_sint_t c = k - 1; fast_sint_t i, l = buckets[c]; for (i = (fast_sint_t)m - 1; i >= prefetch_distance + 3; i -= 4) { libsais_prefetch(&SA[i - 2 * prefetch_distance]); libsais_prefetch(&T[SA[i - prefetch_distance - 0]]); libsais_prefetch(&T[SA[i - prefetch_distance - 1]]); libsais_prefetch(&T[SA[i - prefetch_distance - 2]]); libsais_prefetch(&T[SA[i - prefetch_distance - 3]]); sa_sint_t p0 = SA[i - 0]; if (T[p0] != c) { c = T[p0]; memset(&SA[buckets[c]], 0, (size_t)(l - buckets[c]) * sizeof(sa_sint_t)); l = buckets[c]; } SA[--l] = p0; sa_sint_t p1 = SA[i - 1]; if (T[p1] != c) { c = T[p1]; memset(&SA[buckets[c]], 0, (size_t)(l - buckets[c]) * sizeof(sa_sint_t)); l = buckets[c]; } SA[--l] = p1; sa_sint_t p2 = SA[i - 2]; if (T[p2] != c) { c = T[p2]; memset(&SA[buckets[c]], 0, (size_t)(l - buckets[c]) * sizeof(sa_sint_t)); l = buckets[c]; } SA[--l] = p2; sa_sint_t p3 = SA[i - 3]; if (T[p3] != c) { c = T[p3]; memset(&SA[buckets[c]], 0, (size_t)(l - buckets[c]) * sizeof(sa_sint_t)); l = buckets[c]; } SA[--l] = p3; } for (; i >= 0; i -= 1) { sa_sint_t p = SA[i]; if (T[p] != c) { c = T[p]; memset(&SA[buckets[c]], 0, (size_t)(l - buckets[c]) * sizeof(sa_sint_t)); l = buckets[c]; } SA[--l] = p; } memset(&SA[0], 0, (size_t)l * sizeof(sa_sint_t)); } static void libsais_place_lms_suffixes_histogram_32s_6k(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t m, const sa_sint_t * RESTRICT buckets) { const sa_sint_t * RESTRICT bucket_end = &buckets[5 * k]; fast_sint_t c, j = n; for (c = (fast_sint_t)k - 2; c >= 0; --c) { fast_sint_t l = (fast_sint_t)buckets[BUCKETS_INDEX4(c, 1)]; if (l > 0) { fast_sint_t i = bucket_end[c]; if (j - i > 0) { memset(&SA[i], 0, (size_t)(j - i) * sizeof(sa_sint_t)); } memmove(&SA[j = (i - l)], &SA[m -= (sa_sint_t)l], (size_t)l * sizeof(sa_sint_t)); } } memset(&SA[0], 0, (size_t)j * sizeof(sa_sint_t)); } static void libsais_place_lms_suffixes_histogram_32s_4k(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t m, const sa_sint_t * RESTRICT buckets) { const sa_sint_t * RESTRICT bucket_end = &buckets[3 * k]; fast_sint_t c, j = n; for (c = (fast_sint_t)k - 2; c >= 0; --c) { fast_sint_t l = (fast_sint_t)buckets[BUCKETS_INDEX2(c, 1)]; if (l > 0) { fast_sint_t i = bucket_end[c]; if (j - i > 0) { memset(&SA[i], 0, (size_t)(j - i) * sizeof(sa_sint_t)); } memmove(&SA[j = (i - l)], &SA[m -= (sa_sint_t)l], (size_t)l * sizeof(sa_sint_t)); } } memset(&SA[0], 0, (size_t)j * sizeof(sa_sint_t)); } static void libsais_place_lms_suffixes_histogram_32s_2k(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t m, const sa_sint_t * RESTRICT buckets) { fast_sint_t j = n; if (k > 1) { fast_sint_t c; for (c = BUCKETS_INDEX2((fast_sint_t)k - 2, 0); c >= BUCKETS_INDEX2(0, 0); c -= BUCKETS_INDEX2(1, 0)) { fast_sint_t l = (fast_sint_t)buckets[c + BUCKETS_INDEX2(0, 1)]; if (l > 0) { fast_sint_t i = buckets[c]; if (j - i > 0) { memset(&SA[i], 0, (size_t)(j - i) * sizeof(sa_sint_t)); } memmove(&SA[j = (i - l)], &SA[m -= (sa_sint_t)l], (size_t)l * sizeof(sa_sint_t)); } } } memset(&SA[0], 0, (size_t)j * sizeof(sa_sint_t)); } static void libsais_final_bwt_scan_left_to_right_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; SA[i + 0] = T[p0] | SAINT_MIN; SA[induction_bucket[T[p0]]++] = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] < T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; SA[i + 1] = T[p1] | SAINT_MIN; SA[induction_bucket[T[p1]]++] = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] < T[p1]) << (SAINT_BIT - 1)); } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; SA[i] = T[p] | SAINT_MIN; SA[induction_bucket[T[p]]++] = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); } } } static void libsais_final_bwt_aux_scan_left_to_right_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; SA[i + 0] = T[p0] | SAINT_MIN; SA[induction_bucket[T[p0]]++] = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] < T[p0]) << (SAINT_BIT - 1)); if ((p0 & rm) == 0) { I[p0 / (rm + 1)] = induction_bucket[T[p0]]; }} sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; SA[i + 1] = T[p1] | SAINT_MIN; SA[induction_bucket[T[p1]]++] = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] < T[p1]) << (SAINT_BIT - 1)); if ((p1 & rm) == 0) { I[p1 / (rm + 1)] = induction_bucket[T[p1]]; }} } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; SA[i] = T[p] | SAINT_MIN; SA[induction_bucket[T[p]]++] = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); if ((p & rm) == 0) { I[p / (rm + 1)] = induction_bucket[T[p]]; } } } } static void libsais_final_sorting_scan_left_to_right_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 ^ SAINT_MIN; if (p0 > 0) { p0--; SA[induction_bucket[T[p0]]++] = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] < T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 ^ SAINT_MIN; if (p1 > 0) { p1--; SA[induction_bucket[T[p1]]++] = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] < T[p1]) << (SAINT_BIT - 1)); } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p ^ SAINT_MIN; if (p > 0) { p--; SA[induction_bucket[T[p]]++] = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); } } } static void libsais_final_sorting_scan_left_to_right_32s(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - 2 * prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 3 * prefetch_distance]); sa_sint_t s0 = SA[i + 2 * prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + 2 * prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t s2 = SA[i + 1 * prefetch_distance + 0]; if (s2 > 0) { libsais_prefetchw(&induction_bucket[T[s2 - 1]]); libsais_prefetch(&T[s2] - 2); } sa_sint_t s3 = SA[i + 1 * prefetch_distance + 1]; if (s3 > 0) { libsais_prefetchw(&induction_bucket[T[s3 - 1]]); libsais_prefetch(&T[s3] - 2); } sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 ^ SAINT_MIN; if (p0 > 0) { p0--; SA[induction_bucket[T[p0]]++] = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] < T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 ^ SAINT_MIN; if (p1 > 0) { p1--; SA[induction_bucket[T[p1]]++] = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] < T[p1]) << (SAINT_BIT - 1)); } } for (j += 2 * prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p ^ SAINT_MIN; if (p > 0) { p--; SA[induction_bucket[T[p]]++] = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); } } } #if defined(_OPENMP) static fast_sint_t libsais_final_bwt_scan_left_to_right_8u_block_prepare(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t i, j, count = 0; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; SA[i + 0] = T[p0] | SAINT_MIN; buckets[cache[count].symbol = T[p0]]++; cache[count++].index = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] < T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; SA[i + 1] = T[p1] | SAINT_MIN; buckets[cache[count].symbol = T[p1]]++; cache[count++].index = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] < T[p1]) << (SAINT_BIT - 1)); } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; SA[i] = T[p] | SAINT_MIN; buckets[cache[count].symbol = T[p]]++; cache[count++].index = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); } } return count; } static fast_sint_t libsais_final_sorting_scan_left_to_right_8u_block_prepare(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t i, j, count = 0; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i + 0]; SA[i + 0] = p0 ^ SAINT_MIN; if (p0 > 0) { p0--; buckets[cache[count].symbol = T[p0]]++; cache[count++].index = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] < T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i + 1]; SA[i + 1] = p1 ^ SAINT_MIN; if (p1 > 0) { p1--; buckets[cache[count].symbol = T[p1]]++; cache[count++].index = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] < T[p1]) << (SAINT_BIT - 1)); } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t p = SA[i]; SA[i] = p ^ SAINT_MIN; if (p > 0) { p--; buckets[cache[count].symbol = T[p]]++; cache[count++].index = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); } } return count; } static void libsais_final_order_scan_left_to_right_8u_block_place(sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t count) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = 0, j = count - 3; i < j; i += 4) { libsais_prefetch(&cache[i + prefetch_distance]); SA[buckets[cache[i + 0].symbol]++] = cache[i + 0].index; SA[buckets[cache[i + 1].symbol]++] = cache[i + 1].index; SA[buckets[cache[i + 2].symbol]++] = cache[i + 2].index; SA[buckets[cache[i + 3].symbol]++] = cache[i + 3].index; } for (j += 3; i < j; i += 1) { SA[buckets[cache[i].symbol]++] = cache[i].index; } } static void libsais_final_bwt_aux_scan_left_to_right_8u_block_place(sa_sint_t * RESTRICT SA, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t count) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = 0, j = count - 3; i < j; i += 4) { libsais_prefetch(&cache[i + prefetch_distance]); SA[buckets[cache[i + 0].symbol]++] = cache[i + 0].index; if ((cache[i + 0].index & rm) == 0) { I[(cache[i + 0].index & SAINT_MAX) / (rm + 1)] = buckets[cache[i + 0].symbol]; } SA[buckets[cache[i + 1].symbol]++] = cache[i + 1].index; if ((cache[i + 1].index & rm) == 0) { I[(cache[i + 1].index & SAINT_MAX) / (rm + 1)] = buckets[cache[i + 1].symbol]; } SA[buckets[cache[i + 2].symbol]++] = cache[i + 2].index; if ((cache[i + 2].index & rm) == 0) { I[(cache[i + 2].index & SAINT_MAX) / (rm + 1)] = buckets[cache[i + 2].symbol]; } SA[buckets[cache[i + 3].symbol]++] = cache[i + 3].index; if ((cache[i + 3].index & rm) == 0) { I[(cache[i + 3].index & SAINT_MAX) / (rm + 1)] = buckets[cache[i + 3].symbol]; } } for (j += 3; i < j; i += 1) { SA[buckets[cache[i].symbol]++] = cache[i].index; if ((cache[i].index & rm) == 0) { I[(cache[i].index & SAINT_MAX) / (rm + 1)] = buckets[cache[i].symbol]; } } } static void libsais_final_sorting_scan_left_to_right_32s_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t symbol0 = SAINT_MIN, p0 = SA[i + 0]; SA[i + 0] = p0 ^ SAINT_MIN; if (p0 > 0) { p0--; cache[i + 0].index = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] < T[p0]) << (SAINT_BIT - 1)); symbol0 = T[p0]; } cache[i + 0].symbol = symbol0; sa_sint_t symbol1 = SAINT_MIN, p1 = SA[i + 1]; SA[i + 1] = p1 ^ SAINT_MIN; if (p1 > 0) { p1--; cache[i + 1].index = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] < T[p1]) << (SAINT_BIT - 1)); symbol1 = T[p1]; } cache[i + 1].symbol = symbol1; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t symbol = SAINT_MIN, p = SA[i]; SA[i] = p ^ SAINT_MIN; if (p > 0) { p--; cache[i].index = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); symbol = T[p]; } cache[i].symbol = symbol; } } static void libsais_final_sorting_scan_left_to_right_32s_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j, omp_block_end = omp_block_start + omp_block_size; for (i = omp_block_start, j = omp_block_end - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&cache[i + 2 * prefetch_distance]); sa_sint_t s0 = cache[i + prefetch_distance + 0].symbol; const sa_sint_t * Is0 = &induction_bucket[s0]; libsais_prefetchw(s0 >= 0 ? Is0 : NULL); sa_sint_t s1 = cache[i + prefetch_distance + 1].symbol; const sa_sint_t * Is1 = &induction_bucket[s1]; libsais_prefetchw(s1 >= 0 ? Is1 : NULL); sa_sint_t v0 = cache[i + 0].symbol; if (v0 >= 0) { cache[i + 0].symbol = induction_bucket[v0]++; if (cache[i + 0].symbol < omp_block_end) { sa_sint_t ni = cache[i + 0].symbol, np = cache[i + 0].index; cache[i + 0].index = np ^ SAINT_MIN; if (np > 0) { np--; cache[ni].index = np | ((sa_sint_t)(T[np - (np > 0)] < T[np]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np]; } } } sa_sint_t v1 = cache[i + 1].symbol; if (v1 >= 0) { cache[i + 1].symbol = induction_bucket[v1]++; if (cache[i + 1].symbol < omp_block_end) { sa_sint_t ni = cache[i + 1].symbol, np = cache[i + 1].index; cache[i + 1].index = np ^ SAINT_MIN; if (np > 0) { np--; cache[ni].index = np | ((sa_sint_t)(T[np - (np > 0)] < T[np]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np]; } } } } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t v = cache[i].symbol; if (v >= 0) { cache[i].symbol = induction_bucket[v]++; if (cache[i].symbol < omp_block_end) { sa_sint_t ni = cache[i].symbol, np = cache[i].index; cache[i].index = np ^ SAINT_MIN; if (np > 0) { np--; cache[ni].index = np | ((sa_sint_t)(T[np - (np > 0)] < T[np]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np]; } } } } } static void libsais_final_bwt_scan_left_to_right_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_bwt_scan_left_to_right_8u(T, SA, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_final_bwt_scan_left_to_right_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { fast_sint_t t; for (t = 0; t < omp_num_threads; ++t) { sa_sint_t * RESTRICT temp_bucket = thread_state[t].state.buckets; fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_bucket[c]; induction_bucket[c] = A + B; temp_bucket[c] = A; } } } #pragma omp barrier { libsais_final_order_scan_left_to_right_8u_block_place(SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count); } } #endif } } static void libsais_final_bwt_aux_scan_left_to_right_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT induction_bucket, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_bwt_aux_scan_left_to_right_8u(T, SA, rm, I, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_final_bwt_scan_left_to_right_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { fast_sint_t t; for (t = 0; t < omp_num_threads; ++t) { sa_sint_t * RESTRICT temp_bucket = thread_state[t].state.buckets; fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_bucket[c]; induction_bucket[c] = A + B; temp_bucket[c] = A; } } } #pragma omp barrier { libsais_final_bwt_aux_scan_left_to_right_8u_block_place(SA, rm, I, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count); } } #endif } } static void libsais_final_sorting_scan_left_to_right_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_sorting_scan_left_to_right_8u(T, SA, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_final_sorting_scan_left_to_right_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { fast_sint_t t; for (t = 0; t < omp_num_threads; ++t) { sa_sint_t * RESTRICT temp_bucket = thread_state[t].state.buckets; fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_bucket[c]; induction_bucket[c] = A + B; temp_bucket[c] = A; } } } #pragma omp barrier { libsais_final_order_scan_left_to_right_8u_block_place(SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count); } } #endif } } static void libsais_final_sorting_scan_left_to_right_32s_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_sorting_scan_left_to_right_32s(T, SA, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_final_sorting_scan_left_to_right_32s_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { libsais_final_sorting_scan_left_to_right_32s_block_sort(T, buckets, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_compact_and_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } } #endif static void libsais_final_bwt_scan_left_to_right_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, fast_sint_t n, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { SA[induction_bucket[T[(sa_sint_t)n - 1]]++] = ((sa_sint_t)n - 1) | ((sa_sint_t)(T[(sa_sint_t)n - 2] < T[(sa_sint_t)n - 1]) << (SAINT_BIT - 1)); if (threads == 1 || n < 65536) { libsais_final_bwt_scan_left_to_right_8u(T, SA, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start; for (block_start = 0; block_start < n; ) { if (SA[block_start] == 0) { block_start++; } else { fast_sint_t block_max_end = block_start + ((fast_sint_t)threads) * (LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads); if (block_max_end > n) { block_max_end = n;} fast_sint_t block_end = block_start + 1; while (block_end < block_max_end && SA[block_end] != 0) { block_end++; } fast_sint_t block_size = block_end - block_start; if (block_size < 32) { for (; block_start < block_end; block_start += 1) { sa_sint_t p = SA[block_start]; SA[block_start] = p & SAINT_MAX; if (p > 0) { p--; SA[block_start] = T[p] | SAINT_MIN; SA[induction_bucket[T[p]]++] = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); } } } else { libsais_final_bwt_scan_left_to_right_8u_block_omp(T, SA, induction_bucket, block_start, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif } static void libsais_final_bwt_aux_scan_left_to_right_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, fast_sint_t n, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { SA[induction_bucket[T[(sa_sint_t)n - 1]]++] = ((sa_sint_t)n - 1) | ((sa_sint_t)(T[(sa_sint_t)n - 2] < T[(sa_sint_t)n - 1]) << (SAINT_BIT - 1)); if ((((sa_sint_t)n - 1) & rm) == 0) { I[((sa_sint_t)n - 1) / (rm + 1)] = induction_bucket[T[(sa_sint_t)n - 1]]; } if (threads == 1 || n < 65536) { libsais_final_bwt_aux_scan_left_to_right_8u(T, SA, rm, I, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start; for (block_start = 0; block_start < n; ) { if (SA[block_start] == 0) { block_start++; } else { fast_sint_t block_max_end = block_start + ((fast_sint_t)threads) * (LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads); if (block_max_end > n) { block_max_end = n;} fast_sint_t block_end = block_start + 1; while (block_end < block_max_end && SA[block_end] != 0) { block_end++; } fast_sint_t block_size = block_end - block_start; if (block_size < 32) { for (; block_start < block_end; block_start += 1) { sa_sint_t p = SA[block_start]; SA[block_start] = p & SAINT_MAX; if (p > 0) { p--; SA[block_start] = T[p] | SAINT_MIN; SA[induction_bucket[T[p]]++] = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); if ((p & rm) == 0) { I[p / (rm + 1)] = induction_bucket[T[p]]; } } } } else { libsais_final_bwt_aux_scan_left_to_right_8u_block_omp(T, SA, rm, I, induction_bucket, block_start, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif } static void libsais_final_sorting_scan_left_to_right_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, fast_sint_t n, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { SA[induction_bucket[T[(sa_sint_t)n - 1]]++] = ((sa_sint_t)n - 1) | ((sa_sint_t)(T[(sa_sint_t)n - 2] < T[(sa_sint_t)n - 1]) << (SAINT_BIT - 1)); if (threads == 1 || n < 65536) { libsais_final_sorting_scan_left_to_right_8u(T, SA, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start; for (block_start = 0; block_start < n; ) { if (SA[block_start] == 0) { block_start++; } else { fast_sint_t block_max_end = block_start + ((fast_sint_t)threads) * (LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads); if (block_max_end > n) { block_max_end = n;} fast_sint_t block_end = block_start + 1; while (block_end < block_max_end && SA[block_end] != 0) { block_end++; } fast_sint_t block_size = block_end - block_start; if (block_size < 32) { for (; block_start < block_end; block_start += 1) { sa_sint_t p = SA[block_start]; SA[block_start] = p ^ SAINT_MIN; if (p > 0) { p--; SA[induction_bucket[T[p]]++] = p | ((sa_sint_t)(T[p - (p > 0)] < T[p]) << (SAINT_BIT - 1)); } } } else { libsais_final_sorting_scan_left_to_right_8u_block_omp(T, SA, induction_bucket, block_start, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif } static void libsais_final_sorting_scan_left_to_right_32s_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { SA[induction_bucket[T[n - 1]]++] = (n - 1) | ((sa_sint_t)(T[n - 2] < T[n - 1]) << (SAINT_BIT - 1)); if (threads == 1 || n < 65536) { libsais_final_sorting_scan_left_to_right_32s(T, SA, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = 0; block_start < n; block_start = block_end) { block_end = block_start + (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end > n) { block_end = n; } libsais_final_sorting_scan_left_to_right_32s_block_omp(T, SA, induction_bucket, thread_state[0].state.cache, block_start, block_end - block_start, threads); } } #else UNUSED(thread_state); #endif } static sa_sint_t libsais_final_bwt_scan_right_to_left_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; sa_sint_t index = -1; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 2 * prefetch_distance]); sa_sint_t s0 = SA[i - prefetch_distance - 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - prefetch_distance - 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i - 0]; index = (p0 == 0) ? (sa_sint_t)(i - 0) : index; SA[i - 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; uint8_t c0 = T[p0 - (p0 > 0)], c1 = T[p0]; SA[i - 0] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p0 : t; } sa_sint_t p1 = SA[i - 1]; index = (p1 == 0) ? (sa_sint_t)(i - 1) : index; SA[i - 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; uint8_t c0 = T[p1 - (p1 > 0)], c1 = T[p1]; SA[i - 1] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p1 : t; } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; index = (p == 0) ? (sa_sint_t)i : index; SA[i] = p & SAINT_MAX; if (p > 0) { p--; uint8_t c0 = T[p - (p > 0)], c1 = T[p]; SA[i] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p : t; } } return index; } static void libsais_final_bwt_aux_scan_right_to_left_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 2 * prefetch_distance]); sa_sint_t s0 = SA[i - prefetch_distance - 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - prefetch_distance - 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i - 0]; SA[i - 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; uint8_t c0 = T[p0 - (p0 > 0)], c1 = T[p0]; SA[i - 0] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p0 : t; if ((p0 & rm) == 0) { I[p0 / (rm + 1)] = induction_bucket[T[p0]] + 1; } } sa_sint_t p1 = SA[i - 1]; SA[i - 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; uint8_t c0 = T[p1 - (p1 > 0)], c1 = T[p1]; SA[i - 1] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p1 : t; if ((p1 & rm) == 0) { I[p1 / (rm + 1)] = induction_bucket[T[p1]] + 1; } } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; uint8_t c0 = T[p - (p > 0)], c1 = T[p]; SA[i] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p : t; if ((p & rm) == 0) { I[p / (rm + 1)] = induction_bucket[T[p]] + 1; } } } } static void libsais_final_sorting_scan_right_to_left_8u(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 2 * prefetch_distance]); sa_sint_t s0 = SA[i - prefetch_distance - 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - prefetch_distance - 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i - 0]; SA[i - 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; SA[--induction_bucket[T[p0]]] = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] > T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i - 1]; SA[i - 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; SA[--induction_bucket[T[p1]]] = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] > T[p1]) << (SAINT_BIT - 1)); } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; SA[--induction_bucket[T[p]]] = p | ((sa_sint_t)(T[p - (p > 0)] > T[p]) << (SAINT_BIT - 1)); } } } static void libsais_final_sorting_scan_right_to_left_32s(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + 2 * prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 3 * prefetch_distance]); sa_sint_t s0 = SA[i - 2 * prefetch_distance - 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - 2 * prefetch_distance - 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t s2 = SA[i - 1 * prefetch_distance - 0]; if (s2 > 0) { libsais_prefetchw(&induction_bucket[T[s2 - 1]]); libsais_prefetch(&T[s2] - 2); } sa_sint_t s3 = SA[i - 1 * prefetch_distance - 1]; if (s3 > 0) { libsais_prefetchw(&induction_bucket[T[s3 - 1]]); libsais_prefetch(&T[s3] - 2); } sa_sint_t p0 = SA[i - 0]; SA[i - 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; SA[--induction_bucket[T[p0]]] = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] > T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i - 1]; SA[i - 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; SA[--induction_bucket[T[p1]]] = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] > T[p1]) << (SAINT_BIT - 1)); } } for (j -= 2 * prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; SA[--induction_bucket[T[p]]] = p | ((sa_sint_t)(T[p - (p > 0)] > T[p]) << (SAINT_BIT - 1)); } } } #if defined(_OPENMP) static fast_sint_t libsais_final_bwt_scan_right_to_left_8u_block_prepare(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t i, j, count = 0; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 2 * prefetch_distance]); sa_sint_t s0 = SA[i - prefetch_distance - 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - prefetch_distance - 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i - 0]; SA[i - 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; uint8_t c0 = T[p0 - (p0 > 0)], c1 = T[p0]; SA[i - 0] = c1; sa_sint_t t = c0 | SAINT_MIN; buckets[cache[count].symbol = c1]++; cache[count++].index = (c0 <= c1) ? p0 : t; } sa_sint_t p1 = SA[i - 1]; SA[i - 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; uint8_t c0 = T[p1 - (p1 > 0)], c1 = T[p1]; SA[i - 1] = c1; sa_sint_t t = c0 | SAINT_MIN; buckets[cache[count].symbol = c1]++; cache[count++].index = (c0 <= c1) ? p1 : t; } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; uint8_t c0 = T[p - (p > 0)], c1 = T[p]; SA[i] = c1; sa_sint_t t = c0 | SAINT_MIN; buckets[cache[count].symbol = c1]++; cache[count++].index = (c0 <= c1) ? p : t; } } return count; } static fast_sint_t libsais_final_bwt_aux_scan_right_to_left_8u_block_prepare(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t i, j, count = 0; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 2 * prefetch_distance]); sa_sint_t s0 = SA[i - prefetch_distance - 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - prefetch_distance - 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i - 0]; SA[i - 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; uint8_t c0 = T[p0 - (p0 > 0)], c1 = T[p0]; SA[i - 0] = c1; sa_sint_t t = c0 | SAINT_MIN; buckets[cache[count].symbol = c1]++; cache[count].index = (c0 <= c1) ? p0 : t; cache[count + 1].index = p0; count += 2; } sa_sint_t p1 = SA[i - 1]; SA[i - 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; uint8_t c0 = T[p1 - (p1 > 0)], c1 = T[p1]; SA[i - 1] = c1; sa_sint_t t = c0 | SAINT_MIN; buckets[cache[count].symbol = c1]++; cache[count].index = (c0 <= c1) ? p1 : t; cache[count + 1].index = p1; count += 2; } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; uint8_t c0 = T[p - (p > 0)], c1 = T[p]; SA[i] = c1; sa_sint_t t = c0 | SAINT_MIN; buckets[cache[count].symbol = c1]++; cache[count].index = (c0 <= c1) ? p : t; cache[count + 1].index = p; count += 2; } } return count; } static fast_sint_t libsais_final_sorting_scan_right_to_left_8u_block_prepare(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; memset(buckets, 0, ALPHABET_SIZE * sizeof(sa_sint_t)); fast_sint_t i, j, count = 0; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&SA[i - 2 * prefetch_distance]); sa_sint_t s0 = SA[i - prefetch_distance - 0]; const uint8_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i - prefetch_distance - 1]; const uint8_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); sa_sint_t p0 = SA[i - 0]; SA[i - 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; buckets[cache[count].symbol = T[p0]]++; cache[count++].index = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] > T[p0]) << (SAINT_BIT - 1)); } sa_sint_t p1 = SA[i - 1]; SA[i - 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; buckets[cache[count].symbol = T[p1]]++; cache[count++].index = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] > T[p1]) << (SAINT_BIT - 1)); } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; buckets[cache[count].symbol = T[p]]++; cache[count++].index = p | ((sa_sint_t)(T[p - (p > 0)] > T[p]) << (SAINT_BIT - 1)); } } return count; } static void libsais_final_order_scan_right_to_left_8u_block_place(sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t count) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = 0, j = count - 3; i < j; i += 4) { libsais_prefetch(&cache[i + prefetch_distance]); SA[--buckets[cache[i + 0].symbol]] = cache[i + 0].index; SA[--buckets[cache[i + 1].symbol]] = cache[i + 1].index; SA[--buckets[cache[i + 2].symbol]] = cache[i + 2].index; SA[--buckets[cache[i + 3].symbol]] = cache[i + 3].index; } for (j += 3; i < j; i += 1) { SA[--buckets[cache[i].symbol]] = cache[i].index; } } static void libsais_final_bwt_aux_scan_right_to_left_8u_block_place(sa_sint_t * RESTRICT SA, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t count) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = 0, j = count - 6; i < j; i += 8) { libsais_prefetch(&cache[i + prefetch_distance]); SA[--buckets[cache[i + 0].symbol]] = cache[i + 0].index; if ((cache[i + 1].index & rm) == 0) { I[cache[i + 1].index / (rm + 1)] = buckets[cache[i + 0].symbol] + 1; } SA[--buckets[cache[i + 2].symbol]] = cache[i + 2].index; if ((cache[i + 3].index & rm) == 0) { I[cache[i + 3].index / (rm + 1)] = buckets[cache[i + 2].symbol] + 1; } SA[--buckets[cache[i + 4].symbol]] = cache[i + 4].index; if ((cache[i + 5].index & rm) == 0) { I[cache[i + 5].index / (rm + 1)] = buckets[cache[i + 4].symbol] + 1; } SA[--buckets[cache[i + 6].symbol]] = cache[i + 6].index; if ((cache[i + 7].index & rm) == 0) { I[cache[i + 7].index / (rm + 1)] = buckets[cache[i + 6].symbol] + 1; } } for (j += 6; i < j; i += 2) { SA[--buckets[cache[i].symbol]] = cache[i].index; if ((cache[i + 1].index & rm) == 0) { I[(cache[i + 1].index & SAINT_MAX) / (rm + 1)] = buckets[cache[i].symbol] + 1; } } } static void libsais_final_sorting_scan_right_to_left_32s_block_gather(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 1; i < j; i += 2) { libsais_prefetchw(&SA[i + 2 * prefetch_distance]); sa_sint_t s0 = SA[i + prefetch_distance + 0]; const sa_sint_t * Ts0 = &T[s0] - 1; libsais_prefetch(s0 > 0 ? Ts0 : NULL); Ts0--; libsais_prefetch(s0 > 0 ? Ts0 : NULL); sa_sint_t s1 = SA[i + prefetch_distance + 1]; const sa_sint_t * Ts1 = &T[s1] - 1; libsais_prefetch(s1 > 0 ? Ts1 : NULL); Ts1--; libsais_prefetch(s1 > 0 ? Ts1 : NULL); libsais_prefetchw(&cache[i + prefetch_distance]); sa_sint_t symbol0 = SAINT_MIN, p0 = SA[i + 0]; SA[i + 0] = p0 & SAINT_MAX; if (p0 > 0) { p0--; cache[i + 0].index = p0 | ((sa_sint_t)(T[p0 - (p0 > 0)] > T[p0]) << (SAINT_BIT - 1)); symbol0 = T[p0]; } cache[i + 0].symbol = symbol0; sa_sint_t symbol1 = SAINT_MIN, p1 = SA[i + 1]; SA[i + 1] = p1 & SAINT_MAX; if (p1 > 0) { p1--; cache[i + 1].index = p1 | ((sa_sint_t)(T[p1 - (p1 > 0)] > T[p1]) << (SAINT_BIT - 1)); symbol1 = T[p1]; } cache[i + 1].symbol = symbol1; } for (j += prefetch_distance + 1; i < j; i += 1) { sa_sint_t symbol = SAINT_MIN, p = SA[i]; SA[i] = p & SAINT_MAX; if (p > 0) { p--; cache[i].index = p | ((sa_sint_t)(T[p - (p > 0)] > T[p]) << (SAINT_BIT - 1)); symbol = T[p]; } cache[i].symbol = symbol; } } static void libsais_final_sorting_scan_right_to_left_32s_block_sort(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT induction_bucket, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = omp_block_start + omp_block_size - 1, j = omp_block_start + prefetch_distance + 1; i >= j; i -= 2) { libsais_prefetchw(&cache[i - 2 * prefetch_distance]); sa_sint_t s0 = cache[i - prefetch_distance - 0].symbol; const sa_sint_t * Is0 = &induction_bucket[s0]; libsais_prefetchw(s0 >= 0 ? Is0 : NULL); sa_sint_t s1 = cache[i - prefetch_distance - 1].symbol; const sa_sint_t * Is1 = &induction_bucket[s1]; libsais_prefetchw(s1 >= 0 ? Is1 : NULL); sa_sint_t v0 = cache[i - 0].symbol; if (v0 >= 0) { cache[i - 0].symbol = --induction_bucket[v0]; if (cache[i - 0].symbol >= omp_block_start) { sa_sint_t ni = cache[i - 0].symbol, np = cache[i - 0].index; cache[i - 0].index = np & SAINT_MAX; if (np > 0) { np--; cache[ni].index = np | ((sa_sint_t)(T[np - (np > 0)] > T[np]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np]; } } } sa_sint_t v1 = cache[i - 1].symbol; if (v1 >= 0) { cache[i - 1].symbol = --induction_bucket[v1]; if (cache[i - 1].symbol >= omp_block_start) { sa_sint_t ni = cache[i - 1].symbol, np = cache[i - 1].index; cache[i - 1].index = np & SAINT_MAX; if (np > 0) { np--; cache[ni].index = np | ((sa_sint_t)(T[np - (np > 0)] > T[np]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np]; } } } } for (j -= prefetch_distance + 1; i >= j; i -= 1) { sa_sint_t v = cache[i].symbol; if (v >= 0) { cache[i].symbol = --induction_bucket[v]; if (cache[i].symbol >= omp_block_start) { sa_sint_t ni = cache[i].symbol, np = cache[i].index; cache[i].index = np & SAINT_MAX; if (np > 0) { np--; cache[ni].index = np | ((sa_sint_t)(T[np - (np > 0)] > T[np]) << (SAINT_BIT - 1)); cache[ni].symbol = T[np]; } } } } } static void libsais_final_bwt_scan_right_to_left_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_bwt_scan_right_to_left_8u(T, SA, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_final_bwt_scan_right_to_left_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { fast_sint_t t; for (t = omp_num_threads - 1; t >= 0; --t) { sa_sint_t * RESTRICT temp_bucket = thread_state[t].state.buckets; fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_bucket[c]; induction_bucket[c] = A - B; temp_bucket[c] = A; } } } #pragma omp barrier { libsais_final_order_scan_right_to_left_8u_block_place(SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count); } } #endif } } static void libsais_final_bwt_aux_scan_right_to_left_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT induction_bucket, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_bwt_aux_scan_right_to_left_8u(T, SA, rm, I, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_final_bwt_aux_scan_right_to_left_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { fast_sint_t t; for (t = omp_num_threads - 1; t >= 0; --t) { sa_sint_t * RESTRICT temp_bucket = thread_state[t].state.buckets; fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_bucket[c]; induction_bucket[c] = A - B; temp_bucket[c] = A; } } } #pragma omp barrier { libsais_final_bwt_aux_scan_right_to_left_8u_block_place(SA, rm, I, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count); } } #endif } } static void libsais_final_sorting_scan_right_to_left_8u_block_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT induction_bucket, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 64 * ALPHABET_SIZE && omp_get_dynamic() == 0) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_sorting_scan_right_to_left_8u(T, SA, induction_bucket, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_final_sorting_scan_right_to_left_8u_block_prepare(T, SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { fast_sint_t t; for (t = omp_num_threads - 1; t >= 0; --t) { sa_sint_t * RESTRICT temp_bucket = thread_state[t].state.buckets; fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_sint_t A = induction_bucket[c], B = temp_bucket[c]; induction_bucket[c] = A - B; temp_bucket[c] = A; } } } #pragma omp barrier { libsais_final_order_scan_right_to_left_8u_block_place(SA, thread_state[omp_thread_num].state.buckets, thread_state[omp_thread_num].state.cache, thread_state[omp_thread_num].state.count); } } #endif } } static void libsais_final_sorting_scan_right_to_left_32s_block_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t * RESTRICT buckets, LIBSAIS_THREAD_CACHE * RESTRICT cache, fast_sint_t block_start, fast_sint_t block_size, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && block_size >= 16384) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(cache); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (block_size / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : block_size - omp_block_start; omp_block_start += block_start; if (omp_num_threads == 1) { libsais_final_sorting_scan_right_to_left_32s(T, SA, buckets, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { libsais_final_sorting_scan_right_to_left_32s_block_gather(T, SA, cache - block_start, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { libsais_final_sorting_scan_right_to_left_32s_block_sort(T, buckets, cache - block_start, block_start, block_size); } #pragma omp barrier { libsais_compact_and_place_cached_suffixes(SA, cache - block_start, omp_block_start, omp_block_size); } } #endif } } #endif static sa_sint_t libsais_final_bwt_scan_right_to_left_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t index = -1; if (threads == 1 || n < 65536) { index = libsais_final_bwt_scan_right_to_left_8u(T, SA, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start; for (block_start = (fast_sint_t)n - 1; block_start >= 0; ) { if (SA[block_start] == 0) { index = (sa_sint_t)block_start--; } else { fast_sint_t block_max_end = block_start - ((fast_sint_t)threads) * (LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads); if (block_max_end < 0) { block_max_end = -1; } fast_sint_t block_end = block_start - 1; while (block_end > block_max_end && SA[block_end] != 0) { block_end--; } fast_sint_t block_size = block_start - block_end; if (block_size < 32) { for (; block_start > block_end; block_start -= 1) { sa_sint_t p = SA[block_start]; SA[block_start] = p & SAINT_MAX; if (p > 0) { p--; uint8_t c0 = T[p - (p > 0)], c1 = T[p]; SA[block_start] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p : t; } } } else { libsais_final_bwt_scan_right_to_left_8u_block_omp(T, SA, induction_bucket, block_end + 1, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif return index; } static void libsais_final_bwt_aux_scan_right_to_left_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t rm, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (threads == 1 || n < 65536) { libsais_final_bwt_aux_scan_right_to_left_8u(T, SA, rm, I, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start; for (block_start = (fast_sint_t)n - 1; block_start >= 0; ) { if (SA[block_start] == 0) { block_start--; } else { fast_sint_t block_max_end = block_start - ((fast_sint_t)threads) * ((LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads) / 2); if (block_max_end < 0) { block_max_end = -1; } fast_sint_t block_end = block_start - 1; while (block_end > block_max_end && SA[block_end] != 0) { block_end--; } fast_sint_t block_size = block_start - block_end; if (block_size < 32) { for (; block_start > block_end; block_start -= 1) { sa_sint_t p = SA[block_start]; SA[block_start] = p & SAINT_MAX; if (p > 0) { p--; uint8_t c0 = T[p - (p > 0)], c1 = T[p]; SA[block_start] = c1; sa_sint_t t = c0 | SAINT_MIN; SA[--induction_bucket[c1]] = (c0 <= c1) ? p : t; if ((p & rm) == 0) { I[p / (rm + 1)] = induction_bucket[T[p]] + 1; } } } } else { libsais_final_bwt_aux_scan_right_to_left_8u_block_omp(T, SA, rm, I, induction_bucket, block_end + 1, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif } static void libsais_final_sorting_scan_right_to_left_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (threads == 1 || n < 65536) { libsais_final_sorting_scan_right_to_left_8u(T, SA, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start; for (block_start = (fast_sint_t)n - 1; block_start >= 0; ) { if (SA[block_start] == 0) { block_start--; } else { fast_sint_t block_max_end = block_start - ((fast_sint_t)threads) * (LIBSAIS_PER_THREAD_CACHE_SIZE - 16 * (fast_sint_t)threads); if (block_max_end < -1) { block_max_end = -1; } fast_sint_t block_end = block_start - 1; while (block_end > block_max_end && SA[block_end] != 0) { block_end--; } fast_sint_t block_size = block_start - block_end; if (block_size < 32) { for (; block_start > block_end; block_start -= 1) { sa_sint_t p = SA[block_start]; SA[block_start] = p & SAINT_MAX; if (p > 0) { p--; SA[--induction_bucket[T[p]]] = p | ((sa_sint_t)(T[p - (p > 0)] > T[p]) << (SAINT_BIT - 1)); } } } else { libsais_final_sorting_scan_right_to_left_8u_block_omp(T, SA, induction_bucket, block_end + 1, block_size, threads, thread_state); block_start = block_end; } } } } #else UNUSED(thread_state); #endif } static void libsais_final_sorting_scan_right_to_left_32s_omp(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t * RESTRICT induction_bucket, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (threads == 1 || n < 65536) { libsais_final_sorting_scan_right_to_left_32s(T, SA, induction_bucket, 0, n); } #if defined(_OPENMP) else { fast_sint_t block_start, block_end; for (block_start = (fast_sint_t)n - 1; block_start >= 0; block_start = block_end) { block_end = block_start - (fast_sint_t)threads * LIBSAIS_PER_THREAD_CACHE_SIZE; if (block_end < 0) { block_end = -1; } libsais_final_sorting_scan_right_to_left_32s_block_omp(T, SA, induction_bucket, thread_state[0].state.cache, block_end + 1, block_start - block_end, threads); } } #else UNUSED(thread_state); #endif } static void libsais_clear_lms_suffixes_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT bucket_start, sa_sint_t * RESTRICT bucket_end, sa_sint_t threads) { fast_sint_t c; #if defined(_OPENMP) #pragma omp parallel for schedule(static, 1) num_threads(threads) if(threads > 1 && n >= 65536) #else UNUSED(threads); UNUSED(n); #endif for (c = 0; c < k; ++c) { if (bucket_end[c] > bucket_start[c]) { memset(&SA[bucket_start[c]], 0, ((size_t)bucket_end[c] - (size_t)bucket_start[c]) * sizeof(sa_sint_t)); } } } static sa_sint_t libsais_induce_final_order_8u_omp(const uint8_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t bwt, sa_sint_t r, sa_sint_t * RESTRICT I, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (!bwt) { libsais_final_sorting_scan_left_to_right_8u_omp(T, SA, n, &buckets[6 * ALPHABET_SIZE], threads, thread_state); if (threads > 1 && n >= 65536) { libsais_clear_lms_suffixes_omp(SA, n, ALPHABET_SIZE, &buckets[6 * ALPHABET_SIZE], &buckets[7 * ALPHABET_SIZE], threads); } libsais_final_sorting_scan_right_to_left_8u_omp(T, SA, n, &buckets[7 * ALPHABET_SIZE], threads, thread_state); return 0; } else if (I != NULL) { libsais_final_bwt_aux_scan_left_to_right_8u_omp(T, SA, n, r - 1, I, &buckets[6 * ALPHABET_SIZE], threads, thread_state); if (threads > 1 && n >= 65536) { libsais_clear_lms_suffixes_omp(SA, n, ALPHABET_SIZE, &buckets[6 * ALPHABET_SIZE], &buckets[7 * ALPHABET_SIZE], threads); } libsais_final_bwt_aux_scan_right_to_left_8u_omp(T, SA, n, r - 1, I, &buckets[7 * ALPHABET_SIZE], threads, thread_state); return 0; } else { libsais_final_bwt_scan_left_to_right_8u_omp(T, SA, n, &buckets[6 * ALPHABET_SIZE], threads, thread_state); if (threads > 1 && n >= 65536) { libsais_clear_lms_suffixes_omp(SA, n, ALPHABET_SIZE, &buckets[6 * ALPHABET_SIZE], &buckets[7 * ALPHABET_SIZE], threads); } return libsais_final_bwt_scan_right_to_left_8u_omp(T, SA, n, &buckets[7 * ALPHABET_SIZE], threads, thread_state); } } static void libsais_induce_final_order_32s_6k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { libsais_final_sorting_scan_left_to_right_32s_omp(T, SA, n, &buckets[4 * k], threads, thread_state); libsais_final_sorting_scan_right_to_left_32s_omp(T, SA, n, &buckets[5 * k], threads, thread_state); } static void libsais_induce_final_order_32s_4k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { libsais_final_sorting_scan_left_to_right_32s_omp(T, SA, n, &buckets[2 * k], threads, thread_state); libsais_final_sorting_scan_right_to_left_32s_omp(T, SA, n, &buckets[3 * k], threads, thread_state); } static void libsais_induce_final_order_32s_2k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { libsais_final_sorting_scan_left_to_right_32s_omp(T, SA, n, &buckets[1 * k], threads, thread_state); libsais_final_sorting_scan_right_to_left_32s_omp(T, SA, n, &buckets[0 * k], threads, thread_state); } static void libsais_induce_final_order_32s_1k(const sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { libsais_count_suffixes_32s(T, n, k, buckets); libsais_initialize_buckets_start_32s_1k(k, buckets); libsais_final_sorting_scan_left_to_right_32s_omp(T, SA, n, buckets, threads, thread_state); libsais_count_suffixes_32s(T, n, k, buckets); libsais_initialize_buckets_end_32s_1k(k, buckets); libsais_final_sorting_scan_right_to_left_32s_omp(T, SA, n, buckets, threads, thread_state); } static sa_sint_t libsais_renumber_unique_and_nonunique_lms_suffixes_32s(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t m, sa_sint_t f, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT SAm = &SA[m]; sa_sint_t i, j; for (i = (sa_sint_t)omp_block_start, j = (sa_sint_t)omp_block_start + (sa_sint_t)omp_block_size - 2 * (sa_sint_t)prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&SA[i + 3 * prefetch_distance]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + 2 * prefetch_distance + 0]) >> 1]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + 2 * prefetch_distance + 1]) >> 1]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + 2 * prefetch_distance + 2]) >> 1]); libsais_prefetchw(&SAm[((sa_uint_t)SA[i + 2 * prefetch_distance + 3]) >> 1]); sa_uint_t q0 = (sa_uint_t)SA[i + prefetch_distance + 0]; const sa_sint_t * Tq0 = &T[q0]; libsais_prefetchw(SAm[q0 >> 1] < 0 ? Tq0 : NULL); sa_uint_t q1 = (sa_uint_t)SA[i + prefetch_distance + 1]; const sa_sint_t * Tq1 = &T[q1]; libsais_prefetchw(SAm[q1 >> 1] < 0 ? Tq1 : NULL); sa_uint_t q2 = (sa_uint_t)SA[i + prefetch_distance + 2]; const sa_sint_t * Tq2 = &T[q2]; libsais_prefetchw(SAm[q2 >> 1] < 0 ? Tq2 : NULL); sa_uint_t q3 = (sa_uint_t)SA[i + prefetch_distance + 3]; const sa_sint_t * Tq3 = &T[q3]; libsais_prefetchw(SAm[q3 >> 1] < 0 ? Tq3 : NULL); sa_uint_t p0 = (sa_uint_t)SA[i + 0]; sa_sint_t s0 = SAm[p0 >> 1]; if (s0 < 0) { T[p0] |= SAINT_MIN; f++; s0 = i + 0 + SAINT_MIN + f; } SAm[p0 >> 1] = s0 - f; sa_uint_t p1 = (sa_uint_t)SA[i + 1]; sa_sint_t s1 = SAm[p1 >> 1]; if (s1 < 0) { T[p1] |= SAINT_MIN; f++; s1 = i + 1 + SAINT_MIN + f; } SAm[p1 >> 1] = s1 - f; sa_uint_t p2 = (sa_uint_t)SA[i + 2]; sa_sint_t s2 = SAm[p2 >> 1]; if (s2 < 0) { T[p2] |= SAINT_MIN; f++; s2 = i + 2 + SAINT_MIN + f; } SAm[p2 >> 1] = s2 - f; sa_uint_t p3 = (sa_uint_t)SA[i + 3]; sa_sint_t s3 = SAm[p3 >> 1]; if (s3 < 0) { T[p3] |= SAINT_MIN; f++; s3 = i + 3 + SAINT_MIN + f; } SAm[p3 >> 1] = s3 - f; } for (j += 2 * (sa_sint_t)prefetch_distance + 3; i < j; i += 1) { sa_uint_t p = (sa_uint_t)SA[i]; sa_sint_t s = SAm[p >> 1]; if (s < 0) { T[p] |= SAINT_MIN; f++; s = i + SAINT_MIN + f; } SAm[p >> 1] = s - f; } return f; } static void libsais_compact_unique_and_nonunique_lms_suffixes_32s(sa_sint_t * RESTRICT SA, sa_sint_t m, fast_sint_t * pl, fast_sint_t * pr, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT SAl = &SA[0]; sa_sint_t * RESTRICT SAr = &SA[0]; fast_sint_t i, j, l = *pl - 1, r = *pr - 1; for (i = (fast_sint_t)m + omp_block_start + omp_block_size - 1, j = (fast_sint_t)m + omp_block_start + 3; i >= j; i -= 4) { libsais_prefetch(&SA[i - prefetch_distance]); sa_sint_t p0 = SA[i - 0]; SAl[l] = p0 & SAINT_MAX; l -= p0 < 0; SAr[r] = p0 - 1; r -= p0 > 0; sa_sint_t p1 = SA[i - 1]; SAl[l] = p1 & SAINT_MAX; l -= p1 < 0; SAr[r] = p1 - 1; r -= p1 > 0; sa_sint_t p2 = SA[i - 2]; SAl[l] = p2 & SAINT_MAX; l -= p2 < 0; SAr[r] = p2 - 1; r -= p2 > 0; sa_sint_t p3 = SA[i - 3]; SAl[l] = p3 & SAINT_MAX; l -= p3 < 0; SAr[r] = p3 - 1; r -= p3 > 0; } for (j -= 3; i >= j; i -= 1) { sa_sint_t p = SA[i]; SAl[l] = p & SAINT_MAX; l -= p < 0; SAr[r] = p - 1; r -= p > 0; } *pl = l + 1; *pr = r + 1; } #if defined(_OPENMP) static sa_sint_t libsais_count_unique_suffixes(sa_sint_t * RESTRICT SA, sa_sint_t m, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; sa_sint_t * RESTRICT SAm = &SA[m]; fast_sint_t i, j; sa_sint_t f0 = 0, f1 = 0, f2 = 0, f3 = 0; for (i = omp_block_start, j = omp_block_start + omp_block_size - prefetch_distance - 3; i < j; i += 4) { libsais_prefetch(&SA[i + 2 * prefetch_distance]); libsais_prefetch(&SAm[((sa_uint_t)SA[i + prefetch_distance + 0]) >> 1]); libsais_prefetch(&SAm[((sa_uint_t)SA[i + prefetch_distance + 1]) >> 1]); libsais_prefetch(&SAm[((sa_uint_t)SA[i + prefetch_distance + 2]) >> 1]); libsais_prefetch(&SAm[((sa_uint_t)SA[i + prefetch_distance + 3]) >> 1]); f0 += SAm[((sa_uint_t)SA[i + 0]) >> 1] < 0; f1 += SAm[((sa_uint_t)SA[i + 1]) >> 1] < 0; f2 += SAm[((sa_uint_t)SA[i + 2]) >> 1] < 0; f3 += SAm[((sa_uint_t)SA[i + 3]) >> 1] < 0; } for (j += prefetch_distance + 3; i < j; i += 1) { f0 += SAm[((sa_uint_t)SA[i]) >> 1] < 0; } return f0 + f1 + f2 + f3; } #endif static sa_sint_t libsais_renumber_unique_and_nonunique_lms_suffixes_32s_omp(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t m, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t f = 0; #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && m >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (m / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : m - omp_block_start; if (omp_num_threads == 1) { f = libsais_renumber_unique_and_nonunique_lms_suffixes_32s(T, SA, m, 0, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_count_unique_suffixes(SA, m, omp_block_start, omp_block_size); } #pragma omp barrier { fast_sint_t t, count = 0; for (t = 0; t < omp_thread_num; ++t) { count += thread_state[t].state.count; } if (omp_thread_num == omp_num_threads - 1) { f = (sa_sint_t)(count + thread_state[omp_thread_num].state.count); } libsais_renumber_unique_and_nonunique_lms_suffixes_32s(T, SA, m, (sa_sint_t)count, omp_block_start, omp_block_size); } } #endif } return f; } static void libsais_compact_unique_and_nonunique_lms_suffixes_32s_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t fs, sa_sint_t f, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 131072 && m < fs) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (((fast_sint_t)n >> 1) / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : ((fast_sint_t)n >> 1) - omp_block_start; if (omp_num_threads == 1) { fast_sint_t l = m, r = (fast_sint_t)n + (fast_sint_t)fs; libsais_compact_unique_and_nonunique_lms_suffixes_32s(SA, m, &l, &r, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.position = (fast_sint_t)m + ((fast_sint_t)n >> 1) + omp_block_start + omp_block_size; thread_state[omp_thread_num].state.count = (fast_sint_t)m + omp_block_start + omp_block_size; libsais_compact_unique_and_nonunique_lms_suffixes_32s(SA, m, &thread_state[omp_thread_num].state.position, &thread_state[omp_thread_num].state.count, omp_block_start, omp_block_size); } #pragma omp barrier #pragma omp master { fast_sint_t t, position; for (position = m, t = omp_num_threads - 1; t >= 0; --t) { fast_sint_t omp_block_end = t < omp_num_threads - 1 ? omp_block_stride * (t + 1) : ((fast_sint_t)n >> 1); fast_sint_t count = ((fast_sint_t)m + ((fast_sint_t)n >> 1) + omp_block_end - thread_state[t].state.position); if (count > 0) { position -= count; memcpy(&SA[position], &SA[thread_state[t].state.position], (size_t)count * sizeof(sa_sint_t)); } } for (position = (fast_sint_t)n + (fast_sint_t)fs, t = omp_num_threads - 1; t >= 0; --t) { fast_sint_t omp_block_end = t < omp_num_threads - 1 ? omp_block_stride * (t + 1) : ((fast_sint_t)n >> 1); fast_sint_t count = ((fast_sint_t)m + omp_block_end - thread_state[t].state.count); if (count > 0) { position -= count; memcpy(&SA[position], &SA[thread_state[t].state.count], (size_t)count * sizeof(sa_sint_t)); } } } } #endif } memcpy(&SA[(fast_sint_t)n + (fast_sint_t)fs - (fast_sint_t)m], &SA[(fast_sint_t)m - (fast_sint_t)f], (size_t)f * sizeof(sa_sint_t)); } static sa_sint_t libsais_compact_lms_suffixes_32s_omp(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t fs, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { sa_sint_t f = libsais_renumber_unique_and_nonunique_lms_suffixes_32s_omp(T, SA, m, threads, thread_state); libsais_compact_unique_and_nonunique_lms_suffixes_32s_omp(SA, n, m, fs, f, threads, thread_state); return f; } static void libsais_merge_unique_lms_suffixes_32s(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, fast_sint_t l, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; const sa_sint_t * RESTRICT SAnm = &SA[(fast_sint_t)n - (fast_sint_t)m - 1 + l]; sa_sint_t i, j; fast_sint_t tmp = *SAnm++; for (i = (sa_sint_t)omp_block_start, j = (sa_sint_t)omp_block_start + (sa_sint_t)omp_block_size - 6; i < j; i += 4) { libsais_prefetch(&T[i + prefetch_distance]); sa_sint_t c0 = T[i + 0]; if (c0 < 0) { T[i + 0] = c0 & SAINT_MAX; SA[tmp] = i + 0; i++; tmp = *SAnm++; } sa_sint_t c1 = T[i + 1]; if (c1 < 0) { T[i + 1] = c1 & SAINT_MAX; SA[tmp] = i + 1; i++; tmp = *SAnm++; } sa_sint_t c2 = T[i + 2]; if (c2 < 0) { T[i + 2] = c2 & SAINT_MAX; SA[tmp] = i + 2; i++; tmp = *SAnm++; } sa_sint_t c3 = T[i + 3]; if (c3 < 0) { T[i + 3] = c3 & SAINT_MAX; SA[tmp] = i + 3; i++; tmp = *SAnm++; } } for (j += 6; i < j; i += 1) { sa_sint_t c = T[i]; if (c < 0) { T[i] = c & SAINT_MAX; SA[tmp] = i; i++; tmp = *SAnm++; } } } static void libsais_merge_nonunique_lms_suffixes_32s(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, fast_sint_t l, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { const fast_sint_t prefetch_distance = 32; const sa_sint_t * RESTRICT SAnm = &SA[(fast_sint_t)n - (fast_sint_t)m - 1 + l]; fast_sint_t i, j; sa_sint_t tmp = *SAnm++; for (i = omp_block_start, j = omp_block_start + omp_block_size - 3; i < j; i += 4) { libsais_prefetch(&SA[i + prefetch_distance]); if (SA[i + 0] == 0) { SA[i + 0] = tmp; tmp = *SAnm++; } if (SA[i + 1] == 0) { SA[i + 1] = tmp; tmp = *SAnm++; } if (SA[i + 2] == 0) { SA[i + 2] = tmp; tmp = *SAnm++; } if (SA[i + 3] == 0) { SA[i + 3] = tmp; tmp = *SAnm++; } } for (j += 3; i < j; i += 1) { if (SA[i] == 0) { SA[i] = tmp; tmp = *SAnm++; } } } static void libsais_merge_unique_lms_suffixes_32s_omp(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; if (omp_num_threads == 1) { libsais_merge_unique_lms_suffixes_32s(T, SA, n, m, 0, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_count_negative_marked_suffixes(T, omp_block_start, omp_block_size); } #pragma omp barrier { fast_sint_t t, count = 0; for (t = 0; t < omp_thread_num; ++t) { count += thread_state[t].state.count; } libsais_merge_unique_lms_suffixes_32s(T, SA, n, m, count, omp_block_start, omp_block_size); } } #endif } } static void libsais_merge_nonunique_lms_suffixes_32s_omp(sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t f, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && m >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); UNUSED(thread_state); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = (m / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : m - omp_block_start; if (omp_num_threads == 1) { libsais_merge_nonunique_lms_suffixes_32s(SA, n, m, f, omp_block_start, omp_block_size); } #if defined(_OPENMP) else { { thread_state[omp_thread_num].state.count = libsais_count_zero_marked_suffixes(SA, omp_block_start, omp_block_size); } #pragma omp barrier { fast_sint_t t, count = f; for (t = 0; t < omp_thread_num; ++t) { count += thread_state[t].state.count; } libsais_merge_nonunique_lms_suffixes_32s(SA, n, m, count, omp_block_start, omp_block_size); } } #endif } } static void libsais_merge_compacted_lms_suffixes_32s_omp(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t f, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { libsais_merge_unique_lms_suffixes_32s_omp(T, SA, n, m, threads, thread_state); libsais_merge_nonunique_lms_suffixes_32s_omp(SA, n, m, f, threads, thread_state); } static void libsais_reconstruct_compacted_lms_suffixes_32s_2k_omp(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t m, sa_sint_t fs, sa_sint_t f, sa_sint_t * RESTRICT buckets, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (f > 0) { memmove(&SA[n - m - 1], &SA[n + fs - m], (size_t)f * sizeof(sa_sint_t)); libsais_count_and_gather_compacted_lms_suffixes_32s_2k_omp(T, SA, n, k, buckets, threads, thread_state); libsais_reconstruct_lms_suffixes_omp(SA, n, m - f, threads); memcpy(&SA[n - m - 1 + f], &SA[0], ((size_t)m - (size_t)f) * sizeof(sa_sint_t)); memset(&SA[0], 0, (size_t)m * sizeof(sa_sint_t)); libsais_merge_compacted_lms_suffixes_32s_omp(T, SA, n, m, f, threads, thread_state); } else { libsais_count_and_gather_lms_suffixes_32s_2k(T, SA, n, k, buckets, 0, n); libsais_reconstruct_lms_suffixes_omp(SA, n, m, threads); } } static void libsais_reconstruct_compacted_lms_suffixes_32s_1k_omp(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t m, sa_sint_t fs, sa_sint_t f, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { if (f > 0) { memmove(&SA[n - m - 1], &SA[n + fs - m], (size_t)f * sizeof(sa_sint_t)); libsais_gather_compacted_lms_suffixes_32s(T, SA, n); libsais_reconstruct_lms_suffixes_omp(SA, n, m - f, threads); memcpy(&SA[n - m - 1 + f], &SA[0], ((size_t)m - (size_t)f) * sizeof(sa_sint_t)); memset(&SA[0], 0, (size_t)m * sizeof(sa_sint_t)); libsais_merge_compacted_lms_suffixes_32s_omp(T, SA, n, m, f, threads, thread_state); } else { libsais_gather_lms_suffixes_32s(T, SA, n); libsais_reconstruct_lms_suffixes_omp(SA, n, m, threads); } } static sa_sint_t libsais_main_32s(sa_sint_t * RESTRICT T, sa_sint_t * RESTRICT SA, sa_sint_t n, sa_sint_t k, sa_sint_t fs, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { fs = fs < (SAINT_MAX - n) ? fs : (SAINT_MAX - n); if (k > 0 && fs / k >= 6) { sa_sint_t alignment = (fs - 1024) / k >= 6 ? 1024 : 16; sa_sint_t * RESTRICT buckets = (fs - alignment) / k >= 6 ? (sa_sint_t *)libsais_align_up(&SA[n + fs - 6 * k - alignment], (size_t)alignment * sizeof(sa_sint_t)) : &SA[n + fs - 6 * k]; sa_sint_t m = libsais_count_and_gather_lms_suffixes_32s_4k_omp(T, SA, n, k, buckets, threads, thread_state); if (m > 1) { memset(SA, 0, ((size_t)n - (size_t)m) * sizeof(sa_sint_t)); sa_sint_t first_lms_suffix = SA[n - m]; sa_sint_t left_suffixes_count = libsais_initialize_buckets_for_lms_suffixes_radix_sort_32s_6k(T, k, buckets, first_lms_suffix); libsais_radix_sort_lms_suffixes_32s_6k_omp(T, SA, n, m, &buckets[4 * k], threads, thread_state); libsais_radix_sort_set_markers_32s_6k_omp(SA, k, &buckets[4 * k], threads); if (threads > 1 && n >= 65536) { memset(&SA[(fast_sint_t)n - (fast_sint_t)m], 0, (size_t)m * sizeof(sa_sint_t)); } libsais_initialize_buckets_for_partial_sorting_32s_6k(T, k, buckets, first_lms_suffix, left_suffixes_count); libsais_induce_partial_order_32s_6k_omp(T, SA, n, k, buckets, first_lms_suffix, left_suffixes_count, threads, thread_state); sa_sint_t names = libsais_renumber_and_mark_distinct_lms_suffixes_32s_4k_omp(SA, n, m, threads, thread_state); if (names < m) { sa_sint_t f = libsais_compact_lms_suffixes_32s_omp(T, SA, n, m, fs, threads, thread_state); if (libsais_main_32s(SA + n + fs - m + f, SA, m - f, names - f, fs + n - 2 * m + f, threads, thread_state) != 0) { return -2; } libsais_reconstruct_compacted_lms_suffixes_32s_2k_omp(T, SA, n, k, m, fs, f, buckets, threads, thread_state); } else { libsais_count_lms_suffixes_32s_2k(T, n, k, buckets); } libsais_initialize_buckets_start_and_end_32s_4k(k, buckets); libsais_place_lms_suffixes_histogram_32s_4k(SA, n, k, m, buckets); libsais_induce_final_order_32s_4k(T, SA, n, k, buckets, threads, thread_state); } else { SA[0] = SA[n - 1]; libsais_initialize_buckets_start_and_end_32s_6k(k, buckets); libsais_place_lms_suffixes_histogram_32s_6k(SA, n, k, m, buckets); libsais_induce_final_order_32s_6k(T, SA, n, k, buckets, threads, thread_state); } return 0; } else if (k > 0 && fs / k >= 4) { sa_sint_t alignment = (fs - 1024) / k >= 4 ? 1024 : 16; sa_sint_t * RESTRICT buckets = (fs - alignment) / k >= 4 ? (sa_sint_t *)libsais_align_up(&SA[n + fs - 4 * k - alignment], (size_t)alignment * sizeof(sa_sint_t)) : &SA[n + fs - 4 * k]; sa_sint_t m = libsais_count_and_gather_lms_suffixes_32s_2k_omp(T, SA, n, k, buckets, threads, thread_state); if (m > 1) { libsais_initialize_buckets_for_radix_and_partial_sorting_32s_4k(T, k, buckets, SA[n - m]); libsais_radix_sort_lms_suffixes_32s_2k_omp(T, SA, n, m, &buckets[1], threads, thread_state); libsais_radix_sort_set_markers_32s_4k_omp(SA, k, &buckets[1], threads); libsais_place_lms_suffixes_interval_32s_4k(SA, n, k, m - 1, buckets); libsais_induce_partial_order_32s_4k_omp(T, SA, n, k, buckets, threads, thread_state); sa_sint_t names = libsais_renumber_and_mark_distinct_lms_suffixes_32s_4k_omp(SA, n, m, threads, thread_state); if (names < m) { sa_sint_t f = libsais_compact_lms_suffixes_32s_omp(T, SA, n, m, fs, threads, thread_state); if (libsais_main_32s(SA + n + fs - m + f, SA, m - f, names - f, fs + n - 2 * m + f, threads, thread_state) != 0) { return -2; } libsais_reconstruct_compacted_lms_suffixes_32s_2k_omp(T, SA, n, k, m, fs, f, buckets, threads, thread_state); } else { libsais_count_lms_suffixes_32s_2k(T, n, k, buckets); } } else { SA[0] = SA[n - 1]; } libsais_initialize_buckets_start_and_end_32s_4k(k, buckets); libsais_place_lms_suffixes_histogram_32s_4k(SA, n, k, m, buckets); libsais_induce_final_order_32s_4k(T, SA, n, k, buckets, threads, thread_state); return 0; } else if (k > 0 && fs / k >= 2) { sa_sint_t alignment = (fs - 1024) / k >= 2 ? 1024 : 16; sa_sint_t * RESTRICT buckets = (fs - alignment) / k >= 2 ? (sa_sint_t *)libsais_align_up(&SA[n + fs - 2 * k - alignment], (size_t)alignment * sizeof(sa_sint_t)) : &SA[n + fs - 2 * k]; sa_sint_t m = libsais_count_and_gather_lms_suffixes_32s_2k_omp(T, SA, n, k, buckets, threads, thread_state); if (m > 1) { libsais_initialize_buckets_for_lms_suffixes_radix_sort_32s_2k(T, k, buckets, SA[n - m]); libsais_radix_sort_lms_suffixes_32s_2k_omp(T, SA, n, m, &buckets[1], threads, thread_state); libsais_place_lms_suffixes_interval_32s_2k(SA, n, k, m - 1, buckets); libsais_initialize_buckets_start_and_end_32s_2k(k, buckets); libsais_induce_partial_order_32s_2k_omp(T, SA, n, k, buckets, threads, thread_state); sa_sint_t names = libsais_renumber_and_mark_distinct_lms_suffixes_32s_1k_omp(T, SA, n, m, threads); if (names < m) { sa_sint_t f = libsais_compact_lms_suffixes_32s_omp(T, SA, n, m, fs, threads, thread_state); if (libsais_main_32s(SA + n + fs - m + f, SA, m - f, names - f, fs + n - 2 * m + f, threads, thread_state) != 0) { return -2; } libsais_reconstruct_compacted_lms_suffixes_32s_2k_omp(T, SA, n, k, m, fs, f, buckets, threads, thread_state); } else { libsais_count_lms_suffixes_32s_2k(T, n, k, buckets); } } else { SA[0] = SA[n - 1]; } libsais_initialize_buckets_end_32s_2k(k, buckets); libsais_place_lms_suffixes_histogram_32s_2k(SA, n, k, m, buckets); libsais_initialize_buckets_start_and_end_32s_2k(k, buckets); libsais_induce_final_order_32s_2k(T, SA, n, k, buckets, threads, thread_state); return 0; } else { sa_sint_t * buffer = fs < k ? (sa_sint_t *)libsais_alloc_aligned((size_t)k * sizeof(sa_sint_t), 4096) : (sa_sint_t *)NULL; sa_sint_t alignment = fs - 1024 >= k ? 1024 : 16; sa_sint_t * RESTRICT buckets = fs - alignment >= k ? (sa_sint_t *)libsais_align_up(&SA[n + fs - k - alignment], (size_t)alignment * sizeof(sa_sint_t)) : fs >= k ? &SA[n + fs - k] : buffer; if (buckets == NULL) { return -2; } memset(SA, 0, (size_t)n * sizeof(sa_sint_t)); libsais_count_suffixes_32s(T, n, k, buckets); libsais_initialize_buckets_end_32s_1k(k, buckets); sa_sint_t m = libsais_radix_sort_lms_suffixes_32s_1k(T, SA, n, buckets); if (m > 1) { libsais_induce_partial_order_32s_1k_omp(T, SA, n, k, buckets, threads, thread_state); sa_sint_t names = libsais_renumber_and_mark_distinct_lms_suffixes_32s_1k_omp(T, SA, n, m, threads); if (names < m) { if (buffer != NULL) { libsais_free_aligned(buffer); buckets = NULL; } sa_sint_t f = libsais_compact_lms_suffixes_32s_omp(T, SA, n, m, fs, threads, thread_state); if (libsais_main_32s(SA + n + fs - m + f, SA, m - f, names - f, fs + n - 2 * m + f, threads, thread_state) != 0) { return -2; } libsais_reconstruct_compacted_lms_suffixes_32s_1k_omp(T, SA, n, m, fs, f, threads, thread_state); if (buckets == NULL) { buckets = buffer = (sa_sint_t *)libsais_alloc_aligned((size_t)k * sizeof(sa_sint_t), 4096); } if (buckets == NULL) { return -2; } } libsais_count_suffixes_32s(T, n, k, buckets); libsais_initialize_buckets_end_32s_1k(k, buckets); libsais_place_lms_suffixes_interval_32s_1k(T, SA, k, m, buckets); } libsais_induce_final_order_32s_1k(T, SA, n, k, buckets, threads, thread_state); libsais_free_aligned(buffer); return 0; } } static sa_sint_t libsais_main_8u(const uint8_t * T, sa_sint_t * SA, sa_sint_t n, sa_sint_t * RESTRICT buckets, sa_sint_t bwt, sa_sint_t r, sa_sint_t * RESTRICT I, sa_sint_t fs, sa_sint_t * freq, sa_sint_t threads, LIBSAIS_THREAD_STATE * RESTRICT thread_state) { fs = fs < (SAINT_MAX - n) ? fs : (SAINT_MAX - n); sa_sint_t m = libsais_count_and_gather_lms_suffixes_8u_omp(T, SA, n, buckets, threads, thread_state); libsais_initialize_buckets_start_and_end_8u(buckets, freq); if (m > 0) { sa_sint_t first_lms_suffix = SA[n - m]; sa_sint_t left_suffixes_count = libsais_initialize_buckets_for_lms_suffixes_radix_sort_8u(T, buckets, first_lms_suffix); if (threads > 1 && n >= 65536) { memset(SA, 0, ((size_t)n - (size_t)m) * sizeof(sa_sint_t)); } libsais_radix_sort_lms_suffixes_8u_omp(T, SA, n, m, buckets, threads, thread_state); if (threads > 1 && n >= 65536) { memset(&SA[(fast_sint_t)n - (fast_sint_t)m], 0, (size_t)m * sizeof(sa_sint_t)); } libsais_initialize_buckets_for_partial_sorting_8u(T, buckets, first_lms_suffix, left_suffixes_count); libsais_induce_partial_order_8u_omp(T, SA, n, buckets, first_lms_suffix, left_suffixes_count, threads, thread_state); sa_sint_t names = libsais_renumber_and_gather_lms_suffixes_8u_omp(SA, n, m, fs, threads, thread_state); if (names < m) { if (libsais_main_32s(SA + n + fs - m, SA, m, names, fs + n - 2 * m, threads, thread_state) != 0) { return -2; } libsais_gather_lms_suffixes_8u_omp(T, SA, n, threads, thread_state); libsais_reconstruct_lms_suffixes_omp(SA, n, m, threads); } libsais_place_lms_suffixes_interval_8u(SA, n, m, buckets); } else { memset(SA, 0, (size_t)n * sizeof(sa_sint_t)); } return libsais_induce_final_order_8u_omp(T, SA, n, bwt, r, I, buckets, threads, thread_state); } static sa_sint_t libsais_main(const uint8_t * T, sa_sint_t * SA, sa_sint_t n, sa_sint_t bwt, sa_sint_t r, sa_sint_t * I, sa_sint_t fs, sa_sint_t * freq, sa_sint_t threads) { LIBSAIS_THREAD_STATE * RESTRICT thread_state = threads > 1 ? libsais_alloc_thread_state(threads) : NULL; sa_sint_t * RESTRICT buckets = (sa_sint_t *)libsais_alloc_aligned(8 * ALPHABET_SIZE * sizeof(sa_sint_t), 4096); sa_sint_t index = buckets != NULL && (thread_state != NULL || threads == 1) ? libsais_main_8u(T, SA, n, buckets, bwt, r, I, fs, freq, threads, thread_state) : -2; libsais_free_aligned(buckets); libsais_free_thread_state(thread_state); return index; } static int32_t libsais_main_int(sa_sint_t * T, sa_sint_t * SA, sa_sint_t n, sa_sint_t k, sa_sint_t fs, sa_sint_t threads) { LIBSAIS_THREAD_STATE * RESTRICT thread_state = threads > 1 ? libsais_alloc_thread_state(threads) : NULL; sa_sint_t index = thread_state != NULL || threads == 1 ? libsais_main_32s(T, SA, n, k, fs, threads, thread_state) : -2; libsais_free_thread_state(thread_state); return index; } static sa_sint_t libsais_main_ctx(const LIBSAIS_CONTEXT * ctx, const uint8_t * T, sa_sint_t * SA, sa_sint_t n, sa_sint_t bwt, sa_sint_t r, sa_sint_t * I, sa_sint_t fs, sa_sint_t * freq) { return ctx != NULL && (ctx->buckets != NULL && (ctx->thread_state != NULL || ctx->threads == 1)) ? libsais_main_8u(T, SA, n, ctx->buckets, bwt, r, I, fs, freq, (sa_sint_t)ctx->threads, ctx->thread_state) : -2; } static void libsais_bwt_copy_8u(uint8_t * RESTRICT U, sa_sint_t * RESTRICT A, sa_sint_t n) { const fast_sint_t prefetch_distance = 32; fast_sint_t i, j; for (i = 0, j = (fast_sint_t)n - 7; i < j; i += 8) { libsais_prefetch(&A[i + prefetch_distance]); U[i + 0] = (uint8_t)A[i + 0]; U[i + 1] = (uint8_t)A[i + 1]; U[i + 2] = (uint8_t)A[i + 2]; U[i + 3] = (uint8_t)A[i + 3]; U[i + 4] = (uint8_t)A[i + 4]; U[i + 5] = (uint8_t)A[i + 5]; U[i + 6] = (uint8_t)A[i + 6]; U[i + 7] = (uint8_t)A[i + 7]; } for (j += 7; i < j; i += 1) { U[i] = (uint8_t)A[i]; } } #if defined(_OPENMP) static void libsais_bwt_copy_8u_omp(uint8_t * RESTRICT U, sa_sint_t * RESTRICT A, sa_sint_t n, sa_sint_t threads) { #if defined(_OPENMP) #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); fast_sint_t omp_block_stride = ((fast_sint_t)n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : (fast_sint_t)n - omp_block_start; #else UNUSED(threads); fast_sint_t omp_block_start = 0; fast_sint_t omp_block_size = (fast_sint_t)n; #endif libsais_bwt_copy_8u(U + omp_block_start, A + omp_block_start, (sa_sint_t)omp_block_size); } } #endif void * libsais_create_ctx(void) { return (void *)libsais_create_ctx_main(1); } void libsais_free_ctx(void * ctx) { libsais_free_ctx_main((LIBSAIS_CONTEXT *)ctx); } int32_t libsais(const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq) { if ((T == NULL) || (SA == NULL) || (n < 0) || (fs < 0)) { return -1; } else if (n < 2) { if (n == 1) { SA[0] = 0; } return 0; } return libsais_main(T, SA, n, 0, 0, NULL, fs, freq, 1); } int32_t libsais_int(int32_t * T, int32_t * SA, int32_t n, int32_t k, int32_t fs) { if ((T == NULL) || (SA == NULL) || (n < 0) || (fs < 0)) { return -1; } else if (n < 2) { if (n == 1) { SA[0] = 0; } return 0; } return libsais_main_int(T, SA, n, k, fs, 1); } int32_t libsais_ctx(const void * ctx, const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq) { if ((ctx == NULL) || (T == NULL) || (SA == NULL) || (n < 0) || (fs < 0)) { return -1; } else if (n < 2) { if (n == 1) { SA[0] = 0; } return 0; } return libsais_main_ctx((const LIBSAIS_CONTEXT *)ctx, T, SA, n, 0, 0, NULL, fs, freq); } int32_t libsais_bwt(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq) { if ((T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || (fs < 0)) { return -1; } else if (n <= 1) { if (n == 1) { U[0] = T[0]; } return n; } sa_sint_t index = libsais_main(T, A, n, 1, 0, NULL, fs, freq, 1); if (index >= 0) { index++; U[0] = T[n - 1]; libsais_bwt_copy_8u(U + 1, A, index - 1); libsais_bwt_copy_8u(U + index, A + index, n - index); } return index; } int32_t libsais_bwt_aux(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I) { if ((T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || (fs < 0) || (r < 2) || ((r & (r - 1)) != 0) || (I == NULL)) { return -1; } else if (n <= 1) { if (n == 1) { U[0] = T[0]; } I[0] = n; return 0; } if (libsais_main(T, A, n, 1, r, I, fs, freq, 1) != 0) { return -2; } U[0] = T[n - 1]; libsais_bwt_copy_8u(U + 1, A, I[0] - 1); libsais_bwt_copy_8u(U + I[0], A + I[0], n - I[0]); return 0; } int32_t libsais_bwt_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq) { if ((ctx == NULL) || (T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || (fs < 0)) { return -1; } else if (n <= 1) { if (n == 1) { U[0] = T[0]; } return n; } sa_sint_t index = libsais_main_ctx((const LIBSAIS_CONTEXT *)ctx, T, A, n, 1, 0, NULL, fs, freq); if (index >= 0) { index++; U[0] = T[n - 1]; #if defined(_OPENMP) libsais_bwt_copy_8u_omp(U + 1, A, index - 1, (sa_sint_t)((const LIBSAIS_CONTEXT *)ctx)->threads); libsais_bwt_copy_8u_omp(U + index, A + index, n - index, (sa_sint_t)((const LIBSAIS_CONTEXT *)ctx)->threads); #else libsais_bwt_copy_8u(U + 1, A, index - 1); libsais_bwt_copy_8u(U + index, A + index, n - index); #endif } return index; } int32_t libsais_bwt_aux_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I) { if ((ctx == NULL) || (T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || (fs < 0) || (r < 2) || ((r & (r - 1)) != 0) || (I == NULL)) { return -1; } else if (n <= 1) { if (n == 1) { U[0] = T[0]; } I[0] = n; return 0; } if (libsais_main_ctx((const LIBSAIS_CONTEXT *)ctx, T, A, n, 1, r, I, fs, freq) != 0) { return -2; } U[0] = T[n - 1]; #if defined(_OPENMP) libsais_bwt_copy_8u_omp(U + 1, A, I[0] - 1, (sa_sint_t)((const LIBSAIS_CONTEXT *)ctx)->threads); libsais_bwt_copy_8u_omp(U + I[0], A + I[0], n - I[0], (sa_sint_t)((const LIBSAIS_CONTEXT *)ctx)->threads); #else libsais_bwt_copy_8u(U + 1, A, I[0] - 1); libsais_bwt_copy_8u(U + I[0], A + I[0], n - I[0]); #endif return 0; } #if defined(_OPENMP) void * libsais_create_ctx_omp(int32_t threads) { if (threads < 0) { return NULL; } threads = threads > 0 ? threads : omp_get_max_threads(); return (void *)libsais_create_ctx_main(threads); } int32_t libsais_omp(const uint8_t * T, int32_t * SA, int32_t n, int32_t fs, int32_t * freq, int32_t threads) { if ((T == NULL) || (SA == NULL) || (n < 0) || (fs < 0) || (threads < 0)) { return -1; } else if (n < 2) { if (n == 1) { SA[0] = 0; } return 0; } threads = threads > 0 ? threads : omp_get_max_threads(); return libsais_main(T, SA, n, 0, 0, NULL, fs, freq, threads); } int32_t libsais_int_omp(int32_t * T, int32_t * SA, int32_t n, int32_t k, int32_t fs, int32_t threads) { if ((T == NULL) || (SA == NULL) || (n < 0) || (fs < 0) || (threads < 0)) { return -1; } else if (n < 2) { if (n == 1) { SA[0] = 0; } return 0; } threads = threads > 0 ? threads : omp_get_max_threads(); return libsais_main_int(T, SA, n, k, fs, threads); } int32_t libsais_bwt_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t threads) { if ((T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || (fs < 0) || (threads < 0)) { return -1; } else if (n <= 1) { if (n == 1) { U[0] = T[0]; } return n; } threads = threads > 0 ? threads : omp_get_max_threads(); sa_sint_t index = libsais_main(T, A, n, 1, 0, NULL, fs, freq, threads); if (index >= 0) { index++; U[0] = T[n - 1]; libsais_bwt_copy_8u_omp(U + 1, A, index - 1, threads); libsais_bwt_copy_8u_omp(U + index, A + index, n - index, threads); } return index; } int32_t libsais_bwt_aux_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, int32_t fs, int32_t * freq, int32_t r, int32_t * I, int32_t threads) { if ((T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || (fs < 0) || (r < 2) || ((r & (r - 1)) != 0) || (I == NULL) || (threads < 0)) { return -1; } else if (n <= 1) { if (n == 1) { U[0] = T[0];} I[0] = n; return 0; } threads = threads > 0 ? threads : omp_get_max_threads(); if (libsais_main(T, A, n, 1, r, I, fs, freq, threads) != 0) { return -2; } U[0] = T[n - 1]; libsais_bwt_copy_8u_omp(U + 1, A, I[0] - 1, threads); libsais_bwt_copy_8u_omp(U + I[0], A + I[0], n - I[0], threads); return 0; } #endif static LIBSAIS_UNBWT_CONTEXT * libsais_unbwt_create_ctx_main(sa_sint_t threads) { LIBSAIS_UNBWT_CONTEXT * RESTRICT ctx = (LIBSAIS_UNBWT_CONTEXT *)libsais_alloc_aligned(sizeof(LIBSAIS_UNBWT_CONTEXT), 64); sa_uint_t * RESTRICT bucket2 = (sa_uint_t *)libsais_alloc_aligned(ALPHABET_SIZE * ALPHABET_SIZE * sizeof(sa_uint_t), 4096); uint16_t * RESTRICT fastbits = (uint16_t *)libsais_alloc_aligned((1 + (1 << UNBWT_FASTBITS)) * sizeof(uint16_t), 4096); sa_uint_t * RESTRICT buckets = threads > 1 ? (sa_uint_t *)libsais_alloc_aligned((size_t)threads * (ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)) * sizeof(sa_uint_t), 4096) : NULL; if (ctx != NULL && bucket2 != NULL && fastbits != NULL && (buckets != NULL || threads == 1)) { ctx->bucket2 = bucket2; ctx->fastbits = fastbits; ctx->buckets = buckets; ctx->threads = threads; return ctx; } libsais_free_aligned(buckets); libsais_free_aligned(fastbits); libsais_free_aligned(bucket2); libsais_free_aligned(ctx); return NULL; } static void libsais_unbwt_free_ctx_main(LIBSAIS_UNBWT_CONTEXT * ctx) { if (ctx != NULL) { libsais_free_aligned(ctx->buckets); libsais_free_aligned(ctx->fastbits); libsais_free_aligned(ctx->bucket2); libsais_free_aligned(ctx); } } static void libsais_unbwt_compute_histogram(const uint8_t * RESTRICT T, fast_sint_t n, sa_uint_t * RESTRICT count) { const fast_sint_t prefetch_distance = 256; const uint8_t * RESTRICT T_p = T; if (n >= 1024) { sa_uint_t copy[4 * (ALPHABET_SIZE + 16)]; memset(copy, 0, 4 * (ALPHABET_SIZE + 16) * sizeof(sa_uint_t)); sa_uint_t * RESTRICT copy0 = copy + 0 * (ALPHABET_SIZE + 16); sa_uint_t * RESTRICT copy1 = copy + 1 * (ALPHABET_SIZE + 16); sa_uint_t * RESTRICT copy2 = copy + 2 * (ALPHABET_SIZE + 16); sa_uint_t * RESTRICT copy3 = copy + 3 * (ALPHABET_SIZE + 16); for (; T_p < (uint8_t * )((ptrdiff_t)(T + 63) & (-64)); T_p += 1) { copy0[T_p[0]]++; } fast_uint_t x = ((const uint32_t *)(const void *)T_p)[0], y = ((const uint32_t *)(const void *)T_p)[1]; for (; T_p < (uint8_t * )((ptrdiff_t)(T + n - 8) & (-64)); T_p += 64) { libsais_prefetch(&T_p[prefetch_distance]); fast_uint_t z = ((const uint32_t *)(const void *)T_p)[2], w = ((const uint32_t *)(const void *)T_p)[3]; copy0[(uint8_t)x]++; x >>= 8; copy1[(uint8_t)x]++; x >>= 8; copy2[(uint8_t)x]++; x >>= 8; copy3[x]++; copy0[(uint8_t)y]++; y >>= 8; copy1[(uint8_t)y]++; y >>= 8; copy2[(uint8_t)y]++; y >>= 8; copy3[y]++; x = ((const uint32_t *)(const void *)T_p)[4]; y = ((const uint32_t *)(const void *)T_p)[5]; copy0[(uint8_t)z]++; z >>= 8; copy1[(uint8_t)z]++; z >>= 8; copy2[(uint8_t)z]++; z >>= 8; copy3[z]++; copy0[(uint8_t)w]++; w >>= 8; copy1[(uint8_t)w]++; w >>= 8; copy2[(uint8_t)w]++; w >>= 8; copy3[w]++; z = ((const uint32_t *)(const void *)T_p)[6]; w = ((const uint32_t *)(const void *)T_p)[7]; copy0[(uint8_t)x]++; x >>= 8; copy1[(uint8_t)x]++; x >>= 8; copy2[(uint8_t)x]++; x >>= 8; copy3[x]++; copy0[(uint8_t)y]++; y >>= 8; copy1[(uint8_t)y]++; y >>= 8; copy2[(uint8_t)y]++; y >>= 8; copy3[y]++; x = ((const uint32_t *)(const void *)T_p)[8]; y = ((const uint32_t *)(const void *)T_p)[9]; copy0[(uint8_t)z]++; z >>= 8; copy1[(uint8_t)z]++; z >>= 8; copy2[(uint8_t)z]++; z >>= 8; copy3[z]++; copy0[(uint8_t)w]++; w >>= 8; copy1[(uint8_t)w]++; w >>= 8; copy2[(uint8_t)w]++; w >>= 8; copy3[w]++; z = ((const uint32_t *)(const void *)T_p)[10]; w = ((const uint32_t *)(const void *)T_p)[11]; copy0[(uint8_t)x]++; x >>= 8; copy1[(uint8_t)x]++; x >>= 8; copy2[(uint8_t)x]++; x >>= 8; copy3[x]++; copy0[(uint8_t)y]++; y >>= 8; copy1[(uint8_t)y]++; y >>= 8; copy2[(uint8_t)y]++; y >>= 8; copy3[y]++; x = ((const uint32_t *)(const void *)T_p)[12]; y = ((const uint32_t *)(const void *)T_p)[13]; copy0[(uint8_t)z]++; z >>= 8; copy1[(uint8_t)z]++; z >>= 8; copy2[(uint8_t)z]++; z >>= 8; copy3[z]++; copy0[(uint8_t)w]++; w >>= 8; copy1[(uint8_t)w]++; w >>= 8; copy2[(uint8_t)w]++; w >>= 8; copy3[w]++; z = ((const uint32_t *)(const void *)T_p)[14]; w = ((const uint32_t *)(const void *)T_p)[15]; copy0[(uint8_t)x]++; x >>= 8; copy1[(uint8_t)x]++; x >>= 8; copy2[(uint8_t)x]++; x >>= 8; copy3[x]++; copy0[(uint8_t)y]++; y >>= 8; copy1[(uint8_t)y]++; y >>= 8; copy2[(uint8_t)y]++; y >>= 8; copy3[y]++; x = ((const uint32_t *)(const void *)T_p)[16]; y = ((const uint32_t *)(const void *)T_p)[17]; copy0[(uint8_t)z]++; z >>= 8; copy1[(uint8_t)z]++; z >>= 8; copy2[(uint8_t)z]++; z >>= 8; copy3[z]++; copy0[(uint8_t)w]++; w >>= 8; copy1[(uint8_t)w]++; w >>= 8; copy2[(uint8_t)w]++; w >>= 8; copy3[w]++; } copy0[(uint8_t)x]++; x >>= 8; copy1[(uint8_t)x]++; x >>= 8; copy2[(uint8_t)x]++; x >>= 8; copy3[x]++; copy0[(uint8_t)y]++; y >>= 8; copy1[(uint8_t)y]++; y >>= 8; copy2[(uint8_t)y]++; y >>= 8; copy3[y]++; T_p += 8; fast_uint_t i; for (i = 0; i < ALPHABET_SIZE; i++) { count[i] += copy0[i] + copy1[i] + copy2[i] + copy3[i]; } } for (; T_p < T + n; T_p += 1) { count[T_p[0]]++; } } static void libsais_unbwt_transpose_bucket2(sa_uint_t * RESTRICT bucket2) { fast_uint_t x, y, c, d; for (x = 0; x != ALPHABET_SIZE; x += 16) { for (c = x; c != x + 16; ++c) { for (d = c + 1; d != x + 16; ++d) { sa_uint_t tmp = bucket2[(d << 8) + c]; bucket2[(d << 8) + c] = bucket2[(c << 8) + d]; bucket2[(c << 8) + d] = tmp; } } for (y = x + 16; y != ALPHABET_SIZE; y += 16) { for (c = x; c != x + 16; ++c) { sa_uint_t * bucket2_yc = &bucket2[(y << 8) + c]; sa_uint_t * bucket2_cy = &bucket2[(c << 8) + y]; sa_uint_t tmp00 = bucket2_yc[ 0 * 256]; bucket2_yc[ 0 * 256] = bucket2_cy[ 0]; bucket2_cy[ 0] = tmp00; sa_uint_t tmp01 = bucket2_yc[ 1 * 256]; bucket2_yc[ 1 * 256] = bucket2_cy[ 1]; bucket2_cy[ 1] = tmp01; sa_uint_t tmp02 = bucket2_yc[ 2 * 256]; bucket2_yc[ 2 * 256] = bucket2_cy[ 2]; bucket2_cy[ 2] = tmp02; sa_uint_t tmp03 = bucket2_yc[ 3 * 256]; bucket2_yc[ 3 * 256] = bucket2_cy[ 3]; bucket2_cy[ 3] = tmp03; sa_uint_t tmp04 = bucket2_yc[ 4 * 256]; bucket2_yc[ 4 * 256] = bucket2_cy[ 4]; bucket2_cy[ 4] = tmp04; sa_uint_t tmp05 = bucket2_yc[ 5 * 256]; bucket2_yc[ 5 * 256] = bucket2_cy[ 5]; bucket2_cy[ 5] = tmp05; sa_uint_t tmp06 = bucket2_yc[ 6 * 256]; bucket2_yc[ 6 * 256] = bucket2_cy[ 6]; bucket2_cy[ 6] = tmp06; sa_uint_t tmp07 = bucket2_yc[ 7 * 256]; bucket2_yc[ 7 * 256] = bucket2_cy[ 7]; bucket2_cy[ 7] = tmp07; sa_uint_t tmp08 = bucket2_yc[ 8 * 256]; bucket2_yc[ 8 * 256] = bucket2_cy[ 8]; bucket2_cy[ 8] = tmp08; sa_uint_t tmp09 = bucket2_yc[ 9 * 256]; bucket2_yc[ 9 * 256] = bucket2_cy[ 9]; bucket2_cy[ 9] = tmp09; sa_uint_t tmp10 = bucket2_yc[10 * 256]; bucket2_yc[10 * 256] = bucket2_cy[10]; bucket2_cy[10] = tmp10; sa_uint_t tmp11 = bucket2_yc[11 * 256]; bucket2_yc[11 * 256] = bucket2_cy[11]; bucket2_cy[11] = tmp11; sa_uint_t tmp12 = bucket2_yc[12 * 256]; bucket2_yc[12 * 256] = bucket2_cy[12]; bucket2_cy[12] = tmp12; sa_uint_t tmp13 = bucket2_yc[13 * 256]; bucket2_yc[13 * 256] = bucket2_cy[13]; bucket2_cy[13] = tmp13; sa_uint_t tmp14 = bucket2_yc[14 * 256]; bucket2_yc[14 * 256] = bucket2_cy[14]; bucket2_cy[14] = tmp14; sa_uint_t tmp15 = bucket2_yc[15 * 256]; bucket2_yc[15 * 256] = bucket2_cy[15]; bucket2_cy[15] = tmp15; } } } } static void libsais_unbwt_compute_bigram_histogram_single(const uint8_t * RESTRICT T, sa_uint_t * RESTRICT bucket1, sa_uint_t * RESTRICT bucket2, fast_uint_t index) { fast_uint_t sum, c; for (sum = 1, c = 0; c < ALPHABET_SIZE; ++c) { fast_uint_t prev = sum; sum += bucket1[c]; bucket1[c] = (sa_uint_t)prev; if (prev != sum) { sa_uint_t * RESTRICT bucket2_p = &bucket2[c << 8]; { fast_uint_t hi = index; if (sum < hi) { hi = sum; } libsais_unbwt_compute_histogram(&T[prev], (fast_sint_t)(hi - prev), bucket2_p); } { fast_uint_t lo = index + 1; if (prev > lo) { lo = prev; } libsais_unbwt_compute_histogram(&T[lo - 1], (fast_sint_t)(sum - lo), bucket2_p); } } } libsais_unbwt_transpose_bucket2(bucket2); } static void libsais_unbwt_calculate_fastbits(sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t lastc, fast_uint_t shift) { fast_uint_t v, w, sum, c, d; for (v = 0, w = 0, sum = 1, c = 0; c < ALPHABET_SIZE; ++c) { if (c == lastc) { sum += 1; } for (d = 0; d < ALPHABET_SIZE; ++d, ++w) { fast_uint_t prev = sum; sum += bucket2[w]; bucket2[w] = (sa_uint_t)prev; if (prev != sum) { for (; v <= ((sum - 1) >> shift); ++v) { fastbits[v] = (uint16_t)w; } } } } } static void libsais_unbwt_calculate_biPSI(const uint8_t * RESTRICT T, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket1, sa_uint_t * RESTRICT bucket2, fast_uint_t index, fast_sint_t omp_block_start, fast_sint_t omp_block_end) { { fast_sint_t i = omp_block_start, j = (fast_sint_t)index; if (omp_block_end < j) { j = omp_block_end; } for (; i < j; ++i) { fast_uint_t c = T[i]; fast_uint_t p = bucket1[c]++; fast_sint_t t = (fast_sint_t)(index - p); if (t != 0) { fast_uint_t w = (((fast_uint_t)T[p + (fast_uint_t)(t >> ((sizeof(fast_sint_t) * 8) - 1))]) << 8) + c; P[bucket2[w]++] = (sa_uint_t)i; } } } { fast_sint_t i = (fast_sint_t)index, j = omp_block_end; if (omp_block_start > i) { i = omp_block_start; } for (i += 1; i <= j; ++i) { fast_uint_t c = T[i - 1]; fast_uint_t p = bucket1[c]++; fast_sint_t t = (fast_sint_t)(index - p); if (t != 0) { fast_uint_t w = (((fast_uint_t)T[p + (fast_uint_t)(t >> ((sizeof(fast_sint_t) * 8) - 1))]) << 8) + c; P[bucket2[w]++] = (sa_uint_t)i; } } } } static void libsais_unbwt_init_single(const uint8_t * RESTRICT T, sa_uint_t * RESTRICT P, sa_sint_t n, const sa_sint_t * freq, const sa_uint_t * RESTRICT I, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits) { sa_uint_t bucket1[ALPHABET_SIZE]; fast_uint_t index = I[0]; fast_uint_t lastc = T[0]; fast_uint_t shift = 0; while ((n >> shift) > (1 << UNBWT_FASTBITS)) { shift++; } if (freq != NULL) { memcpy(bucket1, freq, ALPHABET_SIZE * sizeof(sa_uint_t)); } else { memset(bucket1, 0, ALPHABET_SIZE * sizeof(sa_uint_t)); libsais_unbwt_compute_histogram(T, n, bucket1); } memset(bucket2, 0, ALPHABET_SIZE * ALPHABET_SIZE * sizeof(sa_uint_t)); libsais_unbwt_compute_bigram_histogram_single(T, bucket1, bucket2, index); libsais_unbwt_calculate_fastbits(bucket2, fastbits, lastc, shift); libsais_unbwt_calculate_biPSI(T, P, bucket1, bucket2, index, 0, n); } #if defined(_OPENMP) static void libsais_unbwt_compute_bigram_histogram_parallel(const uint8_t * RESTRICT T, fast_uint_t index, sa_uint_t * RESTRICT bucket1, sa_uint_t * RESTRICT bucket2, fast_sint_t omp_block_start, fast_sint_t omp_block_size) { fast_sint_t i; for (i = omp_block_start; i < omp_block_start + omp_block_size; ++i) { fast_uint_t c = T[i]; fast_uint_t p = bucket1[c]++; fast_sint_t t = (fast_sint_t)(index - p); if (t != 0) { fast_uint_t w = (((fast_uint_t)T[p + (fast_uint_t)(t >> ((sizeof(fast_sint_t) * 8) - 1))]) << 8) + c; bucket2[w]++; } } } static void libsais_unbwt_init_parallel(const uint8_t * RESTRICT T, sa_uint_t * RESTRICT P, sa_sint_t n, const sa_sint_t * freq, const sa_uint_t * RESTRICT I, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, sa_uint_t * RESTRICT buckets, sa_sint_t threads) { sa_uint_t bucket1[ALPHABET_SIZE]; fast_uint_t index = I[0]; fast_uint_t lastc = T[0]; fast_uint_t shift = 0; while ((n >> shift) > (1 << UNBWT_FASTBITS)) { shift++; } memset(bucket1, 0, ALPHABET_SIZE * sizeof(sa_uint_t)); memset(bucket2, 0, ALPHABET_SIZE * ALPHABET_SIZE * sizeof(sa_uint_t)); #pragma omp parallel num_threads(threads) if(threads > 1 && n >= 65536) { fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); if (omp_num_threads == 1) { libsais_unbwt_init_single(T, P, n, freq, I, bucket2, fastbits); } else { sa_uint_t * RESTRICT bucket1_local = buckets + omp_thread_num * (ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)); sa_uint_t * RESTRICT bucket2_local = bucket1_local + ALPHABET_SIZE; fast_sint_t omp_block_stride = (n / omp_num_threads) & (-16); fast_sint_t omp_block_start = omp_thread_num * omp_block_stride; fast_sint_t omp_block_size = omp_thread_num < omp_num_threads - 1 ? omp_block_stride : n - omp_block_start; { memset(bucket1_local, 0, ALPHABET_SIZE * sizeof(sa_uint_t)); libsais_unbwt_compute_histogram(T + omp_block_start, omp_block_size, bucket1_local); } #pragma omp barrier #pragma omp master { { sa_uint_t * RESTRICT bucket1_temp = buckets; fast_sint_t t; for (t = 0; t < omp_num_threads; ++t, bucket1_temp += ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)) { fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_uint_t A = bucket1[c], B = bucket1_temp[c]; bucket1[c] = A + B; bucket1_temp[c] = A; } } } { fast_uint_t sum, c; for (sum = 1, c = 0; c < ALPHABET_SIZE; ++c) { fast_uint_t prev = sum; sum += bucket1[c]; bucket1[c] = (sa_uint_t)prev; } } } #pragma omp barrier { fast_sint_t c; for (c = 0; c < ALPHABET_SIZE; c += 1) { sa_uint_t A = bucket1[c], B = bucket1_local[c]; bucket1_local[c] = A + B; } memset(bucket2_local, 0, ALPHABET_SIZE * ALPHABET_SIZE * sizeof(sa_uint_t)); libsais_unbwt_compute_bigram_histogram_parallel(T, index, bucket1_local, bucket2_local, omp_block_start, omp_block_size); } #pragma omp barrier { fast_sint_t omp_bucket2_stride = ((ALPHABET_SIZE * ALPHABET_SIZE) / omp_num_threads) & (-16); fast_sint_t omp_bucket2_start = omp_thread_num * omp_bucket2_stride; fast_sint_t omp_bucket2_size = omp_thread_num < omp_num_threads - 1 ? omp_bucket2_stride : (ALPHABET_SIZE * ALPHABET_SIZE) - omp_bucket2_start; sa_uint_t * RESTRICT bucket2_temp = buckets + ALPHABET_SIZE; fast_sint_t t; for (t = 0; t < omp_num_threads; ++t, bucket2_temp += ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)) { fast_sint_t c; for (c = omp_bucket2_start; c < omp_bucket2_start + omp_bucket2_size; c += 1) { sa_uint_t A = bucket2[c], B = bucket2_temp[c]; bucket2[c] = A + B; bucket2_temp[c] = A; } } } #pragma omp barrier #pragma omp master { libsais_unbwt_calculate_fastbits(bucket2, fastbits, lastc, shift); { fast_sint_t t; for (t = omp_num_threads - 1; t >= 1; --t) { sa_uint_t * RESTRICT dst_bucket1 = buckets + t * (ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)); sa_uint_t * RESTRICT src_bucket1 = dst_bucket1 - (ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)); memcpy(dst_bucket1, src_bucket1, ALPHABET_SIZE * sizeof(sa_uint_t)); } memcpy(buckets, bucket1, ALPHABET_SIZE * sizeof(sa_uint_t)); } } #pragma omp barrier { fast_sint_t c; for (c = 0; c < ALPHABET_SIZE * ALPHABET_SIZE; c += 1) { sa_uint_t A = bucket2[c], B = bucket2_local[c]; bucket2_local[c] = A + B; } libsais_unbwt_calculate_biPSI(T, P, bucket1_local, bucket2_local, index, omp_block_start, omp_block_start + omp_block_size); } #pragma omp barrier #pragma omp master { memcpy(bucket2, buckets + ALPHABET_SIZE + (omp_num_threads - 1) * (ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)), ALPHABET_SIZE * ALPHABET_SIZE * sizeof(sa_uint_t)); } } } } #endif static void libsais_unbwt_decode_1(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t * i0, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; fast_uint_t i, p0 = *i0; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); } *i0 = p0; } static void libsais_unbwt_decode_2(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t r, fast_uint_t * i0, fast_uint_t * i1, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; uint16_t * RESTRICT U1 = (uint16_t *)(void *)(((uint8_t *)U0) + r); fast_uint_t i, p0 = *i0, p1 = *i1; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); uint16_t c1 = fastbits[p1 >> shift]; if (bucket2[c1] <= p1) { do { c1++; } while (bucket2[c1] <= p1); } p1 = P[p1]; U1[i] = libsais_bswap16(c1); } *i0 = p0; *i1 = p1; } static void libsais_unbwt_decode_3(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t r, fast_uint_t * i0, fast_uint_t * i1, fast_uint_t * i2, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; uint16_t * RESTRICT U1 = (uint16_t *)(void *)(((uint8_t *)U0) + r); uint16_t * RESTRICT U2 = (uint16_t *)(void *)(((uint8_t *)U1) + r); fast_uint_t i, p0 = *i0, p1 = *i1, p2 = *i2; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); uint16_t c1 = fastbits[p1 >> shift]; if (bucket2[c1] <= p1) { do { c1++; } while (bucket2[c1] <= p1); } p1 = P[p1]; U1[i] = libsais_bswap16(c1); uint16_t c2 = fastbits[p2 >> shift]; if (bucket2[c2] <= p2) { do { c2++; } while (bucket2[c2] <= p2); } p2 = P[p2]; U2[i] = libsais_bswap16(c2); } *i0 = p0; *i1 = p1; *i2 = p2; } static void libsais_unbwt_decode_4(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t r, fast_uint_t * i0, fast_uint_t * i1, fast_uint_t * i2, fast_uint_t * i3, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; uint16_t * RESTRICT U1 = (uint16_t *)(void *)(((uint8_t *)U0) + r); uint16_t * RESTRICT U2 = (uint16_t *)(void *)(((uint8_t *)U1) + r); uint16_t * RESTRICT U3 = (uint16_t *)(void *)(((uint8_t *)U2) + r); fast_uint_t i, p0 = *i0, p1 = *i1, p2 = *i2, p3 = *i3; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); uint16_t c1 = fastbits[p1 >> shift]; if (bucket2[c1] <= p1) { do { c1++; } while (bucket2[c1] <= p1); } p1 = P[p1]; U1[i] = libsais_bswap16(c1); uint16_t c2 = fastbits[p2 >> shift]; if (bucket2[c2] <= p2) { do { c2++; } while (bucket2[c2] <= p2); } p2 = P[p2]; U2[i] = libsais_bswap16(c2); uint16_t c3 = fastbits[p3 >> shift]; if (bucket2[c3] <= p3) { do { c3++; } while (bucket2[c3] <= p3); } p3 = P[p3]; U3[i] = libsais_bswap16(c3); } *i0 = p0; *i1 = p1; *i2 = p2; *i3 = p3; } static void libsais_unbwt_decode_5(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t r, fast_uint_t * i0, fast_uint_t * i1, fast_uint_t * i2, fast_uint_t * i3, fast_uint_t * i4, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; uint16_t * RESTRICT U1 = (uint16_t *)(void *)(((uint8_t *)U0) + r); uint16_t * RESTRICT U2 = (uint16_t *)(void *)(((uint8_t *)U1) + r); uint16_t * RESTRICT U3 = (uint16_t *)(void *)(((uint8_t *)U2) + r); uint16_t * RESTRICT U4 = (uint16_t *)(void *)(((uint8_t *)U3) + r); fast_uint_t i, p0 = *i0, p1 = *i1, p2 = *i2, p3 = *i3, p4 = *i4; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); uint16_t c1 = fastbits[p1 >> shift]; if (bucket2[c1] <= p1) { do { c1++; } while (bucket2[c1] <= p1); } p1 = P[p1]; U1[i] = libsais_bswap16(c1); uint16_t c2 = fastbits[p2 >> shift]; if (bucket2[c2] <= p2) { do { c2++; } while (bucket2[c2] <= p2); } p2 = P[p2]; U2[i] = libsais_bswap16(c2); uint16_t c3 = fastbits[p3 >> shift]; if (bucket2[c3] <= p3) { do { c3++; } while (bucket2[c3] <= p3); } p3 = P[p3]; U3[i] = libsais_bswap16(c3); uint16_t c4 = fastbits[p4 >> shift]; if (bucket2[c4] <= p4) { do { c4++; } while (bucket2[c4] <= p4); } p4 = P[p4]; U4[i] = libsais_bswap16(c4); } *i0 = p0; *i1 = p1; *i2 = p2; *i3 = p3; *i4 = p4; } static void libsais_unbwt_decode_6(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t r, fast_uint_t * i0, fast_uint_t * i1, fast_uint_t * i2, fast_uint_t * i3, fast_uint_t * i4, fast_uint_t * i5, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; uint16_t * RESTRICT U1 = (uint16_t *)(void *)(((uint8_t *)U0) + r); uint16_t * RESTRICT U2 = (uint16_t *)(void *)(((uint8_t *)U1) + r); uint16_t * RESTRICT U3 = (uint16_t *)(void *)(((uint8_t *)U2) + r); uint16_t * RESTRICT U4 = (uint16_t *)(void *)(((uint8_t *)U3) + r); uint16_t * RESTRICT U5 = (uint16_t *)(void *)(((uint8_t *)U4) + r); fast_uint_t i, p0 = *i0, p1 = *i1, p2 = *i2, p3 = *i3, p4 = *i4, p5 = *i5; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); uint16_t c1 = fastbits[p1 >> shift]; if (bucket2[c1] <= p1) { do { c1++; } while (bucket2[c1] <= p1); } p1 = P[p1]; U1[i] = libsais_bswap16(c1); uint16_t c2 = fastbits[p2 >> shift]; if (bucket2[c2] <= p2) { do { c2++; } while (bucket2[c2] <= p2); } p2 = P[p2]; U2[i] = libsais_bswap16(c2); uint16_t c3 = fastbits[p3 >> shift]; if (bucket2[c3] <= p3) { do { c3++; } while (bucket2[c3] <= p3); } p3 = P[p3]; U3[i] = libsais_bswap16(c3); uint16_t c4 = fastbits[p4 >> shift]; if (bucket2[c4] <= p4) { do { c4++; } while (bucket2[c4] <= p4); } p4 = P[p4]; U4[i] = libsais_bswap16(c4); uint16_t c5 = fastbits[p5 >> shift]; if (bucket2[c5] <= p5) { do { c5++; } while (bucket2[c5] <= p5); } p5 = P[p5]; U5[i] = libsais_bswap16(c5); } *i0 = p0; *i1 = p1; *i2 = p2; *i3 = p3; *i4 = p4; *i5 = p5; } static void libsais_unbwt_decode_7(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t r, fast_uint_t * i0, fast_uint_t * i1, fast_uint_t * i2, fast_uint_t * i3, fast_uint_t * i4, fast_uint_t * i5, fast_uint_t * i6, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; uint16_t * RESTRICT U1 = (uint16_t *)(void *)(((uint8_t *)U0) + r); uint16_t * RESTRICT U2 = (uint16_t *)(void *)(((uint8_t *)U1) + r); uint16_t * RESTRICT U3 = (uint16_t *)(void *)(((uint8_t *)U2) + r); uint16_t * RESTRICT U4 = (uint16_t *)(void *)(((uint8_t *)U3) + r); uint16_t * RESTRICT U5 = (uint16_t *)(void *)(((uint8_t *)U4) + r); uint16_t * RESTRICT U6 = (uint16_t *)(void *)(((uint8_t *)U5) + r); fast_uint_t i, p0 = *i0, p1 = *i1, p2 = *i2, p3 = *i3, p4 = *i4, p5 = *i5, p6 = *i6; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); uint16_t c1 = fastbits[p1 >> shift]; if (bucket2[c1] <= p1) { do { c1++; } while (bucket2[c1] <= p1); } p1 = P[p1]; U1[i] = libsais_bswap16(c1); uint16_t c2 = fastbits[p2 >> shift]; if (bucket2[c2] <= p2) { do { c2++; } while (bucket2[c2] <= p2); } p2 = P[p2]; U2[i] = libsais_bswap16(c2); uint16_t c3 = fastbits[p3 >> shift]; if (bucket2[c3] <= p3) { do { c3++; } while (bucket2[c3] <= p3); } p3 = P[p3]; U3[i] = libsais_bswap16(c3); uint16_t c4 = fastbits[p4 >> shift]; if (bucket2[c4] <= p4) { do { c4++; } while (bucket2[c4] <= p4); } p4 = P[p4]; U4[i] = libsais_bswap16(c4); uint16_t c5 = fastbits[p5 >> shift]; if (bucket2[c5] <= p5) { do { c5++; } while (bucket2[c5] <= p5); } p5 = P[p5]; U5[i] = libsais_bswap16(c5); uint16_t c6 = fastbits[p6 >> shift]; if (bucket2[c6] <= p6) { do { c6++; } while (bucket2[c6] <= p6); } p6 = P[p6]; U6[i] = libsais_bswap16(c6); } *i0 = p0; *i1 = p1; *i2 = p2; *i3 = p3; *i4 = p4; *i5 = p5; *i6 = p6; } static void libsais_unbwt_decode_8(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_uint_t shift, fast_uint_t r, fast_uint_t * i0, fast_uint_t * i1, fast_uint_t * i2, fast_uint_t * i3, fast_uint_t * i4, fast_uint_t * i5, fast_uint_t * i6, fast_uint_t * i7, fast_uint_t k) { uint16_t * RESTRICT U0 = (uint16_t *)(void *)U; uint16_t * RESTRICT U1 = (uint16_t *)(void *)(((uint8_t *)U0) + r); uint16_t * RESTRICT U2 = (uint16_t *)(void *)(((uint8_t *)U1) + r); uint16_t * RESTRICT U3 = (uint16_t *)(void *)(((uint8_t *)U2) + r); uint16_t * RESTRICT U4 = (uint16_t *)(void *)(((uint8_t *)U3) + r); uint16_t * RESTRICT U5 = (uint16_t *)(void *)(((uint8_t *)U4) + r); uint16_t * RESTRICT U6 = (uint16_t *)(void *)(((uint8_t *)U5) + r); uint16_t * RESTRICT U7 = (uint16_t *)(void *)(((uint8_t *)U6) + r); fast_uint_t i, p0 = *i0, p1 = *i1, p2 = *i2, p3 = *i3, p4 = *i4, p5 = *i5, p6 = *i6, p7 = *i7; for (i = 0; i != k; ++i) { uint16_t c0 = fastbits[p0 >> shift]; if (bucket2[c0] <= p0) { do { c0++; } while (bucket2[c0] <= p0); } p0 = P[p0]; U0[i] = libsais_bswap16(c0); uint16_t c1 = fastbits[p1 >> shift]; if (bucket2[c1] <= p1) { do { c1++; } while (bucket2[c1] <= p1); } p1 = P[p1]; U1[i] = libsais_bswap16(c1); uint16_t c2 = fastbits[p2 >> shift]; if (bucket2[c2] <= p2) { do { c2++; } while (bucket2[c2] <= p2); } p2 = P[p2]; U2[i] = libsais_bswap16(c2); uint16_t c3 = fastbits[p3 >> shift]; if (bucket2[c3] <= p3) { do { c3++; } while (bucket2[c3] <= p3); } p3 = P[p3]; U3[i] = libsais_bswap16(c3); uint16_t c4 = fastbits[p4 >> shift]; if (bucket2[c4] <= p4) { do { c4++; } while (bucket2[c4] <= p4); } p4 = P[p4]; U4[i] = libsais_bswap16(c4); uint16_t c5 = fastbits[p5 >> shift]; if (bucket2[c5] <= p5) { do { c5++; } while (bucket2[c5] <= p5); } p5 = P[p5]; U5[i] = libsais_bswap16(c5); uint16_t c6 = fastbits[p6 >> shift]; if (bucket2[c6] <= p6) { do { c6++; } while (bucket2[c6] <= p6); } p6 = P[p6]; U6[i] = libsais_bswap16(c6); uint16_t c7 = fastbits[p7 >> shift]; if (bucket2[c7] <= p7) { do { c7++; } while (bucket2[c7] <= p7); } p7 = P[p7]; U7[i] = libsais_bswap16(c7); } *i0 = p0; *i1 = p1; *i2 = p2; *i3 = p3; *i4 = p4; *i5 = p5; *i6 = p6; *i7 = p7; } static void libsais_unbwt_decode(uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_sint_t n, sa_sint_t r, const sa_uint_t * RESTRICT I, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, fast_sint_t blocks, fast_uint_t reminder) { fast_uint_t shift = 0; while ((n >> shift) > (1 << UNBWT_FASTBITS)) { shift++; } fast_uint_t offset = 0; while (blocks > 8) { fast_uint_t i0 = I[0], i1 = I[1], i2 = I[2], i3 = I[3], i4 = I[4], i5 = I[5], i6 = I[6], i7 = I[7]; libsais_unbwt_decode_8(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, &i5, &i6, &i7, (fast_uint_t)r >> 1); I += 8; blocks -= 8; offset += 8 * (fast_uint_t)r; } if (blocks == 1) { fast_uint_t i0 = I[0]; libsais_unbwt_decode_1(U + offset, P, bucket2, fastbits, shift, &i0, reminder >> 1); } else if (blocks == 2) { fast_uint_t i0 = I[0], i1 = I[1]; libsais_unbwt_decode_2(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, reminder >> 1); libsais_unbwt_decode_1(U + offset + 2 * (reminder >> 1), P, bucket2, fastbits, shift, &i0, ((fast_uint_t)r >> 1) - (reminder >> 1)); } else if (blocks == 3) { fast_uint_t i0 = I[0], i1 = I[1], i2 = I[2]; libsais_unbwt_decode_3(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, reminder >> 1); libsais_unbwt_decode_2(U + offset + 2 * (reminder >> 1), P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, ((fast_uint_t)r >> 1) - (reminder >> 1)); } else if (blocks == 4) { fast_uint_t i0 = I[0], i1 = I[1], i2 = I[2], i3 = I[3]; libsais_unbwt_decode_4(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, reminder >> 1); libsais_unbwt_decode_3(U + offset + 2 * (reminder >> 1), P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, ((fast_uint_t)r >> 1) - (reminder >> 1)); } else if (blocks == 5) { fast_uint_t i0 = I[0], i1 = I[1], i2 = I[2], i3 = I[3], i4 = I[4]; libsais_unbwt_decode_5(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, reminder >> 1); libsais_unbwt_decode_4(U + offset + 2 * (reminder >> 1), P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, ((fast_uint_t)r >> 1) - (reminder >> 1)); } else if (blocks == 6) { fast_uint_t i0 = I[0], i1 = I[1], i2 = I[2], i3 = I[3], i4 = I[4], i5 = I[5]; libsais_unbwt_decode_6(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, &i5, reminder >> 1); libsais_unbwt_decode_5(U + offset + 2 * (reminder >> 1), P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, ((fast_uint_t)r >> 1) - (reminder >> 1)); } else if (blocks == 7) { fast_uint_t i0 = I[0], i1 = I[1], i2 = I[2], i3 = I[3], i4 = I[4], i5 = I[5], i6 = I[6]; libsais_unbwt_decode_7(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, &i5, &i6, reminder >> 1); libsais_unbwt_decode_6(U + offset + 2 * (reminder >> 1), P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, &i5, ((fast_uint_t)r >> 1) - (reminder >> 1)); } else { fast_uint_t i0 = I[0], i1 = I[1], i2 = I[2], i3 = I[3], i4 = I[4], i5 = I[5], i6 = I[6], i7 = I[7]; libsais_unbwt_decode_8(U + offset, P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, &i5, &i6, &i7, reminder >> 1); libsais_unbwt_decode_7(U + offset + 2 * (reminder >> 1), P, bucket2, fastbits, shift, (fast_uint_t)r, &i0, &i1, &i2, &i3, &i4, &i5, &i6, ((fast_uint_t)r >> 1) - (reminder >> 1)); } } static void libsais_unbwt_decode_omp(const uint8_t * RESTRICT T, uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_sint_t n, sa_sint_t r, const sa_uint_t * RESTRICT I, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, sa_sint_t threads) { fast_uint_t lastc = T[0]; fast_sint_t blocks = 1 + (((fast_sint_t)n - 1) / (fast_sint_t)r); fast_uint_t reminder = (fast_uint_t)n - ((fast_uint_t)r * ((fast_uint_t)blocks - 1)); #if defined(_OPENMP) fast_sint_t max_threads = blocks < threads ? blocks : threads; #pragma omp parallel num_threads(max_threads) if(max_threads > 1 && n >= 65536) #endif { #if defined(_OPENMP) fast_sint_t omp_thread_num = omp_get_thread_num(); fast_sint_t omp_num_threads = omp_get_num_threads(); #else UNUSED(threads); fast_sint_t omp_thread_num = 0; fast_sint_t omp_num_threads = 1; #endif fast_sint_t omp_block_stride = blocks / omp_num_threads; fast_sint_t omp_block_reminder = blocks % omp_num_threads; fast_sint_t omp_block_size = omp_block_stride + (omp_thread_num < omp_block_reminder); fast_sint_t omp_block_start = omp_block_stride * omp_thread_num + (omp_thread_num < omp_block_reminder ? omp_thread_num : omp_block_reminder); libsais_unbwt_decode(U + r * omp_block_start, P, n, r, I + omp_block_start, bucket2, fastbits, omp_block_size, omp_thread_num < omp_num_threads - 1 ? (fast_uint_t)r : reminder); } U[n - 1] = (uint8_t)lastc; } static sa_sint_t libsais_unbwt_core(const uint8_t * RESTRICT T, uint8_t * RESTRICT U, sa_uint_t * RESTRICT P, sa_sint_t n, const sa_sint_t * freq, sa_sint_t r, const sa_uint_t * RESTRICT I, sa_uint_t * RESTRICT bucket2, uint16_t * RESTRICT fastbits, sa_uint_t * RESTRICT buckets, sa_sint_t threads) { #if defined(_OPENMP) if (threads > 1 && n >= 262144) { libsais_unbwt_init_parallel(T, P, n, freq, I, bucket2, fastbits, buckets, threads); } else #else UNUSED(buckets); #endif { libsais_unbwt_init_single(T, P, n, freq, I, bucket2, fastbits); } libsais_unbwt_decode_omp(T, U, P, n, r, I, bucket2, fastbits, threads); return 0; } static sa_sint_t libsais_unbwt_main(const uint8_t * T, uint8_t * U, sa_uint_t * P, sa_sint_t n, const sa_sint_t * freq, sa_sint_t r, const sa_uint_t * I, sa_sint_t threads) { fast_uint_t shift = 0; while ((n >> shift) > (1 << UNBWT_FASTBITS)) { shift++; } sa_uint_t * RESTRICT bucket2 = (sa_uint_t *)libsais_alloc_aligned(ALPHABET_SIZE * ALPHABET_SIZE * sizeof(sa_uint_t), 4096); uint16_t * RESTRICT fastbits = (uint16_t *)libsais_alloc_aligned(((size_t)1 + (size_t)(n >> shift)) * sizeof(uint16_t), 4096); sa_uint_t * RESTRICT buckets = threads > 1 && n >= 262144 ? (sa_uint_t *)libsais_alloc_aligned((size_t)threads * (ALPHABET_SIZE + (ALPHABET_SIZE * ALPHABET_SIZE)) * sizeof(sa_uint_t), 4096) : NULL; sa_sint_t index = bucket2 != NULL && fastbits != NULL && (buckets != NULL || threads == 1 || n < 262144) ? libsais_unbwt_core(T, U, P, n, freq, r, I, bucket2, fastbits, buckets, threads) : -2; libsais_free_aligned(buckets); libsais_free_aligned(fastbits); libsais_free_aligned(bucket2); return index; } static sa_sint_t libsais_unbwt_main_ctx(const LIBSAIS_UNBWT_CONTEXT * ctx, const uint8_t * T, uint8_t * U, sa_uint_t * P, sa_sint_t n, const sa_sint_t * freq, sa_sint_t r, const sa_uint_t * I) { return ctx != NULL && ctx->bucket2 != NULL && ctx->fastbits != NULL && (ctx->buckets != NULL || ctx->threads == 1) ? libsais_unbwt_core(T, U, P, n, freq, r, I, ctx->bucket2, ctx->fastbits, ctx->buckets, (sa_sint_t)ctx->threads) : -2; } void * libsais_unbwt_create_ctx(void) { return (void *)libsais_unbwt_create_ctx_main(1); } void libsais_unbwt_free_ctx(void * ctx) { libsais_unbwt_free_ctx_main((LIBSAIS_UNBWT_CONTEXT *)ctx); } int32_t libsais_unbwt(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i) { return libsais_unbwt_aux(T, U, A, n, freq, n, &i); } int32_t libsais_unbwt_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i) { return libsais_unbwt_aux_ctx(ctx, T, U, A, n, freq, n, &i); } int32_t libsais_unbwt_aux(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I) { if ((T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || ((r != n) && ((r < 2) || ((r & (r - 1)) != 0))) || (I == NULL)) { return -1; } else if (n <= 1) { if (I[0] != n) { return -1; } if (n == 1) { U[0] = T[0]; } return 0; } fast_sint_t t; for (t = 0; t <= (n - 1) / r; ++t) { if (I[t] <= 0 || I[t] > n) { return -1; } } return libsais_unbwt_main(T, U, (sa_uint_t *)A, n, freq, r, (const sa_uint_t *)I, 1); } int32_t libsais_unbwt_aux_ctx(const void * ctx, const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I) { if ((T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || ((r != n) && ((r < 2) || ((r & (r - 1)) != 0))) || (I == NULL)) { return -1; } else if (n <= 1) { if (I[0] != n) { return -1; } if (n == 1) { U[0] = T[0]; } return 0; } fast_sint_t t; for (t = 0; t <= (n - 1) / r; ++t) { if (I[t] <= 0 || I[t] > n) { return -1; } } return libsais_unbwt_main_ctx((const LIBSAIS_UNBWT_CONTEXT *)ctx, T, U, (sa_uint_t *)A, n, freq, r, (const sa_uint_t *)I); } #if defined(_OPENMP) void * libsais_unbwt_create_ctx_omp(int32_t threads) { if (threads < 0) { return NULL; } threads = threads > 0 ? threads : omp_get_max_threads(); return (void *)libsais_unbwt_create_ctx_main(threads); } int32_t libsais_unbwt_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t i, int32_t threads) { return libsais_unbwt_aux_omp(T, U, A, n, freq, n, &i, threads); } int32_t libsais_unbwt_aux_omp(const uint8_t * T, uint8_t * U, int32_t * A, int32_t n, const int32_t * freq, int32_t r, const int32_t * I, int32_t threads) { if ((T == NULL) || (U == NULL) || (A == NULL) || (n < 0) || ((r != n) && ((r < 2) || ((r & (r - 1)) != 0))) || (I == NULL) || (threads < 0)) { return -1; } else if (n <= 1) { if (I[0] != n) { return -1; } if (n == 1) { U[0] = T[0]; } return 0; } fast_sint_t t; for (t = 0; t <= (n - 1) / r; ++t) { if (I[t] <= 0 || I[t] > n) { return -1; } } threads = threads > 0 ? threads : omp_get_max_threads(); return libsais_unbwt_main(T, U, (sa_uint_t *)A, n, freq, r, (const sa_uint_t *)I, threads); } #endif
mgl.h
/*************************************************************************** * mgl.h is part of Math Graphic Library * Copyright (C) 2007-2016 Alexey Balakin <mathgl.abalakin@gmail.ru> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef _MGL_H_ #define _MGL_H_ #include "mgl2/mgl_cf.h" #ifdef __cplusplus #include "mgl2/data.h" #include "mgl2/datac.h" #include <sys/stat.h> //----------------------------------------------------------------------------- /// Wrapper class for all graphics class MGL_EXPORT mglGraph { mglGraph(const mglGraph &) {} // copying is not allowed const mglGraph &operator=(const mglGraph &t) { return t; } protected: HMGL gr; public: HMPR pr; ///< Pointer to associated MGL parser mglGraph(int kind=0, int width=600, int height=400) { pr = NULL; if(kind==-1) gr=NULL; #if MGL_HAVE_OPENGL else if(kind==1) gr=mgl_create_graph_gl(); #else else if(kind==1) { gr=mgl_create_graph(width, height); SetGlobalWarn("OpenGL support was disabled. Please, enable it and rebuild MathGL."); } #endif else gr=mgl_create_graph(width, height); } mglGraph(HMGL graph) { pr = NULL; gr = graph; mgl_use_graph(gr,1); } virtual ~mglGraph() { if(mgl_use_graph(gr,-1)<1) mgl_delete_graph(gr); } /// Get pointer to internal HMGL object inline HMGL Self() { return gr; } /// Set default parameters for plotting inline void DefaultPlotParam() { mgl_set_def_param(gr); } /// Set name of plot for saving filename inline void SetPlotId(const char *id) { mgl_set_plotid(gr,id); } /// Get name of plot for saving filename inline const char *GetPlotId() { return mgl_get_plotid(gr); } /// Ask to stop drawing inline void Stop(bool stop=true) { mgl_ask_stop(gr, stop); } /// Check if plot termination is asked inline bool NeedStop() { return mgl_need_stop(gr); } /// Set callback function for event processing inline void SetEventFunc(void (*func)(void *), void *par=NULL) { mgl_set_event_func(gr, func, par); } /// Set the transparency on/off. inline void Alpha(bool enable) { mgl_set_alpha(gr, enable); } /// Set the gray-scale mode on/off. inline void Gray(bool enable) { mgl_set_gray(gr, enable); } /// Set default value of alpha-channel inline void SetAlphaDef(double alpha) { mgl_set_alpha_default(gr, alpha); } /// Set the transparency type (0 - usual, 1 - glass, 2 - lamp) inline void SetTranspType(int type) { mgl_set_transp_type(gr, type); } /// Set the size of semi-transparent area around lines, marks, glyphs, ... Default is 1. inline void SetPenDelta(double d) { mgl_pen_delta(gr,d); } /// Set the using of light on/off. inline void Light(bool enable) { mgl_set_light(gr, enable); } /// Switch on/off the specified light source. inline void Light(int n,bool enable) { mgl_set_light_n(gr, n, enable); } /// Use diffusive light (only for local light sources) -- OBSOLETE inline void SetDifLight(bool dif) { mgl_set_light_dif(gr, dif); } /// Set to attach light settings to inplot. inline void AttachLight(bool enable) { mgl_set_attach_light(gr, enable); } /// Add a light source. inline void AddLight(int n, mglPoint p, char col='w', double bright=0.5, double ap=0) { mgl_add_light_ext(gr, n, p.x, p.y, p.z, col, bright, ap); } inline void AddLight(int n, mglPoint r, mglPoint p, char col='w', double bright=0.5, double ap=0) { mgl_add_light_loc(gr, n, r.x, r.y, r.z, p.x, p.y, p.z, col, bright, ap); } /// Set ambient light brightness inline void SetAmbient(double i) { mgl_set_ambbr(gr, i); } /// Set diffusive light brightness inline void SetDiffuse(double i) { mgl_set_difbr(gr, i); } /// Set the fog distance or switch it off (if d=0). inline void Fog(double d, double dz=0.25) { mgl_set_fog(gr, d, dz); } /// Set relative width of rectangles in Bars, Barh, BoxPlot, Candle, OHLC (default is 0.7) inline void SetBarWidth(double width) { mgl_set_bar_width(gr, width); } /// Set default size of marks (locally you can use "size" option) inline void SetMarkSize(double size) { mgl_set_mark_size(gr, size); } /// Set default size of arrows (locally you can use "size" option) inline void SetArrowSize(double size) { mgl_set_arrow_size(gr, size); } /// Set number of mesh lines (use 0 to draw all of them) inline void SetMeshNum(int num) { mgl_set_meshnum(gr, num); } /// Set number of visible faces (use 0 to draw all of them) inline void SetFaceNum(int num) { mgl_set_facenum(gr, num); } /// Set cutting for points outside of bounding box inline void SetCut(bool cut) { mgl_set_cut(gr, cut); } /// Set additional cutting box inline void SetCutBox(mglPoint p1, mglPoint p2) { mgl_set_cut_box(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z); } /// Set the cutting off condition (formula) inline void CutOff(const char *EqC) { mgl_set_cutoff(gr, EqC); } /// Set default font size inline void SetFontSize(double size) { mgl_set_font_size(gr, size); } /// Set default font style and color inline void SetFontDef(const char *fnt) { mgl_set_font_def(gr, fnt); } /// Set FontSize by size in pt and picture DPI (default is 16 pt for dpi=72) virtual void SetFontSizePT(double pt, int dpi=72) { SetFontSize(pt*27.f/dpi); } /// Set FontSize by size in centimeters and picture DPI (default is 0.56 cm = 16 pt) inline void SetFontSizeCM(double cm, int dpi=72) { SetFontSizePT(cm*28.45f,dpi); } /// Set FontSize by size in inch and picture DPI (default is 0.22 in = 16 pt) inline void SetFontSizeIN(double in, int dpi=72) { SetFontSizePT(in*72.27f,dpi); } /// Load font from file inline void LoadFont(const char *name, const char *path=NULL) { mgl_load_font(gr, name, path); } /// Copy font from another mglGraph instance inline void CopyFont(const mglGraph *GR) { mgl_copy_font(gr, GR->gr);} /// Restore font (load default font for new HMGL objects) inline void RestoreFont() { mgl_restore_font(gr); } /// Set to use or not text rotation inline void SetRotatedText(bool enable) { mgl_set_rotated_text(gr, enable); } /// Set to scale text in relative subplots too inline void SetScaleText(bool enable) { mgl_set_scale_text(gr, enable); } /// Set default font for all new HMGL and mglGraph objects static inline void SetDefFont(const char *name, const char *path=NULL) { mgl_def_font(name,path); } /// Add user-defined glyph for symbol and set its optional id inline void DefineSymbol(char id, const mglDataA &x, const mglDataA &y) { mgl_define_symbol(gr, id, &x, &y); } /// Set default palette inline void SetPalette(const char *colors) { mgl_set_palette(gr, colors); } /// Set default color scheme inline void SetDefScheme(const char *sch) { mgl_set_def_sch(gr, sch); } /// Sets RGB values for color with given id static inline void SetColor(char id, double r, double g, double b) { mgl_set_color(id, r, g, b); } /// Set mask for face coloring as array of type 'unsigned char[8]' static inline void SetMask(char id, const char *mask) { mgl_set_mask(id, mask); } /// Set mask for face coloring as uint64_t number static inline void SetMask(char id, uint64_t mask) { mgl_set_mask_val(id, mask); } /// Set default mask rotation angle inline void SetMaskAngle(int angle) { mgl_set_mask_angle(gr, angle); } /// Get last warning code inline int GetWarn() { return mgl_get_warn(gr);} /// Set warning code ant fill message inline void SetWarn(int code, const char *info) { mgl_set_warn(gr,code,info); } /// Get text of warning message(s) inline const char *Message() { return mgl_get_mess(gr); } /// Set global warning message static inline void SetGlobalWarn(const char *text) { mgl_set_global_warn(text); } /// Get text of global warning message(s) static inline const char *GlobalWarn() { return mgl_get_global_warn(); } /// Suppress printing warnings to stderr static inline void SuppressWarn(bool on) { mgl_suppress_warn(on); } /// Check if MathGL version is valid (return false) or not (return true) static inline bool CheckVersion(const char *ver) { return mgl_check_version(ver); } /// Display progress of something. inline void Progress(int value, int maximal) { mgl_progress(value, maximal, gr); } /// Set axis range scaling -- simplified way to shift/zoom axis range -- need to replot whole image! inline void ZoomAxis(mglPoint p1=mglPoint(0,0,0,0), mglPoint p2=mglPoint(1,1,1,1)) { mgl_zoom_axis(gr, p1.x,p1.y,p1.z,p1.c, p2.x,p2.y,p2.z,p2.c); } /// Add [v1, v2] to the current range in direction dir inline void AddRange(char dir, double v1, double v2) { mgl_add_range_val(gr, dir, v1, v2); } /// Set range in direction dir as [v1, v2] inline void SetRange(char dir, double v1, double v2) { mgl_set_range_val(gr, dir, v1, v2); } /// Set range in direction dir as minimal and maximal values of data a inline void SetRange(char dir, const mglDataA &dat, bool add=false) { mgl_set_range_dat(gr, dir, &dat, add); } /// Set values of axis range as minimal and maximal values of corresponding data inline void SetRanges(const mglDataA &xx, const mglDataA &yy, const mglDataA &zz, const mglDataA &cc) { mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0); mgl_set_range_dat(gr,'z',&zz,0); mgl_set_range_dat(gr,'c',&cc,0); } /// Set values of axis range as minimal and maximal values of corresponding data inline void SetRanges(const mglDataA &xx, const mglDataA &yy, const mglDataA &zz) { mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0); mgl_set_range_dat(gr,'z',&zz,0); mgl_set_range_dat(gr,'c',&zz,0); } /// Set values of axis range as minimal and maximal values of corresponding data inline void SetRanges(const mglDataA &xx, const mglDataA &yy) { mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0); } /// Set values of axis ranges inline void SetRanges(double x1, double x2, double y1, double y2, double z1=0, double z2=0) { mgl_set_ranges(gr, x1, x2, y1, y2, z1, z2); } /// Set values of axis ranges inline void SetRanges(mglPoint p1, mglPoint p2) { mgl_set_ranges(gr, p1.x, p2.x, p1.y, p2.y, p1.z, p2.z); } /// Set ranges for automatic variables inline void SetAutoRanges(double x1, double x2, double y1=0, double y2=0, double z1=0, double z2=0, double c1=0, double c2=0) { mgl_set_auto_ranges(gr, x1, x2, y1, y2, z1, z2, c1, c2); } /// Set ranges for automatic variables inline void SetAutoRanges(mglPoint p1, mglPoint p2) { mgl_set_auto_ranges(gr, p1.x, p2.x, p1.y, p2.y, p1.z, p2.z, p1.c, p2.c); } /// Set axis origin inline void SetOrigin(mglPoint p) { mgl_set_origin(gr, p.x, p.y, p.z); } inline void SetOrigin(double x0, double y0, double z0=mglNaN) { mgl_set_origin(gr, x0, y0, z0); } /// Set the transformation formulas for coordinate. Use "" or NULL for built-in ones inline void SetFunc(const char *EqX, const char *EqY, const char *EqZ=NULL, const char *EqA=NULL) { mgl_set_func(gr, EqX, EqY, EqZ, EqA); } /// Set one of predefined transformation rule inline void SetCoor(int how) { mgl_set_coor(gr, how); } /// Set to draw Ternary axis (triangle like axis, grid and so on) /** val=1 for Ternary axis (a+b+c=1, z=z), * val=2 for Quaternary axis (a+b+c+d=1), * val|4 for projections. */ inline void Ternary(int val) { mgl_set_ternary(gr, val); } /// Set to use or not tick labels rotation inline void SetTickRotate(bool val) { mgl_set_tick_rotate(gr,val); } /// Set to use or not tick labels skipping inline void SetTickSkip(bool val) { mgl_set_tick_skip(gr,val); } /// Set tick length inline void SetTickLen(double len, double stt=1) { mgl_set_tick_len(gr, len, stt); } /// Set axis and ticks style inline void SetAxisStl(const char *stl="k", const char *tck=0, const char *sub=0) { mgl_set_axis_stl(gr, stl, tck, sub); } /// Set time templates for ticks inline void SetTicksTime(char dir, double d=0, const char *t="") { mgl_set_ticks_time(gr,dir,d,t); } /// Set ticks text (\n separated). Use "" to disable this feature. inline void SetTicksVal(char dir, const char *lbl, bool add=false) { mgl_set_ticks_str(gr,dir,lbl,add); } inline void SetTicksVal(char dir, const wchar_t *lbl, bool add=false) { mgl_set_ticks_wcs(gr,dir,lbl,add); } /// Set ticks position and text (\n separated). Use "" to disable this feature. inline void SetTicksVal(char dir, const mglDataA &v, const char *lbl, bool add=false) { mgl_set_ticks_val(gr,dir,&v,lbl,add); } inline void SetTicksVal(char dir, const mglDataA &v, const wchar_t *lbl, bool add=false) { mgl_set_ticks_valw(gr,dir,&v,lbl,add); } /// Add manual tick at given position. Use "" to disable this feature. inline void AddTick(char dir, double val, const char *lbl) { mgl_add_tick(gr,dir,val,lbl); } inline void AddTick(char dir, double val, const wchar_t *lbl) { mgl_add_tickw(gr,dir,val,lbl); } /// Set the ticks parameters and string for its factor inline void SetTicks(char dir, double d=0, int ns=0, double org=mglNaN, const char *factor="") { mgl_set_ticks_fact(gr, dir, d, ns, org, factor); } inline void SetTicks(char dir, double d, int ns, double org, const wchar_t *factor) { mgl_set_ticks_factw(gr, dir, d, ns, org, factor); } /// Auto adjust ticks inline void Adjust(const char *dir="xyzc") { mgl_adjust_ticks(gr, dir); } /// Set templates for ticks inline void SetTickTempl(char dir, const char *t) { mgl_set_tick_templ(gr,dir,t); } inline void SetTickTempl(char dir, const wchar_t *t) { mgl_set_tick_templw(gr,dir,t); } /// Tune ticks (tune|1 for common multiplier, tune|2 for common component) inline void SetTuneTicks(int tune, double fact_pos=1.15) { mgl_tune_ticks(gr, tune, fact_pos); } /// Set additional shift of tick labels inline void SetTickShift(mglPoint p) { mgl_set_tick_shift(gr,p.x,p.y,p.z,p.c); } /// Set to use UTC time instead of local time inline void SetTimeUTC(bool enable) { mgl_set_flag(gr,enable, MGL_USE_GMTIME); } /// Set to draw tick labels at axis origin inline void SetOriginTick(bool enable=true) { mgl_set_flag(gr,!enable, MGL_NO_ORIGIN); } /// Set bit-value flag of HMGL state (for advanced users only) inline void SetFlagAdv(int val, uint32_t flag) { mgl_set_flag(gr, val, flag); } /// Put further plotting in m-th cell of nx*ny grid of the image. /** String \a style may contain: * '<' for reserving space at left * '>' for reserving space at right * '^' for reserving space at top * '_' for reserving space at bottom * '#' for using whole region. */ inline void SubPlot(int nx,int ny,int m,const char *style="<>_^", double dx=0, double dy=0) { mgl_subplot_d(gr, nx, ny, m, style, dx, dy); } /// Put further plotting in rectangle of dx*dy cells starting from m-th cell of nx*ny grid of the image and shift it by distance {sx,sy}. /** String \a style may contain: * '<' for reserving space at left * '>' for reserving space at right * '^' for reserving space at top * '_' for reserving space at bottom * '#' for using whole region. */ inline void MultiPlot(int nx,int ny,int m, int dx, int dy, const char *style="<>_^", double sx=0, double sy=0) { mgl_multiplot_d(gr, nx, ny, m, dx, dy, style, sx, sy); } /// Put further plotting in a region [x1,x2]*[y1,y2] of the image or subplot (x1,x2,y1,y2 in range [0, 1]). inline void InPlot(double x1,double x2,double y1,double y2, bool rel=true) { if(rel) mgl_relplot(gr, x1, x2, y1, y2); else mgl_inplot(gr, x1, x2, y1, y2); } /// Put further plotting in column cell of previous subplot inline void ColumnPlot(int num, int ind, double d=0) { mgl_columnplot(gr,num,ind,d); } /// Put further plotting in matrix cell of previous subplot inline void GridPlot(int nx, int ny, int ind, double d=0) { mgl_gridplot(gr,nx,ny,ind,d); } /// Put further plotting in cell of stick rotated on angles tet, phi inline void StickPlot(int num, int i, double tet, double phi) { mgl_stickplot(gr,num,i,tet,phi); } /// Put further plotting in cell of stick sheared on sx, sy. inline void ShearPlot(int num, int i, mreal sx, mreal sy, mreal xd=1, mreal yd=0) { mgl_shearplot(gr,num,i,sx,sy,xd,yd); } /// Set factor of plot size inline void SetPlotFactor(double val) { mgl_set_plotfactor(gr,val); } /// Push transformation matrix into stack inline void Push() { mgl_mat_push(gr); } /// Pop transformation matrix from stack inline void Pop() { mgl_mat_pop(gr); } /// Add title for current subplot/inplot /** Style '#' draw box around the title. */ inline void Title(const char *title,const char *stl="",double size=-2) { mgl_title(gr,title,stl,size); } /// Add title for current subplot/inplot /** Style '#' draw box around the title. */ inline void Title(const wchar_t *title,const char *stl="",double size=-2) { mgl_titlew(gr,title,stl,size); } /// Set aspect ratio for further plotting. inline void Aspect(double Ax,double Ay,double Az=1) { mgl_aspect(gr, Ax, Ay, Az); } /// Shear a further plotting. inline void Shear(double Sx,double Sy) { mgl_shear(gr, Sx, Sy); } /// Rotate a further plotting. inline void Rotate(double TetX,double TetZ=0,double TetY=0) { mgl_rotate(gr, TetX, TetZ, TetY); } /// Rotate a further plotting around vector {x,y,z}. inline void RotateN(double Tet,double x,double y,double z) { mgl_rotate_vector(gr, Tet, x, y, z); } /// Set perspective (in range [0,1)) for plot. Set to zero for switching off. inline void Perspective(double val) { mgl_perspective(gr, val); } /// Set angle of view independently from Rotate(). inline void View(double TetX,double TetZ=0,double TetY=0) { mgl_view(gr, TetX, TetZ, TetY); } /// Set angle of view independently from Rotate(). inline void ViewAsRotate(double TetZ,double TetX,double TetY=0) { mgl_view(gr, -TetX, -TetZ, -TetY); } /// Zoom in/out a part of picture (use Zoom(0, 0, 1, 1) for restore default) inline void Zoom(double x1, double y1, double x2, double y2) { mgl_zoom(gr, x1, y1, x2, y2); } /// Set size of frame in pixels. Normally this function is called internally. inline void SetSize(int width, int height, bool clf=true) { if(clf) mgl_set_size(gr, width, height); else mgl_scale_size(gr, width, height); } /// Scaling for all further set size calls. static inline void SetSizeScl(double scl) { mgl_set_size_scl(scl); } /// Set plot quality /** qual=0 -- no face drawing (fastest), * qual=1 -- no color interpolation (fast), * qual=2 -- high quality (normal), * qual|4 -- direct bitmap drawing (low memory usage); * qual|8 for dots drawing instead of primitives (extremely fast). */ inline void SetQuality(int qual=MGL_DRAW_NORM) { mgl_set_quality(gr, qual); } /// Get plot quality inline int GetQuality() { return mgl_get_quality(gr); } /// Set drawing region for Quality&4 inline void SetDrawReg(long nx=1, long ny=1, long m=0) { mgl_set_draw_reg(gr,nx,ny,m); } /// Start group of objects inline void StartGroup(const char *name) { mgl_start_group(gr, name); } /// End group of objects inline void EndGroup() { mgl_end_group(gr); } /// Highlight objects with given id inline void Highlight(int id) { mgl_highlight(gr, id); } /// Set boundary box for export graphics into 2D file formats. /** If x2<0 (y2<0) then full width (height) will be used. * If x1<0 or y1<0 or x1>=x2|Width or y1>=y2|Height then cropping will be disabled. */ inline void SetBBox(int x1=0, int y1=0, int x2=-1, int y2=-1) { mgl_set_bbox(gr,x1,y1,x2,y2); } /// Show current image inline void ShowImage(const char *viewer, bool keep=0) { mgl_show_image(gr, viewer, keep); } /// Write the frame in file (depending extension, write current frame if fname is empty) inline void WriteFrame(const char *fname=0,const char *descr="") { mgl_write_frame(gr, fname, descr); } /// Write the frame in file using JPEG format inline void WriteJPEG(const char *fname,const char *descr="") { mgl_write_jpg(gr, fname, descr); } /// Write the frame in file using PNG format with transparency inline void WritePNG(const char *fname,const char *descr="", bool alpha=true) { if(alpha) mgl_write_png(gr, fname, descr); else mgl_write_png_solid(gr, fname, descr); } /// Write the frame in file using BMP format inline void WriteBMP(const char *fname,const char *descr="") { mgl_write_bmp(gr, fname, descr); } /// Write the frame in file using BMP format inline void WriteTGA(const char *fname,const char *descr="") { mgl_write_tga(gr, fname, descr); } /// Write the frame in file using PostScript format inline void WriteEPS(const char *fname,const char *descr="") { mgl_write_eps(gr, fname, descr); } /// Write the frame in file using LaTeX format inline void WriteTEX(const char *fname,const char *descr="") { mgl_write_tex(gr, fname, descr); } /// Write the frame in file using PostScript format as bitmap inline void WriteBPS(const char *fname,const char *descr="") { mgl_write_bps(gr, fname, descr); } /// Write the frame in file using SVG format inline void WriteSVG(const char *fname,const char *descr="") { mgl_write_svg(gr, fname, descr); } /// Write the frame in file using GIF format (only for current frame!) inline void WriteGIF(const char *fname,const char *descr="") { mgl_write_gif(gr, fname, descr); } /// Write the frame in file using OBJ format inline void WriteOBJ(const char *fname,const char *descr="",bool use_png=true) { mgl_write_obj(gr, fname, descr, use_png); } /// Write the frame in file using OBJ format - Balakin way inline void WriteOBJold(const char *fname,const char *descr="",bool use_png=true) { mgl_write_obj_old(gr, fname, descr, use_png); } /// Write the frame in file using XYZ format inline void WriteXYZ(const char *fname,const char *descr="") { mgl_write_xyz(gr, fname, descr); } /// Write the frame in file using STL format (faces only) inline void WriteSTL(const char *fname,const char *descr="") { mgl_write_stl(gr, fname, descr); } /// Write the frame in file using OFF format inline void WriteOFF(const char *fname,const char *descr="", bool colored=false) { mgl_write_off(gr, fname, descr,colored); } // /// Write the frame in file using X3D format // inline void WriteX3D(const char *fname,const char *descr="") // { mgl_write_x3d(gr, fname, descr); } /// Write the frame in file using PRC format inline void WritePRC(const char *fname,const char *descr="",bool make_pdf=true) { mgl_write_prc(gr, fname, descr, make_pdf); } /// Export in JSON format suitable for later drawing by JavaScript inline void WriteJSON(const char *fname,const char *descr="",bool force_z=false) { if(force_z) mgl_write_json_z(gr, fname, descr); else mgl_write_json(gr, fname, descr); } /// Return string of JSON data suitable for later drawing by JavaScript inline const char *GetJSON() { return mgl_get_json(gr); } /// Force preparing the image. It can be useful for OpenGL mode mostly. inline void Finish() { mgl_finish(gr); } /// Create new frame. inline void NewFrame() { mgl_new_frame(gr); } /// Finish frame drawing inline void EndFrame() { mgl_end_frame(gr); } /// Get the number of created frames inline int GetNumFrame() { return mgl_get_num_frame(gr); } /// Reset frames counter (start it from zero) inline void ResetFrames() { mgl_reset_frames(gr); } /// Delete primitives for i-th frame (work if MGL_VECT_FRAME is set on) inline void DelFrame(int i) { mgl_del_frame(gr, i); } /// Get drawing data for i-th frame (work if MGL_VECT_FRAME is set on) inline void GetFrame(int i) { mgl_get_frame(gr, i); } /// Set drawing data for i-th frame (work if MGL_VECT_FRAME is set on). Work as EndFrame() but don't add frame to GIF image. inline void SetFrame(int i) { mgl_set_frame(gr, i); } /// Append drawing data from i-th frame (work if MGL_VECT_FRAME is set on) inline void ShowFrame(int i){ mgl_show_frame(gr, i); } /// Clear list of primitives for current drawing inline void ClearFrame() { mgl_clear_frame(gr); } /// Start write frames to cinema using GIF format inline void StartGIF(const char *fname, int ms=100) { mgl_start_gif(gr, fname,ms); } /// Stop writing cinema using GIF format inline void CloseGIF() { mgl_close_gif(gr); } /// Export points and primitives in file using MGLD format inline void ExportMGLD(const char *fname, const char *descr=0) { mgl_export_mgld(gr, fname, descr); } /// Import points and primitives from file using MGLD format inline void ImportMGLD(const char *fname, bool add=false) { mgl_import_mgld(gr, fname, add); } /// Copy RGB values into array which is allocated by user /** Position of element {i,j} is [3*i + 3*Width*j]. */ inline bool GetRGB(char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr); if(imglen>=3*w*h) memcpy(imgdata, mgl_get_rgb(gr),3*w*h); return imglen>=3*w*h; } /// Get RGB values of current bitmap /** Position of element {i,j} is [3*i + 3*Width*j]. */ inline const unsigned char *GetRGB() { return mgl_get_rgb(gr); } /// Copy RGBA values into array which is allocated by user /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline bool GetRGBA(char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr); if(imglen>=4*w*h) memcpy(imgdata, mgl_get_rgba(gr),4*w*h); return imglen>=4*w*h; } /// Get RGBA values of current bitmap /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline const unsigned char *GetRGBA() { return mgl_get_rgba(gr); } /// Copy BGRN values into array which is allocated by user inline bool GetBGRN(unsigned char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr), i; const unsigned char *buf=mgl_get_rgb(gr); if(imglen>=4*w*h) for(i=0;i<w*h;i++) { imgdata[4*i] = buf[3*i+2]; imgdata[4*i+1] = buf[3*i+1]; imgdata[4*i+2] = buf[3*i]; imgdata[4*i+3] = 255; } return imglen>=4*w*h; } /// Copy RGBA values of background image into array which is allocated by user /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline bool GetBackground(char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr); if(imglen>=4*w*h) memcpy(imgdata, mgl_get_background(gr),4*w*h); return imglen>=4*w*h; } /// Get RGBA values of background image /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline const unsigned char *GetBackground() { return mgl_get_background(gr); } /// Get width of the image inline int GetWidth() { return mgl_get_width(gr); } /// Get height of the image inline int GetHeight() { return mgl_get_height(gr);} /// Calculate 3D coordinate {x,y,z} for screen point {xs,ys} inline mglPoint CalcXYZ(int xs, int ys) { mreal x,y,z; mgl_calc_xyz(gr,xs,ys,&x,&y,&z); return mglPoint(x,y,z); } /// Calculate screen point {xs,ys} for 3D coordinate {x,y,z} inline mglPoint CalcScr(mglPoint p) { int xs,ys; mgl_calc_scr(gr,p.x,p.y,p.z,&xs,&ys); return mglPoint(xs,ys); } /// Set object/subplot id inline void SetObjId(int id) { mgl_set_obj_id(gr,id); } /// Get object id inline int GetObjId(long x,long y) { return mgl_get_obj_id(gr,x,y); } /// Get subplot id inline int GetSplId(long x,long y) { return mgl_get_spl_id(gr,x,y); } /// Check if {\a xs,\a ys} is close to active point with accuracy d, and return its position or -1 inline long IsActive(int xs, int ys, int d=1) { return mgl_is_active(gr,xs,ys,d); } /// Combine plots from 2 canvases. Result will be saved into this inline void Combine(const mglGraph *g) { mgl_combine_gr(gr,g->gr); } /// Clear up the frame and fill background by specified color inline void Clf(double r, double g, double b) { mgl_clf_rgb(gr, r, g, b); } /// Clear up the frame and fill background by specified color with manual transparency inline void Clf(const char *col) { mgl_clf_str(gr, col); } /// Clear up the frame and fill background by specified color inline void Clf(char col) { mgl_clf_chr(gr, col); } /// Clear up the frame inline void Clf() { mgl_clf(gr); } /// Clear unused points and primitives. Useful only in combination with SetFaceNum(). inline void ClearUnused() { mgl_clear_unused(gr); } /// Load background image inline void LoadBackground(const char *fname, double alpha=1) { mgl_load_background(gr,fname,alpha); } /// Force drawing the image and use it as background one inline void Rasterize() { mgl_rasterize(gr); } /// Draws the point (ball) at position {x,y,z} with color c inline void Ball(mglPoint p, char c='r') { char s[3]={'.',c,0}; mgl_mark(gr, p.x, p.y, p.z, s); } /// Draws the mark at position p inline void Mark(mglPoint p, const char *mark) { mgl_mark(gr, p.x, p.y, p.z, mark); } /// Draws the line between points by specified pen /** Large \a n (for example, n=100) should be used for geodesic line in curved coordinates */ inline void Line(mglPoint p1, mglPoint p2, const char *pen="B",int n=2) { mgl_line(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, pen, n); } /// Draws the spline curve between points by specified pen inline void Curve(mglPoint p1, mglPoint d1, mglPoint p2, mglPoint d2, const char *pen="B", int n=100) { mgl_curve(gr, p1.x, p1.y, p1.z, d1.x, d1.y, d1.z, p2.x, p2.y, p2.z, d2.x, d2.y, d2.z, pen, n); } /// Draws the 3d error box e for point p inline void Error(mglPoint p, mglPoint e, const char *pen="k") { mgl_error_box(gr, p.x, p.y, p.z, e.x, e.y, e.z, pen); } /// Draws Lamerey diagram for mapping x_new = f(x_old) /** String \a stl may contain: ‘v’ for drawing arrows; ‘~’ for disable 1st segment. * Option value set the number of segments (default is 20).*/ inline void Lamerey(double x0, const mglDataA &f, const char *stl="", const char *opt="") { mgl_lamerey_dat(gr,x0,&f,stl,opt); } inline void Lamerey(double x0, const char *func, const char *stl="", const char *opt="") { mgl_lamerey_str(gr,x0,func,stl,opt); } /// Draws Bifurcation diagram for mapping x_new = f(x_old) in x-axis range /** Option value set the number of stationary points (default is 1024).*/ inline void Bifurcation(double dx, const mglDataA &f, const char *stl="", const char *opt="") { mgl_bifurcation_dat(gr,dx,&f,stl,opt); } inline void Bifurcation(double dx, const char *func, const char *stl="", const char *opt="") { mgl_bifurcation_str(gr,dx,func,stl,opt); } /// Draws Iris plots for determining cross-dependences of data arrays /** NOTE: using the same ranges and empty ids will not draw axis. This will add data to existing Iris plot. * Option value set the size of data labels ids, separated by ';'.*/ inline void Iris(mglDataA &dats, const char *ids, const char *stl="", const char *opt="") { mgl_iris_1(gr,&dats,ids,stl,opt); } inline void Iris(mglDataA &dats, const wchar_t *ids, const char *stl="", const char *opt="") { mgl_irisw_1(gr,&dats,ids,stl,opt); } inline void Iris(mglDataA &dats, mglDataA &ranges, const char *ids, const char *stl="", const char *opt="") { mgl_iris(gr,&dats,&ranges,ids,stl,opt); } inline void Iris(mglDataA &dats, mglDataA &ranges, const wchar_t *ids, const char *stl="", const char *opt="") { mgl_irisw(gr,&dats,&ranges,ids,stl,opt); } /// Draws the face between points with color stl (include interpolation up to 4 colors). inline void Face(mglPoint p1, mglPoint p2, mglPoint p3, mglPoint p4, const char *stl="r") { mgl_face(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, p3.x, p3.y, p3.z, p4.x, p4.y, p4.z, stl); } /// Draws the face in y-z plane at point p with color stl (include interpolation up to 4 colors). inline void FaceX(mglPoint p, double wy, double wz, const char *stl="w", double dx=0, double dy=0) { mgl_facex(gr, p.x, p.y, p.z, wy, wz, stl, dx, dy); } /// Draws the face in x-z plane at point p with color stl (include interpolation up to 4 colors). inline void FaceY(mglPoint p, double wx, double wz, const char *stl="w", double dx=0, double dy=0) { mgl_facey(gr, p.x, p.y, p.z, wx, wz, stl, dx, dy); } /// Draws the face in x-y plane at point p with color stl (include interpolation up to 4 colors). inline void FaceZ(mglPoint p, double wx, double wy, const char *stl="w", double dx=0, double dy=0) { mgl_facez(gr, p.x, p.y, p.z, wx, wy, stl, dx, dy); } /// Draws the drop at point p in direction d with color col and radius r /** Parameter \a shift set the degree of drop oblongness: ‘0’ is sphere, ‘1’ is maximally oblongness drop. Parameter \a ap set relative width of the drop (this is analogue of “ellipticity” for the sphere).*/ inline void Drop(mglPoint p, mglPoint d, double r, const char *col="r", double shift=1, double ap=1) { mgl_drop(gr, p.x, p.y, p.z, d.x, d.y, d.z, r, col, shift, ap); } /// Draws the sphere at point p with color col and radius r inline void Sphere(mglPoint p, double r, const char *col="r") { mgl_sphere(gr, p.x, p.y, p.z, r, col); } /// Draws the cone between points p1,p2 with radius r1,r2 and with style stl /** Parameter \a stl can contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinder instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones.*/ inline void Cone(mglPoint p1, mglPoint p2, double r1, double r2=-1, const char *stl="r@") { mgl_cone(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z,r1,r2,stl); } /// Draws the ellipse between points p1,p2 with color stl and width r /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Ellipse(mglPoint p1, mglPoint p2, double r, const char *stl="r") { mgl_ellipse(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, r,stl); } /// Draws the circle at point p with color stl and radius r /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Circle(mglPoint p, double r, const char *stl="r") { mgl_ellipse(gr, p.x, p.y, p.z, p.x, p.y, p.z, r,stl); } /// Draws the rhomb between points p1,p2 with color stl and width r /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Rhomb(mglPoint p1, mglPoint p2, double r, const char *stl="r") { mgl_rhomb(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, r,stl); } /// Draws the polygon based on points p1,p2 with color stl /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Polygon(mglPoint p1, mglPoint p2, int n, const char *stl="r") { mgl_polygon(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, n,stl); } /// Draws the arc around axis pr with center at p0 and starting from p1, by color stl and angle a (in degrees) inline void Arc(mglPoint p0, mglPoint pa, mglPoint p1, double a, const char *stl="r") { mgl_arc_ext(gr, p0.x,p0.y,p0.z, pa.x,pa.y,pa.z, p1.x,p1.y,p1.z, a,stl); } /// Draws the arc around axis 'z' with center at p0 and starting from p1, by color stl and angle a (in degrees) inline void Arc(mglPoint p0, mglPoint p1, double a, const char *stl="r") { mgl_arc_ext(gr, p0.x,p0.y,p0.z, 0,0,1, p1.x,p1.y,p0.z, a,stl); } /// Draws bitmap (logo) which is stretched along whole axis range inline void Logo(long w, long h, const unsigned char *rgba, bool smooth=false, const char *opt="") { mgl_logo(gr, w, h, rgba, smooth, opt); } inline void Logo(const char *fname, bool smooth=false, const char *opt="") { mgl_logo_file(gr, fname, smooth, opt); } /// Draw user-defined symbol in position p inline void Symbol(mglPoint p, char id, const char *how="", double size=-1) { mgl_symbol(gr, p.x, p.y, p.z, id, how, size); } /// Draw user-defined symbol in position p along direction d inline void Symbol(mglPoint p, mglPoint d, char id, const char *how="", double size=-1) { mgl_symbol_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, id, how, size); } /// Print text in position p with specified font inline void Putsw(mglPoint p,const wchar_t *text,const char *font=":C",double size=-1) { mgl_putsw(gr, p.x, p.y, p.z, text, font, size); } /// Print text in position p with specified font inline void Puts(mglPoint p,const char *text,const char *font=":C",double size=-1) { mgl_puts(gr, p.x, p.y, p.z, text, font, size); } /// Print text in position p with specified font inline void Putsw(double x, double y,const wchar_t *text,const char *font=":AC",double size=-1) { mgl_putsw(gr, x, y, 0, text, font, size); } /// Print text in position p with specified font inline void Puts(double x, double y,const char *text,const char *font=":AC",double size=-1) { mgl_puts(gr, x, y, 0, text, font, size); } /// Print text in position p along direction d with specified font inline void Putsw(mglPoint p, mglPoint d, const wchar_t *text, const char *font=":L", double size=-1) { mgl_putsw_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, text, font, size); } /// Print text in position p along direction d with specified font inline void Puts(mglPoint p, mglPoint d, const char *text, const char *font=":L", double size=-1) { mgl_puts_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, text, font, size); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *text, const char *font="", const char *opt="") { mgl_text_xyz(gr, &x, &y, &z, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const char *text, const char *font="", const char *opt="") { mgl_text_xy(gr, &x, &y, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &y, const char *text, const char *font="", const char *opt="") { mgl_text_y(gr, &y, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const mglDataA &z, const wchar_t *text, const char *font="", const char *opt="") { mgl_textw_xyz(gr, &x, &y, &z, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const wchar_t *text, const char *font="", const char *opt="") { mgl_textw_xy(gr, &x, &y, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &y, const wchar_t *text, const char *font="", const char *opt="") { mgl_textw_y(gr, &y, text, font, opt); } /// Draws bounding box outside the plotting volume with color c. /** Style ‘@’ produce filled back faces. */ inline void Box(const char *col="", bool ticks=true) { mgl_box_str(gr, col, ticks); } /// Draw axises with ticks in direction(s) dir. /** Parameter \a dir may contain: * ‘xyzt’for drawing axis in corresponding direction; * ‘XYZT’ for drawing axis in corresponding direction but with inverted positions of labels; * ‘~’, ‘_’ for disabling tick labels; * ‘U’ for disabling rotation of tick labels; * ‘^’ for inverting default axis origin; * ‘!’ for disabling ticks tuning; * ‘AKDTVISO’ for drawing arrow at the end of axis; * ‘a’ for forced adjusting of axis ticks; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels. * Option "value" set the manual rotation angle for the ticks. */ inline void Axis(const char *dir="xyzt", const char *stl="", const char *opt="") { mgl_axis(gr, dir,stl,opt); } /// Draw grid lines perpendicular to direction(s) dir. inline void Grid(const char *dir="xyzt",const char *pen="B", const char *opt="") { mgl_axis_grid(gr, dir, pen, opt); } /// Print the label text for axis dir. /** Option "value" set additional shifting of the label. */ inline void Label(char dir, const char *text, double pos=+1, const char *opt="") { mgl_label(gr, dir, text, pos, opt); } /// Print the label text for axis dir. /** Option "value" set additional shifting of the label. */ inline void Label(char dir, const wchar_t *text, double pos=+1, const char *opt="") { mgl_labelw(gr, dir, text, pos, opt); } /// Draw colorbar at edge of axis /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const char *sch="") { mgl_colorbar(gr, sch); } /// Draw colorbar at manual position /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const char *sch,double x,double y,double w=1,double h=1) { mgl_colorbar_ext(gr, sch, x,y,w,h); } /// Draw colorbar with manual colors at edge of axis /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const mglDataA &val, const char *sch="") { mgl_colorbar_val(gr, &val, sch); } /// Draw colorbar with manual colors at manual position /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const mglDataA &val, const char *sch,double x,double y,double w=1,double h=1) { mgl_colorbar_val_ext(gr, &val, sch, x,y,w,h); } /// Add string to legend inline void AddLegend(const char *text,const char *style) { mgl_add_legend(gr, text, style); } inline void AddLegend(const wchar_t *text,const char *style) { mgl_add_legendw(gr, text, style); } /// Clear saved legend string inline void ClearLegend() { mgl_clear_legend(gr); } /// Draw legend of accumulated strings at position {x,y} /** Parameter fnt may contain: * font style for legend text; * colors for background (first one), border (second one) and text (last one); * ‘A’ for positioning in absolute coordinates; * ‘^’ for positioning outside of specified point; * ‘-’ for arranging entries horizontally; * ‘#’ for drawing box around legend. * Option value set the space between line samples and text (default is 0.1).*/ inline void Legend(double x, double y, const char *font="#", const char *opt="") { mgl_legend_pos(gr, x, y, font, opt); } /// Draw legend of accumulated strings /** Parameter fnt may contain: * font style for legend text; * colors for background (first one), border (second one) and text (last one); * ‘A’ for positioning in absolute coordinates; * ‘^’ for positioning outside of specified point; * ‘-’ for arranging entries horizontally; * ‘#’ for drawing box around legend. * Option value set the space between line samples and text (default is 0.1). * Parameter \a where sets position: 0 at bottom-left, 1 at bottom-right, 2 at top-left, 3 at top-right (default).*/ inline void Legend(int where=3, const char *font="#", const char *opt="") { mgl_legend(gr, where, font, opt); } /// Set number of marks in legend sample inline void SetLegendMarks(int num) { mgl_set_legend_marks(gr, num); } /// Draw usual curve {x,y,z} inline void Plot(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_plot_xyz(gr, &x, &y, &z, pen, opt); } /// Draw usual curve {x,y} inline void Plot(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_plot_xy(gr, &x, &y, pen,opt); } /// Draw usual curve {x,y} with x in x-axis range inline void Plot(const mglDataA &y, const char *pen="", const char *opt="") { mgl_plot(gr, &y, pen,opt); } /// Draw tapes which rotates as (bi-)normales of curve {x,y,z} /** The width of tape is proportional to barwidth and can be changed by option "value".*/ inline void Tape(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_tape_xyz(gr, &x, &y, &z, pen, opt); } /// Draw tapes which rotates as (bi-)normales of curve {x,y} /** The width of tape is proportional to barwidth and can be changed by option "value".*/ inline void Tape(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_tape_xy(gr, &x, &y, pen,opt); } /// Draw tapes which rotates as (bi-)normales of curve {x,y} with x in x-axis range /** The width of tape is proportional to barwidth and can be changed by option "value".*/ inline void Tape(const mglDataA &y, const char *pen="", const char *opt="") { mgl_tape(gr, &y, pen,opt); } /// Draw radar chart (plot in curved coordinates) /** Option "value" set the additional shift of data (i.e. the data a+value is used instead of a).*/ inline void Radar(const mglDataA &a, const char *pen="", const char *opt="") { mgl_radar(gr, &a, pen, opt); } /// Draw stairs for points in arrays {x,y,z} inline void Step(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_step_xyz(gr, &x, &y, &z, pen, opt); } /// Draw stairs for points in arrays {x,y} inline void Step(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_step_xy(gr, &x, &y, pen, opt); } /// Draw stairs for points in arrays {x,y} with x in x-axis range inline void Step(const mglDataA &y, const char *pen="", const char *opt="") { mgl_step(gr, &y, pen, opt); } /// Draw curve {x,y,z} which is colored by c (like tension plot) inline void Tens(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *pen="", const char *opt="") { mgl_tens_xyz(gr, &x, &y, &z, &c, pen, opt); } /// Draw curve {x,y} which is colored by c (like tension plot) inline void Tens(const mglDataA &x, const mglDataA &y, const mglDataA &c, const char *pen="", const char *opt="") { mgl_tens_xy(gr, &x, &y, &c, pen, opt); } /// Draw curve {x,y} with x in x-axis range which is colored by c (like tension plot) inline void Tens(const mglDataA &y, const mglDataA &c, const char *pen="", const char *opt="") { mgl_tens(gr, &y, &c, pen, opt); } /// Fill area between curve {x,y,z} and axis plane /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Area(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_area_xyz(gr, &x, &y, &z, pen, opt); } /// Fill area between curve {x,y} and axis plane /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Area(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_area_xy(gr, &x, &y, pen, opt); } /// Fill area between curve {x,y} with x in x-axis range and axis plane /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Area(const mglDataA &y, const char *pen="", const char *opt="") { mgl_area(gr, &y, pen, opt); } /// Fill area between curves {x,y1} and {x,y2} with x in x-axis range /** Style 'i' will fill area only if y1 < y2. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_region(gr, &y1, &y2, pen, opt); } /// Fill area between curves {x,y1} and {x,y2} /** Style 'i' will fill area only if y1 < y2. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &x, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_region_xy(gr, &x, &y1, &y2, pen, opt); } /// Fill area (draw ribbon) between curves {x1,y1,z1} and {x2,y2,z2} /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &x1, const mglDataA &y1, const mglDataA &z1, const mglDataA &x2, const mglDataA &y2, const mglDataA &z2, const char *pen="", const char *opt="") { mgl_region_3d(gr, &x1, &y1, &z1, &x2, &y2, &z2, pen, opt); } /// Fill area (draw ribbon) between curves {x1,y1} and {x2,y2} /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &x1, const mglDataA &y1, const mglDataA &x2, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_region_3d(gr, &x1, &y1, NULL, &x2, &y2, NULL, pen, opt); } /// Draw vertical lines from points {x,y,z} to axis plane inline void Stem(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_stem_xyz(gr, &x, &y, &z, pen, opt); } /// Draw vertical lines from points {x,y} to axis plane inline void Stem(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_stem_xy(gr, &x, &y, pen, opt); } /// Draw vertical lines from points {x,y} with x in x-axis range to axis plane inline void Stem(const mglDataA &y, const char *pen="", const char *opt="") { mgl_stem(gr, &y, pen, opt); } /// Draw vertical bars from points {x,y,z} to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Bars(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_bars_xyz(gr, &x, &y, &z, pen, opt); } /// Draw vertical bars from points {x,y} to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Bars(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_bars_xy(gr, &x, &y, pen, opt); } /// Draw vertical bars from points {x,y} with x in x-axis range to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Bars(const mglDataA &y, const char *pen="", const char *opt="") { mgl_bars(gr, &y, pen, opt); } /// Draw horizontal bars from points {x,y} to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Barh(const mglDataA &y, const mglDataA &v, const char *pen="", const char *opt="") { mgl_barh_yx(gr, &y, &v, pen, opt); } /// Draw horizontal bars from points {x,y} with y in y-axis range to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Barh(const mglDataA &v, const char *pen="", const char *opt="") { mgl_barh(gr, &v, pen, opt); } /// Draw chart for data a /** Space denote transparent color. Style '#' draw black borders. */ inline void Chart(const mglDataA &a, const char *colors="", const char *opt="") { mgl_chart(gr, &a, colors,opt); } /// Draw Open-High-Low-Close (OHLC) diagram /** Different colors for up and down values are used if number of specified colors is equal to 2*number of curves. */ inline void OHLC(const mglDataA &x, const mglDataA &open, const mglDataA &high, const mglDataA &low, const mglDataA &close, const char *pen="", const char *opt="") { mgl_ohlc_x(gr, &x, &open,&high,&low,&close,pen,opt); } /// Draw Open-High-Low-Close (OHLC) diagram with x in x-axis range /** Different colors for up and down values are used if number of specified colors is equal to 2*number of curves. */ inline void OHLC(const mglDataA &open, const mglDataA &high, const mglDataA &low, const mglDataA &close, const char *pen="", const char *opt="") { mgl_ohlc(gr, &open,&high,&low,&close,pen,opt); } /// Draw box-plot (special 5-value plot used in statistic) /** String \a pen may contain ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right.*/ inline void BoxPlot(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_boxplot_xy(gr, &x, &y, pen,opt); } /// Draw box-plot (special 5-value plot used in statistic) with x in x-axis range /** String \a pen may contain ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right.*/ inline void BoxPlot(const mglDataA &y, const char *pen="", const char *opt="") { mgl_boxplot(gr, &y, pen,opt); } /// Draw candle plot /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &x, const mglDataA &v1, const mglDataA &v2, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_candle_xyv(gr, &x, &v1, &v2, &y1, &y2, pen, opt); } /// Draw candle plot with x in x-axis range /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &v1, const mglDataA &v2, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_candle_yv(gr, &v1, &v2, &y1, &y2, pen, opt); } inline void Candle(const mglDataA &v1, const mglDataA &v2, const char *pen="", const char *opt="") { mgl_candle_yv(gr, &v1, &v2, NULL, NULL, pen, opt); } /// Draw candle plot with v1=v[i], v2=v[i+1] /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &y, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_candle(gr, &y, &y1, &y2, pen, opt); } /// Draw candle plot with v1=v[i], v2=v[i+1] /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &y, const char *pen="", const char *opt="") { mgl_candle(gr, &y, NULL, NULL, pen, opt); } /// Draw cones from points {x,y,z} to axis plane /** String \a pen may contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinders instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones; * ‘<’, ‘^’ or ‘>’ for aligning cones left, right or centering them at its x-coordinates. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Cones(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="@", const char *opt="") { mgl_cones_xyz(gr, &x, &y, &z, pen, opt); } /// Draw cones from points {x,z} to axis plane /** String \a pen may contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinders instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones; * ‘<’, ‘^’ or ‘>’ for aligning cones left, right or centering them at its x-coordinates. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Cones(const mglDataA &x, const mglDataA &z, const char *pen="@", const char *opt="") { mgl_cones_xz(gr, &x, &z, pen, opt); } /// Draw cones from points {x,z} with x in x-axis range to axis plane /** String \a pen may contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinders instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones; * ‘<’, ‘^’ or ‘>’ for aligning cones left, right or centering them at its x-coordinates. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Cones(const mglDataA &z, const char *pen="@", const char *opt="") { mgl_cones(gr, &z, pen, opt); } /// Draw error boxes {ey} at points {x,y} with x in x-axis range /** Style ‘@’ set to draw large semitransparent mark instead of error box.*/ inline void Error(const mglDataA &y, const mglDataA &ey, const char *pen="", const char *opt="") { mgl_error(gr, &y, &ey, pen, opt); } /// Draw error boxes {ey} at points {x,y} /** Style ‘@’ set to draw large semitransparent mark instead of error box.*/ inline void Error(const mglDataA &x, const mglDataA &y, const mglDataA &ey, const char *pen="", const char *opt="") { mgl_error_xy(gr, &x, &y, &ey, pen, opt); } /// Draw error boxes {ex,ey} at points {x,y} /** Style ‘@’ set to draw large semitransparent mark instead of error box.*/ inline void Error(const mglDataA &x, const mglDataA &y, const mglDataA &ex, const mglDataA &ey, const char *pen="", const char *opt="") { mgl_error_exy(gr, &x, &y, &ex, &ey, pen, opt); } /// Draw marks with size r at points {x,y,z} inline void Mark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *pen, const char *opt="") { mgl_mark_xyz(gr, &x, &y, &z, &r, pen, opt); } /// Draw marks with size r at points {x,y} inline void Mark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *pen, const char *opt="") { mgl_mark_xy(gr, &x, &y, &r, pen, opt); } /// Draw marks with size r at points {x,y} with x in x-axis range inline void Mark(const mglDataA &y, const mglDataA &r, const char *pen, const char *opt="") { mgl_mark_y(gr, &y, &r, pen, opt); } /// Draw Poincare map at condition s==0 for curve {x,y,z} inline void Pmap(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *pen, const char *opt="") { mgl_pmap_xyz(gr, &x, &y, &z, &s, pen, opt); } /// Draw Poincare map at condition s==0 for curve {x,y} inline void Pmap(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *pen, const char *opt="") { mgl_pmap_xy(gr, &x, &y, &s, pen, opt); } /// Draw Poincare map at condition s==0 for curve {x,y} with x in x-axis range inline void Pmap(const mglDataA &y, const mglDataA &s, const char *pen, const char *opt="") { mgl_pmap(gr, &y, &s, pen, opt); } /// Draw textual marks with size r at points {x,y,z} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *text, const char *fnt="", const char *opt="") { mgl_textmark_xyzr(gr, &x, &y, &z, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *text, const char *fnt="", const char *opt="") { mgl_textmark_xyr(gr, &x, &y, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const mglDataA &r, const char *text, const char *fnt="", const char *opt="") { mgl_textmark_yr(gr, &y, &r, text, fnt, opt); } /// Draw textual marks at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const char *text, const char *fnt="", const char *opt="") { mgl_textmark(gr, &y, text, fnt, opt); } /// Draw textual marks with size r at points {x,y,z} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw_xyzr(gr, &x, &y, &z, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw_xyr(gr, &x, &y, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw_yr(gr, &y, &r, text, fnt, opt); } /// Draw textual marks at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw(gr, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y,z} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *text, const char *fnt="", const char *opt="") { mgl_label_xyz(gr, &x, &y, &z, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const char *text, const char *fnt="", const char *opt="") { mgl_label_xy(gr, &x, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} with x in x-axis range /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &y, const char *text, const char *fnt="", const char *opt="") { mgl_label_y(gr, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y,z} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const mglDataA &z, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_labelw_xyz(gr, &x, &y, &z, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_labelw_xy(gr, &x, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} with x in x-axis range /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_labelw_y(gr, &y, text, fnt, opt); } /// Draw table for values val along given direction with row labels text /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(const mglDataA &val, const char *text, const char *fnt="#|", const char *opt="") { mgl_table(gr, 0, 0, &val, text, fnt, opt); } /// Draw table for values val along given direction with row labels text /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(const mglDataA &val, const wchar_t *text, const char *fnt="#|", const char *opt="") { mgl_tablew(gr, 0, 0, &val, text, fnt, opt); } /// Draw table for values val along given direction with row labels text at given position /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(double x, double y, const mglDataA &val, const char *text, const char *fnt="#|", const char *opt="") { mgl_table(gr, x, y, &val, text, fnt, opt); } /// Draw table for values val along given direction with row labels text at given position /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(double x, double y, const mglDataA &val, const wchar_t *text, const char *fnt="#|", const char *opt="") { mgl_tablew(gr, x, y, &val, text, fnt, opt); } /// Draw tube with radius r around curve {x,y,z} inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *pen="", const char *opt="") { mgl_tube_xyzr(gr, &x, &y, &z, &r, pen, opt); } /// Draw tube with radius r around curve {x,y,z} inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &z, double r, const char *pen="", const char *opt="") { mgl_tube_xyz(gr, &x, &y, &z, r, pen, opt); } /// Draw tube with radius r around curve {x,y} inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *pen="", const char *opt="") { mgl_tube_xyr(gr, &x, &y, &r, pen, opt); } /// Draw tube with radius r around curve {x,y} inline void Tube(const mglDataA &x, const mglDataA &y, double r, const char *pen="", const char *opt="") { mgl_tube_xy(gr, &x, &y, r, pen, opt); } /// Draw tube with radius r around curve {x,y} with x in x-axis range inline void Tube(const mglDataA &y, const mglDataA &r, const char *pen="", const char *opt="") { mgl_tube_r(gr, &y, &r, pen, opt); } /// Draw tube with radius r around curve {x,y} with x in x-axis range inline void Tube(const mglDataA &y, double r, const char *pen="", const char *opt="") { mgl_tube(gr, &y, r, pen, opt); } /// Draw surface of curve {r,z} rotation around axis /** Style ‘#’ produce wire plot. Style ‘.’ produce plot by dots.*/ inline void Torus(const mglDataA &r, const mglDataA &z, const char *pen="", const char *opt="") { mgl_torus(gr, &r, &z, pen,opt); } /// Draw mesh lines for 2d data specified parametrically inline void Mesh(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_mesh_xy(gr, &x, &y, &z, stl, opt); } /// Draw mesh lines for 2d data inline void Mesh(const mglDataA &z, const char *stl="", const char *opt="") { mgl_mesh(gr, &z, stl, opt); } /// Draw waterfall plot for 2d data specified parametrically /** Style 'x' draw lines in x-direction. */ inline void Fall(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_fall_xy(gr, &x, &y, &z, stl, opt); } /// Draw waterfall plot for 2d data /** Style 'x' draw lines in x-direction. */ inline void Fall(const mglDataA &z, const char *stl="", const char *opt="") { mgl_fall(gr, &z, stl, opt); } /// Draw belts for 2d data specified parametrically /** Style 'x' draw belts in x-direction. */ inline void Belt(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_belt_xy(gr, &x, &y, &z, stl, opt); } /// Draw belts for 2d data /** Style 'x' draw belts in x-direction. */ inline void Belt(const mglDataA &z, const char *stl="", const char *opt="") { mgl_belt(gr, &z, stl, opt); } /// Draw belts for 2d data specified parametrically with color proportional to c /** Style 'x' draw belts in x-direction. */ inline void BeltC(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *stl="", const char *opt="") { mgl_beltc_xy(gr, &x, &y, &z, &c, stl, opt); } /// Draw belts for 2d data with color proportional to c /** Style 'x' draw belts in x-direction. */ inline void BeltC(const mglDataA &z, const mglDataA &c, const char *stl="", const char *opt="") { mgl_beltc(gr, &z, &c, stl, opt); } /// Draw surface for 2d data specified parametrically with color proportional to z /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Surf(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_surf_xy(gr, &x, &y, &z, stl, opt); } /// Draw surface for 2d data with color proportional to z /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Surf(const mglDataA &z, const char *stl="", const char *opt="") { mgl_surf(gr, &z, stl, opt); } /// Draw grid lines for density plot of 2d data specified parametrically inline void Grid(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_grid_xy(gr, &x, &y, &z, stl, opt); } /// Draw grid lines for density plot of 2d data inline void Grid(const mglDataA &z, const char *stl="", const char *opt="") { mgl_grid(gr, &z, stl, opt); } /// Draw vertical tiles with manual colors c for 2d data specified parametrically inline void Tile(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *stl="", const char *opt="") { mgl_tile_xyc(gr, &x, &y, &z, &c, stl, opt); } /// Draw vertical tiles for 2d data specified parametrically inline void Tile(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_tile_xy(gr, &x, &y, &z, stl, opt); } /// Draw vertical tiles for 2d data inline void Tile(const mglDataA &z, const char *stl="", const char *opt="") { mgl_tile(gr, &z, stl, opt); } /// Draw density plot for 2d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Dens(const mglDataA &x, const mglDataA &y, const mglDataA &c, const char *stl="", const char *opt="") { mgl_dens_xy(gr, &x, &y, &c, stl, opt); } /// Draw density plot for 2d data /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Dens(const mglDataA &c, const char *stl="", const char *opt="") { mgl_dens(gr, &c, stl, opt); } /// Draw vertical boxes for 2d data specified parametrically /** Style ‘#’ draw filled boxes. */ inline void Boxs(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_boxs_xy(gr, &x, &y, &z, stl, opt); } /// Draw vertical boxes for 2d data /** Style ‘#’ draw filled boxes. */ inline void Boxs(const mglDataA &z, const char *stl="", const char *opt="") { mgl_boxs(gr, &z, stl, opt); } /// Draw contour lines on parametric surface at manual levels for 2d data specified parametrically /** Style ‘f’ to draw solid contours. * Style 't'/'T' draw contour labels below/above contours.*/ inline void ContP(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_contp_val(gr, &v, &x, &y, &z, &a, sch, opt); } /// Draw contour lines on parametric surface at manual levels for 2d data specified parametrically /** Style ‘f’ to draw solid contours. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContP(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_contp(gr, &x, &y, &z, &a, sch, opt); } /// Draw contour lines at manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Style 't'/'T' draw contour labels below/above contours.*/ inline void Cont(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw contour lines for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Style 't'/'T' draw contour labels below/above contours.*/ inline void Cont(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont_val(gr, &v, &z, sch, opt); } /// Draw contour lines at manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont_xy(gr, &x, &y, &z, sch, opt); } /// Draw contour lines for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont(const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont(gr, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContF(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContF(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf_val(gr, &v, &z, sch, opt); } /// Draw solid contours for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContF(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf_xy(gr, &x, &y, &z, sch, opt); } /// Draw solid contours for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContF(const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf(gr, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data specified parametrically with specified colors /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContD(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data with specified colors /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContD(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd_val(gr, &v, &z, sch, opt); } /// Draw solid contours for 2d data specified parametrically with specified colors /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContD(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd_xy(gr, &x, &y, &z, sch, opt); } /// Draw solid contours for 2d data with specified colors /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContD(const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd(gr, &z, sch, opt); } /// Draw contour tubes between manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContV(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw contour tubes between manual levels for 2d data /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContV(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv_val(gr, &v, &z, sch, opt); } /// Draw contour tubes for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContV(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv_xy(gr, &x, &y, &z, sch, opt); } /// Draw contour tubes for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContV(const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv(gr, &z, sch, opt); } /// Draw axial-symmetric isosurfaces at manual levels for 2d data specified parametrically /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). */ inline void Axial(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial_xy_val(gr, &v, &x, &y, &z, sch,opt); } /// Draw axial-symmetric isosurfaces at manual levels for 2d data /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). */ inline void Axial(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial_val(gr, &v, &z, sch, opt); } /// Draw axial-symmetric isosurfaces for 2d data specified parametrically /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). * Option "value" set the number of isosurfaces (default is 3). */ inline void Axial(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial_xy(gr, &x, &y, &z, sch, opt); } /// Draw axial-symmetric isosurfaces for 2d data /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). * Option "value" set the number of isosurfaces (default is 3). */ inline void Axial(const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial(gr, &z, sch, opt); } /// Draw grid lines for density plot at slice for 3d data specified parametrically /** Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Grid3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_grid3_xyz(gr, &x, &y, &z, &a, stl, sVal, opt); } /// Draw grid lines for density plot at slice for 3d data /** Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Grid3(const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_grid3(gr, &a, stl, sVal, opt); } /// Draw density plot at slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Dens3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_dens3_xyz(gr, &x, &y, &z, &a, stl, sVal, opt); } /// Draw density plot at slice for 3d data /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Dens3(const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_dens3(gr, &a, stl, sVal, opt); } /// Draw isosurface for 3d data specified parametrically /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots.*/ inline void Surf3(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3_xyz_val(gr, Val, &x, &y, &z, &a, stl, opt); } /// Draw isosurface for 3d data /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots.*/ inline void Surf3(double Val, const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3_val(gr, Val, &a, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3_xyz(gr, &x, &y, &z, &a, stl, opt); } /// Draw isosurfaces for 3d data /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3(const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3(gr, &a, stl, opt); } /// Draw a semi-transparent cloud for 3d data specified parametrically /** Style ‘.’ produce plot by dots. Style ‘i’ use inverted values for transparency. */ inline void Cloud(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="") { mgl_cloud_xyz(gr, &x, &y, &z, &a, stl, opt); } /// Draw a semi-transparent cloud for 3d data /** Style ‘.’ produce plot by dots. Style ‘i’ use inverted values for transparency. */ inline void Cloud(const mglDataA &a, const char *stl="", const char *opt="") { mgl_cloud(gr, &a, stl, opt); } /// Draw contour lines at manual levels along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void Cont3(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3_xyz_val(gr, &v, &x, &y, &z, &a, sch, sVal, opt); } /// Draw contour lines at manual levels along slice for 3d data /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void Cont3(const mglDataA &v, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3_val(gr, &v, &a, sch, sVal, opt); } /// Draw contour lines along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3_xyz(gr, &x, &y, &z, &a, sch, sVal, opt); } /// Draw contour lines along slice for 3d data /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont3(const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3(gr, &a, sch, sVal, opt); } /// Draw solid contours at manual levels along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. */ inline void ContF3(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3_xyz_val(gr, &v, &x, &y, &z, &a, sch, sVal, opt); } /// Draw solid contours at manual levels along slice for 3d data /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. */ inline void ContF3(const mglDataA &v, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3_val(gr, &v, &a, sch, sVal, opt); } /// Draw solid contours along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Option "value" set the number of contour levels (default is 7).*/ inline void ContF3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3_xyz(gr, &x, &y, &z, &a, sch, sVal, opt); } /// Draw solid contours along slice for 3d data /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Option "value" set the number of contour levels (default is 7).*/ inline void ContF3(const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3(gr, &a, sch, sVal, opt); } /// Draw several isosurfaces for 3d beam in curvilinear coordinates /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots. * Variable \a flag is bitwise: * ‘0x1’ - draw in accompanied (not laboratory) coordinates; * ‘0x2’ - draw projection to \rho-z plane; * ‘0x4’ - draw normalized in each slice field.*/ inline void Beam(const mglDataA &tr, const mglDataA &g1, const mglDataA &g2, const mglDataA &a, double r, const char *stl=0, int flag=0, int num=3) { mgl_beam(gr, &tr,&g1,&g2,&a,r,stl,flag,num); } /// Draw isosurface at value \a val for 3d beam in curvilinear coordinates /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots. * Variable \a flag is bitwise: * ‘0x1’ - draw in accompanied (not laboratory) coordinates; * ‘0x2’ - draw projection to \rho-z plane; * ‘0x4’ - draw normalized in each slice field.*/ inline void Beam(double val, const mglDataA &tr, const mglDataA &g1, const mglDataA &g2, const mglDataA &a, double r, const char *stl=NULL, int flag=0) { mgl_beam_val(gr,val,&tr,&g1,&g2,&a,r,stl,flag); } /// Draw vertical tiles with variable size r and manual colors c for 2d data specified parametrically inline void TileS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const mglDataA &c, const char *stl="", const char *opt="") { mgl_tiles_xyc(gr, &x, &y, &z, &r, &c, stl, opt); } /// Draw vertical tiles with variable size r for 2d data specified parametrically inline void TileS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *stl="", const char *opt="") { mgl_tiles_xy(gr, &x, &y, &z, &r, stl, opt); } /// Draw vertical tiles with variable size r for 2d data inline void TileS(const mglDataA &z, const mglDataA &r, const char *stl="", const char *opt="") { mgl_tiles(gr, &z, &r, stl, opt); } /// Draw surface for 2d data specified parametrically with color proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfC(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfc_xy(gr, &x, &y, &z, &c, sch,opt); } /// Draw surface for 2d data with color proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfC(const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfc(gr, &z, &c, sch,opt); } /// Draw surface for 2d data specified parametrically with alpha proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfA(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfa_xy(gr, &x, &y, &z, &c, sch,opt); } /// Draw surface for 2d data with alpha proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfA(const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfa(gr, &z, &c, sch,opt); } /// Draw surface for 2d data specified parametrically with color proportional to c and alpha proportional to a /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfCA(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const mglDataA &a, const char *sch="", const char *opt="") { mgl_surfca_xy(gr, &x, &y, &z, &c, &a, sch,opt); } /// Draw surface for 2d data with color proportional to c and alpha proportional to a /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfCA(const mglDataA &z, const mglDataA &c, const mglDataA &a, const char *sch="", const char *opt="") { mgl_surfca(gr, &z, &c, &a, sch,opt); } /// Color map of matrix a to matrix b, both matrix can parametrically depend on coordinates /** Style ‘.’ produce plot by dots. */ inline void Map(const mglDataA &x, const mglDataA &y, const mglDataA &a, const mglDataA &b, const char *sch="", const char *opt="") { mgl_map_xy(gr, &x, &y, &a, &b, sch, opt); } /// Color map of matrix a to matrix b /** Style ‘.’ produce plot by dots. */ inline void Map(const mglDataA &a, const mglDataA &b, const char *sch="", const char *opt="") { mgl_map(gr, &a, &b, sch, opt); } /// Draw density plot for spectra-gramm specified parametrically /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void STFA(const mglDataA &x, const mglDataA &y, const mglDataA &re, const mglDataA &im, int dn, const char *sch="", const char *opt="") { mgl_stfa_xy(gr, &x, &y, &re, &im, dn, sch, opt); } /// Draw density plot for spectra-gramm /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void STFA(const mglDataA &re, const mglDataA &im, int dn, const char *sch="", const char *opt="") { mgl_stfa(gr, &re, &im, dn, sch, opt); } /// Draw isosurface for 3d data specified parametrically with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3A(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a_xyz_val(gr, Val, &x, &y, &z, &a, &b, stl, opt); } /// Draw isosurface for 3d data with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3A(double Val, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a_val(gr, Val, &a, &b, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3A(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a_xyz(gr, &x, &y, &z, &a, &b, stl, opt); } /// Draw isosurfaces for 3d data with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3A(const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a(gr, &a, &b, stl, opt); } /// Draw isosurface for 3d data specified parametrically with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3C(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c_xyz_val(gr, Val, &x, &y, &z, &a, &c, stl,opt); } /// Draw isosurface for 3d data with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3C(double Val, const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c_val(gr, Val, &a, &c, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3C(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c_xyz(gr, &x, &y, &z, &a, &c, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3C(const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c(gr, &a, &c, stl, opt); } /// Draw isosurface for 3d data specified parametrically with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3CA(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca_xyz_val(gr, Val, &x, &y, &z, &a, &c, &b, stl,opt); } /// Draw isosurface for 3d data with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3CA(double Val, const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca_val(gr, Val, &a, &c, &b, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3CA(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca_xyz(gr, &x, &y, &z, &a, &c, &b, stl, opt); } /// Draw isosurfaces for 3d data with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3CA(const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca(gr, &a, &c, &b, stl, opt); } /// Plot dew drops for vector field {ax,ay} parametrically depended on coordinate {x,y} inline void Dew(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_dew_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot dew drops for vector field {ax,ay} inline void Dew(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_dew_2d(gr, &ax, &ay, sch, opt); } /// Plot vectors at position {x,y} along {ax,ay} with length/color proportional to |a| /** Option value set the vector length factor (if non-zero) or vector length to be proportional the distance between curve points (if value=0). */ inline void Traj(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_traj_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot vectors at position {x,y,z} along {ax,ay,az} with length/color proportional to |a| /** Option value set the vector length factor (if non-zero) or vector length to be proportional the distance between curve points (if value=0). */ inline void Traj(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_traj_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot vector field {ax,ay} parametrically depended on coordinate {x,y} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_vect_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot vector field {ax,ay} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_vect_2d(gr, &ax, &ay, sch, opt); } /// Plot vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_vect_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot vector field {ax,ay,az} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_vect_3d(gr, &ax, &ay, &az, sch, opt); } /// Draw vector plot along slice for 3d data specified parametrically /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows, * ‘ x’, ‘z’ for producing plot perpendicular to x- or z-direction correspondingly. */ inline void Vect3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *stl="", double sVal=-1, const char *opt="") { mgl_vect3_xyz(gr, &x, &y, &z, &ax,&ay,&az, stl, sVal, opt); } /// Draw vector plot along slice for 3d data /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows, * ‘ x’, ‘z’ for producing plot perpendicular to x- or z-direction correspondingly. */ inline void Vect3(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *stl="", double sVal=-1, const char *opt="") { mgl_vect3(gr, &ax,&ay,&az, stl, sVal, opt); } /// Plot flows for vector field {ax,ay} parametrically depended on coordinate {x,y} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flow_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot flows for vector field {ax,ay} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flow_2d(gr, &ax, &ay, sch, opt); } /// Plot flows for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flow_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot flows for vector field {ax,ay,az} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flow_3d(gr, &ax, &ay, &az, sch, opt); } /// Plot flow from point p for vector field {ax,ay} parametrically depended on coordinate {x,y} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads. */ inline void FlowP(mglPoint p, const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flowp_xy(gr, p.x, p.y, p.z, &x, &y, &ax, &ay, sch, opt); } /// Plot flow from point p for vector field {ax,ay} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads. */ inline void FlowP(mglPoint p, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flowp_2d(gr, p.x, p.y, p.z, &ax, &ay, sch, opt); } /// Plot flow from point p for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. */ inline void FlowP(mglPoint p, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flowp_xyz(gr, p.x, p.y, p.z, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot flow from point p for vector field {ax,ay,az} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. */ inline void FlowP(mglPoint p, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flowp_3d(gr, p.x, p.y, p.z, &ax, &ay, &az, sch, opt); } /// Plot flows from given plain for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * 'v' for drawing arrows on the threads; * 't' for drawing tapes of normals in x-y and y-z planes. * Option "value" sets the number of threads (default is 5). */ inline void Flow3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double sVal=-1, const char *opt="") { mgl_flow3_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, sVal, opt); } /// Plot flows from given plain for vector field {ax,ay,az} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * 'v' for drawing arrows on the threads; * 't' for drawing tapes of normals in x-y and y-z planes. * Option "value" sets the number of threads (default is 5). */ inline void Flow3(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double sVal=-1, const char *opt="") { mgl_flow3(gr, &ax, &ay, &az, sch, sVal, opt); } /// Plot flows for gradient of scalar field phi parametrically depended on coordinate {x,y,z} /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Grad(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &phi, const char *sch="", const char *opt="") { mgl_grad_xyz(gr,&x,&y,&z,&phi,sch,opt); } /// Plot flows for gradient of scalar field phi parametrically depended on coordinate {x,y} /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Grad(const mglDataA &x, const mglDataA &y, const mglDataA &phi, const char *sch="", const char *opt="") { mgl_grad_xy(gr,&x,&y,&phi,sch,opt); } /// Plot flows for gradient of scalar field phi /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Grad(const mglDataA &phi, const char *sch="", const char *opt="") { mgl_grad(gr,&phi,sch,opt); } /// Plot flow pipes for vector field {ax,ay} parametrically depended on coordinate {x,y} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_xy(gr, &x, &y, &ax, &ay, sch, r0, opt); } /// Plot flow pipes for vector field {ax,ay} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &ax, const mglDataA &ay, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_2d(gr, &ax, &ay, sch, r0, opt); } /// Plot flow pipes for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, r0, opt); } /// Plot flow pipes for vector field {ax,ay,az} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_3d(gr, &ax, &ay, &az, sch, r0, opt); } /// Draw density plot for data at x = sVal /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void DensX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_dens_x(gr, &a, stl, sVal, opt); } /// Draw density plot for data at y = sVal /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void DensY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_dens_y(gr, &a, stl, sVal, opt); } /// Draw density plot for data at z = sVal /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void DensZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_dens_z(gr, &a, stl, sVal, opt); } /// Draw contour lines for data at x = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_x(gr, &a, stl, sVal, opt); } /// Draw contour lines at manual levels for data at x = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void ContX(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_x_val(gr, &v, &a, stl, sVal, opt); } /// Draw contour lines for data at y = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_y(gr, &a, stl, sVal, opt); } /// Draw contour lines at manual levels for data at y = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void ContY(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_y_val(gr, &v, &a, stl, sVal, opt); } /// Draw contour lines for data at z = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_z(gr, &a, stl, sVal, opt); } /// Draw contour lines at manual levels for data at z = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void ContZ(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_z_val(gr, &v, &a, stl, sVal, opt); } /// Draw solid contours for data at x = sVal /** Option "value" set the number of contour levels (default is 7). */ inline void ContFX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_x(gr, &a, stl, sVal, opt); } /// Draw solid contours at manual levels for data at x = sVal inline void ContFX(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_x_val(gr, &v, &a, stl, sVal, opt); } /// Draw solid contours for data at y = sVal /** Option "value" set the number of contour levels (default is 7). */ inline void ContFY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_y(gr, &a, stl, sVal, opt); } /// Draw solid contours at manual levels for data at y = sVal inline void ContFY(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_y_val(gr, &v, &a, stl, sVal, opt); } /// Draw solid contours for data at z = sVal /** Option "value" set the number of contour levels (default is 7). */ inline void ContFZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_z(gr, &a, stl, sVal, opt); } /// Draw solid contours at manual levels for data at z = sVal inline void ContFZ(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_z_val(gr, &v, &a, stl, sVal, opt); } /// Draw curve for formula with x in x-axis range /** Option "value" set initial number of points. */ inline void FPlot(const char *fy, const char *stl="", const char *opt="") { mgl_fplot(gr, fy, stl, opt); } /// Draw curve for formulas parametrically depended on t in range [0,1] /** Option "value" set initial number of points. */ inline void FPlot(const char *fx, const char *fy, const char *fz, const char *stl, const char *opt="") { mgl_fplot_xyz(gr, fx, fy, fz, stl, opt); } /// Draw surface by formula with x,y in axis range /** Option "value" set initial number of points. */ inline void FSurf(const char *fz, const char *stl="", const char *opt="") { mgl_fsurf(gr, fz, stl, opt); } /// Draw surface by formulas parametrically depended on u,v in range [0,1] /** Option "value" set initial number of points. */ inline void FSurf(const char *fx, const char *fy, const char *fz, const char *stl, const char *opt="") { mgl_fsurf_xyz(gr, fx, fy, fz, stl, opt); } /// Draw triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘#’ produce wire plot. If id.ny=c.nx then c set the triangle colors, else vertex colors. */ inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_triplot_xyzc(gr, &nums, &x, &y, &z, &c, sch, opt); } /// Draw triangle mesh for points in arrays {x,y,z} /** Style ‘#’ produce wire plot. */ inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_triplot_xyz(gr, &nums, &x, &y, &z, sch, opt); } /// Draw triangle mesh for points in arrays {x,y} /** Style ‘#’ produce wire plot. */ inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const char *sch="", const char *opt="") { mgl_triplot_xy(gr, &nums, &x, &y, sch, opt); } /// Draw quad mesh for points in arrays {x,y,z} with specified color c /** Style ‘#’ produce wire plot. If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_quadplot_xyzc(gr, &nums, &x, &y, &z, &c, sch, opt); } /// Draw quad mesh for points in arrays {x,y,z} /** Style ‘#’ produce wire plot. */ inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_quadplot_xyz(gr, &nums, &x, &y, &z, sch, opt); } /// Draw quad mesh for points in arrays {x,y} /** Style ‘#’ produce wire plot. */ inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const char *sch="", const char *opt="") { mgl_quadplot_xy(gr, &nums, &x, &y, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriCont(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_tricont_xyc(gr, &nums, &x, &y, &z, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. * Option "value" set the number of contour levels (default is 7). */ inline void TriContV(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_tricont_xycv(gr, &v, &nums, &x, &y, &z, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriCont(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricont_xyzc(gr, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriContV(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricont_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriCont(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricont_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour tubes for triangle mesh for points in arrays {x,y,z} /** Option "value" set the number of contour levels (default is 7). */ inline void TriContVt(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_tricontv_xyc(gr, &nums, &x, &y, &z, sch, opt); } /// Draw contour tubes for triangle mesh for points in arrays {x,y,z} with specified color c /** Option "value" set the number of contour levels (default is 7). */ inline void TriContVt(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricontv_xyzc(gr, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour tubes for triangle mesh for points in arrays {x,y,z} with specified color c /** If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriContVt(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricontv_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); } /// Draw dots in points {x,y,z}. inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_dots(gr, &x, &y, &z, sch, opt); } /// Draw semitransparent dots in points {x,y,z} with specified alpha a. inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_dots_a(gr, &x, &y, &z, &a, sch, opt); } /// Draw semitransparent dots in points {x,y,z} with specified color c and alpha a. inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const mglDataA &a, const char *sch="", const char *opt="") { mgl_dots_ca(gr, &x, &y, &z, &c, &a, sch, opt); } /// Draw surface reconstructed for points in arrays {x,y,z}. /** Style ‘#’ produce wired plot. */ inline void Crust(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_crust(gr, &x, &y, &z, sch, opt); } /// Fit data along x-direction for each data row. Return array with values for found formula. inline mglData Fit(const mglDataA &y, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_1(gr, &y, eq,vars,0, opt)); } /// Fit data along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &y, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_1(gr, &y, eq, vars, &ini, opt)); } /// Fit data along x-, y-directions for each data slice. Return array with values for found formula. inline mglData Fit2(const mglDataA &z, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_2(gr, &z, eq, vars,0, opt)); } /// Fit data along x-, y-direction for each data slice starting from \a ini values. Return array with values for found formula. inline mglData Fit2(const mglDataA &z, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_2(gr, &z, eq, vars, &ini, opt)); } /// Fit data along along all directions. Return array with values for found formula. inline mglData Fit3(const mglDataA &a, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_3(gr, &a, eq, vars,0, opt)); } /// Fit data along all directions starting from \a ini values. Return array with values for found formula. inline mglData Fit3(const mglDataA &a, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_3(gr, &a, eq, vars, &ini, opt)); } /// Fit data along x-direction for each data row. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xy(gr, &x, &y, eq, vars,0, opt)); } /// Fit data along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xy(gr, &x, &y, eq, vars, &ini, opt)); } /// Fit data along x-, y-directions for each data slice. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyz(gr, &x, &y, &z, eq, vars,0, opt)); } /// Fit data along x-, y-directions for each data slice starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyz(gr, &x, &y, &z, eq, vars, &ini, opt)); } /// Fit data along along all directions. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyza(gr, &x, &y, &z, &a, eq, vars,0, opt)); } /// Fit data along along all directions starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyza(gr, &x, &y, &z, &a, eq,vars, &ini, opt)); } /// Fit data with dispersion s along x-direction for each data row. Return array with values for found formula. inline mglData FitS(const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_ys(gr, &y, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_ys(gr, &y, &s, eq, vars, &ini, opt)); } /// Fit data with dispersion s along x-direction for each data row. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xys(gr, &x, &y, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xys(gr, &x, &y, &s, eq, vars, &ini, opt)); } /// Fit data with dispersion s along x-, y-directions for each data slice. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyzs(gr, &x, &y, &z, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along x-, y-directions for each data slice starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyzs(gr, &x, &y, &z, &s, eq, vars, &ini, opt)); } /// Fit data with dispersion s along all directions. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyzas(gr, &x, &y, &z, &a, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along all directions starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyzas(gr, &x, &y, &z, &a, &s, eq, vars, &ini, opt)); } /// Print fitted last formula (with coefficients) inline void PutsFit(mglPoint p, const char *prefix=0, const char *font="", double size=-1) { mgl_puts_fit(gr, p.x, p.y, p.z, prefix, font, size); } /// Get last fitted formula inline const char *GetFit() const { return mgl_get_fit(gr); } /// Get chi for last fitted formula static inline mreal GetFitChi() { return mgl_get_fit_chi(); } /// Get covariance matrix for last fitted formula static inline mglData GetFitCovar() { return mglData(mgl_get_fit_covar()); } /// Solve PDE with x,y,z in range axis range inline mglData PDE(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglData(true,mgl_pde_solve(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Solve PDE with x,y,z in range axis range inline mglDataC PDEc(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglDataC(true,mgl_pde_solve_c(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Solve PDE with x,y,z in range axis range using advanced (slow!!!) method (2d only) inline mglData APDE(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglData(true,mgl_pde_adv(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Solve PDE with x,y,z in range axis range using advanced (slow!!!) method (2d only) inline mglDataC APDEc(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglDataC(true,mgl_pde_adv_c(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Fill data by formula with x,y,z in range axis range inline void Fill(mglData &u, const char *eq, const char *opt="") { mgl_data_fill_eq(gr, &u, eq, 0, 0, opt); } inline void Fill(mglData &u, const char *eq, const mglDataA &v, const char *opt="") { mgl_data_fill_eq(gr, &u, eq, &v, 0, opt); } inline void Fill(mglData &u, const char *eq, const mglDataA &v, const mglDataA &w, const char *opt="") { mgl_data_fill_eq(gr, &u, eq, &v, &w, opt); } /// Fill data by formula with x,y,z in range axis range inline void Fill(mglDataC &u, const char *eq, const char *opt="") { mgl_datac_fill_eq(gr, &u, eq, 0, 0, opt); } inline void Fill(mglDataC &u, const char *eq, const mglDataA &v, const char *opt="") { mgl_datac_fill_eq(gr, &u, eq, &v, 0, opt); } inline void Fill(mglDataC &u, const char *eq, const mglDataA &v, const mglDataA &w, const char *opt="") { mgl_datac_fill_eq(gr, &u, eq, &v, &w, opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat for x in axis range inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_data_refill_gr(gr,&dat,&xdat,0,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in axis range inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_data_refill_gr(gr,&dat,&xdat,&ydat,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &zdat, const mglDataA &vdat, const char *opt="") { mgl_data_refill_gr(gr,&dat,&xdat,&ydat,&zdat,&vdat,-1,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat for x in axis range inline void Refill(mglDataC &dat, const mglDataA &xdat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_datac_refill_gr(gr,&dat,&xdat,0,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in axis range inline void Refill(mglDataC &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_datac_refill_gr(gr,&dat,&xdat,&ydat,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range inline void Refill(mglDataC &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &zdat, const mglDataA &vdat, const char *opt="") { mgl_datac_refill_gr(gr,&dat,&xdat,&ydat,&zdat,&vdat,-1,opt); } /// Set the data by triangulated surface values assuming x,y,z in range axis range inline void DataGrid(mglData &d, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *opt="") { mgl_data_grid(gr,&d,&x,&y,&z,opt); } /// Make histogram (distribution) of data. This function do not plot data. /** Option "value" sets the size of output array (default is mglFitPnts=100). */ inline mglData Hist(const mglDataA &x, const mglDataA &a, const char *opt="") { return mglData(true, mgl_hist_x(gr, &x, &a, opt)); } /// Make histogram (distribution) of data. This function do not plot data. /** Option "value" sets the size of output array (default is mglFitPnts=100). */ inline mglData Hist(const mglDataA &x, const mglDataA &y, const mglDataA &a, const char *opt="") { return mglData(true, mgl_hist_xy(gr, &x, &y, &a, opt)); } /// Make histogram (distribution) of data. This function do not plot data. /** Option "value" sets the size of output array (default is mglFitPnts=100). */ inline mglData Hist(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *opt="") { return mglData(true, mgl_hist_xyz(gr, &x, &y, &z, &a, opt)); } inline void Compression(bool){} // NOTE: Add later -- IDTF /// Set the preference for vertex color on/off (for formats that support it, now only PRC does). inline void VertexColor(bool enable) { mgl_set_flag(gr,enable, MGL_PREFERVC); } /// Render only front side of surfaces for dubugging purposes (for formats that support it, now only PRC does). inline void DoubleSided(bool enable) { mgl_set_flag(gr,!enable, MGL_ONESIDED); } // inline void TextureColor(bool){} // NOTE: Add later -- IDTF }; //----------------------------------------------------------------------------- /// Wrapper class for MGL parsing class MGL_EXPORT mglParse { HMPR pr; mglParse &operator=(mglParse &p) { pr = p.pr; mgl_use_parser(pr,1); return p; } public: mglParse(HMPR p) { pr = p; mgl_use_parser(pr,1); } mglParse(mglParse &p) { pr = p.pr; mgl_use_parser(pr,1); } mglParse(bool setsize=false) { pr=mgl_create_parser(); mgl_parser_allow_setsize(pr, setsize); } virtual ~mglParse() { #pragma omp critical if(mgl_use_parser(pr,-1)<1) mgl_delete_parser(pr); } /// Get pointer to internal mglParser object inline HMPR Self() { return pr; } /// Parse and draw single line of the MGL script inline int Parse(mglGraph *gr, const char *str, int pos) { return mgl_parse_line(gr->Self(), pr, str, pos); } inline int Parse(mglGraph *gr, const wchar_t *str, int pos) { return mgl_parse_linew(gr->Self(), pr, str, pos); } /// Execute MGL script text with '\n' separated lines inline void Execute(mglGraph *gr, const char *str) { mgl_parse_text(gr->Self(), pr, str); } inline void Execute(mglGraph *gr, const wchar_t *str) { mgl_parse_textw(gr->Self(), pr, str); } /// Execute and draw script from the file inline void Execute(mglGraph *gr, FILE *fp, bool print=false) { mgl_parse_file(gr->Self(), pr, fp, print); } /// Return type of command: 0 - not found, 1 - other data plot, 2 - func plot, /// 3 - setup, 4 - data handle, 5 - data create, 6 - subplot, 7 - program /// 8 - 1d plot, 9 - 2d plot, 10 - 3d plot, 11 - dd plot, 12 - vector plot /// 13 - axis, 14 - primitives, 15 - axis setup, 16 - text/legend, 17 - data transform inline int CmdType(const char *name) { return mgl_parser_cmd_type(pr, name); } /// Return string of command format (command name and its argument[s]) inline const char *CmdFormat(const char *name) { return mgl_parser_cmd_frmt(pr, name); } /// Return description of MGL command inline const char *CmdDesc(const char *name) { return mgl_parser_cmd_desc(pr, name); } /// Get name of command with number n inline const char *GetCmdName(long n) { return mgl_parser_cmd_name(pr,n); } /// Get number of defined commands inline long GetCmdNum() { return mgl_parser_cmd_num(pr); } /// Load new commands from external dynamic Library (must have "const mglCommand *mgl_cmd_extra" variable) inline void LoadDLL(const char *fname) { mgl_parser_load(pr, fname); } /// Apply one step for equation d vars[i]/dt = eqs[i] using Runge-Kutta method inline void RK_Step(const char *eqs, const char *vars, mreal dt=1) { mgl_rk_step(pr, eqs, vars, dt); } inline void RK_Step(const wchar_t *eqs, const wchar_t *vars, mreal dt=1) { mgl_rk_step_w(pr, eqs, vars, dt); } // Open all data arrays from HDF file and assign it as variables of parser p inline void OpenHDF(const char *fname) { mgl_parser_openhdf(pr, fname); } /// Set value for parameter $N inline void AddParam(int id, const char *str) { mgl_parser_add_param(pr, id, str); } inline void AddParam(int id, const wchar_t *str) { mgl_parser_add_paramw(pr, id, str); } /// Restore once flag inline void RestoreOnce() { mgl_parser_restore_once(pr); } /// Allow changing size of the picture inline void AllowSetSize(bool allow) { mgl_parser_allow_setsize(pr, allow); } /// Allow reading/saving files inline void AllowFileIO(bool allow) { mgl_parser_allow_file_io(pr, allow); } /// Allow loading commands from external libraries inline void AllowDllCall(bool allow) { mgl_parser_allow_dll_call(pr, allow); } /// Set flag to stop script parsing inline void Stop() { mgl_parser_stop(pr); } /// Set variant of argument(s) separated by '?' to be used in further commands inline void SetVariant(int var=0) { mgl_parser_variant(pr, var); } /// Set starting object ID inline void StartID(int id=0) { mgl_parser_start_id(pr, id); } /// Return result of formula evaluation inline mglData Calc(const char *formula) { return mglData(true,mgl_parser_calc(pr,formula)); } inline mglData Calc(const wchar_t *formula) { return mglData(true,mgl_parser_calcw(pr,formula)); } /// Return result of formula evaluation as complex data inline mglDataC CalcComplex(const char *formula) { return mglDataC(true,mgl_parser_calc_complex(pr,formula)); } inline mglDataC CalcComplex(const wchar_t *formula) { return mglDataC(true,mgl_parser_calc_complexw(pr,formula)); } /// Find variable with given name or add a new one /// NOTE !!! You must not delete obtained data arrays !!! inline mglDataA *AddVar(const char *name) { return mgl_parser_add_var(pr, name); } inline mglDataA *AddVar(const wchar_t *name) { return mgl_parser_add_varw(pr, name); } /// Find variable with given name or return NULL if no one /// NOTE !!! You must not delete obtained data arrays !!! inline mglDataA *FindVar(const char *name) { return mgl_parser_find_var(pr, name); } inline mglDataA *FindVar(const wchar_t *name) { return mgl_parser_find_varw(pr, name); } /// Get variable with given id. Can be NULL for temporary ones. /// NOTE !!! You must not delete obtained data arrays !!! inline mglDataA *GetVar(unsigned long id) { return mgl_parser_get_var(pr,id); } /// Get number of variables inline long GetNumVar() { return mgl_parser_num_var(pr); } /// Delete variable with name inline void DeleteVar(const char *name) { mgl_parser_del_var(pr, name); } inline void DeleteVar(const wchar_t *name) { mgl_parser_del_varw(pr, name); } /// Delete all data variables void DeleteAll() { mgl_parser_del_all(pr); } /// Get constant with given id. Can be NULL if not found. /// NOTE !!! You must not delete obtained data arrays !!! inline mglNum *GetConst(unsigned long id) { return mgl_parser_get_const(pr,id); } /// Get number of constants inline long GetNumConst() { return mgl_parser_num_const(pr); } }; //----------------------------------------------------------------------------- #endif #endif
graph.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef GRAPH_H_ #define GRAPH_H_ #include <algorithm> #include <cinttypes> #include <cstddef> #include <iostream> #include <type_traits> #include "pvector.h" #include "util.h" #include "segmentgraph.h" #include <map> /* GAP Benchmark Suite Class: CSRGraph Author: Scott Beamer Simple container for graph in CSR format - Intended to be constructed by a Builder - To make weighted, set DestID_ template type to NodeWeight - MakeInverse parameter controls whether graph stores its inverse */ // Used to hold node & weight, with another node it makes a weighted edge template <typename NodeID_, typename WeightT_> struct NodeWeight { NodeID_ v; WeightT_ w; NodeWeight() {} NodeWeight(NodeID_ v) : v(v), w(1) {} NodeWeight(NodeID_ v, WeightT_ w) : v(v), w(w) {} bool operator< (const NodeWeight& rhs) const { return v == rhs.v ? w < rhs.w : v < rhs.v; } // doesn't check WeightT_s, needed to remove duplicate edges bool operator== (const NodeWeight& rhs) const { return v == rhs.v; } // doesn't check WeightT_s, needed to remove self edges bool operator== (const NodeID_& rhs) const { return v == rhs; } operator NodeID_() { return v; } }; template <typename NodeID_, typename WeightT_> std::ostream& operator<<(std::ostream& os, const NodeWeight<NodeID_, WeightT_>& nw) { os << nw.v << " " << nw.w; return os; } template <typename NodeID_, typename WeightT_> std::istream& operator>>(std::istream& is, NodeWeight<NodeID_, WeightT_>& nw) { is >> nw.v >> nw.w; return is; } // Syntatic sugar for an edge template <typename SrcT, typename DstT = SrcT> struct EdgePair { SrcT u; DstT v; EdgePair() {} EdgePair(SrcT u, DstT v) : u(u), v(v) {} }; // SG = serialized graph, these types are for writing graph to file typedef int32_t SGID; typedef EdgePair<SGID> SGEdge; typedef int64_t SGOffset; template <class NodeID_, class DestID_ = NodeID_, bool MakeInverse = true> class CSRGraph { // Used for *non-negative* offsets within a neighborhood typedef std::make_unsigned<std::ptrdiff_t>::type OffsetT; // Used to access neighbors of vertex, basically sugar for iterators class Neighborhood { NodeID_ n_; DestID_** g_index_; OffsetT start_offset_; public: Neighborhood(NodeID_ n, DestID_** g_index, OffsetT start_offset) : n_(n), g_index_(g_index), start_offset_(0) { OffsetT max_offset = end() - begin(); start_offset_ = std::min(start_offset, max_offset); } typedef DestID_* iterator; iterator begin() { return g_index_[n_] + start_offset_; } iterator end() { return g_index_[n_+1]; } }; void ReleaseResources() { if (out_index_ != nullptr) delete[] out_index_; if (out_neighbors_ != nullptr) delete[] out_neighbors_; if (directed_) { if (in_index_ != nullptr) delete[] in_index_; if (in_neighbors_ != nullptr) delete[] in_neighbors_; } } public: CSRGraph() : directed_(false), num_nodes_(-1), num_edges_(-1), out_index_(nullptr), out_neighbors_(nullptr), in_index_(nullptr), in_neighbors_(nullptr) {} CSRGraph(int64_t num_nodes, DestID_** index, DestID_* neighs) : directed_(false), num_nodes_(num_nodes), out_index_(index), out_neighbors_(neighs), in_index_(index), in_neighbors_(neighs) { num_edges_ = (out_index_[num_nodes_] - out_index_[0]) / 2; } CSRGraph(int64_t num_nodes, DestID_** out_index, DestID_* out_neighs, DestID_** in_index, DestID_* in_neighs) : directed_(true), num_nodes_(num_nodes), out_index_(out_index), out_neighbors_(out_neighs), in_index_(in_index), in_neighbors_(in_neighs) { num_edges_ = out_index_[num_nodes_] - out_index_[0]; } CSRGraph(CSRGraph&& other) : directed_(other.directed_), num_nodes_(other.num_nodes_), num_edges_(other.num_edges_), out_index_(other.out_index_), out_neighbors_(other.out_neighbors_), in_index_(other.in_index_), in_neighbors_(other.in_neighbors_) { other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; } ~CSRGraph() { ReleaseResources(); } CSRGraph& operator=(CSRGraph&& other) { if (this != &other) { ReleaseResources(); directed_ = other.directed_; num_edges_ = other.num_edges_; num_nodes_ = other.num_nodes_; out_index_ = other.out_index_; out_neighbors_ = other.out_neighbors_; in_index_ = other.in_index_; in_neighbors_ = other.in_neighbors_; other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; } return *this; } bool directed() const { return directed_; } int64_t num_nodes() const { return num_nodes_; } int64_t num_edges() const { return num_edges_; } int64_t num_edges_directed() const { return directed_ ? num_edges_ : 2*num_edges_; } int64_t out_degree(NodeID_ v) const { return out_index_[v+1] - out_index_[v]; } int64_t in_degree(NodeID_ v) const { static_assert(MakeInverse, "Graph inversion disabled but reading inverse"); return in_index_[v+1] - in_index_[v]; } Neighborhood out_neigh(NodeID_ n, OffsetT start_offset = 0) const { return Neighborhood(n, out_index_, start_offset); } Neighborhood in_neigh(NodeID_ n, OffsetT start_offset = 0) const { static_assert(MakeInverse, "Graph inversion disabled but reading inverse"); return Neighborhood(n, in_index_, start_offset); } void PrintStats() const { std::cout << "Graph has " << num_nodes_ << " nodes and " << num_edges_ << " "; if (!directed_) std::cout << "un"; std::cout << "directed edges for degree: "; std::cout << num_edges_/num_nodes_ << std::endl; } void PrintTopology() const { for (NodeID_ i=0; i < num_nodes_; i++) { std::cout << i << ": "; for (DestID_ j : out_neigh(i)) { std::cout << j << " "; } std::cout << std::endl; } } void buildPushSegmentedGraphs(std::string label, int numSegments, bool numa_aware=false, bool weighted=false, std::string path="") { auto graphSegments = new GraphSegments<DestID_,NodeID_>(numSegments, numa_aware); label_to_segment[label] = graphSegments; int segmentRange = (num_nodes() + numSegments - 1) / numSegments; //Go through the original graph and count the number of target vertices and edges for each segment for (auto s : vertices()){ for (auto d : out_neigh(s)){ int segment_id; if (weighted) segment_id = d.v/segmentRange; else segment_id = d/segmentRange; graphSegments->getSegmentedGraph(segment_id)->countEdge(s); } } //Allocate each segment graphSegments->allocate(); //Add the edges for each segment for (auto s : vertices()){ for (auto d : out_neigh(s)){ int segment_id; if (weighted) segment_id = d.v/segmentRange; else segment_id = d/segmentRange; graphSegments->getSegmentedGraph(segment_id)->addEdge(s, d); } } } static DestID_** GenIndex(const pvector<SGOffset> &offsets, DestID_* neighs) { NodeID_ length = offsets.size(); DestID_** index = new DestID_*[length]; #pragma omp parallel for for (NodeID_ n=0; n < length; n++) index[n] = neighs + offsets[n]; return index; } pvector<SGOffset> VertexOffsets(bool in_graph = false) const { pvector<SGOffset> offsets(num_nodes_+1); for (NodeID_ n=0; n < num_nodes_+1; n++) if (in_graph) offsets[n] = in_index_[n] - in_index_[0]; else offsets[n] = out_index_[n] - out_index_[0]; return offsets; } Range<NodeID_> vertices() const { return Range<NodeID_>(num_nodes()); } // private: bool directed_; int64_t num_nodes_; int64_t num_edges_; DestID_** out_index_; DestID_* out_neighbors_; DestID_** in_index_; DestID_* in_neighbors_; std::map<std::string, GraphSegments<DestID_,NodeID_>*> label_to_segment; }; #endif // GRAPH_H_
turing.c
#include <stdio.h> #include <stdlib.h> #include "turing.h" #include "common.h" tTransTableItem * getTransition(tTransitions * t, int state, signed char symbol) { if (state < t->states && symbol < t->symbols) return t->table + state*t->symbols + symbol; else { printf("Critical error!\nTrying to get state=%d, symbol=%d, but trans. table size has %d states and %d symbols\n", state, symbol, t->states, t->symbols); exit(-1); } } char * shifts[] = {"R", "L", "RR", "N"}; #pragma omp threadprivate(shifts) inline char * shift2str(tShift shift) { return shifts[shift]; } void turing(tTape * tape, tTransitions * t, int max_steps, tStatus * status) { signed char symbol; int head=1; //turing read/write head position=2nd symbol (our tapes must begin with BLANK symbol) while (status->steps < max_steps && status->state < t->states) { tTransTableItem * trans; status->steps++; symbol=tape->content[head]; //this variable is good only for debugging... trans=getTransition(t, status->state, symbol); status->state=trans->state; if (trans->symbol >= 0) { tape->content[head]=trans->symbol; status->writes++; if (head>status->head_max) status->head_max=head; } switch (trans->shift) { case L: head--; break; case R: head++; break; case RR: head+=2; break; } if (head<0 || head>=TAPE_LEN) { if (log_level>=LOG_DEBUG_3) fprintf(stderr, "Head out of bounds!\n"); status->error=ERR_BOUNDS; return; } } // while(...) - the main loop; }
GB_unop__abs_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__abs_fp32_fp32) // op(A') function: GB (_unop_tran__abs_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = fabsf (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 = fabsf (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] = fabsf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__abs_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] = fabsf (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] = fabsf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__abs_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
nn_index.h
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE 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 AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef RTABMAP_FLANN_NNINDEX_H #define RTABMAP_FLANN_NNINDEX_H #include <vector> #include "rtflann/general.h" #include "rtflann/util/matrix.h" #include "rtflann/util/params.h" #include "rtflann/util/result_set.h" #include "rtflann/util/dynamic_bitset.h" #include "rtflann/util/saving.h" namespace rtflann { #define KNN_HEAP_THRESHOLD 250 class IndexBase { public: virtual ~IndexBase() {}; virtual size_t veclen() const = 0; virtual size_t size() const = 0; virtual flann_algorithm_t getType() const = 0; virtual int usedMemory() const = 0; virtual IndexParams getParameters() const = 0; virtual void loadIndex(FILE* stream) = 0; virtual void saveIndex(FILE* stream) = 0; }; /** * Nearest-neighbour index base class */ template <typename Distance> class NNIndex : public IndexBase { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; NNIndex(Distance d) : distance_(d), last_id_(0), size_(0), size_at_build_(0), veclen_(0), removed_(false), removed_count_(0), data_ptr_(NULL) { } NNIndex(const IndexParams& params, Distance d) : distance_(d), last_id_(0), size_(0), size_at_build_(0), veclen_(0), index_params_(params), removed_(false), removed_count_(0), data_ptr_(NULL) { } NNIndex(const NNIndex& other) : distance_(other.distance_), last_id_(other.last_id_), size_(other.size_), size_at_build_(other.size_at_build_), veclen_(other.veclen_), index_params_(other.index_params_), removed_(other.removed_), removed_points_(other.removed_points_), removed_count_(other.removed_count_), ids_(other.ids_), points_(other.points_), data_ptr_(NULL) { if (other.data_ptr_) { data_ptr_ = new ElementType[size_*veclen_]; std::copy(other.data_ptr_, other.data_ptr_+size_*veclen_, data_ptr_); for (size_t i=0;i<size_;++i) { points_[i] = data_ptr_ + i*veclen_; } } } virtual ~NNIndex() { if (data_ptr_) { delete[] data_ptr_; } } virtual NNIndex* clone() const = 0; /** * Builds the index */ virtual void buildIndex() { freeIndex(); cleanRemovedPoints(); // building index buildIndexImpl(); size_at_build_ = size_; } /** * Builds the index using the specified dataset * @param dataset the dataset to use */ virtual void buildIndex(const Matrix<ElementType>& dataset) { setDataset(dataset); this->buildIndex(); } /** * @brief Incrementally add points to the index. * @param points Matrix with points to be added * @param rebuild_threshold */ virtual void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2) { throw FLANNException("Functionality not supported by this index"); } /** * Remove point from the index * @param index Index of point to be removed */ virtual void removePoint(size_t id) { if (!removed_) { ids_.resize(size_); for (size_t i=0;i<size_;++i) { ids_[i] = i; } removed_points_.resize(size_); removed_points_.reset(); last_id_ = size_; removed_ = true; } size_t point_index = id_to_index(id); if (point_index!=size_t(-1) && !removed_points_.test(point_index)) { removed_points_.set(point_index); removed_count_++; } } /** * Get point with specific id * @param id * @return */ virtual ElementType* getPoint(size_t id) { size_t index = id_to_index(id); if (index!=size_t(-1)) { return points_[index]; } else { return NULL; } } /** * @return number of features in this index. */ inline size_t size() const { return size_ - removed_count_; } inline size_t removedCount() const { return removed_count_; } inline size_t sizeAtBuild() const { return size_at_build_; } /** * @return The dimensionality of the features in this index. */ inline size_t veclen() const { return veclen_; } /** * Returns the parameters used by the index. * * @return The index parameters */ IndexParams getParameters() const { return index_params_; } template<typename Archive> void serialize(Archive& ar) { IndexHeader header; if (Archive::is_saving::value) { header.h.data_type = flann_datatype_value<ElementType>::value; header.h.index_type = getType(); header.h.rows = size_; header.h.cols = veclen_; } ar & header; // sanity checks if (Archive::is_loading::value) { if (strncmp(header.h.signature, FLANN_SIGNATURE_, strlen(FLANN_SIGNATURE_) - strlen("v0.0")) != 0) { throw FLANNException("Invalid index file, wrong signature"); } if (header.h.data_type != flann_datatype_value<ElementType>::value) { throw FLANNException("Datatype of saved index is different than of the one to be created."); } if (header.h.index_type != getType()) { throw FLANNException("Saved index type is different then the current index type."); } // TODO: check for distance type } ar & size_; ar & veclen_; ar & size_at_build_; bool save_dataset; if (Archive::is_saving::value) { save_dataset = get_param(index_params_,"save_dataset", false); } ar & save_dataset; if (save_dataset) { if (Archive::is_loading::value) { if (data_ptr_) { delete[] data_ptr_; } data_ptr_ = new ElementType[size_*veclen_]; points_.resize(size_); for (size_t i=0;i<size_;++i) { points_[i] = data_ptr_ + i*veclen_; } } for (size_t i=0;i<size_;++i) { ar & serialization::make_binary_object (points_[i], veclen_*sizeof(ElementType)); } } else { if (points_.size()!=size_) { throw FLANNException("Saved index does not contain the dataset and no dataset was provided."); } } ar & last_id_; ar & ids_; ar & removed_; if (removed_) { ar & removed_points_; } ar & removed_count_; } /** * @brief Perform k-nearest neighbor search * @param[in] queries The query points for which to find the nearest neighbors * @param[out] indices The indices of the nearest neighbors found * @param[out] dists Distances to the nearest neighbors found * @param[in] knn Number of nearest neighbors to return * @param[in] params Search parameters */ virtual int knnSearch(const Matrix<ElementType>& queries, Matrix<size_t>& indices, Matrix<DistanceType>& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen()); assert(indices.rows >= queries.rows); assert(dists.rows >= queries.rows); assert(indices.cols >= knn); assert(dists.cols >= knn); bool use_heap; if (params.use_heap==FLANN_Undefined) { use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false; } else { use_heap = (params.use_heap==FLANN_True)?true:false; } int count = 0; if (use_heap) { #pragma omp parallel num_threads(params.cores) { KNNResultSet2<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNSimpleResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } } } return count; } /** * * @param queries * @param indices * @param dists * @param knn * @param params * @return */ /*int knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, size_t knn, const SearchParams& params) const { rtflann::Matrix<size_t> indices_(new size_t[indices.rows*indices.cols], indices.rows, indices.cols); int result = knnSearch(queries, indices_, dists, knn, params); for (size_t i=0;i<indices.rows;++i) { for (size_t j=0;j<indices.cols;++j) { indices[i][j] = indices_[i][j]; } } delete[] indices_.ptr(); return result; }*/ /** * @brief Perform k-nearest neighbor search * @param[in] queries The query points for which to find the nearest neighbors * @param[out] indices The indices of the nearest neighbors found * @param[out] dists Distances to the nearest neighbors found * @param[in] knn Number of nearest neighbors to return * @param[in] params Search parameters */ virtual int knnSearch(const Matrix<ElementType>& queries, std::vector< std::vector<size_t> >& indices, std::vector<std::vector<DistanceType> >& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen()); bool use_heap; if (params.use_heap==FLANN_Undefined) { use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false; } else { use_heap = (params.use_heap==FLANN_True)?true:false; } if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); int count = 0; if (use_heap) { #pragma omp parallel num_threads(params.cores) { KNNResultSet2<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n>0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNSimpleResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n>0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } return count; } /** * * @param queries * @param indices * @param dists * @param knn * @param params * @return */ int knnSearch(const Matrix<ElementType>& queries, std::vector< std::vector<int> >& indices, std::vector<std::vector<DistanceType> >& dists, size_t knn, const SearchParams& params) const { std::vector<std::vector<size_t> > indices_; int result = knnSearch(queries, indices_, dists, knn, params); indices.resize(indices_.size()); for (size_t i=0;i<indices_.size();++i) { indices[i].assign(indices_[i].begin(), indices_[i].end()); } return result; } /** * @brief Perform radius search * @param[in] query The query point * @param[out] indices The indices of the neighbors found within the given radius * @param[out] dists The distances to the nearest neighbors found * @param[in] radius The radius used for search * @param[in] params Search parameters * @return Number of neighbors found */ virtual int radiusSearch(const Matrix<ElementType>& queries, Matrix<size_t>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params) const { assert(queries.cols == veclen()); int count = 0; size_t num_neighbors = std::min(indices.cols, dists.cols); int max_neighbors = params.max_neighbors; if (max_neighbors<0) max_neighbors = num_neighbors; else max_neighbors = std::min(max_neighbors,(int)num_neighbors); if (max_neighbors==0) { #pragma omp parallel num_threads(params.cores) { CountRadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); count += resultSet.size(); } } } else { // explicitly indicated to use unbounded radius result set // and we know there'll be enough room for resulting indices and dists if (params.max_neighbors<0 && (num_neighbors>=size())) { #pragma omp parallel num_threads(params.cores) { RadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; if (n>num_neighbors) n = num_neighbors; resultSet.copy(indices[i], dists[i], n, params.sorted); // mark the next element in the output buffers as unused if (n<indices.cols) indices[i][n] = size_t(-1); if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity(); indices_to_ids(indices[i], indices[i], n); } } } else { // number of neighbors limited to max_neighbors #pragma omp parallel num_threads(params.cores) { KNNRadiusResultSet<DistanceType> resultSet(radius, max_neighbors); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; if ((int)n>max_neighbors) n = max_neighbors; resultSet.copy(indices[i], dists[i], n, params.sorted); // mark the next element in the output buffers as unused if (n<indices.cols) indices[i][n] = size_t(-1); if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity(); indices_to_ids(indices[i], indices[i], n); } } } } return count; } /** * * @param queries * @param indices * @param dists * @param radius * @param params * @return */ int radiusSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params) const { rtflann::Matrix<size_t> indices_(new size_t[indices.rows*indices.cols], indices.rows, indices.cols); int result = radiusSearch(queries, indices_, dists, radius, params); for (size_t i=0;i<indices.rows;++i) { for (size_t j=0;j<indices.cols;++j) { indices[i][j] = indices_[i][j]; } } delete[] indices_.ptr(); return result; } /** * @brief Perform radius search * @param[in] query The query point * @param[out] indices The indices of the neighbors found within the given radius * @param[out] dists The distances to the nearest neighbors found * @param[in] radius The radius used for search * @param[in] params Search parameters * @return Number of neighbors found */ virtual int radiusSearch(const Matrix<ElementType>& queries, std::vector< std::vector<size_t> >& indices, std::vector<std::vector<DistanceType> >& dists, float radius, const SearchParams& params) const { assert(queries.cols == veclen()); int count = 0; // just count neighbors if (params.max_neighbors==0) { #pragma omp parallel num_threads(params.cores) { CountRadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); count += resultSet.size(); } } } else { if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); if (params.max_neighbors<0) { // search for all neighbors #pragma omp parallel num_threads(params.cores) { RadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } } } } else { // number of neighbors limited to max_neighbors #pragma omp parallel num_threads(params.cores) { KNNRadiusResultSet<DistanceType> resultSet(radius, params.max_neighbors); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; if ((int)n>params.max_neighbors) n = params.max_neighbors; indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } } } } } return count; } /** * * @param queries * @param indices * @param dists * @param radius * @param params * @return */ int radiusSearch(const Matrix<ElementType>& queries, std::vector< std::vector<int> >& indices, std::vector<std::vector<DistanceType> >& dists, float radius, const SearchParams& params) const { std::vector<std::vector<size_t> > indices_; int result = radiusSearch(queries, indices_, dists, radius, params); indices.resize(indices_.size()); for (size_t i=0;i<indices_.size();++i) { indices[i].assign(indices_[i].begin(), indices_[i].end()); } return result; } virtual void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) const = 0; protected: virtual void freeIndex() = 0; virtual void buildIndexImpl() = 0; size_t id_to_index(size_t id) { if (ids_.size()==0) { return id; } size_t point_index = size_t(-1); if (id < ids_.size() && ids_[id]==id) { return id; } else { // binary search size_t start = 0; size_t end = ids_.size(); while (start<end) { size_t mid = (start+end)/2; if (ids_[mid]==id) { point_index = mid; break; } else if (ids_[mid]<id) { start = mid + 1; } else { end = mid; } } } return point_index; } void indices_to_ids(const size_t* in, size_t* out, size_t size) const { if (removed_) { for (size_t i=0;i<size;++i) { out[i] = ids_[in[i]]; } } } void setDataset(const Matrix<ElementType>& dataset) { size_ = dataset.rows; veclen_ = dataset.cols; last_id_ = 0; ids_.clear(); removed_points_.clear(); removed_ = false; removed_count_ = 0; points_.resize(size_); for (size_t i=0;i<size_;++i) { points_[i] = dataset[i]; } } void extendDataset(const Matrix<ElementType>& new_points) { size_t new_size = size_ + new_points.rows; if (removed_) { removed_points_.resize(new_size); ids_.resize(new_size); } points_.resize(new_size); for (size_t i=size_;i<new_size;++i) { points_[i] = new_points[i-size_]; if (removed_) { ids_[i] = last_id_++; removed_points_.reset(i); } } size_ = new_size; } void cleanRemovedPoints() { if (!removed_) return; size_t last_idx = 0; for (size_t i=0;i<size_;++i) { if (!removed_points_.test(i)) { points_[last_idx] = points_[i]; ids_[last_idx] = ids_[i]; removed_points_.reset(last_idx); ++last_idx; } } points_.resize(last_idx); ids_.resize(last_idx); removed_points_.resize(last_idx); size_ = last_idx; removed_count_ = 0; } void swap(NNIndex& other) { std::swap(distance_, other.distance_); std::swap(last_id_, other.last_id_); std::swap(size_, other.size_); std::swap(size_at_build_, other.size_at_build_); std::swap(veclen_, other.veclen_); std::swap(index_params_, other.index_params_); std::swap(removed_, other.removed_); std::swap(removed_points_, other.removed_points_); std::swap(removed_count_, other.removed_count_); std::swap(ids_, other.ids_); std::swap(points_, other.points_); std::swap(data_ptr_, other.data_ptr_); } protected: /** * The distance functor */ Distance distance_; /** * Each index point has an associated ID. IDs are assigned sequentially in * increasing order. This indicates the ID assigned to the last point added to the * index. */ size_t last_id_; /** * Number of points in the index (and database) */ size_t size_; /** * Number of features in the dataset when the index was last built. */ size_t size_at_build_; /** * Size of one point in the index (and database) */ size_t veclen_; /** * Parameters of the index. */ IndexParams index_params_; /** * Flag indicating if at least a point was removed from the index */ bool removed_; /** * Array used to mark points removed from the index */ DynamicBitset removed_points_; /** * Number of points removed from the index */ size_t removed_count_; /** * Array of point IDs, returned by nearest-neighbour operations */ std::vector<size_t> ids_; /** * Point data */ std::vector<ElementType*> points_; /** * Pointer to dataset memory if allocated by this index, otherwise NULL */ ElementType* data_ptr_; }; #define USING_BASECLASS_SYMBOLS \ using NNIndex<Distance>::distance_;\ using NNIndex<Distance>::size_;\ using NNIndex<Distance>::size_at_build_;\ using NNIndex<Distance>::veclen_;\ using NNIndex<Distance>::index_params_;\ using NNIndex<Distance>::removed_points_;\ using NNIndex<Distance>::ids_;\ using NNIndex<Distance>::removed_;\ using NNIndex<Distance>::points_;\ using NNIndex<Distance>::extendDataset;\ using NNIndex<Distance>::setDataset;\ using NNIndex<Distance>::cleanRemovedPoints;\ using NNIndex<Distance>::indices_to_ids; } #endif //FLANN_NNINDEX_H
DenseSegment.h
/****************************************************************************** * ** Copyright (c) 2016, Intel Corporation ** * ** All rights reserved. ** * ** ** * ** Redistribution and use in source and binary forms, with or without ** * ** modification, are permitted provided that the following conditions ** * ** are met: ** * ** 1. Redistributions of source code must retain the above copyright ** * ** notice, this list of conditions and the following disclaimer. ** * ** 2. Redistributions in binary form must reproduce the above copyright ** * ** notice, this list of conditions and the following disclaimer in the ** * ** documentation and/or other materials provided with the distribution. ** * ** 3. Neither the name of the copyright holder nor the names of its ** * ** contributors may be used to endorse or promote products derived ** * ** from this software without specific prior written permission. ** * ** ** * ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** * ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** * ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** * ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** * ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** * ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** * ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** * ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** * ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** * ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** * ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ******************************************************************************/ /* Michael Anderson (Intel Corp.) * * ******************************************************************************/ #ifndef SRC_DENSESEGMENT_H_ #define SRC_DENSESEGMENT_H_ #include "GMDP/utils/edgelist.h" #include "GMDP/utils/bitvector.h" #include "GMDP/singlenode/unionreduce.h" #include <string> #include <vector> #include <sstream> #include <cstdio> inline double get_compression_threshold(); enum compression_decision { NONE, COMPRESSED, SERIALIZED }; struct send_metadata { int nnz; size_t serialized_nbytes; size_t serialized_npartitions; friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & nnz; ar & serialized_nbytes; ar & serialized_npartitions; } }; template <typename T> class buffer { public: bool uninitialized; int nnz; int capacity; int num_ints; size_t serialized_nbytes; size_t serialized_npartitions; T * value; int * bit_vector; T * compressed_data; int * compressed_indices; char * serialized_data; size_t * serialized_partition_nbytes_scan; size_t * serialized_partition_nnz_scan; // Serialize friend boost::serialization::access; template<class Archive> void save(Archive& ar, const unsigned int version) const { ar & uninitialized; ar & nnz; ar & capacity; ar & num_ints; ar & serialized_nbytes; ar & serialized_npartitions; for(int i = 0 ; i < capacity; i++) { ar & value[i]; } for(int i = 0 ; i < num_ints; i++) { ar & bit_vector[i]; } for(int i = 0 ; i < capacity ; i++) { ar & compressed_data[i]; } for(int i = 0 ; i < capacity ; i++) { ar & compressed_indices[i]; } for(int i = 0 ; i < serialized_nbytes; i++) { ar & serialized_data[i]; } for(int i = 0 ; i < serialized_npartitions + 1; i++) { ar & serialized_partition_nbytes_scan[i]; } for(int i = 0 ; i < serialized_npartitions + 1; i++) { ar & serialized_partition_nnz_scan[i]; } } template<class Archive> void load(Archive& ar, const unsigned int version) { ar & uninitialized; ar & nnz; ar & capacity; ar & num_ints; ar & serialized_nbytes; ar & serialized_npartitions; delete [] value; delete [] bit_vector; delete [] compressed_data; delete [] compressed_indices; delete [] serialized_data; delete [] serialized_partition_nbytes_scan; delete [] serialized_partition_nnz_scan; value = new T[capacity]; bit_vector = new int[num_ints]; compressed_data = new T[capacity]; compressed_indices = new int[capacity]; serialized_data = new char[serialized_nbytes]; serialized_partition_nbytes_scan = new size_t[serialized_npartitions+1]; serialized_partition_nnz_scan = new size_t[serialized_npartitions+1]; for(int i = 0 ; i < capacity; i++) { ar & value[i]; } for(int i = 0 ; i < num_ints; i++) { ar & bit_vector[i]; } for(int i = 0 ; i < capacity ; i++) { ar & compressed_data[i]; } for(int i = 0 ; i < capacity ; i++) { ar & compressed_indices[i]; } for(int i = 0 ; i < serialized_nbytes; i++) { ar & serialized_data[i]; } for(int i = 0 ; i < serialized_npartitions + 1; i++) { ar & serialized_partition_nbytes_scan[i]; } for(int i = 0 ; i < serialized_npartitions + 1; i++) { ar & serialized_partition_nnz_scan[i]; } } BOOST_SERIALIZATION_SPLIT_MEMBER() buffer(int _capacity, int _num_ints) { capacity = _capacity; num_ints = _num_ints; value = new T[capacity]; bit_vector = new int[num_ints]; //compressed_data = reinterpret_cast<T*>(_mm_malloc(capacity * sizeof(T) + capacity*sizeof(int), 64)); compressed_data = new T[capacity]; compressed_indices = new int[capacity]; uninitialized = true; serialized_data = new char[0]; serialized_nbytes = 0; serialized_npartitions = omp_get_max_threads() * 16; serialized_partition_nbytes_scan = new size_t[serialized_npartitions+1]; serialized_partition_nnz_scan = new size_t[serialized_npartitions+1]; } buffer() : buffer(0,0) {} void alloc_serialized(size_t sz) { delete [] serialized_data; serialized_data = new char[sz]; serialized_nbytes = sz; } int compute_nnz() const { int len = 0; #pragma omp parallel for reduction(+:len) for (int ii = 0 ; ii < num_ints ; ii++) { int p = _popcnt32(bit_vector[ii]); len += p; } return len; } int compute_nnz(int start, int finish) const { int len = 0; #pragma omp parallel for reduction(+:len) for (int ii = start ; ii < finish ; ii++) { int p = _popcnt32(bit_vector[ii]); len += p; } return len; } template<bool EXTENDS_SERIALIZABLE = std::is_base_of<Serializable,T>::value, typename std::enable_if<EXTENDS_SERIALIZABLE>::type* = nullptr> void decompress() { memset(bit_vector, 0, num_ints* sizeof(int)); std::stringstream * sss = new std::stringstream[serialized_npartitions]; #pragma omp parallel for for(int p = 0 ; p < serialized_npartitions ; p++) { int i_per_partition = (num_ints + serialized_npartitions - 1) / serialized_npartitions; int start_i = i_per_partition * p; int end_i = i_per_partition * (p+1); if(end_i > num_ints) end_i = num_ints; sss[p].write(serialized_data + serialized_partition_nbytes_scan[p], (serialized_partition_nbytes_scan[p+1]-serialized_partition_nbytes_scan[p])); boost::archive::binary_iarchive ia(sss[p]); for(unsigned long int i = 0 ; i < (serialized_partition_nnz_scan[p+1] - serialized_partition_nnz_scan[p]) ; i++) { int idx; ia >> idx; ia >> value[idx]; set_bitvector(idx, bit_vector); } } delete [] sss; } template<bool EXTENDS_SERIALIZABLE = std::is_base_of<Serializable,T>::value, typename std::enable_if<!EXTENDS_SERIALIZABLE>::type* = nullptr> void decompress() { memset(bit_vector, 0, num_ints* sizeof(int)); //compressed_indices = reinterpret_cast<int*>(compressed_data + nnz); int npartitions = omp_get_max_threads(); int * start_nnzs = new int[npartitions]; int * end_nnzs = new int[npartitions]; int mystart = 0; int my_nz_per = (nnz + npartitions - 1) / npartitions; my_nz_per = ((my_nz_per + 31) / 32) * 32; for(int p = 0 ; p < npartitions ; p++) { start_nnzs[p] = mystart; mystart += my_nz_per; if(mystart > nnz) mystart = nnz; if(mystart < nnz) { int start32 = compressed_indices[mystart] / 32; while((mystart < nnz) && compressed_indices[mystart] / 32 == start32) mystart++; } end_nnzs[p] = mystart; } #pragma omp parallel for for(int p = 0 ; p < npartitions ; p++) { int start_nnz = start_nnzs[p]; int end_nnz = end_nnzs[p]; for(int i = start_nnz ; i < end_nnz ; i++) { int idx = compressed_indices[i]; set_bitvector(idx, bit_vector); value[idx] = compressed_data[i]; } } delete [] start_nnzs; delete [] end_nnzs; } template<bool EXTENDS_SERIALIZABLE = std::is_base_of<Serializable,T>::value, typename std::enable_if<EXTENDS_SERIALIZABLE>::type* = nullptr> void compress() { size_t * serialized_partition_nbytes = new size_t[serialized_npartitions]; size_t * serialized_partition_nnz = new size_t[serialized_npartitions]; std::stringstream * sss = new std::stringstream[serialized_npartitions]; #pragma omp parallel for for(int p = 0 ; p < serialized_npartitions ; p++) { int i_per_partition = (num_ints + serialized_npartitions - 1) / serialized_npartitions; int start_i = i_per_partition * p; int end_i = i_per_partition * (p+1); if(end_i > num_ints) end_i = num_ints; serialized_partition_nnz[p] = 0; boost::archive::binary_oarchive oa(sss[p]); for(int ii = start_i ; ii < end_i ; ii++) { if(_popcnt32(bit_vector[ii]) == 0) continue; for(int i = ii*32 ; i < (ii+1)*32 ; i++) { if(get_bitvector(i, bit_vector)) { oa << i; oa << value[i]; serialized_partition_nnz[p]++; } } } sss[p].seekg(0, sss[p].end); size_t sz = sss[p].tellg(); sss[p].seekg(0, sss[p].beg); serialized_partition_nbytes[p] = sz; } serialized_partition_nnz_scan[0] = 0; serialized_partition_nbytes_scan[0] = 0; for(int p = 0 ; p < serialized_npartitions ; p++) { serialized_partition_nnz_scan[p+1] = serialized_partition_nnz_scan[p] + serialized_partition_nnz[p]; serialized_partition_nbytes_scan[p+1] = serialized_partition_nbytes_scan[p] + serialized_partition_nbytes[p]; } size_t sz = serialized_partition_nbytes_scan[serialized_npartitions]; alloc_serialized(sz); #pragma omp parallel for for(int p = 0 ; p < serialized_npartitions ; p++) { sss[p].read(serialized_data + serialized_partition_nbytes_scan[p], serialized_partition_nbytes[p]); } delete [] serialized_partition_nnz; delete [] serialized_partition_nbytes; delete [] sss; } template<bool EXTENDS_SERIALIZABLE = std::is_base_of<Serializable,T>::value, typename std::enable_if<!EXTENDS_SERIALIZABLE>::type* = nullptr> void compress() { int npartitions = omp_get_max_threads() * 16; int * partition_nnz = new int[npartitions]; int * partition_nnz_scan = new int[npartitions+1]; #pragma omp parallel for for(int p = 0 ; p < npartitions ; p++) { int i_per_partition = (num_ints + npartitions - 1) / npartitions; int start_i = i_per_partition * p; int end_i = i_per_partition * (p+1); if(end_i > num_ints) end_i = num_ints; partition_nnz[p] = compute_nnz(start_i, end_i); } partition_nnz_scan[0] = 0; nnz = 0; for(int p = 0 ; p < npartitions ; p++) { partition_nnz_scan[p+1] = partition_nnz_scan[p] + partition_nnz[p]; nnz += partition_nnz[p]; } #pragma omp parallel for for(int p = 0 ; p < npartitions ; p++) { int i_per_partition = (num_ints + npartitions - 1) / npartitions; int start_i = i_per_partition * p; int end_i = i_per_partition * (p+1); if(end_i > num_ints) end_i = num_ints; int nzcnt = partition_nnz_scan[p]; for(int ii = start_i ; ii < end_i ; ii++) { if(_popcnt32(bit_vector[ii]) == 0) continue; for(int i = ii*32 ; i < (ii+1)*32 ; i++) { if(get_bitvector(i, bit_vector)) { compressed_data[nzcnt] = value[i]; compressed_indices[nzcnt] = i; nzcnt++; } } } } delete [] partition_nnz; delete [] partition_nnz_scan; } ~buffer() { delete [] value; delete [] bit_vector; delete [] compressed_data; delete [] compressed_indices; delete [] serialized_partition_nbytes_scan; delete [] serialized_partition_nnz_scan; delete [] serialized_data; } }; template <typename T> class DenseSegment { public: std::string name; int capacity; int num_ints; buffer<T> *properties; send_metadata received_md; std::vector<send_metadata> queued_md; std::vector<buffer<T> * > received; std::vector<buffer<T> * > uninitialized; friend boost::serialization::access; template<class Archive> void save(Archive& ar, const unsigned int version) const { bool properties_is_null = (properties == NULL); ar & properties_is_null; ar & name; ar & capacity; ar & num_ints; if(properties != NULL) { ar & properties; } ar & received_md; ar & queued_md; ar & received; ar & uninitialized; } template<class Archive> void load(Archive& ar, const unsigned int version) { bool properties_null; ar & properties_null; ar & name; ar & capacity; ar & num_ints; if(!properties_null) { ar & properties; } else { properties = NULL; } ar & received_md; ar & queued_md; ar & received; ar & uninitialized; } BOOST_SERIALIZATION_SPLIT_MEMBER() DenseSegment(int n) { capacity = n; num_ints = (n + sizeof(int) * 8 - 1) / (sizeof(int) * 8); properties = NULL; } DenseSegment() : DenseSegment(0) {} void ingestEdges(edge_t<T>* edges, int _m, int _nnz, int row_start) { alloc(); initialize(); for (uint64_t i = 0; i < (uint64_t)_nnz; i++) { int src = edges[i].src - row_start - 1; set_bitvector(src, properties->bit_vector); properties->value[src] = edges[i].val; } properties->nnz = _nnz; properties->uninitialized = false; } ~DenseSegment() { if(properties != NULL) { delete properties; } for(auto it = received.begin() ; it != received.end() ; it++) { delete *it; } received.clear(); for(auto it = uninitialized.begin() ; it != uninitialized.end() ; it++) { delete *it; } uninitialized.clear(); } int compute_nnz() const { if(properties == NULL) return 0; if(properties->uninitialized) return 0; return properties->compute_nnz(); } int compute_nnz(int start, int finish) const { if(properties == NULL) return 0; if(properties->uninitialized) return 0; return properties->compute_nnz(start, finish); } compression_decision should_compress(int test_nnz) { if(std::is_base_of<Serializable,T>::value) return SERIALIZED; if(test_nnz > get_compression_threshold() * capacity) return NONE; return COMPRESSED; } void compress() { alloc(); initialize(); if(should_compress(properties->nnz) == COMPRESSED || should_compress(properties->nnz) == SERIALIZED) { properties->compress(); } } void decompress() { assert(properties); if(should_compress(properties->nnz) == COMPRESSED || should_compress(properties->nnz) == SERIALIZED) { properties->decompress(); } } void set_uninitialized_received() { for(auto it = received.begin() ; it != received.end() ; it++) { (*it)->uninitialized = true; uninitialized.push_back(*it); } received.clear(); } void set_uninitialized() { set_uninitialized_received(); if(properties != NULL) { properties->uninitialized = true; properties->nnz = 0; } } void alloc() { if(properties == NULL) { properties = new buffer<T>(capacity, num_ints); } } void initialize() { if(properties->uninitialized) { memset(properties->bit_vector, 0, num_ints* sizeof(int)); properties->nnz = 0; } properties->uninitialized = false; } int getNNZ() { return properties->nnz; } void set(int idx, T val) { alloc(); initialize(); if(!get_bitvector(idx-1, properties->bit_vector)) properties->nnz++; properties->value[idx - 1] = val; set_bitvector(idx-1, properties->bit_vector); properties->uninitialized = false; } void setAll(T val) { alloc(); //initialize(); properties->uninitialized=false; if(num_ints == 0) return; properties->bit_vector[num_ints-1] = 0; #pragma omp parallel for for(int i = 0 ; i < num_ints-1 ; i++) { properties->bit_vector[i] = 0xFFFFFFFF; } for(int idx = std::max(0, capacity-32) ; idx < capacity ; idx++) { set_bitvector(idx, properties->bit_vector); } properties->nnz = capacity; #pragma omp parallel for for(int i = 0 ; i < capacity ; i++) { properties->value[i] = val; } } T get(const int idx) const { assert(properties); assert(!properties->uninitialized); return properties->value[idx - 1]; } void send_nnz(int myrank, int dst_rank, std::vector<MPI_Request>* requests) { send_metadata md = {properties->nnz, properties->serialized_nbytes, properties->serialized_npartitions}; MPI_Send(&md, sizeof(md), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); } void recv_nnz_queue(int myrank, int src_rank, std::vector<MPI_Request>* requests) { send_metadata md; MPI_Recv(&md, sizeof(md), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); queued_md.insert(queued_md.begin(), md); } void recv_nnz(int myrank, int src_rank, std::vector<MPI_Request>* requests) { alloc(); MPI_Recv(&received_md, sizeof(send_metadata), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } void send_segment(int myrank, int dst_rank, std::vector<MPI_Request>* requests) { if(should_compress(properties->nnz) == COMPRESSED) { MPI_Request r1; MPI_Request r2; MPI_Isend(properties->compressed_data, properties->nnz * sizeof(T), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r1); MPI_Isend(properties->compressed_indices, properties->nnz * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r2); requests->push_back(r1); requests->push_back(r2); } else if(should_compress(properties->nnz) == SERIALIZED) { MPI_Request r1; MPI_Request r2; MPI_Request r3; MPI_Isend(properties->serialized_data, properties->serialized_nbytes, MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r1); MPI_Isend(properties->serialized_partition_nnz_scan, (properties->serialized_npartitions+1) * sizeof(size_t), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r2); MPI_Isend(properties->serialized_partition_nbytes_scan, (properties->serialized_npartitions+1) * sizeof(size_t), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r3); requests->push_back(r1); requests->push_back(r2); requests->push_back(r3); } else { MPI_Request r1; MPI_Request r2; MPI_Isend(properties->value, capacity * sizeof(T), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r1); MPI_Isend(properties->bit_vector, num_ints * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r2); requests->push_back(r1); requests->push_back(r2); } } void recv_buffer(send_metadata md, buffer<T> * p, int myrank, int src_rank, std::vector<MPI_Request>* requests) { p->nnz = md.nnz; p->serialized_nbytes = md.serialized_nbytes; p->serialized_npartitions = md.serialized_npartitions; if(should_compress(p->nnz) == COMPRESSED) { MPI_Request r1; MPI_Request r2; MPI_Irecv(p->compressed_data, p->nnz * sizeof(T), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r1); MPI_Irecv(p->compressed_indices, p->nnz * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r2); requests->push_back(r1); requests->push_back(r2); } else if(should_compress(p->nnz) == SERIALIZED) { MPI_Request r1; MPI_Request r2; MPI_Request r3; p->alloc_serialized(p->serialized_nbytes); MPI_Irecv(p->serialized_data, p->serialized_nbytes, MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r1); MPI_Irecv(p->serialized_partition_nnz_scan, (p->serialized_npartitions+1) * sizeof(size_t), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r2); MPI_Irecv(p->serialized_partition_nbytes_scan, (p->serialized_npartitions+1) * sizeof(size_t), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r3); requests->push_back(r1); requests->push_back(r2); requests->push_back(r3); } else { MPI_Request r1; MPI_Request r2; MPI_Irecv(p->value, capacity * sizeof(T), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r1); MPI_Irecv(p->bit_vector, num_ints* sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r2); requests->push_back(r1); requests->push_back(r2); } p->uninitialized = false; } void recv_segment_queue(int myrank, int src_rank, std::vector<MPI_Request>* requests) { buffer<T> * new_properties; if(uninitialized.size() > 0) { new_properties = uninitialized.back(); uninitialized.pop_back(); } else { new_properties = new buffer<T>(capacity, num_ints); } send_metadata md = queued_md.back(); queued_md.pop_back(); recv_buffer(md, new_properties, myrank, src_rank, requests); received.push_back(new_properties); } void recv_segment(int myrank, int src_rank, std::vector<MPI_Request>* requests) { recv_buffer(received_md, properties, myrank, src_rank, requests); } void save(std::string fname, int start_id, int _m, bool includeHeader) { int nnz = compute_nnz(); std::ofstream fout; fout.open(fname); if(includeHeader) { fout << _m << " " << nnz << std::endl; } for(int i = 0 ; i < capacity ; i++) { if(get_bitvector(i, properties->bit_vector)) { fout << i + start_id << " " << properties->value[i] << std::endl; } } fout.close(); } void get_edges(edge_t<T> * edges, unsigned int start_nz) const { unsigned int mycnt = 0; for(int i = 0 ; i < capacity ; i++) { if(get_bitvector(i, properties->bit_vector)) { edges[mycnt].src = start_nz + i + 1; edges[mycnt].dst = 1; edges[mycnt].val = properties->value[i]; mycnt++; } } } template <typename Ta, typename Tb, typename Tc> void union_received(void (*op_fp)(Ta, Tb, Tc*, void*), void* vsp) { alloc(); initialize(); for(auto it = received.begin() ; it != received.end() ; it++) { if(should_compress((*it)->nnz) == COMPRESSED) { union_compressed((*it)->compressed_data, (*it)->compressed_indices, (*it)->nnz, capacity, num_ints, properties->value, properties->bit_vector, op_fp, vsp); } else if(should_compress((*it)->nnz) == SERIALIZED) { (*it)->decompress(); union_dense((*it)->value, (*it)->bit_vector, capacity, num_ints, properties->value, properties->bit_vector, properties->value, properties->bit_vector, op_fp, vsp); } else { union_dense((*it)->value, (*it)->bit_vector, capacity, num_ints, properties->value, properties->bit_vector, properties->value, properties->bit_vector, op_fp, vsp); } } } }; #endif // SRC_DENSESEGMENT_H_
example-omp-1.c
// PWD006: Missing deep copy of non-contiguous data to the GPU // https://www.appentra.com/knowledge/checks/pwd006 #include <stdlib.h> void foo(int **A) { #pragma omp target teams distribute parallel for map(tofrom:A) for (size_t i = 0; i < 10; i++) { A[i][i] += i; } }
conv_kernel_int8_arm.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: qwang@openailab.com */ #include "conv_kernel_int8_arm.h" #include "api/c_api.h" #include "utility/sys_port.h" #include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #ifdef __aarch64__ void i8gemm_4x16_a72_int8(int* biases, int8_t* input, int8_t* kernel, long kernel_size, int8_t* output, int* multi, long output_xy, int* shift, int activation_min, int activation_max); void i8gemm_4x4_a72_int8(int* biases, int8_t* input, int8_t* kernel, long kernel_size, int8_t* output, int* multi, long output_xy, int* shift, int activation_min, int activation_max); void im2col_int8_1x1(int8_t* input, long input_xy, int8_t* col, long col_cnt, long input_chan); void im2col_int8_3x3(int8_t* input, long input_x, long input_y, long input_chan, int8_t* col, long stride); // col_start and col_end need to be 16 aligned // kernel_start need to be 4 aligned static void i8gemm4x16(int8_t* col, int8_t* kernel, bool bias_term, int* biases, int8_t* output, int* multi, int kernel_size, int output_xy, int col_start, int col_end, int kernel_start, int kernel_end, int activation_min, int activation_max, int* q_shift, int num_thread, int cpu_affinity) { int col_end3 = col_end & 3; int kernel_size_aligned2 = (kernel_size + 1) & -2; #pragma omp parallel for num_threads(num_thread) for(int kernel_num = (kernel_start & -16); kernel_num < (kernel_end & -16); kernel_num += 16) { int* cur_biases = NULL; if(bias_term) { cur_biases = biases + kernel_num; } int result[64] = {0}; int8_t* output_line[4]; int* pmulti = multi + kernel_num; int* pq_shift = q_shift + kernel_num; int8_t* cur_kernel = kernel + kernel_num * kernel_size_aligned2; int8_t* output_result = output + kernel_num * output_xy; for(int col_line = (col_start & -4); col_line < (col_end & -4); col_line += 4) { int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x16_a72_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, output_result + col_line, pmulti, output_xy, pq_shift, activation_min, activation_max); } if(col_end3) { int col_line = col_end & -4; int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x16_a72_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + i * 4 + j) * output_xy + col_line; } *(output_line[0] + 0) = result[i * 16 + 0]; *(output_line[1] + 0) = result[i * 16 + 5]; *(output_line[2] + 0) = result[i * 16 + 10]; *(output_line[3] + 0) = result[i * 16 + 15]; if((col_end3) >= 2) { *(output_line[0] + 1) = result[i * 16 + 4]; *(output_line[1] + 1) = result[i * 16 + 1]; *(output_line[2] + 1) = result[i * 16 + 14]; *(output_line[3] + 1) = result[i * 16 + 11]; } if((col_end3) == 3) { *(output_line[0] + 2) = result[i * 16 + 8]; *(output_line[1] + 2) = result[i * 16 + 13]; *(output_line[2] + 2) = result[i * 16 + 2]; *(output_line[3] + 2) = result[i * 16 + 7]; } } } } return; } // col_start and kernel_start need to be 4 aligned static void i8gemm4x4(int8_t* col, int8_t* kernel, bool bias_term, int* biases, int8_t* output, int* multi, int kernel_size, int output_xy, int col_start, int col_end, int kernel_start, int kernel_end, int activation_min, int activation_max, int* q_shift, int num_thread, int cpu_affinity) { int col_end3 = col_end & 3; int kernel_end3 = kernel_end & 3; int kernel_size_aligned2 = (kernel_size + 1) & -2; #pragma omp parallel for num_threads(num_thread) for(int kernel_num = kernel_start & -4; kernel_num < (kernel_end & -4); kernel_num += 4) { int* cur_biases = NULL; if(bias_term) { cur_biases = biases + kernel_num; } int result[16] = {0}; int8_t* output_line[4]; int* pmulti = multi + kernel_num; int* pq_shift = q_shift + kernel_num; int8_t* cur_kernel = kernel + kernel_num * kernel_size_aligned2; int8_t* output_result = output + kernel_num * output_xy; for(int col_line = (col_start & -4); col_line < (col_end & -4); col_line += 4) { int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a72_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, output_result + col_line, pmulti, output_xy, pq_shift, activation_min, activation_max); } if(col_end3) { int col_line = col_end & -4; int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a72_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + j) * output_xy + col_line; } *(output_line[0] + 0) = result[0]; *(output_line[1] + 0) = result[5]; *(output_line[2] + 0) = result[10]; *(output_line[3] + 0) = result[15]; if(col_end3 >= 2) { *(output_line[0] + 1) = result[4]; *(output_line[1] + 1) = result[1]; *(output_line[2] + 1) = result[14]; *(output_line[3] + 1) = result[11]; } if(col_end3 == 3) { *(output_line[0] + 2) = result[8]; *(output_line[1] + 2) = result[13]; *(output_line[2] + 2) = result[2]; *(output_line[3] + 2) = result[7]; } } } if(kernel_end3) { int kernel_num = kernel_end & -4; int* cur_biases = NULL; if(bias_term) { cur_biases = biases + kernel_num; } int result[16] = {0}; int8_t* output_line[4]; int* pmulti = multi + kernel_num; int* pq_shift = q_shift + kernel_num; int8_t* cur_kernel = kernel + kernel_num * kernel_size_aligned2; for(int col_line = (col_start & -4); col_line < (col_end & -4); col_line += 4) { int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a72_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + j) * output_xy + col_line; } *(output_line[0] + 0) = result[0]; *(output_line[0] + 1) = result[4]; *(output_line[0] + 2) = result[8]; *(output_line[0] + 3) = result[12]; if(kernel_end3 >= 2) { *(output_line[1] + 0) = result[5]; *(output_line[1] + 1) = result[1]; *(output_line[1] + 2) = result[13]; *(output_line[1] + 3) = result[9]; } if(kernel_end3 == 3) { *(output_line[2] + 0) = result[10]; *(output_line[2] + 1) = result[14]; *(output_line[2] + 2) = result[2]; *(output_line[2] + 3) = result[6]; } } if(col_end3) { int col_line = col_end & -4; int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a72_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + j) * output_xy + col_line; } *(output_line[0] + 0) = result[0]; if(col_end3 >= 2) *(output_line[0] + 1) = result[4]; if(col_end3 == 3) *(output_line[0] + 2) = result[8]; if(kernel_end3 >= 2) { *(output_line[1] + 0) = result[5]; if(col_end3 >= 2) *(output_line[1] + 1) = result[1]; if(col_end3 == 3) *(output_line[1] + 2) = result[13]; } if(kernel_end3 == 3) { *(output_line[2] + 0) = result[10]; if(col_end3 >= 2) *(output_line[2] + 1) = result[14]; if(col_end3 == 3) *(output_line[2] + 2) = result[2]; } } } return; } #else void i8gemm_4x4_a17_int8(int* biases, int8_t* input, int8_t* kernel, int kernel_size, int8_t* output, int* multi, int output_xy, int* shift, int activation_min, int activation_max); void i8gemm_4x8_a17_int8(int* biases, int8_t* input, int8_t* kernel, int kernel_size, int8_t* output, int* multi, int output_xy, int* shift, int activation_min, int activation_max); // col_start and col_end need to be 8 aligned kernel_start need to be 4 aligned static void i8gemm4x8(int8_t* col, int8_t* kernel, bool bias_term, int* biases, int8_t* output, int* multi, int kernel_size, int output_xy, int col_start, int col_end, int kernel_start, int kernel_end, int activation_min, int activation_max, int* q_shift, int num_thread, int cpu_affinity) { int col_end3 = col_end & 3; int kernel_size_aligned2 = (kernel_size + 1) & -2; #pragma omp parallel for num_threads(num_thread) for(int kernel_num = (kernel_start & -8); kernel_num < (kernel_end & -8); kernel_num += 8) { int* cur_biases = NULL; if(bias_term) { cur_biases = biases + kernel_num; } int result[32] = {0}; int8_t* output_line[4]; int* pmulti = multi + kernel_num; int* pq_shift = q_shift + kernel_num; int8_t* cur_kernel = kernel + kernel_num * kernel_size_aligned2; int8_t* output_result = output + kernel_num * output_xy; for(int col_line = (col_start & -4); col_line < (col_end & -4); col_line += 4) { int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x8_a17_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, output_result + col_line, pmulti, output_xy, pq_shift, activation_min, activation_max); } if(col_end3) { int col_line = col_end & -4; int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x8_a17_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int i = 0; i < 2; i++) { for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + i * 4 + j) * output_xy + col_line; } *(output_line[0] + 0) = result[i * 16 + 0]; *(output_line[1] + 0) = result[i * 16 + 5]; *(output_line[2] + 0) = result[i * 16 + 10]; *(output_line[3] + 0) = result[i * 16 + 15]; if(col_end3 >= 2) { *(output_line[0] + 1) = result[i * 16 + 4]; *(output_line[1] + 1) = result[i * 16 + 1]; *(output_line[2] + 1) = result[i * 16 + 14]; *(output_line[3] + 1) = result[i * 16 + 11]; } if(col_end3 == 3) { *(output_line[0] + 2) = result[i * 16 + 8]; *(output_line[1] + 2) = result[i * 16 + 13]; *(output_line[2] + 2) = result[i * 16 + 2]; *(output_line[3] + 2) = result[i * 16 + 7]; } } } } return; } // col_start and kernel_start need to be 4 aligned static void i8gemm4x4(int8_t* col, int8_t* kernel, bool bias_term, int* biases, int8_t* output, int* multi, int kernel_size, int output_xy, int col_start, int col_end, int kernel_start, int kernel_end, int activation_min, int activation_max, int* q_shift, int num_thread, int cpu_affinity) { int col_end3 = col_end & 3; int kernel_end3 = kernel_end & 3; int kernel_size_aligned2 = (kernel_size + 1) & -2; #pragma omp parallel for num_threads(num_thread) for(int kernel_num = (kernel_start & -4); kernel_num < (kernel_end & -4); kernel_num += 4) { int* cur_biases = NULL; if(bias_term) { cur_biases = biases + kernel_num; } int result[16] = {0}; int8_t* output_line[4]; int* pmulti = multi + kernel_num; int* pq_shift = q_shift + kernel_num; int8_t* cur_kernel = kernel + kernel_num * kernel_size_aligned2; int8_t* output_result = output + kernel_num * output_xy; for(int col_line = (col_start & -4); col_line < (col_end & -4); col_line += 4) { int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a17_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, output_result + col_line, pmulti, output_xy, pq_shift, activation_min, activation_max); } if(col_end3) { int col_line = col_end & -4; int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a17_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + j) * output_xy + col_line; } *(output_line[0] + 0) = result[0]; *(output_line[1] + 0) = result[5]; *(output_line[2] + 0) = result[10]; *(output_line[3] + 0) = result[15]; if(col_end3 >= 2) { *(output_line[0] + 1) = result[4]; *(output_line[1] + 1) = result[1]; *(output_line[2] + 1) = result[14]; *(output_line[3] + 1) = result[11]; } if(col_end3 == 3) { *(output_line[0] + 2) = result[8]; *(output_line[1] + 2) = result[13]; *(output_line[2] + 2) = result[2]; *(output_line[3] + 2) = result[7]; } } } if(kernel_end3) { int kernel_num = kernel_end & -4; int* cur_biases = NULL; if(bias_term) { cur_biases = biases + kernel_num; } int result[16] = {0}; int8_t* output_line[4]; int* pmulti = multi + kernel_num; int* pq_shift = q_shift + kernel_num; int8_t* cur_kernel = kernel + kernel_num * kernel_size_aligned2; for(int col_line = (col_start & -4); col_line < (col_end & -4); col_line += 4) { int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a17_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + j) * output_xy + col_line; } *(output_line[0] + 0) = result[0]; *(output_line[0] + 1) = result[4]; *(output_line[0] + 2) = result[8]; *(output_line[0] + 3) = result[12]; if(kernel_end3 >= 2) { *(output_line[1] + 0) = result[5]; *(output_line[1] + 1) = result[1]; *(output_line[1] + 2) = result[13]; *(output_line[1] + 3) = result[9]; } if(kernel_end3 == 3) { *(output_line[2] + 0) = result[10]; *(output_line[2] + 1) = result[14]; *(output_line[2] + 2) = result[2]; *(output_line[2] + 3) = result[6]; } } if(col_end3) { int col_line = col_end & -4; int8_t* cur_col = col + col_line * kernel_size_aligned2; i8gemm_4x4_a17_int8(cur_biases, cur_col, cur_kernel, kernel_size_aligned2, (int8_t*)result, pmulti, 0, pq_shift, activation_min, activation_max); for(int j = 0; j < 4; j++) { output_line[j] = output + (kernel_num + j) * output_xy + col_line; } *(output_line[0] + 0) = result[0]; if(col_end3 >= 2) *(output_line[0] + 1) = result[4]; if(col_end3 == 3) *(output_line[0] + 2) = result[8]; if(kernel_end3 >= 2) { *(output_line[1] + 0) = result[5]; if(col_end3 >= 2) *(output_line[1] + 1) = result[1]; if(col_end3 == 3) *(output_line[1] + 2) = result[13]; } if(kernel_end3 == 3) { *(output_line[2] + 0) = result[10]; if(col_end3 >= 2) *(output_line[2] + 1) = result[14]; if(col_end3 == 3) *(output_line[2] + 2) = result[2]; } } } return; } #endif /* * get the memory size for im2col + sgemm of kernel tensor interleave */ static int get_private_mem_size(struct tensor* filter, struct conv_param* param) { int group = param->group; int out_chan = filter->dims[0] / group; int out_chan_align4 = (out_chan + 3) / 4 * 4; int kernel_size = filter->dims[1] * filter->dims[2] * filter->dims[3]; int mem_size = kernel_size * filter->elem_size * out_chan_align4 * group + 128; // caution return mem_size; } int int8_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 int8_conv_hcl_set_shared_pack4_mem(struct conv_priv_info* priv_info, void* mem, int mem_size) { priv_info->external_im2col_pack4_mem = 0; priv_info->im2col_buffer_pack4 = NULL; priv_info->im2col_buffer_pack4_size = 0; return 0; } int int8_conv_hcl_get_shared_mem_size(struct tensor* input, struct tensor* output, struct conv_param* param) { int in_h = input->dims[2]; int in_w = input->dims[3]; int out_h = output->dims[2]; int out_w = output->dims[3]; int group = param->group; int input_chan = param->input_channel / group; int kernel_size = input_chan * param->kernel_h * param->kernel_w; int out_cstep = out_h * out_w; // channel cstep, output_h * output_w int elem_size = input->elem_size; // uint8/int8 is 1 byte, fp32 is 4 bytes out_cstep = (out_cstep + 3) / 4 * 4; int kernel_size_aligned2 = (kernel_size + 1) & -2; int mem_size = elem_size * kernel_size_aligned2 * out_cstep + 128; return mem_size; } void interleave_kernel_int8(int8_t* kernel, int8_t* kernel_int8, int kernel_chan, int kernel_size) { #ifdef __aarch64__ int8_t* cur_kernel[16]; int8_t* cur_kernel_int8 = kernel_int8; int i, j, k; // interleave 16 kernels for(i = 0; i < (kernel_chan & -16); i += 16) { for(j = 0; j < 16; j++) cur_kernel[j] = kernel + kernel_size * (i + j); for(j = 0; j < (kernel_size & -2); j += 2) for(k = 0; k < 16; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } if(kernel_size & 0x1) for(k = 0; k < 16; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } } // interleave 4 kernels for(i = (kernel_chan & -16); i < (kernel_chan & -4); i += 4) { for(j = 0; j < 4; j++) cur_kernel[j] = kernel + kernel_size * (i + j); for(j = 0; j < (kernel_size & -2); j += 2) for(k = 0; k < 4; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } if(kernel_size & 0x1) for(k = 0; k < 4; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } } // last 4 kernels if((kernel_chan & 0x3) != 0) { for(j = 0; j < 3; j++) cur_kernel[j] = kernel + kernel_size * (i + j); if((kernel_chan & 0x3) == 3) { for(j = 0; j < (kernel_size & -2); j += 2) { for(k = 0; k < 3; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } for(k = 0; k < 2; k++) *(cur_kernel_int8++) = 0; } if(kernel_size & 0x1) { for(k = 0; k < 3; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } for(k = 0; k < 2; k++) *(cur_kernel_int8++) = 0; } } else if((kernel_chan & 0x3) == 2) { for(j = 0; j < (kernel_size & -2); j += 2) { for(k = 0; k < 2; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } for(k = 0; k < 4; k++) *(cur_kernel_int8++) = 0; } if(kernel_size & 0x1) { for(k = 0; k < 2; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } for(k = 0; k < 4; k++) *(cur_kernel_int8++) = 0; } } else if((kernel_chan & 0x3) == 1) { for(j = 0; j < (kernel_size & -2); j += 2) { *(cur_kernel_int8++) = *(cur_kernel[0] + j); *(cur_kernel_int8++) = *(cur_kernel[0] + j + 1); for(k = 0; k < 6; k++) *(cur_kernel_int8++) = 0; } if(kernel_size & 0x1) { *(cur_kernel_int8++) = *(cur_kernel[0] + j); for(k = 0; k < 7; k++) *(cur_kernel_int8++) = 0; } } } #else int8_t* cur_kernel[8]; int8_t* cur_kernel_int8 = kernel_int8; int i, j, k; int kernel_chan3 = kernel_chan & 0x3; int kernel_size1 = kernel_size & 0x1; // interleave 8 kernels for(i = 0; i < (kernel_chan & -8); i += 8) { for(j = 0; j < 8; j++) cur_kernel[j] = kernel + kernel_size * (i + j); for(j = 0; j < (kernel_size & -2); j += 2) for(k = 0; k < 8; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } if(kernel_size1) for(k = 0; k < 8; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } } // interleave 4 kernels for(; i < (kernel_chan & -4); i += 4) { for(j = 0; j < 4; j++) cur_kernel[j] = kernel + kernel_size * (i + j); for(j = 0; j < (kernel_size & -2); j += 2) for(k = 0; k < 4; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } if(kernel_size1) for(k = 0; k < 4; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } } // last 4 kernels if(kernel_chan3) { for(j = 0; j < 3; j++) cur_kernel[j] = kernel + kernel_size * (i + j); if((kernel_chan3) == 3) { for(j = 0; j < (kernel_size & -2); j += 2) { for(k = 0; k < 3; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } for(k = 0; k < 2; k++) *(cur_kernel_int8++) = 0; } if(kernel_size1) { for(k = 0; k < 3; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } for(k = 0; k < 2; k++) *(cur_kernel_int8++) = 0; } } else if((kernel_chan3) == 2) { for(j = 0; j < (kernel_size & -2); j += 2) { for(k = 0; k < 2; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = *(cur_kernel[k] + j + 1); } for(k = 0; k < 4; k++) *(cur_kernel_int8++) = 0; } if(kernel_size1) { for(k = 0; k < 2; k++) { *(cur_kernel_int8++) = *(cur_kernel[k] + j); *(cur_kernel_int8++) = 0; } for(k = 0; k < 4; k++) *(cur_kernel_int8++) = 0; } } else { // kernel_chan & 0x3 == 1 for(j = 0; j < (kernel_size & -2); j += 2) { *(cur_kernel_int8++) = *(cur_kernel[0] + j); *(cur_kernel_int8++) = *(cur_kernel[0] + j + 1); for(k = 0; k < 6; k++) *(cur_kernel_int8++) = 0; } if(kernel_size1) { *(cur_kernel_int8++) = *(cur_kernel[0] + j); for(k = 0; k < 7; k++) *(cur_kernel_int8++) = 0; } } } #endif return; } /* kernel interleave */ static void interleave_int8(struct tensor* filter, struct conv_priv_info* priv_info, struct conv_param* param) { int group = param->group; int kernel_size = filter->dims[1] * filter->dims[2] * filter->dims[3]; int out_chan = filter->dims[0] / group; int out_chan_align4 = (out_chan + 3) / 4 * 4; int kernel_size_algin = kernel_size * out_chan_align4; int kernel_size_group = kernel_size * out_chan; int8_t* kernel = filter->data; int8_t* interleave_buf = priv_info->interleave_buffer; for (int g = 0; g < group; g++) { int8_t* cur_kernel = kernel + g * kernel_size_group; int8_t* cur_interleave = interleave_buf + g * kernel_size_algin; interleave_kernel_int8(cur_kernel, cur_interleave, out_chan, kernel_size); } } static void im2col_int8(int8_t* im, int8_t* col, int input_chan, int input_x, int input_y, int kernel_x, int kernel_y, int stride_x, int stride_y, int dilation_x, int dilation_y, int pad_x0, int pad_x1, int pad_y0, int pad_y1, int output_x, int output_y, int num_thread) { int col_start = 0; int col_end = output_x * output_y; int kernel_xy = kernel_x * kernel_y; int kernel_size = kernel_xy * input_chan; int kernel_size_aligned2 = (kernel_size + 1) & -2; int input_xy = input_x * input_y; int col_end3 = col_end & 0x3; int kernel_size1 = kernel_size & 0x1; int is_1x1 = (kernel_x == 1) && (kernel_y == 1) && (stride_x == 1) && (stride_y == 1); int is_3x3 = (kernel_x == 3) && (kernel_y == 3) && (dilation_x == 1) && (dilation_y == 1); bool is_pad0 = (pad_x0 == 0) && (pad_y0 == 0) && (pad_x1 == 0) && (pad_y1 == 0); #ifdef __aarch64__ // is 1x1 if(is_1x1) { int8_t* cur_col = col + col_start * kernel_size_aligned2; int col_cnt = (col_end & -4) - (col_start & -4); im2col_int8_1x1(( int8_t* )im + col_start, input_xy, cur_col, col_cnt, kernel_size); cur_col += col_cnt * kernel_size_aligned2; int col_i = col_end & -4; // final 4 input if(col_end3) { for(int kch = 0; kch < (kernel_size & -2); kch += 2) { for(int i = 0; i < 4; i++) { if((col_i + i) < col_end) { *cur_col++ = *(im + input_xy * (kch + 0) + col_i + i); *cur_col++ = *(im + input_xy * (kch + 1) + col_i + i); } else { *cur_col++ = 0; *cur_col++ = 0; } } } int kch = kernel_size & -2; if(kernel_size1) { for(int i = 0; i < 4; i++) { if((col_i + i) < col_end) { *cur_col++ = *(im + input_xy * (kch + 0) + col_i + i); *cur_col++ = 0; } else { *cur_col++ = 0; *cur_col++ = 0; } } } } } // 3x3 non dilation else if(is_3x3) { #pragma omp parallel for num_threads(num_thread) for(int col_i = (col_start & -4); col_i < (col_end & -4); col_i += 4) { int imx[4] = {0}; int imy[4] = {0}; int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; int8_t* cur_col = col + col_i * kernel_size_aligned2; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } if((cnt_y[0] == cnt_y[3]) && (is_pad0 || (cnt_y[0] > 0 && cnt_x[0] > 0 && cnt_y[0] < (output_y - 1) && cnt_x[3] < (output_x - 1)))) { int8_t* input_start = ( int8_t* )(im + imy_start[0] * input_x + imx_start[0]); im2col_int8_3x3(input_start, input_x, input_y, input_chan, cur_col, stride_x); cur_col += 4 * kernel_size_aligned2; } else { bool odd_line = false; int kchp = 0; int kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(int ky = 0; ky < 3; ky++) { if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky; if(imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + 1 + k; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } odd_line = false; } // even line 2n else { for(int i = 0; i < 4; i++) imy[i] = imy_start[i] + ky; for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + k; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } kchp = kch; kyp = ky; odd_line = true; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } } int col_i = col_end & -4; if(col_end3) { int imx[4] = {0}; int imy[4] = {0}; int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; int8_t* cur_col = col + col_i * kernel_size_aligned2; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } bool odd_line = false; int kchp = 0; int kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(int ky = 0; ky < 3; ky++) { // odd line 1 + 2n if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky; if((i < col_end3) && imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (1 + k); if((i < col_end3) && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } odd_line = false; } // even line 2n + 1 else { for(int i = 0; i < 4; i++) imy[i] = imy_start[i] + ky; for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + k; if(i < col_end3 && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } kchp = kch; kyp = ky; odd_line = true; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } } // general case for kernel size <=3 else if((kernel_x) < 4 && (kernel_y < 4)) { int kch[2], kx[2], ky[2], imx[4][2], imy[4][2]; int8_t* cur_col = col + col_start * kernel_size_aligned2; for(int col_i = (col_start & -4); col_i < (col_end & -4); col_i += 4) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } for(int col_j = 0; col_j < (kernel_size & -2); col_j += 2) { for(int k = 0; k < 2; k++) { kch[k] = (col_j + k) / kernel_xy; ky[k] = (col_j + k - kch[k] * kernel_xy) / kernel_x; kx[k] = (col_j + k - kch[k] * kernel_xy) - ky[k] * kernel_x; ky[k] = ky[k] * dilation_y; kx[k] = kx[k] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][k] = imx_start[i] + kx[k]; imy[i][k] = imy_start[i] + ky[k]; } } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { if(imx[i][k] >= 0 && imx[i][k] < input_x && imy[i][k] >= 0 && imy[i][k] < input_y) *cur_col++ = *(im + input_xy * kch[k] + input_x * imy[i][k] + imx[i][k]); else *cur_col++ = 0; } } } int col_j = kernel_size & -2; if(kernel_size1) { kch[0] = col_j / kernel_xy; ky[0] = (col_j - kch[0] * kernel_xy) / kernel_x; kx[0] = col_j - kch[0] * kernel_xy - ky[0] * kernel_x; ky[0] = ky[0] * dilation_y; kx[0] = kx[0] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][0] = imx_start[i] + kx[0]; imy[i][0] = imy_start[i] + ky[0]; if(imx[i][0] >= 0 && imx[i][0] < input_x && imy[i][0] >= 0 && imy[i][0] < input_y) *cur_col++ = *(im + input_xy * kch[0] + input_x * imy[i][0] + imx[i][0]); else *cur_col++ = 0; *cur_col++ = 0; } } } int col_i = col_end & -4; // final 4 input if(col_end3) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } for(int col_j = 0; col_j < (kernel_size & -2); col_j += 2) { for(int k = 0; k < 2; k++) { kch[k] = (col_j + k) / kernel_xy; ky[k] = (col_j + k - kch[k] * kernel_xy) / kernel_x; kx[k] = (col_j + k - kch[k] * kernel_xy) - ky[k] * kernel_x; ky[k] = ky[k] * dilation_y; kx[k] = kx[k] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][k] = imx_start[i] + kx[k]; imy[i][k] = imy_start[i] + ky[k]; } } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { if((col_i + i) < col_end && imx[i][k] >= 0 && imx[i][k] < input_x && imy[i][k] >= 0 && imy[i][k] < input_y) *cur_col++ = *(im + input_xy * kch[k] + input_x * imy[i][k] + imx[i][k]); else *cur_col++ = 0; } } } int col_j = kernel_size & -2; if(kernel_size1) { kch[0] = col_j / kernel_xy; ky[0] = (col_j - kch[0] * kernel_xy) / kernel_x; kx[0] = col_j - kch[0] * kernel_xy - ky[0] * kernel_x; ky[0] = ky[0] * dilation_y; kx[0] = kx[0] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][0] = imx_start[i] + kx[0]; imy[i][0] = imy_start[i] + ky[0]; if((col_i + i) < col_end && imx[i][0] >= 0 && imx[i][0] < input_x && imy[i][0] >= 0 && imy[i][0] < input_y) *cur_col++ = *(im + input_xy * kch[0] + input_x * imy[i][0] + imx[i][0]); else *cur_col++ = 0; *cur_col++ = 0; } } } } // general case for kernel size >=3 else { int kch, kx, ky, kchp, kyp, imx[4], imy[4] = {0}; int kernel_x1 = kernel_x & 0x1; int8_t* cur_col = col + col_start * kernel_size_aligned2; for(int col_i = (col_start & -4); col_i < (col_end & -4); col_i += 4) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } bool odd_line = false; kchp = 0; kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(ky = 0; ky < kernel_y; ky++) { // odd line 2 + 2n if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky * dilation_y; if(imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(kx = 1; kx < kernel_x; kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } odd_line = false; } // even line 2n else { for(int i = 0; i < 4; i++) imy[i] = imy_start[i] + ky * dilation_y; for(kx = 0; kx < (kernel_x - 1); kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } kchp = kch; kyp = ky; odd_line = kernel_x1 ? true : false; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } int col_i = col_end & -4; // final 4 input if(col_end3) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } bool odd_line = false; kchp = 0; kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(ky = 0; ky < kernel_y; ky++) { // odd line 1 + 2n if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky * dilation_y; if((i < col_end3) && imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(kx = 1; kx < kernel_x; kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if((i < col_end3) && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } odd_line = false; } // even line 2n + 1 else { for(int i = 0; i < 4; i++) imy[i] = imy_start[i] + ky * dilation_y; for(kx = 0; kx < (kernel_x - 1); kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if(i < col_end3 && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } kchp = kch; kyp = ky; odd_line = kernel_x1 ? true : false; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } } #else if(is_3x3) { int stride_x2 = stride_x * 2; int stride_x3 = stride_x * 3; // #pragma omp parallel for num_threads(num_thread) for(int col_i = (col_start & -4); col_i < (col_end & -4); col_i += 4) { int imx[4] = {0}; int imy[4] = {0}; int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; int8_t* cur_col = col + col_i * kernel_size_aligned2; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } if((cnt_y[0] == cnt_y[3]) && (is_pad0 || (cnt_y[0] > 0 && cnt_x[0] > 0 && cnt_y[0] < (output_y - 1) && cnt_x[3] < (output_x - 1)))) { int8_t* l00 = ( int8_t* )(im + imy_start[0] * input_x + imx_start[0]); int8_t* l01 = l00 + input_x; int8_t* l02 = l00 + input_x * 2; int8_t* l10 = l00 + input_xy; int8_t* l11 = l10 + input_x; int8_t* l12 = l10 + input_x * 2; for(int kch = 0; kch < (input_chan & -2); kch += 2) { cur_col[0] = l00[0]; cur_col[1] = l00[1]; cur_col[2] = l00[0 + stride_x]; cur_col[3] = l00[1 + stride_x]; cur_col[4] = l00[0 + stride_x2]; cur_col[5] = l00[1 + stride_x2]; cur_col[6] = l00[0 + stride_x3]; cur_col[7] = l00[1 + stride_x3]; cur_col[8] = l00[2]; cur_col[9] = l01[0]; cur_col[10] = l00[2 + stride_x]; cur_col[11] = l01[0 + stride_x]; cur_col[12] = l00[2 + stride_x2]; cur_col[13] = l01[0 + stride_x2]; cur_col[14] = l00[2 + stride_x3]; cur_col[15] = l01[0 + stride_x3]; cur_col[16] = l01[1]; cur_col[17] = l01[2]; cur_col[18] = l01[1 + stride_x]; cur_col[19] = l01[2 + stride_x]; cur_col[20] = l01[1 + stride_x2]; cur_col[21] = l01[2 + stride_x2]; cur_col[22] = l01[1 + stride_x3]; cur_col[23] = l01[2 + stride_x3]; cur_col[24] = l02[0]; cur_col[25] = l02[1]; cur_col[26] = l02[0 + stride_x]; cur_col[27] = l02[1 + stride_x]; cur_col[28] = l02[0 + stride_x2]; cur_col[29] = l02[1 + stride_x2]; cur_col[30] = l02[0 + stride_x3]; cur_col[31] = l02[1 + stride_x3]; cur_col[32] = l02[2]; cur_col[33] = l10[0]; cur_col[34] = l02[2 + stride_x]; cur_col[35] = l10[0 + stride_x]; cur_col[36] = l02[2 + stride_x2]; cur_col[37] = l10[0 + stride_x2]; cur_col[38] = l02[2 + stride_x3]; cur_col[39] = l10[0 + stride_x3]; cur_col[40] = l10[1]; cur_col[41] = l10[2]; cur_col[42] = l10[1 + stride_x]; cur_col[43] = l10[2 + stride_x]; cur_col[44] = l10[1 + stride_x2]; cur_col[45] = l10[2 + stride_x2]; cur_col[46] = l10[1 + stride_x3]; cur_col[47] = l10[2 + stride_x3]; cur_col[48] = l11[0]; cur_col[49] = l11[1]; cur_col[50] = l11[0 + stride_x]; cur_col[51] = l11[1 + stride_x]; cur_col[52] = l11[0 + stride_x2]; cur_col[53] = l11[1 + stride_x2]; cur_col[54] = l11[0 + stride_x3]; cur_col[55] = l11[1 + stride_x3]; cur_col[56] = l11[2]; cur_col[57] = l12[0]; cur_col[58] = l11[2 + stride_x]; cur_col[59] = l12[0 + stride_x]; cur_col[60] = l11[2 + stride_x2]; cur_col[61] = l12[0 + stride_x2]; cur_col[62] = l11[2 + stride_x3]; cur_col[63] = l12[0 + stride_x3]; cur_col[64] = l12[1]; cur_col[65] = l12[2]; cur_col[66] = l12[1 + stride_x]; cur_col[67] = l12[2 + stride_x]; cur_col[68] = l12[1 + stride_x2]; cur_col[69] = l12[2 + stride_x2]; cur_col[70] = l12[1 + stride_x3]; cur_col[71] = l12[2 + stride_x3]; cur_col += 72; l00 += input_xy * 2; l01 += input_xy * 2; l02 += input_xy * 2; l10 += input_xy * 2; l11 += input_xy * 2; l12 += input_xy * 2; } if(input_chan & 0x1) { cur_col[0] = l00[0]; cur_col[1] = l00[1]; cur_col[2] = l00[0 + stride_x]; cur_col[3] = l00[1 + stride_x]; cur_col[4] = l00[0 + stride_x2]; cur_col[5] = l00[1 + stride_x2]; cur_col[6] = l00[0 + stride_x3]; cur_col[7] = l00[1 + stride_x3]; cur_col[8] = l00[2]; cur_col[9] = l01[0]; cur_col[10] = l00[2 + stride_x]; cur_col[11] = l01[0 + stride_x]; cur_col[12] = l00[2 + stride_x2]; cur_col[13] = l01[0 + stride_x2]; cur_col[14] = l00[2 + stride_x3]; cur_col[15] = l01[0 + stride_x3]; cur_col[16] = l01[1]; cur_col[17] = l01[2]; cur_col[18] = l01[1 + stride_x]; cur_col[19] = l01[2 + stride_x]; cur_col[20] = l01[1 + stride_x2]; cur_col[21] = l01[2 + stride_x2]; cur_col[22] = l01[1 + stride_x3]; cur_col[23] = l01[2 + stride_x3]; cur_col[24] = l02[0]; cur_col[25] = l02[1]; cur_col[26] = l02[0 + stride_x]; cur_col[27] = l02[1 + stride_x]; cur_col[28] = l02[0 + stride_x2]; cur_col[29] = l02[1 + stride_x2]; cur_col[30] = l02[0 + stride_x3]; cur_col[31] = l02[1 + stride_x3]; cur_col[32] = l02[2]; cur_col[33] = 0; cur_col[34] = l02[2 + stride_x]; cur_col[35] = 0; cur_col[36] = l02[2 + stride_x2]; cur_col[37] = 0; cur_col[38] = l02[2 + stride_x3]; cur_col[39] = 0; } } else { bool odd_line = false; int kchp = 0; int kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(int ky = 0; ky < 3; ky++) { if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky; if(imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + 1 + k; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } odd_line = false; } // even line 2n else { for(int i = 0; i < 4; i++) imy[i] = imy_start[i] + ky; for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + k; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } kchp = kch; kyp = ky; odd_line = true; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } } int col_i = col_end & -4; if(col_end3) { int imx[4] = {0}; int imy[4] = {0}; int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; int8_t* cur_col = col + col_i * kernel_size_aligned2; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } bool odd_line = false; int kchp = 0; int kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(int ky = 0; ky < 3; ky++) { // odd line 1 + 2n if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky; if((i < col_end3) && imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (1 + k); if((i < col_end3) && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } odd_line = false; } // even line 2n + 1 else { for(int i = 0; i < 4; i++) imy[i] = imy_start[i] + ky; for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + k; if(i < col_end3 && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } kchp = kch; kyp = ky; odd_line = true; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp; imx[i] = imx_start[i] + 2; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } } // general case for kernel size <=3 else if((kernel_x) < 4 && (kernel_y < 4)) { int kch[2], kx[2], ky[2], imx[4][2], imy[4][2]; for(int col_i = (col_start & -4); col_i < (col_end & -4); col_i += 4) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; int8_t* cur_col = col + col_i * kernel_size_aligned2; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } for(int col_j = 0; col_j < (kernel_size & -2); col_j += 2) { for(int k = 0; k < 2; k++) { kch[k] = (col_j + k) / kernel_xy; ky[k] = (col_j + k - kch[k] * kernel_xy) / kernel_x; kx[k] = (col_j + k - kch[k] * kernel_xy) - ky[k] * kernel_x; ky[k] = ky[k] * dilation_y; kx[k] = kx[k] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][k] = imx_start[i] + kx[k]; imy[i][k] = imy_start[i] + ky[k]; } } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { if(imx[i][k] >= 0 && imx[i][k] < input_x && imy[i][k] >= 0 && imy[i][k] < input_y) *cur_col++ = *(im + input_xy * kch[k] + input_x * imy[i][k] + imx[i][k]); else *cur_col++ = 0; } } } int col_j = kernel_size & -2; if(kernel_size1) { kch[0] = col_j / kernel_xy; ky[0] = (col_j - kch[0] * kernel_xy) / kernel_x; kx[0] = col_j - kch[0] * kernel_xy - ky[0] * kernel_x; ky[0] = ky[0] * dilation_y; kx[0] = kx[0] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][0] = imx_start[i] + kx[0]; imy[i][0] = imy_start[i] + ky[0]; if(imx[i][0] >= 0 && imx[i][0] < input_x && imy[i][0] >= 0 && imy[i][0] < input_y) *cur_col++ = *(im + input_xy * kch[0] + input_x * imy[i][0] + imx[i][0]); else *cur_col++ = 0; *cur_col++ = 0; } } } int col_i = col_end & -4; // final 4 input if(col_end3) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; int8_t* cur_col = col + col_i * kernel_size_aligned2; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } for(int col_j = 0; col_j < (kernel_size & -2); col_j += 2) { for(int k = 0; k < 2; k++) { kch[k] = (col_j + k) / kernel_xy; ky[k] = (col_j + k - kch[k] * kernel_xy) / kernel_x; kx[k] = (col_j + k - kch[k] * kernel_xy) - ky[k] * kernel_x; ky[k] = ky[k] * dilation_y; kx[k] = kx[k] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][k] = imx_start[i] + kx[k]; imy[i][k] = imy_start[i] + ky[k]; } } for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { if((col_i + i) < col_end && imx[i][k] >= 0 && imx[i][k] < input_x && imy[i][k] >= 0 && imy[i][k] < input_y) *cur_col++ = *(im + input_xy * kch[k] + input_x * imy[i][k] + imx[i][k]); else *cur_col++ = 0; } } } int col_j = kernel_size & -2; if(kernel_size1) { kch[0] = col_j / kernel_xy; ky[0] = (col_j - kch[0] * kernel_xy) / kernel_x; kx[0] = col_j - kch[0] * kernel_xy - ky[0] * kernel_x; ky[0] = ky[0] * dilation_y; kx[0] = kx[0] * dilation_x; for(int i = 0; i < 4; i++) { imx[i][0] = imx_start[i] + kx[0]; imy[i][0] = imy_start[i] + ky[0]; if((col_i + i) < col_end && imx[i][0] >= 0 && imx[i][0] < input_x && imy[i][0] >= 0 && imy[i][0] < input_y) *cur_col++ = *(im + input_xy * kch[0] + input_x * imy[i][0] + imx[i][0]); else *cur_col++ = 0; *cur_col++ = 0; } } } } // general case for kernel size >=3 else { int kch, kx, ky, kchp, kyp, imx[4], imy[4]; int kernel_x1 = kernel_x & 0x1; int8_t* cur_col = col + col_start * kernel_size_aligned2; for(int col_i = (col_start & -4); col_i < (col_end & -4); col_i += 4) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } bool odd_line = false; kchp = 0; kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(int ky = 0; ky < kernel_y; ky++) { // odd line 2 + 2n if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky * dilation_y; if(imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(int kx = 1; kx < kernel_x; kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } odd_line = false; } // even line 2n else { for(int i = 0; i < 4; i++) imy[i] = imy_start[i] + ky * dilation_y; for(int kx = 0; kx < (kernel_x - 1); kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if(imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } kchp = kch; kyp = ky; odd_line = kernel_x1 ? true : false; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if(imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } int col_i = col_end & -4; // final 4 input if(col_end3) { int cnt_x[4] = {0}; int cnt_y[4] = {0}; int imx_start[4] = {0}; int imy_start[4] = {0}; for(int i = 0; i < 4; i++) { cnt_y[i] = (col_i + i) / output_x; cnt_x[i] = col_i + i - cnt_y[i] * output_x; imx_start[i] = cnt_x[i] * stride_x - pad_x0; imy_start[i] = cnt_y[i] * stride_y - pad_y0; } bool odd_line = false; kchp = 0; kyp = 0; for(int kch = 0; kch < input_chan; kch++) { for(int ky = 0; ky < kernel_y; ky++) { // odd line 1 + 2n if(odd_line) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; imy[i] = imy_start[i] + ky * dilation_y; if((i < col_end3) && imx_start[i] >= 0 && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx_start[i]); else *cur_col++ = 0; } for(int kx = 1; kx < kernel_x; kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if((i < col_end3) && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } odd_line = false; } // even line 2n + 1 else { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + ky * dilation_y; } for(int kx = 0; kx < (kernel_x - 1); kx += 2) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 2; k++) { imx[i] = imx_start[i] + (kx + k) * dilation_x; if(i < col_end3 && imx[i] >= 0 && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kch + input_x * imy[i] + imx[i]); else *cur_col++ = 0; } } } kchp = kch; kyp = ky; odd_line = kernel_x1 ? true : false; } } } if(kernel_size1) { for(int i = 0; i < 4; i++) { imy[i] = imy_start[i] + kyp * dilation_y; imx[i] = imx_start[i] + (kernel_x - 1) * dilation_x; if((i < col_end3) && imx[i] < input_x && imy[i] >= 0 && imy[i] < input_y) *cur_col++ = *(im + input_xy * kchp + input_x * imy[i] + imx[i]); else *cur_col++ = 0; *cur_col++ = 0; } } } } #endif return; } int int8_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_c = input_tensor->dims[1]; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int out_c = output_tensor->dims[1]; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; /* alloc mem of im2col */ if (!priv_info->external_im2col_mem) { int mem_size = int8_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; } /* alloc mem of kernel interleave */ if (!priv_info->external_interleave_mem) { int mem_size = get_private_mem_size(filter_tensor, param); void* mem = sys_malloc(mem_size); priv_info->interleave_buffer = mem; priv_info->interleave_buffer_size = mem_size; } /* kernel interleave */ interleave_int8(filter_tensor, priv_info, param); priv_info->multi = (int*)sys_malloc(out_c * sizeof(int)); priv_info->q_shift = (int*)sys_malloc(out_c * sizeof(int)); float input_scale = input_tensor->scale; float* kernel_scales = filter_tensor->scale_list; float output_scale = output_tensor->scale; priv_info->activation_min = -127; priv_info->activation_max = 127; /* set activation */ if(param->activation >= 0) { priv_info->activation_min = 0; if(param->activation == 1) priv_info->activation_max = round(1.0 / output_scale); if(param->activation == 6) priv_info->activation_max = round(6.0 / output_scale); if(priv_info->activation_max > 127) priv_info->activation_max = 127; } for(int i=0; i<out_c; i++) { float kernel_scale = kernel_scales[i]; float scale = input_scale * kernel_scale / output_scale; int shift; float q = frexp(scale, &shift); int fix_q = round(q * (1ll << 31)); // TLOG_ERR("prerun: %f,%lld,%d,%d, %lld\n",q, fix_q, multi, q_shift, 1ll<<31); if(fix_q == (1l << 31)) { fix_q /= 2; shift++; } priv_info->multi[i] = (int)fix_q; priv_info->q_shift[i] = (int)shift; } return 0; } int int8_conv_hcl_postrun(struct conv_priv_info* priv_info) { if (!priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = 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->multi) { sys_free(priv_info->multi); priv_info->multi = NULL; } if (priv_info->q_shift) { sys_free(priv_info->q_shift); priv_info->q_shift = NULL; } return 0; } int int8_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) { /* param */ int group = param->group; 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 pad_h0 = param->pad_h0; int pad_h1 = param->pad_h1; int pad_w0 = param->pad_w0; int pad_w1 = param->pad_w1; int act_type = param->activation; int batch = input_tensor->dims[0]; int in_c = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int input_size = in_c * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int input_image_size = input_tensor->dims[1] * input_tensor->dims[2] * input_tensor->dims[3]; int out_c = output_tensor->dims[1] / group; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; int out_hw = out_h * out_w; int output_size = out_c * out_h * out_w; int out_c_align = ((out_c + 3) & -4); int output_image_size = output_tensor->dims[1] * output_tensor->dims[2] * output_tensor->dims[3]; int activation_min = priv_info->activation_min; int activation_max = priv_info->activation_max; /* buffer addr */ int8_t* input_buf = ( int8_t* )input_tensor->data; int8_t* output_buf = ( int8_t* )output_tensor->data; int32_t* biases_buf = NULL; bool have_biases = false; if (bias_tensor != NULL) { biases_buf = (int32_t*)bias_tensor->data; have_biases = true; } int8_t* col_buf = ( int8_t* )priv_info->im2col_buffer; int8_t* interleave_buf = ( int8_t* )priv_info->interleave_buffer; /* block size split parameter */ int L2_CACHE_SIZE = (cpu_affinity == TENGINE_CLUSTER_LITTLE)? 512 * 1024 : 1024 * 1024; int kernel_size_l1 = kernel_size; #ifdef __aarch64__ int col_cnt_l2 = L2_CACHE_SIZE * 3 / kernel_size_l1 / 4; #else int col_cnt_l2 = L2_CACHE_SIZE / 4 / kernel_size_l1 * 3 / 4; #endif col_cnt_l2 = col_cnt_l2 > 4 ? (col_cnt_l2 & -4) : 4; for (int n = 0; n < batch; n++) // batch size { int8_t* input = input_buf + n * input_size * group; int8_t* output = output_buf + n * output_size * group; for (int g = 0; g < group; g++) { int8_t* cur_input = input + g * input_size; im2col_int8(cur_input, col_buf, in_c, in_w, in_h, kernel_w, kernel_h, stride_w, stride_h, dilation_w, dilation_h, pad_w0, pad_w1, pad_h0, pad_h1, out_w, out_h, num_thread); int kernel_size_aligned2 = (kernel_size + 1) & -2; int output_chan_aligned4 = (out_c + 3) & -4; int8_t* kernel_g = interleave_buf + g * kernel_size_aligned2 * output_chan_aligned4; int8_t* output_g = output + g * output_size; int* bias_g = have_biases ? (biases_buf + g * out_c) : NULL; int* multi_g = priv_info->multi + g * out_c; int* q_shift_g = priv_info->q_shift + g * out_c; // for input block of L2 cache size for(int col_i = 0; col_i < out_hw; col_i += col_cnt_l2) { int col_start = col_i; int col_end = col_i + col_cnt_l2; col_end = col_end > out_hw ? out_hw : col_end; #ifdef __aarch64__ i8gemm4x16(col_buf, kernel_g, have_biases, bias_g, output_g, multi_g, kernel_size, out_hw, col_start, col_end, 0, out_c & -16, activation_min, activation_max, q_shift_g, num_thread, cpu_affinity); if(out_c & 0xf) i8gemm4x4(col_buf, kernel_g, have_biases, bias_g, output_g, multi_g, kernel_size, out_hw, col_start, col_end, out_c & -16, out_c, activation_min, activation_max, q_shift_g, num_thread, cpu_affinity); #else i8gemm4x8(col_buf, kernel_g, have_biases, bias_g, output_g, multi_g, kernel_size, out_hw, col_start, col_end, 0, out_c & -8, activation_min, activation_max, q_shift_g, num_thread, cpu_affinity); if(out_c & 0x7) i8gemm4x4(col_buf, kernel_g, have_biases, bias_g, output_g, multi_g, kernel_size, out_hw, col_start, col_end, out_c & -8, out_c, activation_min, activation_max, q_shift_g, num_thread, cpu_affinity); #endif } // col_cont } } return 0; }
test_deflate.h
#if UFBXT_IMPL static ptrdiff_t ufbxt_inflate_no_fuzz(void *dst, size_t dst_size, const void *src, size_t src_size) { ufbx_inflate_retain retain; retain.initialized = false; ufbx_inflate_input input = { 0 }; input.data = src; input.data_size = src_size; input.total_size = src_size; return ufbx_inflate(dst, dst_size, &input, &retain); } static ptrdiff_t ufbxt_inflate(void *dst, size_t dst_size, const void *src, size_t src_size) { if (ufbxt_begin_fuzz()) { ufbx_inflate_input input = { 0 }; input.data = src; input.data_size = src_size; input.total_size = src_size; int i; uint8_t *data_copy[256] = { 0 }; #pragma omp parallel for schedule(static, 16) for (i = 0; i < (int)src_size; i++) { ufbx_inflate_retain retain; retain.initialized = false; if (omp_get_thread_num() == 0) { if (i % 16 == 0) { fprintf(stderr, "\rFuzzing %d/%d", i, (int)src_size); fflush(stderr); } } uint8_t **p_data_copy = &data_copy[omp_get_thread_num()]; if (*p_data_copy == NULL) { *p_data_copy = malloc(src_size); memcpy(*p_data_copy, src, src_size); } uint8_t *data_u8 = *p_data_copy; size_t step = i * 10; uint8_t original = data_u8[i]; if (src_size < 256) { // Small input: Try all possible byte values for (uint32_t byte = 0; byte < 0x100; byte++) { data_u8[i] = (uint8_t)byte; ufbx_inflate(dst, dst_size, &input, &retain); } } else { // Large input: Try +1, -1, 0, 0xff data_u8[i] = original + 1; ufbx_inflate(dst, dst_size, &input, &retain); data_u8[i] = original - 1; ufbx_inflate(dst, dst_size, &input, &retain); if (original != 0) { data_u8[i] = 0; ufbx_inflate(dst, dst_size, &input, &retain); } if (original != 0xff) { data_u8[i] = 0xff; ufbx_inflate(dst, dst_size, &input, &retain); } } data_u8[i] = original; } for (size_t i = 0; i < ufbxt_arraycount(data_copy); i++) { free(data_copy[i]); } fprintf(stderr, "\rFuzzing %d/%d\n", (int)src_size, (int)src_size); } return ufbxt_inflate_no_fuzz(dst, dst_size, src, src_size); } #endif UFBXT_TEST(deflate_empty) #if UFBXT_IMPL { char src[1], dst[1]; ptrdiff_t res = ufbxt_inflate(dst, 1, src, 0); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res != 0); } #endif UFBXT_TEST(deflate_simple) #if UFBXT_IMPL { char src[] = "\x78\x9c\x01\x06\x00\xf9\xffHello!\x07\xa2\x02\x16"; char dst[6]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 6); ufbxt_assert(!memcmp(dst, "Hello!", 6)); } #endif UFBXT_TEST(deflate_simple_chunks) #if UFBXT_IMPL { char src[] = "\x78\x9c\x00\x06\x00\xf9\xffHello \x01\x06\x00\xf9\xffworld!\x1d\x09\x04\x5e"; char dst[12]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 12); ufbxt_assert(!memcmp(dst, "Hello world!", 12)); } #endif UFBXT_TEST(deflate_static) #if UFBXT_IMPL { char src[] = "x\xda\xf3H\xcd\xc9\xc9W(\xcf/\xcaIQ\x04\x00\x1d\t\x04^"; char dst[12]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 12); ufbxt_assert(!memcmp(dst, "Hello world!", 12)); } #endif UFBXT_TEST(deflate_static_match) #if UFBXT_IMPL { char src[] = "x\xda\xf3H\xcd\xc9\xc9W\xf0\x00\x91\x8a\x00\x1b\xbb\x04*"; char dst[12]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 12); ufbxt_assert(!memcmp(dst, "Hello Hello!", 12)); } #endif UFBXT_TEST(deflate_static_rle) #if UFBXT_IMPL { char src[] = "x\xdastD\x00\x00\x13\xda\x03\r"; char dst[12]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 12); ufbxt_assert(!memcmp(dst, "AAAAAAAAAAAA", 12)); } #endif UFBXT_TEST(deflate_dynamic) #if UFBXT_IMPL { char src[] = "\x78\x9c\x1d\xc4\x31\x0d\x00\x00\x0c\x02\x41\x2b\xad" "\x1b\x8c\xb0\x7d\x82\xff\x8d\x84\xe5\x64\xc8\xcd\x2f\x1b\xbb\x04\x2a"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 12); ufbxt_assert(!memcmp(dst, "Hello Hello!", 12)); } #endif UFBXT_TEST(deflate_dynamic_no_match) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\x80\x41\x09\x00\x00\x08\x03\xab\x68\x1b\x1b\x58\x40\x7f\x07\x83\xf5" "\x7f\x8c\x79\x50\xad\xcc\x75\x00\x1c\x49\x04\x3e"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 12); ufbxt_assert(!memcmp(dst, "Hello World!", 12)); } #endif UFBXT_TEST(deflate_dynamic_rle) #if UFBXT_IMPL { char src[] = "\x78\x9c\x5d\xc0\xb1\x00\x00\x00\x00\x80\x30\xb6\xfc\xa5\xfa\xb7\x34\x26\xea\x04" "\x52"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 17); ufbxt_assert(!memcmp(dst, "AAAAAAAAAAAAAAAAA", 17)); } #endif UFBXT_TEST(deflate_repeat_length) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\x00\x05\x0d\x00\x20\x2c\x1b\xee\x0e\xb7" "\xfe\x41\x98\xd2\xc6\x3a\x1f\x62\xca\xa5\xb6\x3e\xe6\xda\xe7\x3e\x40" "\x62\x11\x26\x84\x77\xcf\x5e\x73\xf4\x56\x4b\x4e\x31\x78\x67\x8d\x56\x1f\xa1\x6e\x0f\xbf"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 52); ufbxt_assert(!memcmp(dst, "ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFEDCBA", 52)); } #endif UFBXT_TEST(deflate_huff_lengths) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\xe0\xc1\x95\x65\x59\x96\x65\xd9\xb1\x84" "\xca\x70\x53\xf9\xaf\x79\xcf\x5e\x93\x7f\x96\x30\xfe\x7f\xff\xdf\xff" "\xfb\xbf\xff\xfd\xf7\xef\xef\xf7\xbd\x5b\xfe\xff\x19\x28\x03\x5d"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 15); ufbxt_assert(!memcmp(dst, "0123456789ABCDE", 15)); } #endif UFBXT_TEST(deflate_multi_part_matches) #if UFBXT_IMPL { char src[] = "\x78\x9c\x00\x04\x00\xfb\xff\x54\x65\x73\x74\x52\x08" "\x48\x2c\x02\x10\x00\x06\x32\x00\x00\x00\x0c\x52\x39\xcc\x45\x72\xc8" "\x7f\xcd\x9d\x00\x08\x00\xf7\xff\x74\x61\x20\x44\x61\x74\x61\x20\x02" "\x8b\x01\x38\x8c\x43\x12\x00\x00\x00\x00\x40\xff\x5f\x0b\x36\x8b\xc0" "\x12\x80\xf9\xa5\x96\x23\x84\x00\x8e\x36\x10\x41"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == 48); ufbxt_assert(!memcmp(dst, "Test Part Data Data Test Data Part New Test Data", 48)); } #endif UFBXT_TEST(deflate_uncompressed_bounds) #if UFBXT_IMPL { char src[] = "\x78\x9c\x01\x06\x00\xf9\xffHello!"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -9); } #endif UFBXT_TEST(deflate_fail_cfm) #if UFBXT_IMPL { char src[] = "\x79\x9c"; char dst[4]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -1); } #endif UFBXT_TEST(deflate_fail_fdict) #if UFBXT_IMPL { char src[] = "\x78\xbc"; char dst[4]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -2); } #endif UFBXT_TEST(deflate_fail_fcheck) #if UFBXT_IMPL { char src[] = "\x78\0x9d"; char dst[4]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -3); } #endif UFBXT_TEST(deflate_fail_nlen) #if UFBXT_IMPL { char src[] = "\x78\x9c\x01\x06\x00\xf8\xffHello!\x07\xa2\x02\x16"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -4); } #endif UFBXT_TEST(deflate_fail_dst_overflow) #if UFBXT_IMPL { char src[] = "\x78\x9c\x01\x06\x00\xf9\xffHello!\x07\xa2\x02\x16"; char dst[5]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -6); } #endif UFBXT_TEST(deflate_fail_src_overflow) #if UFBXT_IMPL { char src[] = "\x78\x9c\x01\x06\x00\xf9\xffHello"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res < 0); } #endif UFBXT_TEST(deflate_fail_bad_block) #if UFBXT_IMPL { char src[] = "\x78\x9c\x07\x08\x00\xf8\xff"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -7); } #endif UFBXT_TEST(deflate_fail_bad_truncated_checksum) #if UFBXT_IMPL { char src[] = "\x78\x9c\x01\x06\x00\xf9\xffHello!\x07\xa2\x02"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -9); } #endif UFBXT_TEST(deflate_fail_bad_checksum) #if UFBXT_IMPL { char src[] = "\x78\x9c\x01\x06\x00\xf9\xffHello!\x07\xa2\x02\xff"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -9); } #endif UFBXT_TEST(deflate_fail_codelen_16_overflow) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\x80\x85\x0c\x00\x00\x00\xc0\xfc\xa1\x5f\xc3\x06\x05\xf5\x02\xfb"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -18); } #endif UFBXT_TEST(deflate_fail_codelen_17_overflow) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\xc0\xb1\x0c\x00\x00\x00\x00\x20\x7f\xe7\xae\x26\x00\xfd\x00\xfd"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -19); } #endif UFBXT_TEST(deflate_fail_codelen_18_overflow) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\xc0\x81\x08\x00\x00\x00\x00\x20\x7f\xdf\x09\x4e\x00\xf5\x00\xf5"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -20); } #endif UFBXT_TEST(deflate_fail_codelen_overfull) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\x80\x31\x11\x01\x00\x00\x01\xc3\xa9\xe2\x37\x47\xff\xcd\x69\x26\xf4\x0a\x7a\x02\xbb"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -14); } #endif UFBXT_TEST(deflate_fail_codelen_underfull) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\x80\x31\x11\x00\x00\x00\x41\xc3\xa9\xe2\x37\x47\xff\xcd\x69\x26\xf4\x0a\x7a\x02\xbb"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -15); } #endif UFBXT_TEST(deflate_fail_litlen_bad_huffman) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\x40\x81\x09\x00\x20\x08\x7b\xa5\x0f\x7a\xa4\x27\xa2" "\x46\x0a\xa2\xa0\xfb\x1f\x11\x23\xea\xf8\x16\xc4\xa7\xae\x9b\x0f\x3d\x4e\xe4\x07\x8d"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -17); } #endif UFBXT_TEST(deflate_fail_distance_bad_huffman) #if UFBXT_IMPL { char src[] = "\x78\x9c\x1d\xc5\x31\x0d\x00\x00\x0c\x02\x41\x2b\x55\x80\x8a\x9a" "\x61\x06\xff\x21\xf9\xe5\xfe\x9d\x1e\x48\x3c\x31\xba\x05\x79"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -23); } #endif UFBXT_TEST(deflate_fail_bad_distance) #if UFBXT_IMPL { char src[] = "\x78\x9c\x73\xc9\x2c\x2e\x51\x00\x3d\x00\x0f\xd7\x03\x49"; char dst[64]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -11); } #endif UFBXT_TEST(deflate_fail_literal_overflow) #if UFBXT_IMPL { char src[] = "x\xda\xf3H\xcd\xc9\xc9W(\xcf/\xcaIQ\x04\x00\x1d\t\x04^"; char dst[8]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -10); } #endif UFBXT_TEST(deflate_fail_match_overflow) #if UFBXT_IMPL { char src[] = "x\xda\xf3H\xcd\xc9\xc9W\xf0\x00\x91\x8a\x00\x1b\xbb\x04*"; char dst[8]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -12); } #endif UFBXT_TEST(deflate_fail_bad_distance_bit) #if UFBXT_IMPL { char src[] = "\x78\x9c\x0d\xc3\x41\x09\x00\x00\x00\xc2\xc0\x2a\x56\x13" "\x6c\x60\x7f\xd8\x1e\xd7\x2f\x06\x0a\x41\x02\x91"; char dst[8]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -11); } #endif UFBXT_TEST(deflate_fail_bad_distance_empty) #if UFBXT_IMPL { char src[] = "\x78\x9c\x0d\xc4\x41\x09\x00\x00\x00\xc2\xc0\x2a\x56\x13\x6c\x60\x7f\xd8\x1e\xd0" "\x2f\x02\x0a\x41\x02\x91"; char dst[8]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -11); } #endif UFBXT_TEST(deflate_fail_bad_lit_length) #if UFBXT_IMPL { char src[] = "\x78\x9c\x05\xc0\x81\x08\x00\x00\x00\x00\x20\x7f\xeb\x0b\x00\x00\x00\x01"; char dst[8]; ptrdiff_t res = ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == -13); } #endif #if UFBXT_IMPL static uint32_t fnv1a(const void *data, size_t size) { const char *ptr = data, *end = ptr + size; uint32_t h = 0x811c9dc5u; for (; ptr != end; ptr++) { h = (h ^ (uint8_t)*ptr) * 0x01000193; } return h; } #endif UFBXT_TEST(deflate_bit_flip) #if UFBXT_IMPL { char src[] = "\x78\x9c\x00\x04\x00\xfb\xff\x54\x65\x73\x74\x52\x08" "\x48\x2c\x02\x10\x00\x06\x32\x00\x00\x00\x0c\x52\x39\xcc\x45\x72\xc8" "\x7f\xcd\x9d\x00\x08\x00\xf7\xff\x74\x61\x20\x44\x61\x74\x61\x20\x02" "\x8b\x01\x38\x8c\x43\x12\x00\x00\x00\x00\x40\xff\x5f\x0b\x36\x8b\xc0" "\x12\x80\xf9\xa5\x96\x23\x84\x00\x8e\x36\x10\x41"; char dst[64]; int num_res[64] = { 0 }; for (size_t byte_ix = 0; byte_ix < sizeof(src) - 1; byte_ix++) { for (size_t bit_ix = 0; bit_ix < 8; bit_ix++) { size_t bit = (size_t)1 << bit_ix; ufbxt_hintf("byte_ix==%u && bit_ix==%u", (unsigned)byte_ix, (unsigned)bit_ix); src[byte_ix] ^= bit; ptrdiff_t res = ufbxt_inflate_no_fuzz(dst, sizeof(dst), src, sizeof(src) - 1); src[byte_ix] ^= bit; res = -res; if (res < 0) res = 0; if (res > ufbxt_arraycount(num_res)) res = ufbxt_arraycount(num_res); num_res[res]++; } } char line[128], *ptr = line, *end = line + sizeof(line); for (size_t i = 0; i < ufbxt_arraycount(num_res); i++) { if (num_res[i] > 0) { ptr += snprintf(ptr, end - ptr, "%3d:%3d ", -(int)i, num_res[i]); if (ptr - line > 70) { ufbxt_logf("%s", line); ptr = line; } } } } #endif UFBXT_TEST(deflate_static_distances_and_lengths) #if UFBXT_IMPL { char src[] = "\x78\x9c\x63\x60\x04\x02\x26\x66\x10\x62\x61\x05\x53\x6c\xec\x10\x36\x07\x27\x54" "\x80\x8b\x1b\x26\xc1\xc3\x0b\x57\xc0\xc7\x8f\x50\x27\x20\x88\xa4\x43\x48\x18\x59" "\x87\x88\x28\x8a\x51\x62\xe2\xa8\x46\x49\x48\xa2\x59\x20\x25\x8d\x6e\x9b\x8c\x2c" "\x86\x03\xe4\xe4\x31\x1d\xa0\xa0\x88\xc5\x7d\x4a\xca\xd8\xdc\xa7\xa2\x8a\xd5\x03" "\x6a\xea\xd8\x3d\xa0\xa1\x89\xc3\x97\x5a\xda\xb8\x02\x40\x47\x17\x67\x00\xe8\xe9" "\xe3\x0e\x00\x03\x43\x3c\x21\x69\x64\x8c\x2f\x24\x4d\x4c\xf1\xc6\x87\x99\x39\xfe" "\xf8\xb0\xb0\x24\x10\x1f\x56\xd6\x84\xe2\xc3\xc6\x96\x60\x02\xb0\xb3\x27\x9c\x00" "\x1c\x1c\x89\x48\x00\x4e\xce\x44\xa6\x2b\x17\x57\xe2\xd3\x95\x9b\x3b\x09\xe9\xca" "\xc3\x93\xd4\x74\xe5\xe5\x4d\x7a\x06\xf0\xf1\x25\x23\x03\xf8\xf9\x93\x99\x07\x03" "\x02\xc9\xcf\x83\x41\xc1\x14\xe4\xc1\x90\x50\x0a\x0b\x80\xb0\x70\xca\x0b\x80\x88" "\x48\x2a\x14\x00\x51\xd1\xd4\x29\xe1\x62\x62\xa9\x5f\xc2\xc5\xc5\xd3\xa0\x84\x4b" "\x48\xa4\x5d\x09\x97\x94\x4c\xfb\x0a\x20\x25\x95\x0e\x15\x40\x5a\x3a\xdd\x2a\x80" "\x8c\x4c\xfa\xd7\x83\x59\xd9\x03\x50\x0f\xe6\xe4\x0e\x54\x03\x20\x2f\x7f\xe0\x1b" "\x00\x05\x85\x83\xa0\x01\x50\x54\x3c\x98\xda\x70\x25\xa5\x83\xb3\x0d\x57\x56\x3e" "\xf8\xdb\x70\x15\x95\x43\xa0\x0d\x57\x55\x3d\x74\x3a\x00\x35\xb5\x43\xb1\x03\x50" "\x57\x3f\xf4\x3b\x00\x0d\x8d\xc3\xa0\xaf\xd6\xd4\x3c\x5c\xfa\x6a\x2d\xad\xc3\xaf" "\xaf\xd6\xd6\x3e\xfc\x07\x00\x3a\x3a\x47\xc0\x00\x40\x57\xf7\xc8\x18\x00\xe8\xe9" "\x1d\x69\x03\x00\x7d\xfd\x23\x77\x1c\x6e\xc2\xc4\x11\x3f\x0e\x37\x69\xf2\xe8\x38" "\xdc\x94\xa9\xa3\xe3\x70\xd3\xa6\x8f\x4e\x00\xcc\x98\x39\x3a\x01\x30\x6b\xf6\xe8" "\x04\xc0\x9c\xb9\xa3\x13\x00\xf3\xe6\x8f\xce\xab\x2d\x58\x38\x3a\xaf\xb6\x68\xf1" "\xe8\xbc\xda\x92\xa5\xa3\xf3\x6a\xcb\x96\x8f\x2e\x00\x58\xb1\x72\x74\x01\xc0\xaa" "\xd5\xa3\x0b\x00\xd6\xac\x1d\x5d\x00\xb0\x6e\xfd\xe8\x02\x80\x0d\x1b\x47\x17\x00" "\x6c\xda\x3c\xba\x00\x60\xcb\xd6\xd1\xf5\x70\xdb\xb6\x8f\xae\x87\xdb\xb1\x73\x74" "\x3d\xdc\xae\xdd\xa3\xeb\xe1\xf6\xec\x1d\x5d\x0f\xb7\x6f\xff\xe8\x7a\xb8\x03\x07" "\x47\xd7\xc3\x1d\x3a\x3c\xba\x1e\xee\xc8\xd1\xd1\xf5\x70\xc7\x8e\x8f\x6e\x00\x38" "\x71\x72\x74\x03\xc0\xa9\xd3\xa3\x1b\x00\xce\x9c\x1d\xdd\x00\x70\xee\xfc\xe8\x06" "\x80\x0b\x17\x47\x37\x00\x5c\xba\x3c\xba\x01\xe0\xca\xd5\xd1\xfd\x6a\xd7\xae\x8f" "\xee\x57\xbb\x71\x73\x74\xbf\xda\xad\xdb\xa3\xfb\xd5\xee\xdc\x1d\xdd\xaf\x76\xef" "\xfe\xe8\x7e\xb5\x07\x0f\x47\xf7\xab\x3d\x7a\x3c\xba\x5f\xed\xc9\xd3\xd1\xfd\x6a" "\xcf\x9e\x8f\x1e\x00\xf0\xe2\xe5\xe8\x01\x00\xaf\x5e\x8f\x1e\x00\xf0\xe6\xed\xe8" "\x01\x00\xef\xde\x8f\x1e\x00\xf0\xe1\xe3\xe8\x01\x00\x9f\x3e\x8f\x1e\x00\xf0\xe5" "\xeb\xe8\x01\x00\xdf\xbe\x8f\x1e\x00\xf0\xe3\xe7\xe8\x01\x00\xbf\x7e\x8f\x1e\x00" "\xf0\xe7\xef\xe8\x01\x00\xff\xfe\x8f\x1e\x00\xc0\xc0\x38\x7a\x00\x00\x13\xf3\xe8" "\xf9\x70\x2c\xac\xa3\xe7\xc3\xb1\xb1\x8f\x9e\x0f\xc7\xc1\x39\x7a\x3e\x1c\x17\xf7" "\xe8\xf9\x70\x3c\xbc\xa3\xe7\xc3\xf1\xf1\x8f\x9e\x0f\x27\x20\x38\x7a\x3e\x9c\x90" "\xf0\xe8\xf9\x70\x22\xa2\xa3\xe7\xc3\x89\x89\x8f\x9e\x0f\x27\x21\x39\x7a\x3e\x9c" "\x94\xf4\xe8\xf9\x70\x32\xb2\xa3\xe7\xc3\xc9\xc9\x8f\x9e\x0f\xa7\xa0\x38\x7a\x3e" "\x9c\x92\xf2\xe8\xf9\x70\x2a\xaa\xa3\xe7\xc3\xa9\xa9\x8f\x5e\x00\xa0\xa1\x39\x7a" "\x4f\x83\x96\xf6\xe8\x3d\x0d\x3a\xba\xa3\xf7\x34\xe8\xe9\x8f\xde\xd3\x60\x60\x38" "\x7a\x1f\x8b\x91\xf1\xe8\x7d\x2c\x26\xa6\xa3\xf7\xb1\x98\x99\x8f\xde\xc7\x62\x61" "\x39\x7a\xef\x92\x95\xf5\xe8\xbd\x4b\x36\xb6\xa3\xf7\x2e\xd9\xd9\x8f\xde\xbb\xe4" "\xe0\x38\x7a\xbf\x9a\x93\xf3\xe8\xfd\x6a\x2e\xae\xa3\xf7\xab\xb9\xb9\x8f\xde\xaf" "\xe6\xe1\x39\x7a\x8f\xa2\x97\xf7\xe8\x3d\x8a\x3e\xbe\xa3\xf7\x28\xfa\xf9\x8f\xde" "\xa3\x18\x10\x38\x7a\x5f\x6a\x50\xf0\xe8\x7d\xa9\x21\xa1\xa3\xf7\xa5\x86\x85\x8f" "\xde\x97\x1a\x11\x39\x7a\x2f\x72\x54\xf4\xe8\xbd\xc8\x31\xb1\xa3\xf7\x22\xc7\xc5" "\x8f\xde\x8b\x9c\x90\x38\x7a\x2f\x72\x52\xf2\xe8\xbd\xc8\x29\xa9\xa3\xf7\xff\xa7" "\xa5\x8f\xde\xff\x0f\x00\x5e\x3b\xcf\x7c"; size_t dst_size = 33665; char *dst = malloc(dst_size); ptrdiff_t res = ufbxt_inflate(dst, dst_size, src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == dst_size); ufbxt_assert(fnv1a(dst, dst_size) == 0x88398917); free(dst); } #endif UFBXT_TEST(deflate_dynamic_distances_and_lengths) #if UFBXT_IMPL { char src[] = "\x78\x9c\xed\x9d\x03\x70\x34\x41\x14\x84\x63\xdb\xb6\x6d\xdb\xb6\xed\xfc\xb6\x6d" "\xdb\xb6\x6d\xdb\xb6\x6d\xdb\x36\x82\xb3\xb1\x9d\x4a\x55\x52\xc9\xdd\xed\xee\x78" "\xe6\xbd\xee\x4f\x44\xf4\xe7\x97\x98\xf8\xaf\x6f\x09\xc9\xdf\x3f\xa4\xa4\xff\xfc" "\x2e\x23\xfb\xf7\x0f\x72\xf2\xff\xfe\xa1\xa0\xf8\xff\x05\x4a\xca\x35\xaf\x53\x51" "\xad\xf5\x0e\x35\xf5\xda\xef\xd0\xd0\xac\xf3\x51\x5a\xda\x75\x3f\x4a\x47\xb7\xde" "\x05\xf4\xf4\xeb\x5f\xcd\xc0\x90\xe4\x06\x8c\x8c\x49\x6f\xc0\xc4\x94\xcc\xfd\x99" "\x99\x93\xbb\x3f\x0b\x4b\xb2\x0f\x60\x65\x4d\xfe\x01\x6c\x6c\x29\x3c\xa5\x9d\x3d" "\xa5\x02\x70\x70\xa4\x58\x00\x4e\xce\x94\x0b\xc0\xc5\x95\x4a\x49\xba\xb9\x53\x2b" "\x49\x0f\x4f\xaa\xf5\xe1\xe5\x4d\xbd\x3e\x7c\x7c\x69\xd4\x87\x9f\x3f\xad\xfa\x08" "\x08\xa4\xd9\x00\x82\x82\x69\x37\x80\x90\x50\x3a\x1a\x40\x58\x38\x9d\xed\x2a\x22" "\x92\xfe\x76\x15\x15\xcd\x40\xbb\x8a\x89\x65\xb4\x5d\xc5\xc5\x33\xde\x01\x12\x12" "\x99\xe8\x00\x49\xc9\x4c\xf6\xc1\x94\x54\xe6\xfb\x60\x5a\x3a\x0b\x7d\x30\x23\x93" "\xc5\x01\x20\x2b\x9b\xf5\x01\x20\x27\x97\x0d\x03\x40\x5e\x3e\x7b\x46\xb8\x82\x42" "\xf6\x8f\x70\x45\xc5\x1c\x18\xe1\x4a\x4a\x39\x37\xc2\x95\x95\x73\x7e\x02\xa8\xa8" "\xe4\xc2\x04\x50\x55\xcd\xb5\x09\xa0\x41\x43\xee\xcf\x83\x8d\x1a\xf3\x60\x1e\x6c" "\xd2\x94\x57\x0b\x80\x66\xcd\x79\xbf\x00\x68\xd1\x92\x0f\x16\x00\xad\x5a\xf3\xd3" "\x1a\xae\x4d\x5b\xfe\x5c\xc3\xb5\x6b\xcf\xff\x6b\xb8\x0e\x1d\x05\x60\x0d\xd7\xa9" "\xb3\xe0\x6c\x00\xba\x74\x15\xc4\x0d\x40\xb7\xee\x82\xbf\x01\xe8\xd1\x53\x08\xf6" "\x6a\xbd\x7a\x0b\xcb\x5e\xad\x4f\x5f\xe1\xdb\xab\xf5\xeb\x2f\xfc\x07\x00\x03\x06" "\x12\xe0\x00\x60\xd0\x60\x62\x1c\x00\x0c\x19\x4a\xb4\x03\x80\x61\xc3\x89\x7b\x0e" "\x37\x62\x24\xe1\xcf\xe1\x46\x8d\xc6\x39\xdc\x98\xb1\x38\x87\x1b\x37\x1e\x01\x80" "\x09\x13\x11\x00\x98\x34\x19\x01\x80\x29\x53\x11\x00\x98\x36\x1d\x71\xb5\x19\x33" "\x11\x57\x9b\x35\x1b\x71\xb5\x39\x73\x11\x57\x9b\x37\x1f\x09\x00\x0b\x16\x22\x01" "\x60\xd1\x62\x24\x00\x2c\x59\x8a\x04\x80\x65\xcb\x91\x00\xb0\x62\x25\x12\x00\x56" "\xad\x46\x02\xc0\x9a\xb5\xc8\x87\x5b\xb7\x1e\xf9\x70\x1b\x36\x22\x1f\x6e\xd3\x66" "\xe4\xc3\x6d\xd9\x8a\x7c\xb8\x6d\xdb\x91\x0f\xb7\x63\x27\xf2\xe1\x76\xed\x46\x3e" "\xdc\x9e\xbd\xc8\x87\xdb\xb7\x1f\x02\x80\x03\x07\x21\x00\x38\x74\x18\x02\x80\x23" "\x47\x21\x00\x38\x76\x1c\x02\x80\x13\x27\x21\x00\x38\x75\x1a\x02\x80\x33\x67\xa1" "\x57\x3b\x77\x1e\x7a\xb5\x0b\x17\xa1\x57\xbb\x74\x19\x7a\xb5\x2b\x57\xa1\x57\xbb" "\x76\x1d\x7a\xb5\x1b\x37\xa1\x57\xbb\x75\x1b\x7a\xb5\x3b\x77\xa1\x57\xbb\x77\x1f" "\x06\x00\x0f\x1e\xc2\x00\xe0\xd1\x63\x18\x00\x3c\x79\x0a\x03\x80\x67\xcf\x61\x00" "\xf0\xe2\x25\x0c\x00\x5e\xbd\x86\x01\xc0\x9b\xb7\x30\x00\x78\xf7\x1e\x06\x00\x1f" "\x3e\xc2\x00\xe0\xd3\x67\x18\x00\x7c\xf9\x0a\x03\x80\x6f\xdf\x61\x00\x20\x22\x0a" "\x03\x00\x31\x71\xf8\xc3\x49\x48\xc2\x1f\x4e\x4a\x1a\xfe\x70\x32\xb2\xf0\x87\x93" "\x93\x87\x3f\x9c\x82\x22\xfc\xe1\x94\x94\xe1\x0f\xa7\xa2\x0a\x7f\x38\x35\x75\xf8" "\xc3\x69\x68\xc2\x1f\x4e\x4b\x1b\xfe\x70\x3a\xba\xf0\x87\xd3\xd3\x87\x3f\x9c\x81" "\x21\xfc\xe1\x8c\x8c\xe1\x0f\x67\x62\x0a\x7f\x38\x33\x73\xf8\xc3\x59\x58\xc2\x1f" "\xce\xca\x1a\x00\x00\x1b\x5b\x70\x1a\xec\xec\xc1\x69\x70\x70\x04\xa7\xc1\xc9\x19" "\x9c\x06\x17\x57\xf0\x58\xdc\xdc\xc1\x63\xf1\xf0\x04\x8f\xc5\xcb\x1b\x3c\x16\x1f" "\x5f\x70\x97\xfc\xfc\xc1\x5d\x0a\x08\x04\x77\x29\x28\x18\xdc\xa5\x90\x50\xf0\xd5" "\xc2\xc2\xc1\x57\x8b\x88\x04\x5f\x2d\x2a\x1a\x7c\xb5\x98\x58\x70\x14\xe3\xe2\xc1" "\x51\x4c\x48\x04\x47\x31\x29\x19\x1c\xc5\x94\x54\xf0\x52\xd3\xd2\xc1\x4b\xcd\xc8" "\x04\x2f\x35\x2b\x1b\xbc\xd4\x9c\x5c\x70\x91\xf3\xf2\xc1\x45\x2e\x28\x04\x17\xb9" "\xa8\x18\x5c\xe4\x92\x52\x70\x91\xcb\xca\xc1\x45\xae\xa8\x04\xff\xbf\xaa\x1a\xfc" "\xff\x1f\x5e\x3b\xcf\x7c"; size_t dst_size = 33665; char *dst = malloc(dst_size); ptrdiff_t res = ufbxt_inflate(dst, dst_size, src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == dst_size); ufbxt_assert(fnv1a(dst, dst_size) == 0x88398917); free(dst); } #endif UFBXT_TEST(deflate_long_codes) #if UFBXT_IMPL { char src[] = "\x78\x9c\xed\xfd\xc7\xb9\x65\x5d\xb6\x65\xd9\xc9\x06\x40\x85\xae\xc2\x90\x60\x2e" "\xfd\x3f\x14\xf6\xb9\xe6\xfe\x32\xc1\x39\x69\x85\x56\xeb\x63\xae\x7d\xae\xfd\x1e" "\x01\x8e\xb7\x7b\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\xff\x27\xfd\x7f\x1e\xee" "\xff\xa3\xfe\x3f\x0f\xf7\xbf\xf9\xff\xac\xff\xcf\xc3\xfd\x6f\xfe\xb7\xff\x1f\xf6" "\xff\x79\xb8\xff\xcd\xff\xf6\x7f\xf7\xff\x69\xff\x9f\x87\x03\x00\x00\xe0\xff\x1b" "\xff\xbf\xaf\xf6\xff\x95\xff\xdf\x57\xfb\xdf\xfc\x7f\xe7\xff\xf7\xd5\xfe\x37\xff" "\xdb\xff\x2f\xfd\xff\xbe\xda\xff\xe6\x7f\xfb\xbf\xfb\xff\xd6\xff\xef\xab\x01\x00" "\x00\x00\x00\xfc\xff\xde\xff\xef\xc3\xfd\xff\xe0\xff\xef\xc3\xfd\x6f\xfe\x7f\xf1" "\xff\xf7\xe1\xfe\x37\xff\xdb\xff\x9f\xfc\xff\x7d\xb8\xff\xcd\xff\xf6\x7f\xf7\xff" "\x9b\xff\xbf\x0f\x07\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xf1\xff\x7f\xa9\xff" "\x7f\xf2\xff\x7f\xa9\xff\x9b\xff\x7f\xf9\xff\xbf\xd4\xff\xcd\xff\xf6\xff\x6f\xfe" "\xff\x2f\xf5\x7f\xf3\xbf\xfd\xdf\xfd\xff\xcf\xff\xff\xa5\xfe\xef\x01\x7e\xa8\x57" "\xe0"; size_t dst_size = 31216; char *dst = malloc(dst_size); ptrdiff_t res = ufbxt_inflate(dst, dst_size, src, sizeof(src) - 1); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == dst_size); ufbxt_assert(fnv1a(dst, dst_size) == 0x9e9ed1e5); free(dst); } #endif UFBXT_TEST(deflate_fuzz_1) #if UFBXT_IMPL { char src[] = "\x78\x9c\x30\x04\x00\xfb\xff\x30\x30\x30\x30\x52\x30\x30\x30\x02\x10\x00\x06\x32" "\x00\x00\x00\x0c\x52\x39\xcc\x45\x72\xc8\x7f\xcd\x9d\x30\x08\x00\xf7\xff\x30\x30" "\x30\x30\x30\x30\x30\x30\x02\x8b\x01\x38\x8c\x43\x12\x00\x00\x00\x00\x40\xff\x5f" "\x0b"; char dst[4096]; ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); } #endif UFBXT_TEST(deflate_fuzz_2) #if UFBXT_IMPL { char src[] = "\x78\x9c\x00\x04\x00\xfb\xff\x54\x65\x73\x74\x52\x08\x48\x2c\x02\x10\x00\x06\x32" "\x00\x00\x00\x0c\x52\x39\xcc\x45\x72\xc8\x7f\xcd\x9d\x00\x08\x00\xf7\xff\x74\x61" "\x20\x44\x61\x74\x61\x20\x02\x8b\x01\x38\x8c\x43\x12\x00\x00\x00\x00\x40\xff\x5f" "\x0b\x36\x8b\xc0\x12\x80\xf9\xa5\x92\x23\x84\x00\x8e\x36\x10\x41"; char dst[4096]; ufbxt_inflate(dst, sizeof(dst), src, sizeof(src) - 1); } #endif UFBXT_TEST(deflate_benchmark) #if UFBXT_IMPL { char src[] = "\x78\x9c\x4d\x9c\x79\x7c\x56\xc5\xd5\xc7\x6f\xf6\xa0\x40\x40\xa5\x40\x15\x12\xc1" "\x95\x2a\x22\x6e\x08\x79\x66\xa2\xa0\xe0\x4a\x44\xa2\x68\xb5\xc4\x56\x6d\x4b\x6b" "\xc5\xb6\x56\x5f\xdf\xb6\xcf\xd3\xba\xd6\x0d\xd4\x52\xf7\x26\xd6\x05\x4d\x5d\xb0" "\xe2\xce\x9d\x93\x2e\x16\xb5\x8a\x68\xeb\x52\x6d\x25\x6a\x95\xaa\xaf\x06\x44\x21" "\xfb\x7d\x7f\xbf\x79\xf8\x05\xff\xf0\xe3\xd7\xeb\xef\xcc\x33\x77\x96\x33\x67\x66" "\xce\xcd\xc8\xa4\xcf\x0d\xe4\xa7\x59\x75\xe2\xdc\xc8\xa4\x2f\x88\xcb\x93\x1a\x9f" "\x24\x75\xd6\x95\xed\x4a\x36\x71\x92\x74\xb8\xca\xc2\x1e\x76\x51\x56\x9b\x03\x07" "\x71\x57\xf6\xb2\xeb\xcb\xea\x6d\x42\xf2\x06\x39\x88\xcb\x93\x1b\xa1\x3f\x5c\x1c" "\xc4\x49\x72\x05\x9e\x4f\xde\x5a\xce\x15\x41\xdc\x99\xed\x88\xe7\x53\xe3\x6f\x81" "\x83\x78\x64\x72\x1a\xca\x9f\xb5\xb5\x9e\xa7\x85\x2f\x71\x7c\xde\x95\xdd\x3c\xf8" "\x9c\xac\x72\x92\xe4\xde\xc1\x72\xc8\xfa\xdd\xea\xe4\x03\xa7\xdf\x25\xab\x9e\x9d" "\xd9\x9f\x9d\xea\x49\xd6\x7b\x6d\xe5\x20\x56\x3b\x14\xcb\x29\xb6\x43\xb1\x9c\x62" "\xbb\xf1\xb7\xd4\x6e\xe4\x91\x5b\xdb\xb9\x58\xcf\x62\x3b\x93\xbb\xb2\x0f\x63\xfd" "\x37\x65\xd7\x93\x83\x78\x53\xf6\x3c\xf4\x73\xc0\x7f\x20\x07\x71\x79\xd2\x02\xfd" "\xb1\xe2\x20\xee\xcb\x0a\xf8\xef\xb9\xd1\x16\x1c\xbe\xc4\xf1\x79\x75\x72\xfc\xe0" "\x73\xb2\xca\xe9\xca\x46\x0e\x96\x43\xd6\xef\x6e\xe5\x20\x56\x3d\x69\xab\x7a\x92" "\x1b\x9b\xfe\xe9\x16\x34\x1d\x63\x7f\x6c\x3b\x95\x1c\xc4\x6c\x23\xfc\x7f\xbc\xfb" "\x14\x72\x10\x9f\xd1\x74\x37\x74\x27\x88\x83\x38\x49\x96\xba\x15\x6d\xf3\xa2\x2d" "\x38\x7c\x89\xe3\xf3\x91\xc9\xd5\x83\xcf\xc9\x2a\xa7\xa5\xed\x77\x83\xe5\x90\xf5" "\xbb\x5b\x39\x88\x55\x4f\xda\xaa\x9e\xe4\x99\xc9\x0a\x8c\xd7\xb1\xd6\x97\xfd\xd8" "\xc0\xa9\xf8\xed\xec\xdb\x28\xe7\x2b\x36\x90\x5f\x4c\x0e\xe2\xbe\xec\x26\xf4\x3b" "\xf9\x4c\x72\x10\x57\x27\xbf\x45\xfb\xec\x62\xe5\xc9\x6c\x72\x10\xb3\xfe\x95\x85" "\x09\x6c\x43\x72\x10\x0f\x4b\x96\x41\xbf\x9b\x4d\x4d\x3e\x4f\xc1\x41\xdc\x93\xaf" "\xf0\xa5\x85\xd1\xa8\xcb\x14\xb2\x89\x4b\x0b\x07\xf8\x9e\xfc\x30\xd4\x79\x55\x0e" "\x6c\xe2\xae\xec\x28\x5f\x9e\xec\x88\x31\x79\x03\xfa\xe5\x28\x13\x27\x49\x83\xe7" "\x98\xec\xca\xfe\x49\x36\x71\x5f\xb6\x13\xca\x39\x08\xba\x32\x0f\x36\x71\x92\x3c" "\xeb\x4a\x0b\x33\xc1\x13\xc9\x41\x5c\x9d\xfc\x1c\xcf\x8f\x01\xef\x47\x0e\xe2\xf5" "\x59\x45\x1c\x3f\x03\xf9\x11\xe4\x20\x3e\x2b\xd9\x8b\x75\x8a\xbf\x05\x4e\xc5\x13" "\x92\x69\x68\x87\xe3\x61\xbb\x85\x1c\xc4\xc5\x7e\x3d\x16\x6d\x39\xd4\x83\x83\xb8" "\x2f\x6b\x47\xfb\x1f\x89\x7a\x57\x92\x83\xb8\x2b\x1b\x82\x7f\x0e\xc5\xd8\x7e\x17" "\xef\x3b\xc4\xc4\xe5\xc9\xd7\xfc\x40\x7e\x1f\xf0\x53\x64\xdb\xc6\xfb\xa1\x3d\x27" "\x1a\xe7\x3d\xd8\xc4\x3d\xf9\x71\x68\xb7\x89\xb0\x2f\x21\x9b\xb8\x2f\xdb\x10\xed" "\x0f\xc9\x1e\xaa\x07\x07\xf1\xb0\xe4\x1a\xb4\xc3\x0c\xbb\xa1\xa4\x6e\x15\x38\x88" "\x31\x97\xf1\xbe\x87\xc1\xa7\x4d\xcb\x81\x53\xf1\xdb\xd9\xea\x1c\xdb\x24\x49\xda" "\x1d\x38\x15\x77\x66\x17\xe7\x38\x2e\xba\xb2\x5f\x91\x53\xf1\x84\xe4\xa6\x1c\xfb" "\x69\x64\xb2\x0b\x39\x15\x9f\x95\x7c\x07\xe5\xef\x8d\x7e\xfa\xae\x81\x53\x31\xfd" "\x1b\xeb\x96\x24\x67\x92\x83\x78\x6c\x32\x1d\xf5\xdc\x0f\x6d\x35\x8f\x1c\xc4\x6f" "\x67\x7b\x6e\xf5\x3f\x23\xc9\x41\x4c\x1f\x3a\x90\x3f\xd0\xf8\x3e\xe0\x20\x66\x3f" "\x96\x27\xde\xd8\xf6\xec\x47\xf1\xdb\xd9\xec\x1c\x74\xec\x6b\x94\x33\x3b\x15\xb3" "\x9e\x49\x52\x8f\xdf\x3a\x38\xd6\x53\x0c\xdf\x98\x1b\xc8\xd3\x27\xff\x02\x7d\xdb" "\x91\x8a\x67\x26\x1b\xe2\xf3\x91\x49\x3d\x39\x15\x27\x49\x01\xbf\x3b\x13\x3c\x94" "\x9c\x8a\xd1\xd6\xf5\xd4\xac\xcf\x76\x27\xaf\x12\xb3\xad\xa9\xd9\x94\xdd\x42\x4e" "\xc5\x98\x33\x78\x7e\x0c\xea\xbc\x94\x9c\x8a\xd9\x97\xf4\x09\x63\x93\x49\xe4\x55" "\xe2\xa9\xc9\xaf\x73\x1c\x7b\x49\x32\x82\x9c\x8a\x3b\xb3\xf7\x72\xd4\xb0\x6d\xc0" "\xa9\x78\x6a\xf2\x8f\x5c\x4f\xfe\x38\xd8\x5e\x44\x4e\xc5\xac\x7f\x57\x76\x82\xde" "\x25\xdd\xc6\x0d\x18\x0f\x8d\x18\x1b\x17\x92\x53\x31\xdb\xad\x27\x7f\x58\xf4\x3d" "\x6c\x37\x71\x67\x56\x86\xb1\xd8\xc0\xb1\x84\xdf\x2d\x0b\xe2\xea\x64\x38\xe6\xd1" "\x74\xbc\xcb\x15\xe4\xf0\x25\x8e\xcf\xcb\x13\x1b\x7c\x4e\x5e\x9f\x9d\xef\x38\xb6" "\xd9\x77\xe0\xb0\x8d\x9b\x30\x7f\x76\x85\x66\x09\x39\x88\x39\x7e\xfa\xb2\xbd\xd8" "\xb7\xe4\x20\x4e\xb3\xb9\x39\x96\xc9\x71\x09\x4e\xc5\x6c\x07\x8e\xa5\xd2\xc2\x6c" "\x72\x2a\xee\xcc\xee\x8c\x7e\xaa\x2b\x3b\x85\x9c\x8a\x2f\x4b\x3a\xd0\x8f\x53\x50" "\x87\x66\xf2\x2a\xf1\xd0\x92\xf6\x7a\xfe\x56\x5f\x76\x1a\x79\x95\x38\xcd\x96\xe4" "\x38\xb6\x2b\x0b\x27\x91\x53\x31\xe6\x52\x8e\x63\x3b\x49\xe6\x90\xd3\x6d\xcc\x76" "\x9e\x62\x1c\x07\xc5\x76\x2e\x72\x9a\xd5\xa0\x9d\x77\x47\xdd\xe6\x92\x53\x71\x92" "\xb4\xe6\x1a\x9b\x76\xb7\xe2\xfa\xd4\x9a\x8a\x39\x5f\x92\x64\x56\x9c\x4f\x9c\x2f" "\x62\xce\xc9\x9e\xfc\x11\x78\xa7\x8b\xc9\x41\x5c\x9d\x4c\x46\xfb\x1f\x89\x77\x7c" "\x98\x1c\xc4\x68\x3b\x57\xac\x4b\x42\x0e\x62\xc6\x1b\x9c\x3b\xc5\xf7\xbb\x31\x88" "\x47\x26\xff\x72\xf4\xc9\x18\x1b\xe4\x20\x2e\x4f\xb6\x87\xff\x9d\xcc\xb9\x00\xdb" "\xed\x4d\x5c\x5a\xd8\x19\x7e\x7e\x12\x35\x64\x13\xf7\x65\x63\xa2\x3f\x64\xec\x01" "\xb6\x6d\x9c\xf8\xe2\xbc\x7c\x96\x6c\xe2\xae\xec\x8f\xb0\xf7\x68\xab\x75\xe4\x20" "\x4e\x92\x9b\x1c\x7d\x5a\x31\xce\xb9\x29\x88\xd7\x67\x67\xc5\x76\x28\x4f\x5e\x27" "\x07\x31\xc6\x7c\x8c\x13\xca\x93\xd5\xe4\x20\x1e\x96\xdc\x1e\xdb\xa1\x33\xfb\x3b" "\x39\x88\xe9\xe7\x59\x66\x92\xac\x25\x07\x31\xd7\x86\x9e\xfc\xa1\x58\x27\x53\x72" "\xd8\xc6\x35\x9e\x7e\xbc\x2f\x6b\x8d\xf1\x95\xb8\x2f\x1b\x81\x75\x6d\x5f\xce\x41" "\xb2\x89\x93\xa4\x1c\xcf\xf7\x67\x1c\x46\xb6\x6d\xfc\x06\x74\xd3\xe2\x1a\x0a\x0e" "\xe2\x91\xc9\x6d\xf0\x87\x0d\x8c\xf1\xc8\x61\x1b\x9f\x16\xc7\x03\x7c\x42\x8c\x33" "\xc5\x98\xdf\x5b\xe3\xcf\xfb\xc8\x41\x5c\xf4\xab\xb3\x50\xe7\x4b\x5d\xd1\xaf\x16" "\x19\xef\x17\xd7\xd9\xf5\xd9\x11\xe4\x20\xa6\xbf\xea\xcb\xf6\x81\xe6\x7d\x72\x2a" "\xe6\x3a\xcb\x77\xec\xc9\x8f\x8a\xeb\xac\x98\x71\x1d\x35\x7d\xd9\x81\xe4\xb0\x8d" "\xd7\xe2\x77\x77\xe3\x7a\x4f\x0e\x62\xc4\x11\x68\xb7\xd1\xe8\xbb\xca\x18\x5f\x88" "\xd1\x0f\x9e\xe3\xa9\xb8\x86\x72\xcd\x2f\xf2\x40\xbe\x11\x71\xc0\x86\xc0\x18\x12" "\x6c\x62\x8c\x47\x8f\xff\x1f\xd6\x64\x57\xe5\x38\x36\xc5\xe5\x49\x15\xd6\xe5\x6e" "\x32\xe6\x68\x95\x89\xd1\x86\x5b\xdb\x31\x41\xfb\xde\x96\x8a\xdf\xce\x2e\x87\x9f" "\x7c\x38\xae\x5b\xe0\x54\x4c\x7d\x75\xb2\x06\xbc\x30\xea\xc5\xc5\x38\xad\x04\xf5" "\xb8\x70\x6b\x9c\x56\x64\x8e\xb7\x61\xc9\x17\x18\x1f\xe7\x91\xc3\x36\xbe\x17\xf1" "\xeb\x47\xe0\xd3\xc9\x41\xcc\xb1\xc2\x77\x29\x4f\x0e\x20\x07\x31\x63\x59\xf8\x11" "\xd4\xad\x8e\x1c\xc4\x23\x93\xef\xc7\x38\xb8\x2f\x9b\x4f\x0e\xe2\xb1\xc9\xd1\xf8" "\xdd\x47\x61\xbb\x1e\x7e\xf2\xe8\x20\x66\x1b\x25\x49\x17\xe6\xf3\x00\x39\x88\x59" "\x0e\xdf\x9b\xbe\x9a\xe5\x88\x37\x65\xbf\x44\xf9\x3d\x28\x73\x05\x39\x88\xc7\x26" "\xa7\x3a\xc6\x7f\xf4\xcd\xe0\x20\x86\x2f\x8d\xe3\x78\x42\x32\x86\x1c\xc4\xf4\x3f" "\x18\x03\xfe\xb2\xa4\x39\xa5\xff\x11\x77\x66\x13\x63\xec\x8e\xb1\x07\xfd\xc4\x20" "\x66\xac\xc3\x3e\xa8\x4e\xfe\x4a\x0e\x62\xc6\x2d\x9d\xd9\xb7\xb8\x56\x93\x53\xf1" "\x84\x64\x81\x2b\xb6\xd7\x13\xe4\x20\xee\xc9\xe7\xfc\xd8\x64\x11\xd6\xc0\x95\x18" "\x0f\x39\x13\x8f\x4c\x8e\xe5\x78\xf2\x8c\x7f\xc1\x41\xcc\xb8\x9a\xfe\xba\xb2\xb0" "\xc8\x33\xae\xfe\x12\x3b\xc6\x41\xa5\x85\xef\xc5\xe7\x62\x94\x87\x72\x6a\x31\x96" "\xa7\xc4\xdf\x11\x73\x1c\xf6\x65\xcf\x06\xf9\x4b\x31\xfa\xd2\xf3\xf7\x92\xa4\xda" "\xb3\x5f\xc5\x49\x32\x0d\xe5\x56\x61\xad\xda\x8b\x6c\x5f\x62\xe8\x96\xa0\x8c\xdd" "\xe3\x73\x31\xe7\x12\xdb\x2a\x49\xfe\x8b\xf7\x3e\xd0\xc4\xf4\xc3\xa5\x85\x2a\x68" "\x77\x8a\xf3\x46\x9c\x24\x31\x7e\x65\x8c\x4b\xb6\x2f\xb1\x7f\xab\xcf\x9e\xc6\xbe" "\x2b\x3e\xff\x12\x7b\x8e\x57\xac\xbb\xf1\xb9\x98\x31\x74\x5f\xd6\xc1\x31\xe3\x18" "\x57\x89\xd9\x0e\x9b\xb2\x3f\x81\x0f\x8e\xed\x20\x66\x9b\x26\xc9\x18\xee\x13\xc8" "\x41\x5c\x9e\x5c\x8e\xdf\xdf\xce\x38\x2f\xc1\x41\xdc\x37\x7f\x54\x8e\x9a\x33\x9a" "\xbe\x70\xe0\x54\xdc\x93\x3f\xca\xd3\x2f\x23\x76\x22\x9b\x98\x75\x65\x7c\x86\xdf" "\x8b\xfb\x48\x71\x4f\xfe\x04\xcf\x75\x89\xed\x02\x36\x31\xe2\xa6\xd8\x9e\xdc\x1f" "\x33\x86\x12\x8f\x4c\xee\xe7\x7e\x20\x57\x1c\xff\xf7\x07\x31\xea\xe5\xb9\xef\x1f" "\x9b\x6c\x17\xeb\x28\x2e\x2d\x6c\xef\x19\x67\x73\x4d\x06\x9b\x78\x53\xf6\xbb\xb8" "\x3e\xc1\x67\xa2\x7e\xbf\x0b\xe2\x15\x6d\xd7\x62\x1f\xf8\xb3\x50\xdc\x23\x5e\x1b" "\xc4\x8d\x4d\xd7\xe1\xf9\x17\x81\x6b\x38\x38\x88\xfb\xb2\x3a\xb4\x57\xe2\xb9\x9e" "\x83\x4d\xbc\x29\xfb\x0c\xf5\xad\xf3\x1c\xef\xe0\x20\xee\xc9\x0f\x41\x7d\x1e\x70" "\xf4\x49\x60\x13\x17\xd7\x39\xae\x9f\xbb\x62\x6c\xae\x0e\xe2\x15\x6d\x7f\xc5\x3e" "\x73\x94\x67\x2c\x03\x0e\xe2\xca\xc2\x4f\x62\xdf\x70\xed\x03\x9b\xb8\xdf\xae\x45" "\xf9\x8f\xd2\x67\x91\x4d\x5c\xd6\x70\x87\xe7\x19\x04\x7f\x07\x6c\xe2\xd2\xc2\x9d" "\xd0\xbf\x1a\xd7\x19\xb0\x89\x93\xe4\x7a\xbc\xc7\x2a\xb7\xa6\x37\x7b\x0a\x6c\xe2" "\xf2\xe4\x7b\x1e\x73\xd9\x61\x6e\xa2\xce\xdf\x33\x71\x57\x76\x1e\xca\xff\x05\xe6" "\x65\x15\xd9\xc4\xe8\x37\xcf\x7e\xe6\x3c\x01\x9b\xb8\xdf\x6e\xf3\xdc\xcf\xad\xcf" "\x0e\x42\x3d\x6f\x33\x71\x69\xe1\x56\xcf\xf5\x7f\x53\xd6\x46\x36\x71\xbf\x5d\xed" "\x8b\xeb\xf6\x6a\xb2\x89\xbb\xb2\xff\xf1\xdc\xa7\x56\x27\x8f\x91\x4d\x8c\xf5\xd9" "\xaf\xc9\x7e\x9f\xe3\xde\x82\x6b\xb5\x18\xf1\x26\xfa\x61\x0c\xf6\x46\x4f\xc4\xd8" "\x53\x8c\xb8\xde\xf3\xfd\xe8\xcf\x18\xe3\x8b\x2b\x0b\xdf\x40\xbc\xf4\x0d\xf4\xed" "\x0a\xb2\x89\x11\xf3\x79\xfa\x6e\xbe\x23\xe3\x3f\x31\xf6\x97\xd1\x07\xad\xe9\xcd" "\xcf\xe0\x5e\x53\xdc\x97\xcd\x89\x6b\xed\xcc\x64\x31\xc6\xeb\x1c\x13\x63\xdf\x86" "\x76\x38\xcf\x15\x7f\x97\x7b\xb8\x22\x97\x16\x4e\xf6\x8c\xb9\x69\x0f\x36\x71\x65" "\xe1\x6c\xf4\xcb\x4f\x5d\xf1\xfc\xe0\x6c\x13\x0f\xe4\xe7\xe3\xf9\x3e\xb0\xbd\x8e" "\x6c\x62\xc4\x8f\x9e\x7b\x00\xc6\x18\x8c\x25\xc5\xf7\xb6\x4d\xf3\x2d\x6d\x3b\xb8" "\x75\xcb\xdb\x66\x80\x4d\x4c\x5f\xc9\xd8\x05\x73\x8a\x7e\xd3\xc4\x58\xf3\x3c\x63" "\x4d\xc6\x29\x5c\xff\xc4\xd8\x8f\x7a\xc6\x76\x78\x77\x57\xdc\x9b\x16\x99\xed\x49" "\xa6\x0f\x67\x7b\x8a\xab\x93\x93\xb6\xea\xb9\xff\x3b\xc9\xc4\xac\x3f\x19\xf3\x27" "\x61\xfd\xc5\x7d\xd9\x02\xcf\xdf\x47\x4c\x8b\x58\x7e\x81\x89\x7b\xf2\x3f\xc3\x7b" "\x3d\x82\x3a\xdc\x81\xfa\xfc\xcc\xc4\xa5\x85\x6b\xa0\x7f\x03\xb6\xec\xa3\x6b\x4c" "\x5c\xd6\x70\x2b\xfa\xf1\xd3\xd8\x56\x60\x13\x0f\xe4\x6f\xc3\x7b\x75\x3a\xb6\x17" "\xd8\xc4\xa5\x85\x25\x9e\xeb\x00\xf7\x85\x60\x13\x73\xde\xf1\x77\xb8\x77\xe4\xbc" "\x13\x0f\xe4\x9b\x51\xce\xf2\xb8\x16\x82\x4d\x5c\x59\xf8\xa1\xe7\x78\xe1\x3e\x15" "\x6c\x62\xf4\x7f\x1c\xcf\x3c\xcf\x00\x9b\x78\x20\x7f\x05\x9e\x3f\x13\xfb\x1a\x6c" "\xe2\xf2\xe4\xe2\x38\x8f\xe8\xa7\xc1\x26\x1e\xc8\xff\xd8\x17\xf7\x0a\x3f\x20\x9b" "\xb8\x27\x7f\x16\x7e\x97\xe7\x94\x53\xc8\x26\x46\xcc\x81\xf2\xef\x46\x99\xeb\x73" "\x8c\x3f\xc4\x88\x8d\x3c\xcf\xf2\x86\x96\x34\xd4\x33\x4e\x12\x97\x16\x2e\x88\xe5" "\x33\xae\x04\x9b\x38\x49\xae\xf4\xf4\x37\x6b\xb2\xbf\x91\x4d\x9c\xf9\x5f\x7b\xfa" "\x69\xee\x71\xc0\x26\x1e\xc8\xff\x9a\xeb\x51\x1c\x4b\x60\x13\x2f\x68\xba\x26\xb6" "\x73\x63\xd3\x1d\x64\x13\xf7\x65\xdf\xf1\xf4\xd1\xa8\x1b\x62\xd8\xef\x98\xb8\xb4" "\xb0\x0c\xbf\xfb\x9e\xbb\x28\x6b\x59\x05\x36\x71\x92\xb4\x79\x9e\xb9\xf0\xb7\xc0" "\x26\x1e\xc8\xdf\x83\xfa\x6f\x44\x9f\xbe\x40\x36\x31\xf6\xf0\x78\xfe\x8e\xe3\x7f" "\x83\x4d\x5c\x9e\xfc\x28\xfa\x4f\xfa\x23\xb0\x89\x7b\xf2\xe7\x78\xc6\xfa\xc5\x7d" "\xdb\x39\x26\x4e\x92\x5f\x63\x1d\xe7\xb9\x57\x33\xd9\xc4\xf7\xb7\x2d\xf7\x2b\xda" "\x2a\xe3\x5a\x0e\x36\x31\xc7\x7f\x71\x9f\xb1\x82\x6c\x62\xec\x03\x50\x9f\xe7\x5c" "\x71\x7e\x32\xf6\x2f\x32\xe3\x90\xea\xe4\x32\xb6\x6d\x5a\x8c\x2f\x8b\xcc\xfd\x57" "\xb7\x1d\x62\x35\x85\x0b\x51\x9f\x4f\x5c\x49\x47\x03\xda\xe8\x68\x8c\xdb\x8f\x5d" "\xcf\xc2\xe9\xd8\xa7\x0d\x75\xbd\xbe\xca\x57\xd7\xed\xcb\x3d\x1e\xd9\xc4\xd0\x04" "\x69\x60\x1b\x64\xcb\x7d\x9c\xca\x2c\x2d\xec\x88\xf1\x50\x1b\xb9\xdf\x4a\x7d\x69" "\xeb\x04\x1b\x97\x3c\x8c\x39\xfb\x15\xcf\xf3\x1e\xfa\x4d\x9e\x65\x8a\xa1\x31\x69" "\x60\x6b\xb2\xdd\xae\xf0\x4f\xd7\xb5\x6e\x2a\xfc\xe3\x95\x39\xce\xd1\x7e\x9b\x64" "\xc5\xb3\x93\x0f\xe2\x7e\x12\xf1\x0a\x39\x88\xa1\x09\xd2\xc0\x36\xc8\xb6\xaa\xe1" "\x05\x57\xd6\x3c\xcb\xde\xc9\x6f\xef\xaa\x1a\x56\xba\x8a\x0e\x1f\xf7\xee\xe0\xb0" "\x8d\x5f\x08\xd2\xf4\xe4\x6f\x47\x9b\xcc\x89\x3c\x90\xff\x69\xb4\xe5\xfb\x0e\x6f" "\xbf\xd6\x95\xb4\x1f\x1a\xcb\x04\x07\x31\x34\x41\x1a\xd8\x06\xd9\x0e\x4b\x8e\x80" "\xbf\xd8\x3f\xbe\x17\xd7\x34\x9e\x6f\xb0\x9e\x3c\x7b\x12\x43\x13\xa4\xe9\xcc\x0e" "\xc0\xef\xd6\xc7\x76\xa6\x1f\xef\xb7\xa9\xb1\x1d\x38\xe7\xcb\x93\x3d\x63\x5b\x31" "\xf6\x11\x33\x66\x96\x06\xb6\x41\xb6\xef\xe4\xff\x37\xae\x43\xec\x97\x24\x69\x8c" "\x7b\x43\x6a\xc0\x41\x0c\x4d\x90\x46\xfa\xaa\x86\x5f\x0f\xbe\x6f\x69\xe1\x11\xa7" "\xfa\x6c\x57\xb8\x63\xb0\x7c\xb2\xde\x97\x1a\x95\x43\x5b\xbd\x6f\x4f\xfe\xc5\xc1" "\x3a\x57\x27\x0f\x0e\xd6\x99\xac\xf7\xa5\x46\xed\xb9\x39\xff\x9a\x53\xff\xd2\x87" "\xaa\xad\x3a\xb3\x4d\x4e\x6d\x45\x56\xff\x52\xa3\xf6\xa7\xad\xfa\x6b\x83\x3d\x3a" "\xd8\xbf\x9c\x03\xea\x5f\xb2\xfa\xa5\xa8\x29\x8e\x07\xb2\xc6\x3c\xdf\x45\xe3\x8d" "\x65\x6a\xfc\x90\x35\xe6\xa9\xd1\x38\xa1\xad\xc6\x36\xdf\x45\x63\x92\xf5\xd4\x98" "\x24\x6b\x6c\x53\xa3\x39\xc5\x36\xd4\x5c\x60\x9b\x68\x2e\x90\x35\xd7\xa8\xd1\xdc" "\x64\xdb\x6a\xae\x91\xb9\xfe\x70\x2f\xdf\x97\x5d\x08\x3f\xf9\x36\xea\x7f\x24\xea" "\x79\x8f\x3b\xea\xd5\x0f\xdc\xdc\x65\xb3\xad\xa4\xfd\x3a\x72\x10\x43\x13\xa4\x81" "\x6d\x90\xed\x40\x7e\x25\xde\xf7\x68\xdb\x98\x7f\x1c\xfd\xf0\x9c\xcb\x6a\x8f\xb1" "\x87\x17\xad\x20\x07\x31\x34\x41\x1a\x9e\x3f\xf3\xcc\x9c\xe5\x9c\x3e\xaa\x15\xbf" "\x35\x37\x6a\xc0\x41\xcc\x18\x59\x1a\xfe\x06\xe3\x75\xfe\x7b\x68\xc3\xc5\xee\x81" "\x45\x27\xc4\xfa\x80\x83\x18\xff\x2f\x48\xa3\xf2\xc7\x26\x93\x06\xf5\x4f\x4f\x6a" "\x1c\xd4\x93\x55\x3e\x35\xaa\x7f\x5f\x56\x3d\x58\x9f\xd1\x85\xaf\x0c\xd6\x87\xac" "\xfa\x53\xa3\xb6\xa2\xad\xde\x97\x1a\xbd\x2f\x59\x6d\x45\x8d\xda\x93\xbf\xab\xf6" "\x24\xaf\x68\x7b\xcd\xb5\x4d\x3a\xd6\x9e\x6b\xbb\x10\x71\xfd\x8b\x58\x73\x8e\x03" "\xcf\xe1\xf3\xf0\xa5\xe7\x41\xcf\xcf\x6a\x5a\xe9\xe6\x37\x35\x1a\xe7\x13\x38\x6c" "\xe3\xdb\x1c\xcf\xc5\x8b\x9a\xdb\x82\x98\xb1\xd7\xa9\xaf\xce\x8b\xe5\x80\x83\x58" "\xfa\x95\x6d\xcb\x06\xf5\x45\x2e\x96\x3f\xbf\xa9\x75\xb0\x7c\xb2\xea\x46\x8d\xea" "\x43\x66\x2c\x55\x5a\xa8\xc1\x58\xba\x70\xeb\x19\xe3\x18\xeb\x5a\xf7\x43\xfb\x38" "\xbb\x2d\xc7\xbb\xa1\xfe\x96\x73\xb9\x17\x49\xca\x93\x9d\x31\x26\x7f\xc2\xe7\xa9" "\x9e\x17\xcf\x21\x8b\x7a\xc6\xee\x2a\x87\xb1\x64\x75\xdd\x10\xe3\xba\x37\xb4\xe1" "\x2a\xf0\x28\x3c\xff\xbe\x15\x7d\xc2\xae\x96\xd5\x7e\xcf\x8a\x73\xbf\xc8\xd0\x04" "\x69\x60\x1b\x64\xfb\x99\xbf\x0f\xef\x58\x89\xdf\x3d\xdb\x86\xb7\xff\xd6\x0d\x2c" "\x1c\x6b\x65\xcd\x0b\xe0\xa7\x2e\x8a\x67\x4a\x15\xed\xa7\x91\x83\x18\x9a\x20\x0d" "\x6c\x83\x6c\xbb\xed\xf7\xae\xdb\xb6\x37\xae\x87\x35\x05\xc4\x6d\xcd\x75\x78\xb6" "\x1f\x34\xf0\x2d\xeb\xe0\x43\xea\x0e\x27\x07\x31\x34\x41\x1a\xd8\x06\xd9\x6e\xb0" "\xdb\x5d\x77\xcb\x08\xfc\xd6\x50\xf0\xa5\xae\xaa\x79\xa2\x8d\x68\xf8\x28\x30\xae" "\xaa\x6a\x98\x62\x95\x85\x1d\xe2\xdd\x9c\x18\x9a\x20\x0d\x6c\x83\x6c\x3f\xce\x8e" "\x85\x1f\xe1\xb9\xf1\x57\xc3\x16\xdf\x0a\xdb\x11\xf8\xcd\x31\xd8\x3f\xbe\xe2\x7a" "\x6b\x77\xb1\x57\xb2\x3f\xa0\x2d\xaf\xc2\x98\x3c\x04\xf5\xbf\x96\x1c\xc4\xd0\x04" "\x69\x60\x1b\x64\x8b\x32\x83\xca\xec\x6f\xa9\xf2\x95\xad\xdc\x13\x2e\x4b\x33\x3f" "\x1e\xeb\xfb\x8e\xf6\xdd\xec\xe2\xfa\x81\x7c\xe2\xfb\x5b\x26\xda\x65\x49\xf3\xd3" "\x3c\xef\x11\x43\x63\xd2\xc0\xd6\x64\x8b\x35\xdc\xf7\xe4\xfb\x03\xd7\xb5\xae\x75" "\x87\xfb\xac\x76\x7b\xac\x65\x33\x30\x2f\x26\xc1\xd7\x7d\x95\xf7\x83\x88\xd3\x26" "\x99\x18\x1a\x93\x86\xeb\xbf\x6c\x4b\x5b\xe7\xf9\xb2\x86\x0a\xfc\xc6\x0d\x8e\xfb" "\x97\x9e\x85\xe3\x51\xcf\x3f\xe1\xbd\xeb\x7d\x79\xdd\x78\xde\x83\x90\x4d\xcc\x7d" "\x8d\x34\xb0\x35\xd9\x96\x35\x1c\x01\xdb\xaf\x62\x9c\xfc\x07\xbe\x74\x72\x3c\x5f" "\xe5\x9e\x34\xf3\x07\xa3\xfc\x7d\xd1\xce\xcf\x93\x4d\x0c\x8d\x49\x03\x5b\x93\x6d" "\x6f\xed\x18\xbc\xcb\x9e\x28\xb3\x0a\x31\xd7\x26\xfc\xbf\x1c\xef\x29\xd1\x4e\x35" "\x7e\x60\x61\x0e\xf6\x5f\xa0\xfe\x35\x26\x86\x26\x48\x03\x5b\x93\x6d\xe6\xd7\xc4" "\xb3\x98\x81\x85\x7b\xfb\x7e\xfb\x1d\xde\x61\x0e\xd7\x5c\x3f\xa2\xe1\x4f\xd1\x17" "\xf5\x2c\xfc\x0a\x39\x88\xa1\x09\xd2\xc0\x36\xc8\x96\xe7\xc2\x95\xad\x39\xac\x29" "\x87\xf8\x8f\xb3\x7a\xcc\x97\xe3\xf0\x7c\x77\xff\xb9\x5d\xe2\xfa\xd6\x9d\x80\xe7" "\xb5\xe4\x20\x86\x26\x48\xc3\x3b\x1e\xd9\xae\xcf\xbe\xc8\x15\xcf\xc9\x47\xc7\x3d" "\x6b\xb7\x1d\x63\x9f\xdb\xe7\x6e\xe7\xc2\x38\x8c\xd5\x13\xe3\xf9\x2a\x38\x88\xa1" "\x49\xa5\x81\x6d\x2a\xdb\xf5\xd9\xa8\x1c\xdf\x77\x83\xbd\xbf\x75\xef\xc4\x7d\xe6" "\x5a\x77\x4e\xf2\x13\xc4\x46\x8d\xe8\x97\xe7\xc9\xa9\x18\xfa\x54\xfa\x4d\xd9\x76" "\xf0\xab\xc7\xc3\x9f\xff\x13\xeb\xe6\x09\x71\x2f\x3a\x90\xff\x4f\x71\xcf\xd9\x7a" "\x9c\x71\x6c\x72\x8e\x88\xa1\x09\xd2\xc0\x36\xc8\x96\xe7\x96\x3c\x8b\xee\xcb\xba" "\xd0\x3f\x77\xc7\x33\xa0\xb2\xe6\xa1\xe8\xe7\xbb\x83\x98\xe7\x99\xd2\x94\xb4\xff" "\x11\x6d\xee\x78\x2e\xec\xd8\xc7\xbc\x9f\xea\xca\xba\xc9\x41\x0c\x4d\x90\xa6\xa2" "\xbd\xdc\x77\xb7\x1c\x68\xfd\xf6\x0a\xfa\xba\x16\xe3\x79\x2a\xea\xf0\x02\xd9\xc4" "\xd0\x98\x34\x03\xf9\x3a\xcf\xb1\x3e\xbc\xfd\xc1\xad\x77\xb8\x7b\x82\xef\xd9\x7a" "\x87\x5b\x64\x9e\xcf\x4a\x83\xb9\xe5\x8b\x39\x18\x3f\xc7\x7b\xef\x8d\xf9\xb8\x2b" "\xe6\xe9\x1c\xb2\x89\x39\xff\xb6\x69\x46\xfa\x8a\xf6\xbd\x18\xf7\xa3\x9c\xa1\xd1" "\xb6\xb8\x07\x1c\x6a\x62\x68\x4c\x9a\x11\x0d\xef\x62\x1c\x4f\xc1\xda\x31\x31\xc7" "\x79\x52\xd9\xba\xbf\xdd\x50\xd2\xfa\x34\x38\x88\xa1\x09\xd2\xc4\x7c\x8e\x75\xd3" "\xed\x97\xd9\xbe\x39\xee\x67\x38\x57\x2f\x4b\x3a\x66\xf0\x4e\x4d\xcc\xf6\x94\x66" "\xc7\xc2\x7e\x78\xff\x06\x7b\x2f\x5b\x83\xfd\xdd\x13\xf1\xee\xf5\xb9\xec\x2f\x3c" "\x3b\xcf\x55\x35\xcf\xb4\xf3\x93\xbf\xac\xe2\x79\x93\x18\x9a\x54\x1a\xd8\x06\xd9" "\x6e\xce\x0f\xc7\xd8\x9b\x8d\xf7\x7d\xc2\xbd\x92\x5d\x8f\xba\x1e\x1d\xe3\x01\x70" "\x2a\x86\x26\x6c\xd3\x7c\x96\xeb\x6e\x99\x85\x79\x7b\xe9\xe0\xd8\x63\x2c\xb0\x29" "\xbb\x32\xd7\xeb\x67\x5a\xf1\x1c\xec\xca\x54\x0c\x7d\xfa\x65\x3d\xc7\x30\xcf\x25" "\xb8\xc6\xf3\xee\x92\xef\x01\x0e\xe2\x43\x92\xb7\xa2\xcf\xaa\x6a\xfe\xb6\x71\x9c" "\x67\xb5\xfb\x59\x6f\xed\x99\x71\x8d\xe3\x5d\x76\xe6\x17\xf1\x79\xaa\xe7\xd0\xa7" "\xd2\xef\x5c\xd8\x17\xfe\x7f\x1f\xf4\xdf\xe9\xf1\xdd\xd8\xce\x3c\xc3\x00\xa7\x62" "\x68\x82\x34\x3c\xff\x62\x9e\x0f\xcf\x6f\x46\x25\x65\x8e\x77\x5b\xcc\x3f\x00\x07" "\x31\xef\x62\xa4\xd9\x98\x1f\x0d\xff\x35\x1d\xe3\xed\xa3\x30\x2e\x79\x19\xed\x80" "\x18\xbe\x6e\x24\x9e\x1f\x52\xf4\x6b\xcd\xfb\x90\x83\x18\x9a\x74\x9b\x66\x74\x90" "\x6d\x8c\xb7\xeb\xa6\xc7\xbb\xb4\x18\x6f\x0f\xf2\x8a\x5c\xdf\xba\x1c\x7e\x2b\x84" "\xe2\x3e\xdc\x83\xef\x09\xc5\xf5\xdd\x63\x5c\xfd\x39\xac\xc9\xbe\x86\x76\xf6\xd0" "\x7f\x44\x4e\xc5\xc5\x9c\x8f\xa2\x9e\xf7\x1d\x2a\xa7\x33\xfb\x16\xc6\x68\x3d\xfc" "\xe4\xde\xb1\x0d\x79\x6f\xc8\x35\x09\xcf\xd3\x2f\x3f\xe7\xfd\x3b\xd7\x84\x67\xb2" "\xd3\x73\xfd\x2d\x33\x8c\xf5\x06\xa7\x62\xf8\xe8\xf8\xbb\xf4\x73\x13\x92\xae\x1c" "\xfd\x35\xcf\xfa\xdf\xcc\x3a\x72\x9c\xef\x3b\x16\xf2\x58\x1f\xdb\xe2\xd8\xeb\xf5" "\x4b\xc8\xa9\x18\x9a\x54\x1a\xd8\xa6\xb2\x45\x99\xa9\xca\xc4\x9e\x3c\xc7\x98\x99" "\xbe\x93\x77\x0a\xb4\x1d\x9b\x7c\x15\xed\xbc\x11\xfd\x78\x14\xde\x71\x3a\x39\x15" "\xf3\xae\x41\x1a\xd8\xa6\xb2\x9d\x91\x7c\x33\xd7\x5b\xdb\x10\xfb\xb0\x33\x7b\xaf" "\x9e\x9a\x4f\xf2\x23\x60\x7b\x1d\xfc\xed\x6c\xc6\x96\xe4\x54\x0c\xcd\x2a\x69\x60" "\x9b\xca\x96\x2d\x52\xd2\x7e\x18\x34\x7b\x45\x66\x9d\x87\x25\x07\x85\x34\x5b\x52" "\xcf\x3a\xf0\x6e\x84\xe7\x53\xe2\x62\x1f\xcd\xc4\x1c\x69\x0d\xaf\x65\x87\xe6\x78" "\xa7\xcd\x7b\x5a\x70\x2a\x2e\x6a\x8e\xc1\x9c\xfa\x4d\x18\x95\xdc\x89\x76\x26\x5f" "\x16\xfb\x94\x77\xc8\x5b\xfc\x15\xb1\x4f\xc5\xd0\xa4\xd2\x14\x6d\x19\x7b\x4f\x0b" "\x93\x92\xca\x98\x1b\x50\x5a\x38\x20\xe6\x33\x0c\xe4\x8f\xb5\xda\xc2\x4e\x31\x9f" "\x41\x0c\x4d\x2a\xcd\xe4\xe4\x9a\x1c\xcf\x2e\xc7\x25\xbb\xe2\xf9\x5f\xa3\x9e\xeb" "\x0c\x38\x15\x43\x93\x4a\xf3\x66\xd6\x1e\xcb\xff\x24\xdf\x80\xf8\xe0\x23\xc4\x0d" "\xc7\x63\x2e\x9c\x41\x4e\xc5\xd0\xa4\xd2\x4c\x4e\x1e\x40\x9b\x37\x22\x26\xff\x09" "\x39\x15\x23\x76\xc9\xf5\xdb\x3c\x8c\x9d\x53\xc9\xa9\xb8\xe8\x37\x1a\xb7\xe6\x3f" "\x24\x49\xbf\xb9\x78\xa7\xf7\x4a\xf6\x0a\xca\x99\xc5\xb3\xcb\x00\x4e\xc5\xf4\x51" "\x65\xcd\xcc\x0f\x59\x14\x3e\xcc\x8f\x75\x1c\xab\xcc\x6d\x00\x07\x31\x7d\x94\x34" "\x5c\xe3\x38\xd7\x98\xa7\x36\x2e\xd9\xdf\x95\xd7\x4d\x8d\xf7\x01\xe0\x20\xe6\x5a" "\x26\x0d\xe3\xde\x9e\x85\x53\x63\x9e\x03\xe3\x5e\x71\x4d\xe1\x0a\xf8\xf0\x11\x58" "\x6b\x56\xa1\x2f\xbe\x85\x32\x27\x30\x37\x81\x1c\xc4\xd0\x04\x69\x36\xe7\x7f\x80" "\x35\xa3\x86\x71\x20\xef\xf8\xb0\x56\x4d\xc4\xbc\xbf\x20\xde\xf7\x89\xa1\x09\xd2" "\x0c\x4b\x9a\x10\x43\xee\x88\xe7\x27\x93\x83\xf8\x8f\xd9\x63\x39\xd6\xad\xaa\xd9" "\xc7\xb9\x49\x66\x7e\xe1\xf9\xc9\x2c\xcc\x8b\x43\x8c\xe3\x12\x9c\x8a\xa1\x4f\xa5" "\x1f\x9b\x3c\x8f\xb1\x74\x30\xe2\x99\x79\xd1\xd7\x93\x2b\x3a\x66\x93\x53\x31\x34" "\xa9\x34\x9c\xef\x3c\x37\xef\xb7\x6f\x30\xa6\xcc\x55\xd7\xed\x0f\xbf\xba\x20\xc6" "\x97\x62\xfa\x01\x69\x58\x1f\xc6\xcf\x3d\xf9\x33\xd0\x67\xab\xeb\x7b\x16\x4e\x36" "\x9e\x23\x82\x57\x89\x8b\xfd\xbb\x97\x15\xef\x52\x1b\x50\xfe\xde\xd8\x83\x9c\x6a" "\xb7\x66\xaf\xd7\x77\xb7\xec\x06\x7f\xb2\x80\xbc\x4a\xcc\xbc\x0b\x69\xe2\xd9\x31" "\xf6\xd4\x1c\x43\xcc\xb1\x39\x79\xd9\xee\x88\x43\x4e\x24\xa7\xdb\x78\x65\x2a\xcd" "\xdb\xd9\xf2\x58\xe7\xcc\x33\x4f\xf4\x89\xdc\xc9\x8f\xf2\x77\x8f\x22\xa7\x62\x68" "\x52\x69\x8a\xe7\xce\xcc\x21\x99\x65\xf7\x67\x07\xc0\x0f\x33\x3e\x3e\x92\x9c\x8a" "\x8b\xf3\x7d\x77\xac\xe5\x8d\x36\x23\xf9\x65\x6e\xde\xa3\xbb\x5b\xdf\xba\xe3\xc8" "\xa9\xf8\xbd\x6c\x3c\xf6\xfb\xb3\x30\x37\xbf\x11\xef\x33\xb8\xde\x21\xb6\x77\xa3" "\x0b\x07\x63\x1f\x74\x04\xdf\x89\x1c\xc4\xd0\x04\x69\x60\x1b\x64\xfb\x49\xbe\x6e" "\x6b\xde\xda\x2d\xe0\x29\xf1\xec\xbe\xaa\xe1\x12\x72\xd8\xc6\x75\x41\x1a\x8e\x55" "\x3e\xef\xf5\xab\x5d\x67\x36\x13\x71\xc2\x91\xf1\x6e\x09\x1c\xc4\x1c\xc3\xd2\xbc" "\x93\xff\x9e\xe3\x18\xe1\x99\xed\xa8\xe4\xc4\x18\x67\xf3\xdc\x1e\x1c\xc4\xd0\x04" "\x69\x3e\xb7\x55\xa8\xff\xa1\xbc\x3b\xce\x95\xb4\xdf\x8c\x58\xf7\x30\xe3\xfc\x06" "\x07\x31\x34\x41\x9a\x9a\x42\x17\x62\xe0\xfd\x8d\x31\x08\xcf\x4f\xab\xeb\x0e\x45" "\x3b\xfd\x8e\x1c\xc4\xd0\x04\x69\x4a\x5b\xbf\x82\xd8\xfe\x6b\xf0\xb1\x33\xe3\x19" "\xcb\xc0\xc2\xfd\x19\xd3\xc6\xb3\x14\x31\x34\x26\x4d\x7f\xcb\xce\xbe\xd7\x7f\x2d" "\xde\xf7\x54\xb6\x8e\x8a\x7b\x0a\x9e\x89\x81\x4d\x0c\x8d\x49\xc3\xbc\x0e\xee\x0b" "\xf1\x5b\xf1\x6c\xb3\xaa\x79\x3f\xb4\xe1\x5d\x64\x13\x33\xdf\x43\x9a\xea\xe4\xed" "\x98\xaf\xfb\xb9\xfd\x03\xb1\x68\x9f\x63\x7e\xe0\x67\xfe\x8f\xe4\x20\x86\x26\x48" "\x53\x5a\xf8\x3d\x7c\x51\x03\xd6\xcd\xf7\x63\x4c\xdb\xb3\xf0\x70\xc4\xd5\xaf\xc6" "\xd8\x55\x0c\x4d\x90\x86\xfb\xd0\x8a\x8e\x99\x28\xe7\x1d\x37\xb4\xe1\xd6\x38\x4e" "\x4a\x0b\x6f\x91\x83\x98\xfb\x50\x69\x7a\xf2\xe7\xc3\x5f\x1d\x19\xcf\xa0\xc0\x41" "\x9c\xf9\x6b\xe3\x39\xd2\x90\xf6\x97\x30\xae\xce\x8e\xe7\x84\x23\x1a\x9e\x62\x4e" "\x60\xcc\xc3\x60\x3e\x0e\x38\x88\xa1\x09\xd2\xc0\x36\xc8\xb6\x27\xff\x40\x1c\x0f" "\x3c\xc7\x67\x0e\x6a\x31\x3f\x67\x0d\x39\x88\xa1\x09\xd2\xf0\x5e\x85\xef\xb2\xc5" "\x3f\xcb\x7b\x78\x57\xcc\x33\x7c\x21\xe6\x3e\x88\xa1\x09\xd2\x74\xb7\x54\x7b\xfa" "\xd8\x8d\xf9\x87\xb6\x9e\xb3\x1f\x82\xfa\x3c\x49\x0e\x62\x68\x4c\x1a\xf6\x57\x79" "\xdd\x64\xf4\xe3\xd2\x78\x57\xce\xbc\x14\xd6\x8b\x77\xe5\x62\xf6\x97\x34\x65\x0d" "\xc3\x10\xe7\x4f\xc6\xdc\x61\x7e\x32\xef\xc4\xf7\xd9\x7a\x37\xc6\x3b\xf1\x22\x43" "\x63\xd2\x70\x2f\x51\xd9\x7a\x10\xe6\xeb\xa7\x39\x9e\xa5\x27\xc9\x94\x78\x8e\xc2" "\x33\x70\x31\x73\x3a\xa4\xe1\xfd\x0c\xd7\x11\xee\xcf\xaa\x93\xd7\x62\xfd\xd3\xec" "\x25\x72\x10\x43\x13\xa4\xf9\x38\xfb\x29\xc6\xdf\x4c\x63\x9c\xc2\xba\x32\xbe\x62" "\xbe\x3a\xdb\x53\x0c\x4d\x90\xe6\x9d\xfc\x31\x8e\xf1\xc6\x87\xf9\xbd\x1d\xef\x54" "\x8b\x79\x7a\x63\xc8\x41\x0c\x4d\xd8\xa6\x99\x19\xfd\xcc\x90\xf6\x1b\x63\xee\x7a" "\x31\xdf\xe9\xde\x98\x53\x24\xe6\xdc\x97\xa6\x78\xa7\xcb\x5c\xc7\xb3\x62\x2e\x19" "\xcb\xe4\x5d\x02\x73\xc9\xc4\x8c\x69\xa5\x61\xde\x45\xb1\x1f\x8f\x75\xc5\xdc\x87" "\x22\x17\xfd\xe4\x3e\x18\x7b\xff\x76\xc5\xfb\x00\xe6\xbd\x0f\xb8\xd7\x9a\x0e\xc3" "\x9a\x3e\xde\x4e\x5e\xf6\x3e\x39\x15\x43\x93\x4a\x33\x32\xa9\x8f\xfb\x2e\xcc\x61" "\xcf\xd8\xb8\xaa\xa1\x0e\xf3\x73\x47\x72\x10\x33\xc7\x51\x9a\x9a\xc2\xbd\xf0\x39" "\x7b\x63\x7e\x1e\xe0\x11\xf7\x38\x96\xc9\x3d\x19\x63\x20\x31\x34\x41\x9a\x61\x49" "\xbf\xe3\xf9\x43\x75\xdd\x28\xcf\xf9\xd9\xdd\x32\x86\xf7\x10\xe4\x20\x86\x26\x48" "\xd3\xdf\xb2\x1f\xfa\x9d\x73\x7e\x13\xe6\xd0\x4e\xbe\xa4\xa3\x1c\xeb\x66\x89\x07" "\x9b\x18\x1a\x93\x06\x31\x8e\xaf\x6a\x28\xc7\x78\xe3\x78\xae\xf7\x25\xed\x1b\xc3" "\x06\xfb\x37\xd9\xc4\x8c\x83\xa4\x49\x92\x39\x1e\xcf\x10\x53\x4c\x8a\xf7\xa1\x3c" "\x3b\x18\xc8\xff\x3a\x9e\xd3\x8b\x99\x6b\x38\xa8\xa9\x1b\x8f\xba\x6e\x8c\x79\xa9" "\x15\xed\x07\x62\x9f\xfc\x14\x73\x73\x72\x60\x13\xf3\xac\x45\x9a\x81\xfc\xbf\xd0" "\x86\x09\xde\x6b\x3d\xf6\x3d\x55\x1e\xfb\xdd\xc0\xfd\x3d\xd8\xc4\xd0\x04\x69\x7c" "\xf2\x2b\xec\xe3\xda\xe0\x73\x47\xc6\xb5\x8c\xf9\xad\xdd\x56\xc6\x3b\xae\x1c\xe3" "\x95\xa1\x0d\x1f\x07\xe6\x03\x0f\x6d\xb8\x13\xff\xde\x44\x0e\x62\x68\x52\x69\x50" "\x4e\xaa\x72\x18\x3f\xb3\x6e\x5c\x57\x8a\xfb\x88\x07\x43\xd1\xff\x56\xbb\xed\x0a" "\x4f\x42\xb3\x3b\x39\x88\x19\x63\x4b\x5f\x9e\x2c\xcf\x6d\xcc\xaf\xc7\x9e\x73\xf1" "\x56\xdb\x35\x81\xf1\xc3\x40\x7e\x17\xcc\xd5\x17\x03\xf3\x3c\xc1\x41\x0c\x7d\x2a" "\x3d\xef\x48\xca\x1a\xfa\x31\xbe\x7f\x6c\xc5\xfd\x63\x19\xc6\xe4\xff\xf0\x79\xd0" "\xf3\xe2\xbc\xfb\x14\x63\x65\x51\x3c\x9b\xde\x94\xbd\x89\x71\xf0\x1d\x72\x10\x17" "\xe7\x63\x51\x93\xf9\x7b\x10\x9b\x7d\x1c\x4a\x5b\xb9\xbf\xfd\x0d\xea\xff\x32\x34" "\xf3\x63\x5c\x2e\x86\x26\x48\xc3\xef\x2e\x98\x27\xc6\x7b\x02\xe6\x5f\x94\x27\x2f" "\x61\x6c\x4d\x20\x07\x31\x34\x41\x9a\x81\xfc\x69\x18\xc3\x7f\xc2\x1c\x9e\x11\x73" "\xf5\xca\x1a\xd2\x50\x5a\xa8\x22\x07\x31\x34\x41\x9a\xf7\xf3\xf3\x1c\xdb\x99\x67" "\xdb\xcc\xc5\xfc\xcc\xbf\x8c\xf8\xf2\x03\x72\x10\x43\x13\xa4\xe1\xd9\x63\x49\x7b" "\x37\xda\x67\x2d\x39\x88\x11\x73\x3b\x8e\x7b\xc4\x09\xf8\xe7\x22\xbc\xe3\x7b\xb1" "\x8c\xd2\xc2\xb7\x50\xe7\x32\xf8\xf3\x1f\x91\x83\x18\x9a\x20\x0d\xe3\x75\xd9\x32" "\x66\xe0\xb7\x2b\x43\x1b\x7e\x4f\x0e\xe2\x4f\xf2\x8b\x31\xef\x2a\xe3\x1e\xf7\xf1" "\x49\xdf\x75\xc7\x8d\xea\x63\x1e\x27\x39\x88\xa1\x09\xd2\x2c\x68\x6a\x71\xb3\x9b" "\x7a\xe3\xf8\x02\x07\x31\xfb\x11\xfb\x5d\x3f\x33\x59\x9c\xd6\x16\x0e\x64\x9e\xbc" "\x67\xdc\xf7\xd4\xa2\xdf\xba\x93\x97\x8d\xf3\xdc\xcb\xc2\xf7\xc4\x7b\x97\x9a\xc2" "\x5e\x98\x3f\xfb\x04\x31\x34\x41\x1a\xd8\x06\xd9\x16\xf7\xb0\x5d\x98\xdf\x57\x87" "\x2d\xfe\x26\x94\xf9\x77\xf8\xa4\x33\x50\xa7\x51\xf1\x8c\x9e\xe7\xc4\xe0\x20\x86" "\x26\x48\x43\x4b\xe6\xd3\xb3\x2f\x19\x4f\x30\xae\xd9\x60\x0f\x84\x3d\x92\x75\xcc" "\x21\x44\xcc\xfe\x1a\x39\x15\x43\x13\xa4\xa1\x2d\xf3\xab\xfa\xb2\xff\x62\x5f\x70" "\x40\x5c\xb3\x87\x25\x2f\x92\x83\xf8\xbb\x4d\xdf\x73\x8f\x7c\x74\x43\x60\x5e\x21" "\x38\x88\x4b\xda\xf9\x2d\xc6\x05\x5b\xf7\x0a\x7b\x7a\xae\x13\x4b\x06\x46\xaf\xea" "\x6f\x99\xed\xd7\x67\x8f\x32\x97\x11\x7b\xc4\xd9\x26\x86\xc6\xa4\x81\xad\xc9\xb6" "\x18\x6f\x1f\xeb\x99\xe7\xc0\xbe\xc6\x9e\x08\xbe\xad\x0f\x3e\x63\x15\xcf\xbd\x63" "\x1e\x09\x38\x88\x39\x06\xa4\xa1\x2d\xef\x99\x4b\xda\xcf\x41\xfb\x7e\xc7\x71\x8f" "\x8e\x98\x3f\xe6\xe6\x60\x7c\xa7\x65\xcd\xcd\x31\xcf\x65\x52\x72\x0f\xda\x78\x71" "\x3c\x1b\x14\x43\x13\xa4\x81\x6d\x90\x2d\xcb\xe4\xf7\x2a\x99\xff\x41\x2c\xe7\xbd" "\xec\xe7\x68\x97\x33\x62\xf9\x68\x27\x47\x0d\xf5\x62\x96\x23\xcd\xd6\xbd\x83\x67" "\xae\xda\x90\xf6\xd7\xb1\x3f\xaa\xf1\x15\xed\xbb\x91\x83\x98\xf9\x76\x88\x89\x30" "\x56\x79\x6e\x7c\x18\xd6\x15\x83\x4f\x7e\x06\xb1\xe7\xfe\xf0\x8d\xb7\xc4\x72\x19" "\xef\x8b\xa1\x31\x69\x98\xc7\xbd\xcd\x76\x57\xb4\xd9\x9c\xc0\x35\x01\x6b\x29\xea" "\x31\x1b\xf3\x68\x03\xe6\xee\xc1\x3e\xae\x67\x75\xe3\x50\xde\xc1\x26\xe6\x7a\x2b" "\x0d\xef\x46\x64\xcb\xef\x5e\xb8\x87\xef\x5a\x37\xdd\x97\x35\xcf\xf1\xbc\xd3\xee" "\x5a\xb7\x43\xcc\x15\x64\xee\x30\xbf\x35\x61\xae\xa0\x18\x1a\x93\x86\xf9\xf5\xb2" "\x65\x39\x15\xed\xcc\x55\x61\x8e\xe1\x6c\xf4\xcf\x25\x88\x15\x6a\x10\xff\x1e\xe2" "\xcb\x1a\x9e\x41\x5c\xb2\x13\xd9\xc4\xc5\x73\xd9\xa2\x86\xe5\xc8\xb6\xa2\x7d\x16" "\xd6\xaf\xbf\xc4\xd8\xad\xb2\xc0\x73\xf8\x7e\xf8\xb8\x9b\xe3\x19\x69\x75\x5d\x89" "\xaf\x2c\x94\xfa\x98\xb7\xba\x95\xf9\x4d\x9b\x34\xb0\x35\xd9\x96\xd7\x55\xa2\xae" "\xbb\x78\xe6\x5f\x75\xdb\xf6\x28\x77\x2d\x62\x9d\x19\x9e\xf7\x2d\x62\x68\x4c\x1a" "\xe6\x28\x72\x3d\xe8\x5a\x37\x2f\xe6\x28\x7e\x89\xfd\x3b\xf9\xed\xe1\x6b\x7c\x7c" "\x2e\xde\xe2\xdf\x40\xec\x7b\x37\x73\x51\x51\xaf\x61\x7e\x68\x03\xef\x8c\x2b\xc9" "\x26\x86\x26\x48\xc3\x3c\xe3\xd2\x42\x2f\xef\x8d\x62\x4e\xb1\x98\x63\x66\x63\xfe" "\x25\xe6\x64\x7b\xf8\x35\xf8\x8d\xcd\xf0\xb3\xa3\xc8\x41\x1c\xef\x56\xb1\xbf\x66" "\x7c\x0a\x0e\xe2\x5f\xb6\xbd\x9c\xeb\xad\xdd\xc9\xee\x5b\x54\x4a\x4e\xc5\xc5\xf3" "\x96\xd1\x76\x7f\xdb\x16\xde\x3d\xfa\x4f\xf2\x8d\x58\x1b\xee\x8b\xf7\x90\xe2\x24" "\x99\xef\x1f\xcd\x4a\xd2\xf8\xad\x50\xdd\x3c\x7f\x43\x36\x24\xad\x6a\xf8\x17\xd9" "\xc4\xd0\x98\x34\xc5\x9c\x9c\x2f\x98\xc7\x1c\x63\x0c\x8c\xf3\x78\xa7\xcd\x58\x42" "\x5c\xcc\xd5\x29\x6a\x98\x0f\xca\xb5\x6d\x8b\x5f\x11\xef\x5a\xc5\x2b\xdb\x6e\x77" "\xf3\x5e\x2d\x0f\x8c\xeb\x4b\xda\x9f\x74\x9c\x57\xef\x65\x3f\x80\x8f\x7e\xcb\xfd" "\x3c\xd9\x21\xc7\xfd\x1f\x38\x88\xa1\x09\xd2\xc0\x36\xc8\x36\x49\x76\xf3\xdc\xff" "\xd3\xbf\x54\x16\x86\xa3\x73\x3e\x4c\x3f\xce\xfe\x95\xb2\x4d\x3f\xc9\x37\x30\xbf" "\x2b\xde\xd1\x6d\xe3\xe1\x26\x0d\x6c\x6d\x9b\xed\x9b\x8e\x77\x27\x1f\xe6\x87\x40" "\xf3\x66\x10\xf3\x9e\xf7\xf8\x57\xdf\x0f\x3c\x73\xbd\x63\xd1\x6d\xee\x0f\x93\x6e" "\x01\x9f\x43\x0e\x62\xde\xff\x4a\xd3\x6d\x07\xf8\xed\x0a\xef\xb8\xb1\xc9\x76\xd8" "\x03\xee\x80\xbe\xff\xaf\xbb\x2a\x7b\xba\x9e\x63\x83\x79\xae\x88\xbf\x1d\xc7\x86" "\x18\x1a\x93\x06\xb6\x26\xdb\xc7\x16\xbd\xee\x4e\x7d\xf5\xab\x9e\x67\xf2\xe0\x20" "\x66\xdc\xc5\x39\xf2\x4c\x76\x7b\xca\xb6\xce\x7c\x70\x88\xe7\xc9\x41\xcc\xb8\x4b" "\x9a\xdb\x16\xbd\xe8\x4e\x7a\xb5\xcc\xf3\x4e\x15\x1c\xc4\x25\xed\x17\xc7\xdc\xb9" "\x92\xf6\x77\x10\x9b\xff\xd8\xd3\xd7\x31\x46\x2b\x6b\xf8\xae\x47\x1b\x23\xae\xfa" "\x33\xfc\xda\x85\xf0\x59\x97\xc3\xdf\x3c\x43\x36\x31\x34\x26\x0d\x63\x17\xd9\xa2" "\x4c\x1b\x2c\x73\xca\x52\xcc\xb1\x3f\x3b\xde\x6d\x0d\x2c\xbc\xc6\x2b\xdf\xa1\xb4" "\x70\xb3\xe7\x5d\x78\x4f\xfe\x7d\xb2\x89\xa1\x19\xcc\x89\x80\xad\xc9\x36\x7b\xe8" "\x2e\xd4\xed\xdf\x6e\x78\xfb\x1a\x57\xb6\xe2\x76\xb4\xe7\x5a\xc6\x6a\x6e\xa0\xf3" "\x2e\x94\xff\x77\xb7\x31\x7f\x23\xd9\xc4\xd0\x98\x34\xb0\x35\xd9\xf6\xb7\x2c\xf7" "\x9b\xf3\x6f\xc7\xbd\x45\x49\x63\x4b\xb4\xdd\x94\x4d\xc7\x5c\xb8\x1d\xfe\xe8\x25" "\xc7\x3d\x3e\xd8\xc4\xd0\x98\x34\xb0\x35\xd9\x96\xd7\x31\x37\xec\x59\x37\x3f\xb9" "\x7a\x55\x92\x2c\x85\x6f\x7d\x8a\x39\x7e\xf5\xe5\x75\x97\xa0\x7f\x6f\x73\x6b\xb2" "\xef\xa1\xfd\x2f\x31\x31\x34\xb6\x4d\xc3\x5c\xb2\xa2\x2d\x73\xc6\x36\xe7\x7f\xee" "\x46\x25\xef\xa5\x5c\x63\x98\xeb\x4c\x7d\x45\xc7\x5c\xf8\x6d\x7e\x7f\xbc\x9a\x6c" "\x62\x68\x4c\x1a\xe6\x98\x6d\xb3\xbd\x04\xf5\x5f\x1e\xf3\xfa\xaa\xeb\xce\xe7\x7d" "\x95\xfb\x38\xb9\x62\x55\xdf\xba\xd3\x3d\xf7\x69\x9d\xd9\xc4\x14\x6c\x62\x68\x4c" "\x1a\xd8\x9a\x6c\xcb\x56\xdc\x08\x7f\xfb\x0f\x7e\x3f\x9a\x2b\xe9\xb8\xd6\x73\x9f" "\xcd\xf3\x7b\xb0\x89\xa1\x31\x69\x06\x6a\x7e\x8b\xf8\xff\x9f\x6e\x73\xfe\x32\x97" "\xbd\x74\xab\xe7\x7d\x18\xcf\x7e\xc0\x26\x86\xc6\xa4\x49\x96\x2e\xc3\x78\x7f\xc9" "\xf1\x1e\x29\x7b\xe8\x16\xcf\xbb\x25\xe6\xed\x81\x4d\x0c\x8d\x49\x53\xb6\xe2\xe2" "\xf8\x5e\x5b\x7c\xbb\x2b\x5b\x7b\x35\xc6\xcf\xdf\xdc\x90\xf6\xc7\xc9\x36\xc8\x2b" "\x2e\x36\x69\xfa\x5b\xce\xf5\xbc\x9f\xa9\x68\xbf\xd7\x55\x74\xfc\x6f\xcc\x1b\x64" "\x1e\x21\xd8\xc4\xcc\x27\x90\x86\x7b\xa2\xb3\x92\x7b\xeb\xd7\xf4\x66\x33\x78\xd7" "\xb6\x5d\x61\x64\xbc\x2f\x7a\x64\xbb\x43\xfc\xd4\xa6\x0d\xb9\x7b\xe7\xff\x6a\x15" "\xd8\xc4\xdc\xe7\x49\xc3\x3d\x94\x6c\xbb\xd6\x4d\xf5\x8c\x99\xe8\x53\x10\x3b\xfa" "\xd1\x85\x3d\x5c\xf1\xac\xf1\x08\x13\x33\xaf\x47\x9a\xbe\x75\x47\xf9\xd7\xb2\xff" "\xc9\x31\xf7\x03\x6c\xe2\xd2\xd6\x53\x99\x5b\x8e\xb6\x7a\xcc\xf5\xfa\x93\x31\x96" "\x8e\xc5\x3b\xa2\x7d\xfc\x37\x7d\x6d\xe1\x4c\xcc\x91\xbb\xc9\x26\x86\xc6\xa4\x81" "\xad\xc9\xb6\xb4\xf5\x24\xd4\xe7\x47\xcc\x13\x5e\x55\xd5\x3c\xdb\xf3\x7c\x8e\xe3" "\x8d\x77\x5f\x62\x68\x4c\x9a\xee\x96\xc6\x98\xb3\xfa\xe0\xf0\xc2\xf4\x6e\x9b\xed" "\x19\x1f\xcf\x4c\x36\xd4\xdf\xdf\x36\xc3\xff\xb1\x6d\xba\xbb\xf2\xf7\xcf\xcf\x00" "\x9b\x98\x77\x0e\xd2\xc0\xd6\x64\xcb\x6f\x72\xab\x1a\xae\x76\xdc\x27\x55\x16\x0e" "\x8f\x75\xe0\xfd\x40\xe6\xe7\xc5\xe7\x8c\x35\xc1\x26\xe6\x59\xb0\x34\xbc\xa3\x92" "\x2d\xf7\x9e\x23\x1a\xae\x74\xa3\x0b\x95\xf0\x39\x8d\x31\xaf\xb8\xb2\x30\x9d\xf9" "\x53\x18\x03\x33\xdd\xfb\xf9\xd2\xad\xf9\x62\x45\xe6\xf9\xa9\x34\xdc\xab\xca\x96" "\xb9\xd0\xdc\x4b\xf4\xfa\xcb\xe3\x1a\x57\x5b\x98\x8f\x35\xa6\x80\x18\xe0\xeb\xe8" "\xeb\x5f\x81\x17\x90\x4d\xcc\x35\x4e\x1a\xe6\x4e\xcb\xb6\x2b\xfb\x2e\xc6\xd5\x35" "\x68\xdb\x6b\xc9\x26\xae\x68\x6f\xf4\xfc\xfe\x90\xef\xc0\x33\x56\xf1\xdd\x47\xd7" "\xfb\xfb\xdb\xaa\xdc\x19\x4d\xb9\x1c\xd8\xc4\xdd\xf6\xa3\x38\x26\x87\xb7\xff\x06" "\x71\xec\x99\x9e\xe7\x1c\xd4\x57\x27\x3f\x88\x67\x07\xfc\x26\x06\x6c\x62\x68\x4c" "\x1a\xd8\x9a\x6c\xcb\xeb\x4e\x8a\xb6\x9b\xf3\x93\xf1\x7c\x61\xcc\xef\xe5\x3d\x2f" "\xd8\xc4\xd0\x98\x34\xa5\x85\xd9\x31\x57\x99\x77\x7d\xcc\x03\xff\xcc\xdf\xe1\x78" "\x4f\xc8\x7b\x92\x6d\x3c\xdb\xa4\x29\x69\x3f\x21\xea\x5f\xcb\x6e\xe6\x7d\x4e\xd4" "\xef\x91\x58\xbc\xdb\x11\x43\x63\xd2\x64\xb5\x27\x47\x7d\x5f\x72\x17\xd6\xb8\x53" "\xe0\xdb\xef\x88\xfd\x0b\x36\x31\x34\x26\x4d\x55\xf3\x89\x9e\x39\x65\x6f\x67\xb3" "\x31\x26\x4f\xf6\x1c\xbf\xae\xa2\x61\x06\xd8\xb6\xf1\x89\x26\x4d\x49\xc7\x99\x71" "\x0d\xa2\xbf\xaa\x2c\x9c\x1a\xd7\x29\xee\x1d\xc0\x26\x86\xc6\xa4\x29\x1d\x71\xa9" "\xcf\xfc\x5f\xb9\x17\xc5\x3a\x52\xf0\xc3\xdb\x03\x73\xf3\xc9\x26\x86\xc6\xa4\x29" "\x5b\xb1\x0c\xe5\xaf\x47\x7b\xdf\xef\x4e\xfd\xe2\x1a\xac\x2f\x1d\xee\xd8\xa6\x36" "\xb2\x89\xa1\x31\x69\xb8\x06\xf5\xfa\xce\x78\xc6\x59\x32\xe5\x16\xcf\x38\xba\xb4" "\x70\x03\xd9\xc4\x5c\x83\x06\x35\xed\x37\xa2\x4d\x3e\xc4\xdc\x7f\x2e\xd7\xbf\xdf" "\xad\x51\xcf\x3b\x5e\xb0\x89\xa1\x31\x69\xfa\xce\xbd\x14\x73\xff\x2f\x58\x2f\x6a" "\xea\x4b\x5b\xaf\x8d\xf9\xc9\xf0\xf9\x39\xb0\x89\xa1\x31\x69\xb0\x7f\x8a\xdf\x68" "\x74\x96\x2d\x85\x1f\xbb\xc0\xc4\x55\xcd\x5f\xc7\xf8\xbc\xc7\xf1\xfb\xbe\x9e\x85" "\xdf\xf4\xf4\x19\xfc\xce\xa4\xa4\xfd\xbb\x9e\xdf\x28\x20\xe6\x21\x9b\x18\x1a\x93" "\x06\xb6\x26\xdb\x81\xfc\xf7\x3d\xcf\x5b\xf9\xf7\x10\x98\x4f\xde\x6f\x7f\x00\x3f" "\x8c\xfa\x5c\xe4\x99\xa3\xc7\xb3\x3e\xb0\x89\x99\x67\x2e\x0d\x6c\x4d\xb6\xbd\xb5" "\x3f\xc5\xbb\x3f\x11\xf3\x35\x10\xef\xc7\xd8\x9e\x77\xd1\xa5\xad\x97\x60\x3e\xf2" "\xdc\xf7\x44\xb2\x89\xa1\x31\x69\x60\x6b\xb2\x2d\xaf\xbb\xcc\x17\xff\x2e\xc5\x2f" "\x5c\xb2\xf8\x6a\xcf\xdc\x4a\x9e\x91\x32\x97\x9e\x67\xcc\x3c\x33\x60\x2e\xbd\x18" "\x1a\x93\x06\xb6\x26\xdb\xa6\x51\x57\x78\xc6\x05\x8d\x4d\x37\x63\x2d\xf8\x29\xc6" "\xf9\x93\x8e\xb9\x30\x60\x13\x43\x63\xd2\xf4\x65\xdf\xf7\x9f\xdb\xfd\xd8\x5b\xce" "\x25\x9b\xb8\xb2\xf5\x74\xcf\xfc\x82\x71\xc9\x48\xb2\x89\xcb\xeb\x16\xc5\xb9\xf3" "\x5c\xb2\x16\xeb\xfe\x22\x13\x0f\x74\xfe\x12\xfa\xbf\x3a\x9e\x6f\x81\x6d\x90\x6b" "\x96\xc6\xdc\x72\xfa\x11\xb0\x89\x4b\x37\x2c\xf3\x3c\x53\x2f\x4f\xbe\x4d\x36\xf1" "\xfc\x83\xae\xc3\x38\x5c\xe7\x8e\x5c\x76\x33\xd9\xc4\x7d\xd9\x25\xe8\xa3\xe7\x1d" "\xbf\x3f\xa6\x2f\xe5\xdd\x0b\x62\xf1\xb4\xb4\x75\x11\xc6\xf9\xea\xf8\x9d\x25\xd8" "\xc4\xc5\x5c\xda\xa2\x06\xb6\x26\xdb\x92\x8e\xdf\x61\x2e\x6c\x88\x39\x11\xfd\x2d" "\xcb\xfc\x06\xeb\x77\xdc\xe3\x81\x4d\x0c\x8d\x49\x93\xd5\xfe\x1e\xed\xf9\xa9\xfb" "\xcc\xdf\xec\xda\x26\xb5\xf9\x15\xcf\x97\x78\xb6\x39\xd8\xc4\xd0\x98\x34\x03\x0b" "\x6f\x8f\x39\xf0\x03\xf9\xff\x73\xf7\x1d\xbd\xdc\x2f\xff\x88\xfb\x95\x27\xc8\x26" "\x86\xc6\xa4\x61\x7c\xd5\x6d\x7f\x8b\xdf\xa3\xf1\x7b\x9f\xcc\xf3\x5b\x31\x9e\xe1" "\x5f\x6f\x62\xc6\x5d\xd2\x70\xdd\x1c\xc8\xdf\xe5\xf8\x9e\xdd\x2d\x8b\xb1\xa6\xbc" "\xe2\xf8\x37\x43\xc0\x26\xe6\x7a\x2a\x4d\xf6\xd0\x25\x9e\x39\x4a\xd8\x7f\x61\x5d" "\x6e\xc2\x5a\xf3\xe7\x18\x87\x83\x4d\x0c\x8d\x49\xb3\xfc\xa3\x56\xff\xf0\x95\x55" "\xf1\x3b\x22\xb0\x89\xf9\xed\x18\x63\xd7\x21\xed\x4b\x62\x2e\xaa\xb8\xac\xe1\xd0" "\x98\xab\x3f\x35\xf9\xc7\x2a\xb0\x89\xab\x57\x74\xb8\xfe\xb9\x87\xdb\xce\xad\xbb" "\x39\x70\x10\x6f\x57\xe8\x8e\x7f\xd3\xe0\x8d\xfc\xbf\x73\xe0\x20\xae\x6a\xa8\xc6" "\x3c\xda\xc9\xf8\xfd\x29\xd8\xc4\xcc\x67\x2e\x69\x1f\x67\x6b\x7a\xf3\x4f\x33\x6f" "\x59\x3c\x7c\xc4\x4a\x57\x71\xc5\xc1\xf1\x9e\x0b\x1c\xc4\xc9\xe2\x95\x78\x9f\x23" "\xed\x53\x5f\x8a\x39\xb2\x32\x88\x87\x35\x5e\xe9\xaa\x2e\x3c\x3a\xd6\x01\x1c\x06" "\xb9\xe3\x74\x97\x55\xd5\xc7\x3a\x80\x83\xf8\xbd\x8c\x67\x9b\xbb\xc7\x3a\x80\x83" "\x98\xf9\x0f\xcc\x59\xe2\x59\x26\xf3\x1c\xc4\xb5\x85\xdd\x10\xaf\xd7\xdb\x98\x86" "\xc8\x41\xfc\xa9\xff\x61\x5c\xbf\x4b\x3a\x22\x07\xb1\xea\xc3\x98\x4d\xf5\x89\xbc" "\xb5\x3e\xf4\x17\xaa\x0f\x59\xf5\xa9\x29\xbc\xe1\x54\x1f\xb2\xda\x87\x67\xfb\x6a" "\x1f\xb2\xda\x87\xb9\xba\x6a\x1f\xb2\xda\x67\xfb\xe6\xa7\x06\xdb\x87\xac\xfe\x62" "\x1d\xd4\x5f\x64\xf5\x17\xeb\xa0\xfe\x22\xab\xbf\x58\x07\xf5\x17\xb9\x3c\xd9\xd9" "\xf3\x4e\xa8\x98\xb3\xbc\xb3\x89\xb3\xda\xed\x7d\xf7\x7e\xfb\xc4\x36\x61\x9e\xa3" "\x98\xf7\x50\x15\x8d\x0d\xb1\x4d\x78\x0f\x25\x7e\x7c\xd2\x87\xee\xee\x45\xb3\xad" "\xfd\xa3\xc8\x41\xbc\xe0\xfd\x37\xdd\x49\xfb\x1e\x65\xf7\x1d\x7d\x27\x39\x88\x9b" "\xcf\x5f\xe9\xe6\x3f\x70\x9c\x9d\x79\xfe\x23\xe4\x20\x3e\xe2\xd5\x25\x8e\xf9\x0c" "\xd4\x80\x83\xb8\xb7\xb6\xe0\x4e\x3b\xff\x84\x58\x26\x38\x88\xa5\xbf\xaa\x6d\xbf" "\x41\x3d\x79\xce\x41\x2b\xdd\x5d\x57\xce\xb3\xed\x5a\x2f\x24\x07\xb1\x7e\x77\x8b" "\x1f\x31\xf8\xbb\x64\xd5\x93\xb6\xaa\x27\x99\x67\x17\x8c\xb3\xbf\x68\xf9\x77\xe4" "\xda\xd9\x73\xed\xb5\xf3\x56\x6e\xbd\xd3\xd9\x96\xf3\xc3\xd8\xe5\x73\xbb\xad\x98" "\x5b\xb2\xf4\xe8\x98\x2b\x12\xef\xf7\x37\x30\x4f\x60\x66\x31\xaf\x18\xfb\xe1\x3b" "\x9f\xef\x70\xc5\xf3\xd5\xa1\xf6\xb3\x21\x23\xe3\xd9\xc8\xd0\x86\x5e\xc4\x02\x5f" "\xf7\xc5\x3c\x99\x23\x7c\x77\x4b\x79\xe4\xca\xd6\x23\x3c\xe3\x1c\x32\xf7\xb3\x65" "\xcd\x2b\xc3\x8e\xcd\xdf\x71\x95\x6f\xec\xc8\xbf\x1d\x43\x0e\xe2\xcd\x2f\x61\xbd" "\x5f\x3b\x22\x7e\x13\x0e\x0e\xe2\x61\x1d\x77\xbb\x92\x31\x35\x56\x32\x65\x92\x81" "\x83\x98\xeb\x61\x45\x63\x35\xfc\xce\x02\x72\x18\xe4\x97\x6e\x71\xc9\xbd\x95\xc6" "\x7d\x1e\x38\x88\x99\x4f\xd6\x7f\xf9\x50\xcb\x5e\x3a\x9f\x1c\xc4\xb1\xce\x1d\x23" "\x6c\x60\xe1\xff\x58\x69\xeb\x9b\xae\xe7\xf1\xed\x6d\x6d\xbe\x13\xbe\xfd\xcd\x20" "\xee\x1b\x5d\xe7\xab\x2e\xac\xb4\xbe\x81\xe3\x56\x81\x4d\x5c\x31\xe6\x68\xf8\xea" "\xcd\xa1\xb6\xf5\x6b\x0e\x6c\xe2\xae\xd1\x27\xf8\xbe\xd5\x3b\x60\xdc\x3e\x47\x36" "\x71\xef\x05\xfb\xfb\x8a\x8e\x5a\xdb\xf4\xd0\x17\x64\x13\xf7\xb7\xf4\xa2\xce\x93" "\xad\x6f\xf9\x68\x0f\x0e\xe2\xed\x46\xdc\xed\xaa\xaa\xa7\x5b\x32\xed\x60\x72\x10" "\x8f\x6f\x9f\xea\x4a\xae\xf0\xfc\xde\x80\x1c\xc4\xfb\x36\xdc\x9a\xeb\x3a\xd7\x59" "\xe9\x86\xcc\x81\x53\x31\xef\x99\x2a\xdf\x60\xce\xde\x5a\x72\x10\x1f\x92\xf4\xe6" "\x78\xa7\xcc\x7c\x6d\x70\x2a\x1e\xdf\x71\x8a\xeb\x5b\xee\xed\xfd\xfc\xf5\x39\x70" "\x10\x57\x8e\x08\xae\xa4\xe3\x40\x6b\x4e\xde\xa9\x07\x07\x71\xdf\xb9\x25\xbe\xeb" "\x90\x7d\xec\x45\x7f\x0b\x62\xaa\x12\x13\x97\x4c\x19\xef\xcb\x97\xee\x61\x7d\xeb" "\x0e\x43\x5c\x37\xde\xc4\xd5\xcf\x4e\xf4\xa5\x1b\xf6\xb4\xb2\x15\x37\x93\x4d\x5c" "\x3a\x62\xb4\x4f\xa6\x4d\xc6\x7c\x6c\x27\x9b\xb8\x6c\x6d\x07\xe6\xf6\x0c\xdb\xdc" "\xf9\x2e\x39\x0c\x72\xf3\x4f\x63\x7e\x45\x69\xeb\x67\xe4\x20\x8e\xc3\x73\xe9\x0c" "\x2b\x1d\xe1\xed\xec\xb3\x3f\xc8\x85\x2f\x0e\xb5\x53\x9f\xa8\x27\xa7\xe2\xcf\x7c" "\x77\xae\xfa\xd9\x03\x8c\xeb\x12\x38\x15\x6f\x57\xb8\x0e\x31\xc4\x14\xeb\x5d\x7f" "\x06\x39\x15\xb3\xc8\x9e\x97\x26\x5b\xf5\x8a\x62\xfe\x21\xcf\x46\xcb\x93\x3d\xe3" "\x1c\x59\xd0\xe4\xed\xae\xb6\x21\xe1\xef\xf6\x97\xdc\xd6\x7b\x5b\x72\x2a\x7e\xd7" "\xf7\xe7\x7a\xf6\x6c\xb0\x1d\x5a\xcf\x26\xa7\xe2\xaa\xd3\x1e\xcf\xad\x3a\xdf\xd9" "\x9e\x97\xde\x4c\x4e\xc5\x95\xad\xcf\xb9\xaa\x0d\x93\xd0\xe6\x53\x53\x70\x10\x97" "\x6e\x18\xed\xab\x36\x8c\xb7\xb6\x7c\x63\x0e\x6c\x83\xdc\x7a\xb0\xef\x3b\x77\xac" "\x55\x16\x8e\x46\xec\x77\xb0\x89\x2b\x3a\x66\xf8\xd2\x27\x76\xb7\xca\x11\x8f\x91" "\x4d\xcc\x6f\xd7\x7b\xab\x0e\xb2\xae\x75\x6f\x92\x4d\xdc\xd3\xf9\xa1\xeb\xae\x39" "\x02\x73\x61\x88\x07\x07\x71\x65\xe1\x77\xe8\x8f\xb9\x36\xf0\xf8\x78\x72\x10\x63" "\xff\xe2\xba\xe6\x9e\x68\xfd\x2d\xa3\xc9\x41\x0c\xbf\x9c\x1b\x98\x3d\x0f\x63\xf2" "\x7d\xec\xa3\xde\x48\xc5\xb9\x57\x47\xba\x53\x5f\x3d\xd2\x3a\xa7\x3d\x93\x82\x83" "\xb8\xac\xa1\x09\xe3\x7c\xaa\xf1\x9e\x11\x1c\xc4\xf4\x77\x15\xf7\xee\x8b\xf9\x33" "\x99\xbe\x2f\x88\x7b\x3a\x7f\x81\xf1\xbc\x27\xc6\x59\x23\x39\x88\x99\x0b\xd1\xd3" "\xb9\x2b\xc6\xcd\xd9\xe4\x20\xae\x6a\xde\x11\x7b\x89\x5d\xad\x7a\xe9\x39\xe4\x20" "\x2e\x9e\xeb\x4e\xb4\xbe\x25\xc5\xbb\xc8\xeb\x27\xe6\xec\xc9\x69\x93\xa2\xbf\xa2" "\xcf\x1b\x5d\x38\x09\x6b\xec\xbd\x2e\x59\xc0\xbb\xf5\x2e\x72\x10\x6f\xa9\x1d\xeb" "\xfa\x96\x34\x60\x1d\xaa\x26\x07\x31\xfb\xba\xac\x7a\xa6\x75\xd6\x7e\x9d\x9c\x8a" "\x47\x34\x7c\x94\xab\xda\x30\xdd\xaa\xaa\x27\xf1\x1b\x83\x54\xec\x1a\x1e\x8f\x7f" "\x13\xe9\x8b\x9a\x8f\x02\x38\x15\xb3\x0e\xcc\x87\xe4\xdf\x9e\x50\xae\x2c\xef\xfc" "\x0e\x2b\xdc\x9f\xe3\xfd\x71\xf9\xe2\xab\xc8\xa9\xb8\xa6\xd0\x95\xab\xb8\xe2\x68" "\x8c\x93\x6f\x92\x53\xf1\xce\x85\x17\x73\x5d\x87\xcc\xb1\xcd\x0b\x47\x93\x53\xf1" "\x5e\x85\x09\xf1\xf9\x0e\xed\xc3\xc8\xa9\x38\xde\x7f\xad\x9e\x67\xcf\x4c\x9b\x1b" "\x26\x5d\x3b\x33\xf7\x93\x5d\xe6\xda\xd4\x6b\x77\x25\xa7\xe2\xae\xf3\x56\xc6\xe7" "\x4b\x76\xd9\x9b\x9c\x8a\x3f\xc9\xb7\xe7\x92\x67\x4f\xc0\x7a\xd4\x4c\x4e\xc5\x5d" "\xd7\x2c\xc9\xad\xdd\x78\x9c\xcd\x6e\xba\x98\x9c\x8a\x8b\xf7\xbf\xc7\x5b\x59\xf3" "\xd5\x81\x73\xb9\x7c\x71\x8d\x55\xb6\xde\x41\x0e\xe2\xed\x5a\xf7\x72\x5d\xcb\x0f" "\x44\x9b\x2f\x26\x07\x71\x4d\x61\x5a\xcc\xe5\xe3\xf9\x32\x38\x88\xbf\xda\xf1\xcd" "\xb8\x8e\x74\xad\xbb\x88\x1c\xc4\x31\xb7\x70\xee\x64\xac\x6b\x0b\xb1\xc7\x9a\x1d" "\x73\x89\xcb\x9f\x3d\x8d\x9c\x8a\x3f\xcc\x3f\x99\xeb\x5b\x7e\x00\xc6\xea\x09\xe4" "\x54\xfc\xba\xfd\x3e\x57\x76\xe1\x21\x56\xb5\xd7\x61\xe4\x54\x1c\x73\xc3\x56\x60" "\xfd\x5c\x3c\xc7\x0e\x2d\xfc\x36\xd7\x78\xd0\x24\xeb\xbe\xfc\x08\x72\x2a\xbe\xe1" "\xbc\xfb\x73\x1b\xee\xde\xcb\x1e\x9c\x34\x97\x9c\x8a\x6f\xcc\x1a\x73\xc7\x7f\xb2" "\x9b\x65\x0f\x9d\x44\x4e\xc5\xf1\xce\x6b\xc9\x6e\x56\xd2\x78\x8a\xfd\xc7\xa6\x60" "\x5d\x39\xd2\x36\xd5\x7e\xd3\x81\x83\x98\x3e\x34\x5b\x3f\x2b\xfe\x6d\x43\x70\x10" "\x73\xcf\x5a\x55\x7d\xb8\x6d\xac\x79\x8b\x1c\xc4\xd8\x57\xb8\xfe\x2d\xb3\xb6\x7e" "\x57\x7f\x65\x10\x33\xdf\xa8\xf4\x8d\x06\xac\xfb\x2f\x90\x83\x18\x6b\xa3\x2f\xbb" "\x09\xed\xd9\xf2\x48\x5c\x33\xc5\x15\xf7\x8e\xf2\xbd\x27\x4f\x46\x1d\xae\x27\x9b" "\xb8\xf7\x82\x91\xbe\x62\xcc\x64\xdb\xb1\x79\x0e\xd9\xc4\x43\xeb\x3e\x8f\xf9\x36" "\x7d\xd9\x1b\x39\x70\x10\xd7\x6c\x58\x85\x98\xaf\xde\xf6\x6c\x5f\x4a\x0e\xe2\xea" "\xba\xf3\x5d\xcf\x8d\xb3\x6c\x97\x86\x75\xe4\x20\xde\xa1\xf5\x60\x37\xf0\xf8\x91" "\x36\x74\xe9\x4d\x0e\x1c\xc4\x25\x1d\x0b\x5c\xbf\x1d\x89\xf1\x6c\xe4\x20\x1e\x97" "\x9c\xe7\x98\xdf\xc7\x73\x3c\x70\x10\xf3\x5b\x1e\xe6\x32\xf1\x7c\x9b\xdf\xe0\x88" "\xb9\xdf\x60\x0e\xfc\xb8\xa4\x24\x7e\xb7\x28\x66\xfe\x0f\x73\x29\x67\x24\x7f\x8a" "\x79\x3e\xe2\x91\xc9\xff\x39\xde\x31\xa0\xab\xb0\xb7\xff\xbf\x20\xe6\xdf\x79\x28" "\xfe\xed\x9d\x26\xb2\x89\x99\x9b\x54\xd5\xb0\x4f\xfc\x7b\x16\xcc\x4d\xda\xc6\xe5" "\x31\x07\x89\x7f\xdf\x02\x6c\x62\x7e\xbb\x58\xd2\x9e\x33\xde\x11\xf0\x8e\x59\xcc" "\x9c\x27\xe6\x89\xf1\xbb\x48\x70\x10\x33\x16\xe2\xdf\x1a\xda\x9c\x2f\xe6\x6b\x89" "\xb9\xff\xaf\x6a\xe0\xbb\xec\x4f\x0e\xe2\xbe\x6c\x4e\x7c\xce\x73\x70\xde\x5b\x8a" "\x7f\x7d\x45\xe2\xce\xf9\x60\x17\x9b\xf7\xf3\x1e\x72\x10\xb7\xb4\xcd\x73\xbc\xe3" "\x59\xd0\x34\xd1\x83\x83\x78\xdc\xea\xe5\xae\x76\x76\xad\x9d\xd6\x34\x89\x1c\xc4" "\xa7\x2d\xf9\xc8\x9d\x9b\x0e\xb7\x71\x0f\x0e\x23\x07\x71\x59\xf5\xd7\xfc\xf6\xcd" "\x3d\xa1\xa4\xf1\x13\x07\x36\x71\xf5\xb3\xb3\x3d\xf3\x1a\x4a\x1a\x9f\x21\x9b\x18" "\xeb\x8f\x1f\xd6\xf8\x54\xd8\xb5\xe1\xe0\xb8\x2e\x89\xcb\x6e\x1a\xef\xbb\xce\xfd" "\x6b\x58\xf1\x9e\x3d\x09\x36\xf1\x19\x4d\xaf\xba\xf3\xca\x3e\x08\x7b\xbc\xf3\x6e" "\x0a\x0e\xe2\x98\x37\x5b\x7b\x79\xe8\xdf\xaf\x18\xa3\x32\xb7\xbe\xd7\xff\x28\x72" "\xcf\xc2\xf1\x7e\x68\x43\x31\xd6\xad\x2d\x94\x87\x8d\xf9\x75\x5b\xf3\xbd\x3f\xc4" "\x78\xfa\x61\x9c\x8f\x35\x85\x27\xb0\x2e\x1d\x15\x79\x78\xfb\x3d\x88\x35\x77\xb2" "\x62\xde\x02\xe6\x52\xcb\x26\xf8\xfe\x46\x3f\xb1\xfd\xc3\x74\x63\xfe\xdb\x58\x13" "\x1a\x4d\x7c\xd3\xd8\x93\xfc\xa1\x7b\x1f\x9b\xbb\x7a\xa7\x5b\xc8\x26\x7e\x6c\xf6" "\x4c\x7f\xf6\xd9\xaf\xb9\xd1\xaf\x2f\x25\x9b\xf8\x33\xff\xb2\xeb\x3d\x79\x12\xda" "\xe8\xdd\x98\xf7\x21\xbe\x67\xf6\x01\xfe\xfc\xf1\xcb\xd2\x27\xc6\x57\xa4\x60\x13" "\x9f\xf4\xc4\xb8\xf8\xf7\x1f\x9e\x3f\xa1\x83\x6c\xe2\xde\x93\xf7\x40\xbc\xf8\xa2" "\x3b\x2b\xb9\x77\x06\xd8\xc4\x2b\xda\xee\x71\xf3\x0f\xda\xdb\x3f\x93\xdd\x9e\x03" "\x07\xf1\x87\x0b\x7f\xe8\x36\xcc\x7d\x39\x8c\xa8\xfb\x73\x00\x07\xf1\x06\xdb\xdd" "\xf1\xef\xba\xf1\x1e\x0f\x1c\xc4\x59\xed\x12\xd7\xb3\x70\x4d\xcc\x7b\x03\x07\x31" "\xff\x9e\x52\xd9\xda\xb5\xf1\x9b\x40\xfe\x4d\x1a\x71\x7a\xde\xf5\xee\xac\xa6\x7f" "\x85\x9f\xec\xf2\x2d\x72\x10\x97\xb4\x8f\x74\x9f\x9f\x6b\xf0\x47\x0d\xe4\x20\xce" "\x6a\xab\xdc\xe6\xce\x3f\xc0\x1f\x0d\x25\x07\xf1\x0e\xad\x7b\xb8\x4d\xb5\xef\x86" "\xca\x27\xbe\x4f\x0e\xe2\x83\x7e\x7e\x9e\x3b\x7e\xd6\x4b\xe1\x9f\x2f\x5c\x17\xc0" "\x41\x7c\xed\x47\x3f\x76\x0b\x1f\xfd\x0c\x75\x3b\x8d\x1c\xc4\x7f\xb9\xf1\x17\xee" "\xda\x9f\x24\x36\x6e\xf5\x7e\xe4\x20\x7e\xf0\xe9\x53\xdc\x8a\xeb\x6b\x43\x7e\xa7" "\x94\x1c\xc4\x9f\xaf\xbb\xca\x0d\x5d\x5a\x70\x95\x23\x7e\x43\x0e\xe2\xdb\x27\xb5" "\xb8\x53\x46\x0d\xf1\xbd\xbe\x8a\x1c\xc4\xfd\xfb\xbd\x0e\xff\xb6\x16\x9a\xe3\x3d" "\x38\x88\xe9\x73\xff\x66\x8f\xe5\x7a\x2f\x38\x2b\xe6\x39\x88\xbb\xe6\xbe\x0e\x7f" "\x72\x62\xa8\xe8\x3a\x9e\x1c\xc4\xc9\xd2\xb7\x60\xf7\x5a\xe0\xb7\x6e\xe0\x20\xee" "\x9f\xeb\xf8\xf7\x4f\xe0\x4f\x5f\xc6\x1e\xda\x99\xb8\xef\xdc\x5d\x3d\xf3\xbb\x2a" "\x5b\xbb\xc9\x26\x2e\x5f\x3a\x81\x7f\xa7\x22\xed\xde\xb2\x2f\xe2\xf1\x09\x26\x2e" "\x19\x33\xdb\x73\x9d\xab\x9c\x32\x84\x6c\xe2\x9e\xc7\x39\x1f\x87\x63\xce\x8d\x22" "\x9b\x98\x39\x09\xe5\x75\x93\x5d\xd5\x4d\xb9\x98\x63\x20\xee\x59\x38\xc1\x17\xff" "\x26\xcd\x1e\x64\x13\x5f\xb4\xcb\xe1\x9e\x7f\x87\xe3\x0f\x93\x2a\xc9\x26\xee\xfe" "\xf6\x57\x7d\xf5\x7f\x87\xfb\x2f\x5a\x1e\x70\x60\x13\x9f\xf6\xdc\x66\x77\xfc\xab" "\x15\xfe\xa2\xac\xa5\x1e\x1c\xc4\xff\x9e\x78\xa2\x9f\x9b\x9b\xc7\xb3\x50\x07\x36" "\x71\xad\xbd\xe4\x06\x6e\x9b\x10\xff\xd6\x20\x38\x88\x79\xb6\xf0\x95\xf6\xf9\xee" "\x53\x3f\x95\x1c\xc4\x7d\xeb\xce\x8a\x79\x14\xfc\x0e\x0e\x6c\xe2\x92\x31\xc7\xf8" "\xf1\x1d\x87\x3a\x7e\x8f\x02\x36\x71\xd9\x4d\x97\xa0\xbd\xda\xdc\x8e\x85\x16\xb2" "\x89\x4b\x5b\x5b\x31\x2f\xdf\x74\x3b\x35\x5c\x87\xd8\xbb\xd5\xc4\xe5\xe5\xf7\xf9" "\x0d\xeb\xfe\xe5\x7a\x1f\xba\xd5\x81\x4d\x5c\xd2\x75\x2b\xc7\x81\xdb\x98\xef\x24" "\x9b\xb8\x6f\xf4\x25\x7e\x73\x67\x9b\x1b\x3e\xe5\x63\xb2\x89\xcb\x7e\x7a\xb1\xdf" "\xfc\xd2\xad\xcc\x45\x23\x9b\xb8\xbc\xfc\x46\xff\xf9\xb9\xab\xe1\xeb\xff\x41\x36" "\x71\xf6\x50\x2b\xf3\x00\x51\xe6\x12\xb2\x89\xcb\x56\xde\x8c\x76\x65\xee\xf0\xa3" "\x39\xb0\x89\xcb\xff\x7b\xb1\xdf\xf2\xd0\x6d\xee\x98\x64\x60\x15\xd8\xc4\x55\x1b" "\x4e\xc2\xde\x7d\x1f\xf7\x81\xbf\x04\xf1\xe9\x49\x26\xce\x2e\xf8\xbe\x7f\x3f\xff" "\xc3\x78\x2f\x06\x36\x71\x32\xed\x87\x18\x0f\xbf\x71\xd5\x75\xb7\x93\x4d\x5c\x3a" "\xe2\x5b\xfe\x3f\xb6\xd8\xf1\x5b\x33\xb0\x89\x4b\xfe\x75\x09\xfc\xf6\x63\xee\xc9" "\xbe\xcb\x67\x80\x4d\x5c\x3a\xf4\x46\xcf\xbf\x17\xf8\x91\xff\x5b\x0e\x6c\x83\x3c" "\xe2\x76\xff\xf9\xba\xf7\xdc\xe8\xd6\x9f\xa1\xcc\xdb\x4d\x9c\xd5\x2e\xf3\xe5\x8b" "\xdf\x42\xdb\x3e\x42\xb6\x41\xf6\x97\xf8\xe1\xad\x8f\x63\x0f\xf0\x30\xd9\xc4\x3d" "\x9d\xa7\xf8\x77\xfd\xe9\x6e\x68\xc3\x0d\x64\x13\x77\xef\x37\xdf\x0f\x59\x7c\x25" "\xd6\xda\xfd\xc9\x26\xe6\x19\xc6\xf6\xcd\x57\x3a\x7e\x1f\x03\x36\xf1\xb8\xd5\x73" "\xfd\x79\xbb\x2c\x75\x0b\x56\x5f\x47\x36\x71\xf7\xeb\xf3\xfc\x17\x35\x57\x62\x2d" "\x7d\xa2\x1e\x6c\xe2\x8a\xc6\x46\x8c\x87\x4b\xdc\x65\x49\xf3\x2a\xb0\x89\xef\x9c" "\x9e\xf3\xe7\x37\xb5\xe6\xae\x6c\x2a\xcb\x81\x4d\xbc\xbb\x9f\xee\x0f\x9d\xb5\x8f" "\xbb\xe3\xcd\x8e\x55\x60\x13\xaf\x28\xc9\xf9\xdd\x7f\x33\xcb\xdd\x7e\xf4\x91\x39" "\xb0\x89\x4b\x9f\x38\x2e\xde\x4d\xf7\x2c\x3c\xde\x81\x4d\x9c\x3d\xf4\x4d\xec\xc7" "\x7e\xe5\x46\x75\xfc\x2f\xd9\xc4\xe5\x4b\xcf\x46\x7b\xde\xe9\xc6\xd5\x7d\x87\x6c" "\xe2\xdd\x66\x9f\xe4\x79\x36\x7f\xd1\xba\xae\xa7\xc1\x26\xee\x59\x78\xaa\xaf\x69" "\xbe\xc3\x3d\x99\x3d\x5b\x0f\x36\x71\xd7\xf2\xf9\x9e\x7f\xe7\x00\x73\x21\x07\x36" "\xf1\x73\xe7\x1d\xe3\x27\xac\xfe\xad\xeb\x9b\xf6\x26\xd9\xc4\xc9\xe2\x05\xbe\x7a" "\xe9\x1d\x6e\x48\xc7\x1e\x0e\x6c\xe2\x93\x8e\xba\x2c\xe6\x0c\xcc\x39\xe8\x2e\xb2" "\x89\x4f\x19\xbb\xcc\x77\xdb\xc7\x6e\xde\xa3\x77\x93\x4d\x9c\x5d\x70\x9b\xaf\x6c" "\xdd\xe8\x86\xb7\x9e\x4b\x36\x71\xff\xc5\xbf\xf1\xbd\x0f\x7d\xec\x5e\xf4\x6f\xe6" "\xc0\x26\x2e\x19\x73\x69\x3c\xeb\x1e\x9b\x85\x7a\xb0\x89\x33\x7f\x76\xbc\xff\xfa" "\x63\xe9\x4d\x4f\x83\x4d\x5c\x75\xe1\x4f\x7c\x77\xcd\xc3\xee\xb3\x85\x4b\x1d\xd8" "\xc4\x25\x5d\xdf\xf2\x25\x1d\xf7\x3a\x7e\xff\x04\x36\x71\xcf\x8d\xdf\xc7\x7b\xdd" "\xc7\xbf\x85\x40\x36\x31\xd6\x3e\x5f\x8c\x1d\x3f\x25\x9b\xb8\x6b\xf9\x8f\xfd\xc6" "\x9a\x47\xf8\x8d\x04\xf6\x34\x3f\x36\x71\xff\x5b\xbf\xc0\xbc\x08\x6e\x58\xc7\x39" "\x64\x13\x27\xf7\x5f\xe1\xb7\xd4\x3e\x17\xbf\x29\x01\x9b\x78\xfa\x9a\x25\x3e\x3d" "\xef\x15\x77\xd1\x7b\x67\x92\x4d\x7c\xf2\xee\x57\xf9\x2d\x4b\x5e\x74\xa7\xdc\x7d" "\x35\xd9\xc4\x25\x07\x62\xde\xad\xfb\x08\xef\xd2\x4e\x36\xf1\x43\x7f\xf8\xad\xbf" "\xe7\xf0\x72\x5f\x5d\xf7\x22\xd9\xc4\xed\xe5\x6d\xfe\xeb\x87\x0f\xb8\xd7\xa6\xdd" "\x40\x36\xf1\x03\x53\xef\xf4\xf7\x3f\x5f\xca\x58\x27\x07\x36\x71\xb2\xcb\xa5\xbe" "\x6f\xdd\x87\xee\xce\x92\xfa\x55\x60\x13\x77\xbf\x8e\xf5\xec\xdc\x07\xdd\x0b\xf9" "\x39\x29\xd8\xc4\xa5\x73\x4e\x8f\x7f\xa3\x79\xf8\x94\x3b\x1d\xd8\xc4\xff\x0f\x0d" "\xa9\x7f\xa1"; size_t dst_size = 24144; char *dst = malloc(dst_size); ufbxt_bechmark_begin(); ptrdiff_t res = ufbxt_inflate(dst, dst_size, src, sizeof(src) - 1); double sec = ufbxt_bechmark_end(); ufbxt_logf("-> %.2f MB/s", (double)dst_size / sec * 1e-6); ufbxt_hintf("res = %d", (int)res); ufbxt_assert(res == dst_size); ufbxt_assert(fnv1a(dst, dst_size) == 0xbaccc7ea); free(dst); } #endif
SE_fg_int_split_kaiser_mex.c
#include "mex.h" #include "../SE_fgg.h" #include "../SE_fkg.h" void SE_FGG_MEX_params(SE_FGG_params*, const mxArray*, int); #define X prhs[0] // this arg is unused #define HH prhs[1] #define OPT prhs[2] #define ZX prhs[3] #define ZY prhs[4] #define ZZ prhs[5] #define IDX prhs[6] #define PHI_OUT plhs[0] // Output #ifndef VERBOSE #define VERBOSE 0 #endif void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { const int N = mxGetM(IDX); const double* H_per = mxGetPr(HH); SE_FGG_params params; SE_FGG_MEX_params(&params, OPT, N); // scratch arrays SE_FGG_work work; SE_FKG_allocate_workspace(&work, &params, false); // attach pre-computed quantities work.zx = mxGetPr(ZX); work.zy = mxGetPr(ZY); work.zz = mxGetPr(ZZ); work.idx = (int*)mxGetData(IDX); // output vector PHI_OUT = mxCreateDoubleMatrix(N,1,mxREAL); double* phi = mxGetPr(PHI_OUT); if(VERBOSE) mexPrintf("[SE%s FG(i)] N=%d, P=%d\n",PER_STR,N,params.P); // now do the work #ifdef _OPENMP #pragma omp parallel default(shared) #endif { #ifdef THREE_PERIODIC SE_FGG_extend_fcn(&work, H_per, &params); #endif #ifdef TWO_PERIODIC SE2P_FGG_extend_fcn(&work, H_per, &params); #endif #ifdef ONE_PERIODIC SE1P_FGG_extend_fcn(&work, H_per, &params); #endif SE_FKG_int_split_AVX_dispatch(phi, &work, &params); } // done SE_FGG_free_workspace(&work); }
for-2.c
void bar (short *); void foo (short *q, short *r, short *s) { short *p; #pragma omp for for (p = q; p != r; p++) bar (p); #pragma omp for for (p = s; p != r; p--) bar (p); #pragma omp for for (p = q; p != r; p = p + 1) bar (p); #pragma omp for for (p = s; p != r; p = p - 1) bar (p); #pragma omp for for (p = q; p != r; p = 1 + p) bar (p); #pragma omp for for (p = s; p != r; p = -1 + p) bar (p); #pragma omp for for (p = q; p != r; p += 1) bar (p); #pragma omp for for (p = s; p != r; p -= 1) bar (p); }
loop-5.c
#include <omp.h> #include <stdlib.h> #include <string.h> int test1 (void) { short int buf[64], *p; int i; memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[10]; p < &buf[54]; p++) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[3]; p <= &buf[63]; p += 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[16]; p < &buf[51]; p = 4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[16]; p <= &buf[40]; p = p + 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[53]; p > &buf[9]; --p) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[63]; p >= &buf[3]; p -= 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[48]; p > &buf[15]; p = -4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for for (p = &buf[40]; p >= &buf[16]; p = p - 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); return 0; } int test2 (void) { int buf[64], *p; int i; memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[10]; p < &buf[54]; p++) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[3]; p <= &buf[63]; p += 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[16]; p < &buf[51]; p = 4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[16]; p <= &buf[40]; p = p + 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[53]; p > &buf[9]; --p) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[63]; p >= &buf[3]; p -= 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[48]; p > &buf[15]; p = -4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (static, 3) for (p = &buf[40]; p >= &buf[16]; p = p - 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); return 0; } int test3 (void) { int buf[64], *p; int i; memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[10]; p < &buf[54]; p++) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[3]; p <= &buf[63]; p += 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[16]; p < &buf[51]; p = 4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[16]; p <= &buf[40]; p = p + 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[53]; p > &buf[9]; --p) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[63]; p >= &buf[3]; p -= 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[48]; p > &buf[15]; p = -4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (dynamic, 3) for (p = &buf[40]; p >= &buf[16]; p = p - 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); return 0; } int test4 (void) { int buf[64], *p; int i; memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[10]; p < &buf[54]; p++) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[3]; p <= &buf[63]; p += 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[16]; p < &buf[51]; p = 4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[16]; p <= &buf[40]; p = p + 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[53]; p > &buf[9]; --p) *p = 5; for (i = 0; i < 64; i++) if (buf[i] != 5 * (i >= 10 && i < 54)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[63]; p >= &buf[3]; p -= 2) p[-2] = 6; for (i = 0; i < 64; i++) if (buf[i] != 6 * ((i & 1) && i <= 61)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[48]; p > &buf[15]; p = -4 + p) p[2] = 7; for (i = 0; i < 64; i++) if (buf[i] != 7 * ((i & 3) == 2 && i >= 18 && i < 53)) abort (); memset (buf, '\0', sizeof (buf)); #pragma omp parallel for schedule (runtime) for (p = &buf[40]; p >= &buf[16]; p = p - 4ULL) p[2] = -7; for (i = 0; i < 64; i++) if (buf[i] != -7 * ((i & 3) == 2 && i >= 18 && i <= 42)) abort (); return 0; } int main (void) { test1 (); test2 (); test3 (); omp_set_schedule (omp_sched_static, 0); test4 (); omp_set_schedule (omp_sched_static, 3); test4 (); omp_set_schedule (omp_sched_dynamic, 5); test4 (); omp_set_schedule (omp_sched_guided, 2); test4 (); return 0; }
mandelbrot_6.c
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // Contributed by Kevin Miller // // ver 2: added a couple of optimizations // - Reduced number of times a vector of 8 was checked to see if // they had all escaped, similar to Dominic Letz's C #5 entry. // - Processed 64 pixels at a time if width was a multiple of 64, // thereby reducing writes to the bitmap. // // compile with following gcc flags // -pipe -Wall -O3 -ffast-math -fno-finite-math-only -march=native -mfpmath=sse -msse3 -fopenmp #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <emmintrin.h> long numDigits(long n) { long len = 0; while(n) { n=n/10; len++; } return len; } inline long vec_nle(__m128d *v, double f) { return (v[0][0] <= f || v[0][1] <= f || v[1][0] <= f || v[1][1] <= f || v[2][0] <= f || v[2][1] <= f || v[3][0] <= f || v[3][1] <= f) ? 0 : -1; } inline void clrPixels_nle(__m128d *v, double f, unsigned long * pix8) { if(!(v[0][0] <= f)) *pix8 &= 0x7f; if(!(v[0][1] <= f)) *pix8 &= 0xbf; if(!(v[1][0] <= f)) *pix8 &= 0xdf; if(!(v[1][1] <= f)) *pix8 &= 0xef; if(!(v[2][0] <= f)) *pix8 &= 0xf7; if(!(v[2][1] <= f)) *pix8 &= 0xfb; if(!(v[3][0] <= f)) *pix8 &= 0xfd; if(!(v[3][1] <= f)) *pix8 &= 0xfe; } inline void calcSum(__m128d *r, __m128d *i, __m128d *sum, __m128d *init_r, __m128d init_i) { for(long pair=0; pair<4; pair++) { __m128d r2 = r[pair] * r[pair]; __m128d i2 = i[pair] * i[pair]; __m128d ri = r[pair] * i[pair]; sum[pair] = r2 + i2; r[pair]=r2 - i2 + init_r[pair]; i[pair]=ri + ri + init_i; } } inline unsigned long mand8(__m128d *init_r, __m128d init_i) { __m128d r[4], i[4], sum[4]; for(long pair=0; pair<4; pair++) { r[pair]=init_r[pair]; i[pair]=init_i; } unsigned long pix8 = 0xff; for (long j = 0; j < 6; j++) { for(long k=0; k<8; k++) calcSum(r, i, sum, init_r, init_i); if (vec_nle(sum, 4.0)) { pix8 = 0x00; break; } } if (pix8) { calcSum(r, i, sum, init_r, init_i); calcSum(r, i, sum, init_r, init_i); clrPixels_nle(sum, 4.0, &pix8); } return pix8; } unsigned long mand64(__m128d *init_r, __m128d init_i) { unsigned long pix64 = 0; for(long byte=0; byte<8; byte++) { unsigned long pix8 = mand8(init_r, init_i); pix64 = (pix64 >> 8) | (pix8 << 56); init_r += 4; } return pix64; } int main(int argc, char ** argv) { // get width/height from arguments long wid_ht = 200; if (argc >= 2) { wid_ht = atoi(argv[1]); } wid_ht = (wid_ht+7) & ~7; // allocate memory for header and pixels long headerLength = numDigits(wid_ht)*2+5; long pad = ((headerLength + 7) & ~7) - headerLength; // pad aligns pixels on 8 long dataLength = headerLength + wid_ht*(wid_ht>>3); unsigned char * const buffer = malloc(pad + dataLength); unsigned char * const header = buffer + pad; unsigned char * const pixels = header + headerLength; // generate the bitmap header sprintf((char *)header, "P4\n%ld %ld\n", wid_ht, wid_ht); // calculate initial values, store in r0, i0 __m128d r0[wid_ht/2]; double i0[wid_ht]; for(long xy=0; xy<wid_ht; xy+=2) { r0[xy>>1] = 2.0 / wid_ht * (__m128d){xy, xy+1} - 1.5; i0[xy] = 2.0 / wid_ht * xy - 1.0; i0[xy+1] = 2.0 / wid_ht * (xy+1) - 1.0; } // generate the bitmap long use8 = wid_ht%64; if (use8) { // process 8 pixels (one byte) at a time #pragma omp parallel for schedule(guided) for(long y=0; y<wid_ht; y++) { __m128d init_i = (__m128d){i0[y], i0[y]}; long rowstart = y*wid_ht/8; for(long x=0; x<wid_ht; x+=8) { pixels[rowstart + x/8] = mand8(r0+x/2, init_i); } } } else { // process 64 pixels (8 bytes) at a time #pragma omp parallel for schedule(guided) for(long y=0; y<wid_ht; y++) { __m128d init_i = (__m128d){i0[y], i0[y]}; long rowstart = y*wid_ht/64; for(long x=0; x<wid_ht; x+=64) { ((unsigned long *)pixels)[rowstart + x/64] = mand64(r0+x/2, init_i); } } } // write the data long ret = ret = write(STDOUT_FILENO, header, dataLength); free(buffer); return 0; }
GB_unop__identity_int8_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_int8_fp32 // op(A') function: GB_unop_tran__identity_int8_fp32 // C type: int8_t // A type: float // cast: int8_t cij = GB_cast_to_int8_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int8_t z = GB_cast_to_int8_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = GB_cast_to_int8_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int8_fp32 ( int8_t *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; int8_t z = GB_cast_to_int8_t ((double) (aij)) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; int8_t z = GB_cast_to_int8_t ((double) (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_int8_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
resample.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % RRRR EEEEE SSSSS AAA M M PPPP L EEEEE % % R R E SS A A MM MM P P L E % % RRRR EEE SSS AAAAA M M M PPPP L EEE % % R R E SS A A M M P L E % % R R EEEEE SSSSS A A M M P LLLLL EEEEE % % % % % % MagickCore Pixel Resampling Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % August 2007 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/color-private.h" #include "MagickCore/cache.h" #include "MagickCore/draw.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/resample.h" #include "MagickCore/resize.h" #include "MagickCore/resize-private.h" #include "MagickCore/resource_.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/signature-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/option.h" /* EWA Resampling Options */ /* select ONE resampling method */ #define EWA 1 /* Normal EWA handling - raw or clamped */ /* if 0 then use "High Quality EWA" */ #define EWA_CLAMP 1 /* EWA Clamping from Nicolas Robidoux */ #define FILTER_LUT 1 /* Use a LUT rather then direct filter calls */ /* output debugging information */ #define DEBUG_ELLIPSE 0 /* output ellipse info for debug */ #define DEBUG_HIT_MISS 0 /* output hit/miss pixels (as gnuplot commands) */ #define DEBUG_NO_PIXEL_HIT 0 /* Make pixels that fail to hit anything - RED */ #if ! FILTER_DIRECT #define WLUT_WIDTH 1024 /* size of the filter cache */ #endif /* Typedef declarations. */ struct _ResampleFilter { CacheView *view; Image *image; ExceptionInfo *exception; MagickBooleanType debug; /* Information about image being resampled */ ssize_t image_area; PixelInterpolateMethod interpolate; VirtualPixelMethod virtual_pixel; FilterType filter; /* processing settings needed */ MagickBooleanType limit_reached, do_interpolate, average_defined; PixelInfo average_pixel; /* current ellipitical area being resampled around center point */ double A, B, C, Vlimit, Ulimit, Uwidth, slope; #if FILTER_LUT /* LUT of weights for filtered average in elliptical area */ double filter_lut[WLUT_WIDTH]; #else /* Use a Direct call to the filter functions */ ResizeFilter *filter_def; double F; #endif /* the practical working support of the filter */ double support; size_t signature; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e R e s a m p l e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireResampleFilter() initializes the information resample needs do to a % scaled lookup of a color from an image, using area sampling. % % The algorithm is based on a Elliptical Weighted Average, where the pixels % found in a large elliptical area is averaged together according to a % weighting (filter) function. For more details see "Fundamentals of Texture % Mapping and Image Warping" a master's thesis by Paul.S.Heckbert, June 17, % 1989. Available for free from, http://www.cs.cmu.edu/~ph/ % % As EWA resampling (or any sort of resampling) can require a lot of % calculations to produce a distorted scaling of the source image for each % output pixel, the ResampleFilter structure generated holds that information % between individual image resampling. % % This function will make the appropriate AcquireCacheView() calls % to view the image, calling functions do not need to open a cache view. % % Usage Example... % resample_filter=AcquireResampleFilter(image,exception); % SetResampleFilter(resample_filter, GaussianFilter); % for (y=0; y < (ssize_t) image->rows; y++) { % for (x=0; x < (ssize_t) image->columns; x++) { % u= ....; v= ....; % ScaleResampleFilter(resample_filter, ... scaling vectors ...); % (void) ResamplePixelColor(resample_filter,u,v,&pixel); % ... assign resampled pixel value ... % } % } % DestroyResampleFilter(resample_filter); % % The format of the AcquireResampleFilter method is: % % ResampleFilter *AcquireResampleFilter(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ResampleFilter *AcquireResampleFilter(const Image *image, ExceptionInfo *exception) { register ResampleFilter *resample_filter; 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); resample_filter=(ResampleFilter *) AcquireCriticalMemory(sizeof( *resample_filter)); (void) memset(resample_filter,0,sizeof(*resample_filter)); resample_filter->exception=exception; resample_filter->image=ReferenceImage((Image *) image); resample_filter->view=AcquireVirtualCacheView(resample_filter->image, exception); resample_filter->debug=IsEventLogging(); resample_filter->image_area=(ssize_t) (image->columns*image->rows); resample_filter->average_defined=MagickFalse; resample_filter->signature=MagickCoreSignature; SetResampleFilter(resample_filter,image->filter); (void) SetResampleFilterInterpolateMethod(resample_filter,image->interpolate); (void) SetResampleFilterVirtualPixelMethod(resample_filter, GetImageVirtualPixelMethod(image)); return(resample_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y R e s a m p l e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyResampleFilter() finalizes and cleans up the resampling % resample_filter as returned by AcquireResampleFilter(), freeing any memory % or other information as needed. % % The format of the DestroyResampleFilter method is: % % ResampleFilter *DestroyResampleFilter(ResampleFilter *resample_filter) % % A description of each parameter follows: % % o resample_filter: resampling information structure % */ MagickExport ResampleFilter *DestroyResampleFilter( ResampleFilter *resample_filter) { assert(resample_filter != (ResampleFilter *) NULL); assert(resample_filter->signature == MagickCoreSignature); assert(resample_filter->image != (Image *) NULL); if (resample_filter->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", resample_filter->image->filename); resample_filter->view=DestroyCacheView(resample_filter->view); resample_filter->image=DestroyImage(resample_filter->image); #if ! FILTER_LUT resample_filter->filter_def=DestroyResizeFilter(resample_filter->filter_def); #endif resample_filter->signature=(~MagickCoreSignature); resample_filter=(ResampleFilter *) RelinquishMagickMemory(resample_filter); return(resample_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s a m p l e P i x e l C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResamplePixelColor() samples the pixel values surrounding the location % given using an elliptical weighted average, at the scale previously % calculated, and in the most efficent manner possible for the % VirtualPixelMethod setting. % % The format of the ResamplePixelColor method is: % % MagickBooleanType ResamplePixelColor(ResampleFilter *resample_filter, % const double u0,const double v0,PixelInfo *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o resample_filter: the resample filter. % % o u0,v0: A double representing the center of the area to resample, % The distortion transformed transformed x,y coordinate. % % o pixel: the resampled pixel is returned here. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ResamplePixelColor( ResampleFilter *resample_filter,const double u0,const double v0, PixelInfo *pixel,ExceptionInfo *exception) { MagickBooleanType status; ssize_t u,v, v1, v2, uw, hit; double u1; double U,V,Q,DQ,DDQ; double divisor_c,divisor_m; register double weight; register const Quantum *pixels; assert(resample_filter != (ResampleFilter *) NULL); assert(resample_filter->signature == MagickCoreSignature); status=MagickTrue; /* GetPixelInfo(resample_filter->image,pixel); */ if ( resample_filter->do_interpolate ) { status=InterpolatePixelInfo(resample_filter->image,resample_filter->view, resample_filter->interpolate,u0,v0,pixel,resample_filter->exception); return(status); } #if DEBUG_ELLIPSE (void) FormatLocaleFile(stderr, "u0=%lf; v0=%lf;\n", u0, v0); #endif /* Does resample area Miss the image Proper? If and that area a simple solid color - then simply return that color! This saves a lot of calculation when resampling outside the bounds of the source image. However it probably should be expanded to image bounds plus the filters scaled support size. */ hit = 0; switch ( resample_filter->virtual_pixel ) { case BackgroundVirtualPixelMethod: case TransparentVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case WhiteVirtualPixelMethod: case MaskVirtualPixelMethod: if ( resample_filter->limit_reached || u0 + resample_filter->Ulimit < 0.0 || u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0 || v0 + resample_filter->Vlimit < 0.0 || v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 ) hit++; break; case UndefinedVirtualPixelMethod: case EdgeVirtualPixelMethod: if ( ( u0 + resample_filter->Ulimit < 0.0 && v0 + resample_filter->Vlimit < 0.0 ) || ( u0 + resample_filter->Ulimit < 0.0 && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 ) || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0 && v0 + resample_filter->Vlimit < 0.0 ) || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0 && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 ) ) hit++; break; case HorizontalTileVirtualPixelMethod: if ( v0 + resample_filter->Vlimit < 0.0 || v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 ) hit++; /* outside the horizontally tiled images. */ break; case VerticalTileVirtualPixelMethod: if ( u0 + resample_filter->Ulimit < 0.0 || u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0 ) hit++; /* outside the vertically tiled images. */ break; case DitherVirtualPixelMethod: if ( ( u0 + resample_filter->Ulimit < -32.0 && v0 + resample_filter->Vlimit < -32.0 ) || ( u0 + resample_filter->Ulimit < -32.0 && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+31.0 ) || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+31.0 && v0 + resample_filter->Vlimit < -32.0 ) || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+31.0 && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+31.0 ) ) hit++; break; case TileVirtualPixelMethod: case MirrorVirtualPixelMethod: case RandomVirtualPixelMethod: case HorizontalTileEdgeVirtualPixelMethod: case VerticalTileEdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: /* resampling of area is always needed - no VP limits */ break; } if ( hit ) { /* The area being resampled is simply a solid color * just return a single lookup color. * * Should this return the users requested interpolated color? */ status=InterpolatePixelInfo(resample_filter->image,resample_filter->view, IntegerInterpolatePixel,u0,v0,pixel,resample_filter->exception); return(status); } /* When Scaling limits reached, return an 'averaged' result. */ if ( resample_filter->limit_reached ) { switch ( resample_filter->virtual_pixel ) { /* This is always handled by the above, so no need. case BackgroundVirtualPixelMethod: case ConstantVirtualPixelMethod: case TransparentVirtualPixelMethod: case GrayVirtualPixelMethod, case WhiteVirtualPixelMethod case MaskVirtualPixelMethod: */ case UndefinedVirtualPixelMethod: case EdgeVirtualPixelMethod: case DitherVirtualPixelMethod: case HorizontalTileEdgeVirtualPixelMethod: case VerticalTileEdgeVirtualPixelMethod: /* We need an average edge pixel, from the correct edge! How should I calculate an average edge color? Just returning an averaged neighbourhood, works well in general, but falls down for TileEdge methods. This needs to be done properly!!!!!! */ status=InterpolatePixelInfo(resample_filter->image, resample_filter->view,AverageInterpolatePixel,u0,v0,pixel, resample_filter->exception); break; case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: /* just return the background pixel - Is there more direct way? */ status=InterpolatePixelInfo(resample_filter->image, resample_filter->view,IntegerInterpolatePixel,-1.0,-1.0,pixel, resample_filter->exception); break; case TileVirtualPixelMethod: case MirrorVirtualPixelMethod: case RandomVirtualPixelMethod: case CheckerTileVirtualPixelMethod: default: /* generate a average color of the WHOLE image */ if ( resample_filter->average_defined == MagickFalse ) { Image *average_image; CacheView *average_view; GetPixelInfo(resample_filter->image,(PixelInfo *) &resample_filter->average_pixel); resample_filter->average_defined=MagickTrue; /* Try to get an averaged pixel color of whole image */ average_image=ResizeImage(resample_filter->image,1,1,BoxFilter, resample_filter->exception); if (average_image == (Image *) NULL) { *pixel=resample_filter->average_pixel; /* FAILED */ break; } average_view=AcquireVirtualCacheView(average_image,exception); pixels=GetCacheViewVirtualPixels(average_view,0,0,1,1, resample_filter->exception); if (pixels == (const Quantum *) NULL) { average_view=DestroyCacheView(average_view); average_image=DestroyImage(average_image); *pixel=resample_filter->average_pixel; /* FAILED */ break; } GetPixelInfoPixel(resample_filter->image,pixels, &(resample_filter->average_pixel)); average_view=DestroyCacheView(average_view); average_image=DestroyImage(average_image); if ( resample_filter->virtual_pixel == CheckerTileVirtualPixelMethod ) { /* CheckerTile is a alpha blend of the image's average pixel color and the current background color */ /* image's average pixel color */ weight = QuantumScale*((double) resample_filter->average_pixel.alpha); resample_filter->average_pixel.red *= weight; resample_filter->average_pixel.green *= weight; resample_filter->average_pixel.blue *= weight; divisor_c = weight; /* background color */ weight = QuantumScale*((double) resample_filter->image->background_color.alpha); resample_filter->average_pixel.red += weight*resample_filter->image->background_color.red; resample_filter->average_pixel.green += weight*resample_filter->image->background_color.green; resample_filter->average_pixel.blue += weight*resample_filter->image->background_color.blue; resample_filter->average_pixel.alpha += resample_filter->image->background_color.alpha; divisor_c += weight; /* alpha blend */ resample_filter->average_pixel.red /= divisor_c; resample_filter->average_pixel.green /= divisor_c; resample_filter->average_pixel.blue /= divisor_c; resample_filter->average_pixel.alpha /= 2; /* 50% blend */ } } *pixel=resample_filter->average_pixel; break; } return(status); } /* Initialize weighted average data collection */ hit = 0; divisor_c = 0.0; divisor_m = 0.0; pixel->red = pixel->green = pixel->blue = 0.0; if (pixel->colorspace == CMYKColorspace) pixel->black = 0.0; if (pixel->alpha_trait != UndefinedPixelTrait) pixel->alpha = 0.0; /* Determine the parellelogram bounding box fitted to the ellipse centered at u0,v0. This area is bounding by the lines... */ v1 = (ssize_t)ceil(v0 - resample_filter->Vlimit); /* range of scan lines */ v2 = (ssize_t)floor(v0 + resample_filter->Vlimit); /* scan line start and width accross the parallelogram */ u1 = u0 + (v1-v0)*resample_filter->slope - resample_filter->Uwidth; uw = (ssize_t)(2.0*resample_filter->Uwidth)+1; #if DEBUG_ELLIPSE (void) FormatLocaleFile(stderr, "v1=%ld; v2=%ld\n", (long)v1, (long)v2); (void) FormatLocaleFile(stderr, "u1=%ld; uw=%ld\n", (long)u1, (long)uw); #else # define DEBUG_HIT_MISS 0 /* only valid if DEBUG_ELLIPSE is enabled */ #endif /* Do weighted resampling of all pixels, within the scaled ellipse, bound by a Parellelogram fitted to the ellipse. */ DDQ = 2*resample_filter->A; for( v=v1; v<=v2; v++ ) { #if DEBUG_HIT_MISS long uu = ceil(u1); /* actual pixel location (for debug only) */ (void) FormatLocaleFile(stderr, "# scan line from pixel %ld, %ld\n", (long)uu, (long)v); #endif u = (ssize_t)ceil(u1); /* first pixel in scanline */ u1 += resample_filter->slope; /* start of next scan line */ /* location of this first pixel, relative to u0,v0 */ U = (double)u-u0; V = (double)v-v0; /* Q = ellipse quotent ( if Q<F then pixel is inside ellipse) */ Q = (resample_filter->A*U + resample_filter->B*V)*U + resample_filter->C*V*V; DQ = resample_filter->A*(2.0*U+1) + resample_filter->B*V; /* get the scanline of pixels for this v */ pixels=GetCacheViewVirtualPixels(resample_filter->view,u,v,(size_t) uw, 1,resample_filter->exception); if (pixels == (const Quantum *) NULL) return(MagickFalse); /* count up the weighted pixel colors */ for( u=0; u<uw; u++ ) { #if FILTER_LUT /* Note that the ellipse has been pre-scaled so F = WLUT_WIDTH */ if ( Q < (double)WLUT_WIDTH ) { weight = resample_filter->filter_lut[(int)Q]; #else /* Note that the ellipse has been pre-scaled so F = support^2 */ if ( Q < (double)resample_filter->F ) { weight = GetResizeFilterWeight(resample_filter->filter_def, sqrt(Q)); /* a SquareRoot! Arrggghhhhh... */ #endif pixel->alpha += weight*GetPixelAlpha(resample_filter->image,pixels); divisor_m += weight; if (pixel->alpha_trait != UndefinedPixelTrait) weight *= QuantumScale*((double) GetPixelAlpha(resample_filter->image,pixels)); pixel->red += weight*GetPixelRed(resample_filter->image,pixels); pixel->green += weight*GetPixelGreen(resample_filter->image,pixels); pixel->blue += weight*GetPixelBlue(resample_filter->image,pixels); if (pixel->colorspace == CMYKColorspace) pixel->black += weight*GetPixelBlack(resample_filter->image,pixels); divisor_c += weight; hit++; #if DEBUG_HIT_MISS /* mark the pixel according to hit/miss of the ellipse */ (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n", (long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1); (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n", (long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1); } else { (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n", (long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1); (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n", (long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1); } uu++; #else } #endif pixels+=GetPixelChannels(resample_filter->image); Q += DQ; DQ += DDQ; } } #if DEBUG_ELLIPSE (void) FormatLocaleFile(stderr, "Hit=%ld; Total=%ld;\n", (long)hit, (long)uw*(v2-v1) ); #endif /* Result sanity check -- this should NOT happen */ if ( hit == 0 || divisor_m <= MagickEpsilon || divisor_c <= MagickEpsilon ) { /* not enough pixels, or bad weighting in resampling, resort to direct interpolation */ #if DEBUG_NO_PIXEL_HIT pixel->alpha = pixel->red = pixel->green = pixel->blue = 0; pixel->red = QuantumRange; /* show pixels for which EWA fails */ #else status=InterpolatePixelInfo(resample_filter->image, resample_filter->view,resample_filter->interpolate,u0,v0,pixel, resample_filter->exception); #endif return status; } /* Finialize results of resampling */ divisor_m = 1.0/divisor_m; if (pixel->alpha_trait != UndefinedPixelTrait) pixel->alpha = (double) ClampToQuantum(divisor_m*pixel->alpha); divisor_c = 1.0/divisor_c; pixel->red = (double) ClampToQuantum(divisor_c*pixel->red); pixel->green = (double) ClampToQuantum(divisor_c*pixel->green); pixel->blue = (double) ClampToQuantum(divisor_c*pixel->blue); if (pixel->colorspace == CMYKColorspace) pixel->black = (double) ClampToQuantum(divisor_c*pixel->black); return(MagickTrue); } #if EWA && EWA_CLAMP /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % - C l a m p U p A x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampUpAxes() function converts the input vectors into a major and % minor axis unit vectors, and their magnitude. This allows us to % ensure that the ellipse generated is never smaller than the unit % circle and thus never too small for use in EWA resampling. % % This purely mathematical 'magic' was provided by Professor Nicolas % Robidoux and his Masters student Chantal Racette. % % Reference: "We Recommend Singular Value Decomposition", David Austin % http://www.ams.org/samplings/feature-column/fcarc-svd % % By generating major and minor axis vectors, we can actually use the % ellipse in its "canonical form", by remapping the dx,dy of the % sampled point into distances along the major and minor axis unit % vectors. % % Reference: http://en.wikipedia.org/wiki/Ellipse#Canonical_form */ static inline void ClampUpAxes(const double dux, const double dvx, const double duy, const double dvy, double *major_mag, double *minor_mag, double *major_unit_x, double *major_unit_y, double *minor_unit_x, double *minor_unit_y) { /* * ClampUpAxes takes an input 2x2 matrix * * [ a b ] = [ dux duy ] * [ c d ] = [ dvx dvy ] * * and computes from it the major and minor axis vectors [major_x, * major_y] and [minor_x,minor_y] of the smallest ellipse containing * both the unit disk and the ellipse which is the image of the unit * disk by the linear transformation * * [ dux duy ] [S] = [s] * [ dvx dvy ] [T] = [t] * * (The vector [S,T] is the difference between a position in output * space and [X,Y]; the vector [s,t] is the difference between a * position in input space and [x,y].) */ /* * Output: * * major_mag is the half-length of the major axis of the "new" * ellipse. * * minor_mag is the half-length of the minor axis of the "new" * ellipse. * * major_unit_x is the x-coordinate of the major axis direction vector * of both the "old" and "new" ellipses. * * major_unit_y is the y-coordinate of the major axis direction vector. * * minor_unit_x is the x-coordinate of the minor axis direction vector. * * minor_unit_y is the y-coordinate of the minor axis direction vector. * * Unit vectors are useful for computing projections, in particular, * to compute the distance between a point in output space and the * center of a unit disk in output space, using the position of the * corresponding point [s,t] in input space. Following the clamping, * the square of this distance is * * ( ( s * major_unit_x + t * major_unit_y ) / major_mag )^2 * + * ( ( s * minor_unit_x + t * minor_unit_y ) / minor_mag )^2 * * If such distances will be computed for many [s,t]'s, it makes * sense to actually compute the reciprocal of major_mag and * minor_mag and multiply them by the above unit lengths. * * Now, if you want to modify the input pair of tangent vectors so * that it defines the modified ellipse, all you have to do is set * * newdux = major_mag * major_unit_x * newdvx = major_mag * major_unit_y * newduy = minor_mag * minor_unit_x = minor_mag * -major_unit_y * newdvy = minor_mag * minor_unit_y = minor_mag * major_unit_x * * and use these tangent vectors as if they were the original ones. * Usually, this is a drastic change in the tangent vectors even if * the singular values are not clamped; for example, the minor axis * vector always points in a direction which is 90 degrees * counterclockwise from the direction of the major axis vector. */ /* * Discussion: * * GOAL: Fix things so that the pullback, in input space, of a disk * of radius r in output space is an ellipse which contains, at * least, a disc of radius r. (Make this hold for any r>0.) * * ESSENCE OF THE METHOD: Compute the product of the first two * factors of an SVD of the linear transformation defining the * ellipse and make sure that both its columns have norm at least 1. * Because rotations and reflexions map disks to themselves, it is * not necessary to compute the third (rightmost) factor of the SVD. * * DETAILS: Find the singular values and (unit) left singular * vectors of Jinv, clampling up the singular values to 1, and * multiply the unit left singular vectors by the new singular * values in order to get the minor and major ellipse axis vectors. * * Image resampling context: * * The Jacobian matrix of the transformation at the output point * under consideration is defined as follows: * * Consider the transformation (x,y) -> (X,Y) from input locations * to output locations. (Anthony Thyssen, elsewhere in resample.c, * uses the notation (u,v) -> (x,y).) * * The Jacobian matrix of the transformation at (x,y) is equal to * * J = [ A, B ] = [ dX/dx, dX/dy ] * [ C, D ] [ dY/dx, dY/dy ] * * that is, the vector [A,C] is the tangent vector corresponding to * input changes in the horizontal direction, and the vector [B,D] * is the tangent vector corresponding to input changes in the * vertical direction. * * In the context of resampling, it is natural to use the inverse * Jacobian matrix Jinv because resampling is generally performed by * pulling pixel locations in the output image back to locations in * the input image. Jinv is * * Jinv = [ a, b ] = [ dx/dX, dx/dY ] * [ c, d ] [ dy/dX, dy/dY ] * * Note: Jinv can be computed from J with the following matrix * formula: * * Jinv = 1/(A*D-B*C) [ D, -B ] * [ -C, A ] * * What we do is modify Jinv so that it generates an ellipse which * is as close as possible to the original but which contains the * unit disk. This can be accomplished as follows: * * Let * * Jinv = U Sigma V^T * * be an SVD decomposition of Jinv. (The SVD is not unique, but the * final ellipse does not depend on the particular SVD.) * * We could clamp up the entries of the diagonal matrix Sigma so * that they are at least 1, and then set * * Jinv = U newSigma V^T. * * However, we do not need to compute V for the following reason: * V^T is an orthogonal matrix (that is, it represents a combination * of rotations and reflexions) so that it maps the unit circle to * itself. For this reason, the exact value of V does not affect the * final ellipse, and we can choose V to be the identity * matrix. This gives * * Jinv = U newSigma. * * In the end, we return the two diagonal entries of newSigma * together with the two columns of U. */ /* * ClampUpAxes was written by Nicolas Robidoux and Chantal Racette * of Laurentian University with insightful suggestions from Anthony * Thyssen and funding from the National Science and Engineering * Research Council of Canada. It is distinguished from its * predecessors by its efficient handling of degenerate cases. * * The idea of clamping up the EWA ellipse's major and minor axes so * that the result contains the reconstruction kernel filter support * is taken from Andreas Gustaffson's Masters thesis "Interactive * Image Warping", Helsinki University of Technology, Faculty of * Information Technology, 59 pages, 1993 (see Section 3.6). * * The use of the SVD to clamp up the singular values of the * Jacobian matrix of the pullback transformation for EWA resampling * is taken from the astrophysicist Craig DeForest. It is * implemented in his PDL::Transform code (PDL = Perl Data * Language). */ const double a = dux; const double b = duy; const double c = dvx; const double d = dvy; /* * n is the matrix Jinv * transpose(Jinv). Eigenvalues of n are the * squares of the singular values of Jinv. */ const double aa = a*a; const double bb = b*b; const double cc = c*c; const double dd = d*d; /* * Eigenvectors of n are left singular vectors of Jinv. */ const double n11 = aa+bb; const double n12 = a*c+b*d; const double n21 = n12; const double n22 = cc+dd; const double det = a*d-b*c; const double twice_det = det+det; const double frobenius_squared = n11+n22; const double discriminant = (frobenius_squared+twice_det)*(frobenius_squared-twice_det); /* * In exact arithmetic, discriminant can't be negative. In floating * point, it can, because of the bad conditioning of SVD * decompositions done through the associated normal matrix. */ const double sqrt_discriminant = sqrt(discriminant > 0.0 ? discriminant : 0.0); /* * s1 is the largest singular value of the inverse Jacobian * matrix. In other words, its reciprocal is the smallest singular * value of the Jacobian matrix itself. * If s1 = 0, both singular values are 0, and any orthogonal pair of * left and right factors produces a singular decomposition of Jinv. */ /* * Initially, we only compute the squares of the singular values. */ const double s1s1 = 0.5*(frobenius_squared+sqrt_discriminant); /* * s2 the smallest singular value of the inverse Jacobian * matrix. Its reciprocal is the largest singular value of the * Jacobian matrix itself. */ const double s2s2 = 0.5*(frobenius_squared-sqrt_discriminant); const double s1s1minusn11 = s1s1-n11; const double s1s1minusn22 = s1s1-n22; /* * u1, the first column of the U factor of a singular decomposition * of Jinv, is a (non-normalized) left singular vector corresponding * to s1. It has entries u11 and u21. We compute u1 from the fact * that it is an eigenvector of n corresponding to the eigenvalue * s1^2. */ const double s1s1minusn11_squared = s1s1minusn11*s1s1minusn11; const double s1s1minusn22_squared = s1s1minusn22*s1s1minusn22; /* * The following selects the largest row of n-s1^2 I as the one * which is used to find the eigenvector. If both s1^2-n11 and * s1^2-n22 are zero, n-s1^2 I is the zero matrix. In that case, * any vector is an eigenvector; in addition, norm below is equal to * zero, and, in exact arithmetic, this is the only case in which * norm = 0. So, setting u1 to the simple but arbitrary vector [1,0] * if norm = 0 safely takes care of all cases. */ const double temp_u11 = ( (s1s1minusn11_squared>=s1s1minusn22_squared) ? n12 : s1s1minusn22 ); const double temp_u21 = ( (s1s1minusn11_squared>=s1s1minusn22_squared) ? s1s1minusn11 : n21 ); const double norm = sqrt(temp_u11*temp_u11+temp_u21*temp_u21); /* * Finalize the entries of first left singular vector (associated * with the largest singular value). */ const double u11 = ( (norm>0.0) ? temp_u11/norm : 1.0 ); const double u21 = ( (norm>0.0) ? temp_u21/norm : 0.0 ); /* * Clamp the singular values up to 1. */ *major_mag = ( (s1s1<=1.0) ? 1.0 : sqrt(s1s1) ); *minor_mag = ( (s2s2<=1.0) ? 1.0 : sqrt(s2s2) ); /* * Return the unit major and minor axis direction vectors. */ *major_unit_x = u11; *major_unit_y = u21; *minor_unit_x = -u21; *minor_unit_y = u11; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e R e s a m p l e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleResampleFilter() does all the calculations needed to resample an image % at a specific scale, defined by two scaling vectors. This not using % a orthogonal scaling, but two distorted scaling vectors, to allow the % generation of a angled ellipse. % % As only two deritive scaling vectors are used the center of the ellipse % must be the center of the lookup. That is any curvature that the % distortion may produce is discounted. % % The input vectors are produced by either finding the derivitives of the % distortion function, or the partial derivitives from a distortion mapping. % They do not need to be the orthogonal dx,dy scaling vectors, but can be % calculated from other derivatives. For example you could use dr,da/r % polar coordinate vector scaling vectors % % If u,v = DistortEquation(x,y) OR u = Fu(x,y); v = Fv(x,y) % Then the scaling vectors are determined from the deritives... % du/dx, dv/dx and du/dy, dv/dy % If the resulting scaling vectors is othogonally aligned then... % dv/dx = 0 and du/dy = 0 % Producing an othogonally alligned ellipse in source space for the area to % be resampled. % % Note that scaling vectors are different to argument order. Argument order % is the general order the deritives are extracted from the distortion % equations, and not the scaling vectors. As such the middle two vaules % may be swapped from what you expect. Caution is advised. % % WARNING: It is assumed that any SetResampleFilter() method call will % always be performed before the ScaleResampleFilter() method, so that the % size of the ellipse will match the support for the resampling filter being % used. % % The format of the ScaleResampleFilter method is: % % void ScaleResampleFilter(const ResampleFilter *resample_filter, % const double dux,const double duy,const double dvx,const double dvy) % % A description of each parameter follows: % % o resample_filter: the resampling resample_filterrmation defining the % image being resampled % % o dux,duy,dvx,dvy: % The deritives or scaling vectors defining the EWA ellipse. % NOTE: watch the order, which is based on the order deritives % are usally determined from distortion equations (see above). % The middle two values may need to be swapped if you are thinking % in terms of scaling vectors. % */ MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter, const double dux,const double duy,const double dvx,const double dvy) { double A,B,C,F; assert(resample_filter != (ResampleFilter *) NULL); assert(resample_filter->signature == MagickCoreSignature); resample_filter->limit_reached = MagickFalse; /* A 'point' filter forces use of interpolation instead of area sampling */ if ( resample_filter->filter == PointFilter ) return; /* EWA turned off - nothing to do */ #if DEBUG_ELLIPSE (void) FormatLocaleFile(stderr, "# -----\n" ); (void) FormatLocaleFile(stderr, "dux=%lf; dvx=%lf; duy=%lf; dvy=%lf;\n", dux, dvx, duy, dvy); #endif /* Find Ellipse Coefficents such that A*u^2 + B*u*v + C*v^2 = F With u,v relative to point around which we are resampling. And the given scaling dx,dy vectors in u,v space du/dx,dv/dx and du/dy,dv/dy */ #if EWA /* Direct conversion of derivatives into elliptical coefficients However when magnifying images, the scaling vectors will be small resulting in a ellipse that is too small to sample properly. As such we need to clamp the major/minor axis to a minumum of 1.0 to prevent it getting too small. */ #if EWA_CLAMP { double major_mag, minor_mag, major_x, major_y, minor_x, minor_y; ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag, &major_x, &major_y, &minor_x, &minor_y); major_x *= major_mag; major_y *= major_mag; minor_x *= minor_mag; minor_y *= minor_mag; #if DEBUG_ELLIPSE (void) FormatLocaleFile(stderr, "major_x=%lf; major_y=%lf; minor_x=%lf; minor_y=%lf;\n", major_x, major_y, minor_x, minor_y); #endif A = major_y*major_y+minor_y*minor_y; B = -2.0*(major_x*major_y+minor_x*minor_y); C = major_x*major_x+minor_x*minor_x; F = major_mag*minor_mag; F *= F; /* square it */ } #else /* raw unclamped EWA */ A = dvx*dvx+dvy*dvy; B = -2.0*(dux*dvx+duy*dvy); C = dux*dux+duy*duy; F = dux*dvy-duy*dvx; F *= F; /* square it */ #endif /* EWA_CLAMP */ #else /* HQ_EWA */ /* This Paul Heckbert's "Higher Quality EWA" formula, from page 60 in his thesis, which adds a unit circle to the elliptical area so as to do both Reconstruction and Prefiltering of the pixels in the resampling. It also means it is always likely to have at least 4 pixels within the area of the ellipse, for weighted averaging. No scaling will result with F == 4.0 and a circle of radius 2.0, and F smaller than this means magnification is being used. NOTE: This method produces a very blury result at near unity scale while producing perfect results for strong minitification and magnifications. However filter support is fixed to 2.0 (no good for Windowed Sinc filters) */ A = dvx*dvx+dvy*dvy+1; B = -2.0*(dux*dvx+duy*dvy); C = dux*dux+duy*duy+1; F = A*C - B*B/4; #endif #if DEBUG_ELLIPSE (void) FormatLocaleFile(stderr, "A=%lf; B=%lf; C=%lf; F=%lf\n", A,B,C,F); /* Figure out the various information directly about the ellipse. This information currently not needed at this time, but may be needed later for better limit determination. It is also good to have as a record for future debugging */ { double alpha, beta, gamma, Major, Minor; double Eccentricity, Ellipse_Area, Ellipse_Angle; alpha = A+C; beta = A-C; gamma = sqrt(beta*beta + B*B ); if ( alpha - gamma <= MagickEpsilon ) Major=MagickMaximumValue; else Major=sqrt(2*F/(alpha - gamma)); Minor = sqrt(2*F/(alpha + gamma)); (void) FormatLocaleFile(stderr, "# Major=%lf; Minor=%lf\n", Major, Minor ); /* other information about ellipse include... */ Eccentricity = Major/Minor; Ellipse_Area = MagickPI*Major*Minor; Ellipse_Angle = atan2(B, A-C); (void) FormatLocaleFile(stderr, "# Angle=%lf Area=%lf\n", (double) RadiansToDegrees(Ellipse_Angle), Ellipse_Area); } #endif /* If one or both of the scaling vectors is impossibly large (producing a very large raw F value), we may as well not bother doing any form of resampling since resampled area is very large. In this case some alternative means of pixel sampling, such as the average of the whole image is needed to get a reasonable result. Calculate only as needed. */ if ( (4*A*C - B*B) > MagickMaximumValue ) { resample_filter->limit_reached = MagickTrue; return; } /* Scale ellipse to match the filters support (that is, multiply F by the square of the support) Simplier to just multiply it by the support twice! */ F *= resample_filter->support; F *= resample_filter->support; /* Orthogonal bounds of the ellipse */ resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B)); resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B)); /* Horizontally aligned parallelogram fitted to Ellipse */ resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */ resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */ #if DEBUG_ELLIPSE (void) FormatLocaleFile(stderr, "Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\n", resample_filter->Ulimit, resample_filter->Vlimit, resample_filter->Uwidth, resample_filter->slope ); #endif /* Check the absolute area of the parallelogram involved. * This limit needs more work, as it is too slow for larger images * with tiled views of the horizon. */ if ( (resample_filter->Uwidth * resample_filter->Vlimit) > (4.0*resample_filter->image_area)) { resample_filter->limit_reached = MagickTrue; return; } /* Scale ellipse formula to directly index the Filter Lookup Table */ { register double scale; #if FILTER_LUT /* scale so that F = WLUT_WIDTH; -- hardcoded */ scale = (double)WLUT_WIDTH/F; #else /* scale so that F = resample_filter->F (support^2) */ scale = resample_filter->F/F; #endif resample_filter->A = A*scale; resample_filter->B = B*scale; resample_filter->C = C*scale; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t R e s a m p l e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetResampleFilter() set the resampling filter lookup table based on a % specific filter. Note that the filter is used as a radial filter not as a % two pass othogonally aligned resampling filter. % % The format of the SetResampleFilter method is: % % void SetResampleFilter(ResampleFilter *resample_filter, % const FilterType filter) % % A description of each parameter follows: % % o resample_filter: resampling resample_filterrmation structure % % o filter: the resize filter for elliptical weighting LUT % */ MagickExport void SetResampleFilter(ResampleFilter *resample_filter, const FilterType filter) { ResizeFilter *resize_filter; assert(resample_filter != (ResampleFilter *) NULL); assert(resample_filter->signature == MagickCoreSignature); resample_filter->do_interpolate = MagickFalse; resample_filter->filter = filter; /* Default cylindrical filter is a Cubic Keys filter */ if ( filter == UndefinedFilter ) resample_filter->filter = RobidouxFilter; if ( resample_filter->filter == PointFilter ) { resample_filter->do_interpolate = MagickTrue; return; /* EWA turned off - nothing more to do */ } resize_filter = AcquireResizeFilter(resample_filter->image, resample_filter->filter,MagickTrue,resample_filter->exception); if (resize_filter == (ResizeFilter *) NULL) { (void) ThrowMagickException(resample_filter->exception,GetMagickModule(), ModuleError, "UnableToSetFilteringValue", "Fall back to Interpolated 'Point' filter"); resample_filter->filter = PointFilter; resample_filter->do_interpolate = MagickTrue; return; /* EWA turned off - nothing more to do */ } /* Get the practical working support for the filter, * after any API call blur factors have been accoded for. */ #if EWA resample_filter->support = GetResizeFilterSupport(resize_filter); #else resample_filter->support = 2.0; /* fixed support size for HQ-EWA */ #endif #if FILTER_LUT /* Fill the LUT with the weights from the selected filter function */ { register int Q; double r_scale; /* Scale radius so the filter LUT covers the full support range */ r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH); for(Q=0; Q<WLUT_WIDTH; Q++) resample_filter->filter_lut[Q] = (double) GetResizeFilterWeight(resize_filter,sqrt((double)Q)*r_scale); /* finished with the resize filter */ resize_filter = DestroyResizeFilter(resize_filter); } #else /* save the filter and the scaled ellipse bounds needed for filter */ resample_filter->filter_def = resize_filter; resample_filter->F = resample_filter->support*resample_filter->support; #endif /* Adjust the scaling of the default unit circle This assumes that any real scaling changes will always take place AFTER the filter method has been initialized. */ ScaleResampleFilter(resample_filter, 1.0, 0.0, 0.0, 1.0); #if 0 /* This is old code kept as a reference only. Basically it generates a Gaussian bell curve, with sigma = 0.5 if the support is 2.0 Create Normal Gaussian 2D Filter Weighted Lookup Table. A normal EWA guassual lookup would use exp(Q*ALPHA) where Q = distance squared from 0.0 (center) to 1.0 (edge) and ALPHA = -4.0*ln(2.0) ==> -2.77258872223978123767 The table is of length 1024, and equates to support radius of 2.0 thus needs to be scaled by ALPHA*4/1024 and any blur factor squared The it comes from reference code provided by Fred Weinhaus. */ r_scale = -2.77258872223978123767/(WLUT_WIDTH*blur*blur); for(Q=0; Q<WLUT_WIDTH; Q++) resample_filter->filter_lut[Q] = exp((double)Q*r_scale); resample_filter->support = WLUT_WIDTH; #endif #if FILTER_LUT #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp single #endif { if (IsStringTrue(GetImageArtifact(resample_filter->image, "resample:verbose")) != MagickFalse) { register int Q; double r_scale; /* Debug output of the filter weighting LUT Gnuplot the LUT data, the x scale index has been adjusted plot [0:2][-.2:1] "lut.dat" with lines The filter values should be normalized for comparision */ printf("#\n"); printf("# Resampling Filter LUT (%d values) for '%s' filter\n", WLUT_WIDTH, CommandOptionToMnemonic(MagickFilterOptions, resample_filter->filter) ); printf("#\n"); printf("# Note: values in table are using a squared radius lookup.\n"); printf("# As such its distribution is not uniform.\n"); printf("#\n"); printf("# The X value is the support distance for the Y weight\n"); printf("# so you can use gnuplot to plot this cylindrical filter\n"); printf("# plot [0:2][-.2:1] \"lut.dat\" with lines\n"); printf("#\n"); /* Scale radius so the filter LUT covers the full support range */ r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH); for(Q=0; Q<WLUT_WIDTH; Q++) printf("%8.*g %.*g\n", GetMagickPrecision(),sqrt((double)Q)*r_scale, GetMagickPrecision(),resample_filter->filter_lut[Q] ); printf("\n\n"); /* generate a 'break' in gnuplot if multiple outputs */ } /* Output the above once only for each image, and each setting (void) DeleteImageArtifact(resample_filter->image,"resample:verbose"); */ } #endif /* FILTER_LUT */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t R e s a m p l e F i l t e r I n t e r p o l a t e M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetResampleFilterInterpolateMethod() sets the resample filter interpolation % method. % % The format of the SetResampleFilterInterpolateMethod method is: % % MagickBooleanType SetResampleFilterInterpolateMethod( % ResampleFilter *resample_filter,const InterpolateMethod method) % % A description of each parameter follows: % % o resample_filter: the resample filter. % % o method: the interpolation method. % */ MagickExport MagickBooleanType SetResampleFilterInterpolateMethod( ResampleFilter *resample_filter,const PixelInterpolateMethod method) { assert(resample_filter != (ResampleFilter *) NULL); assert(resample_filter->signature == MagickCoreSignature); assert(resample_filter->image != (Image *) NULL); if (resample_filter->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", resample_filter->image->filename); resample_filter->interpolate=method; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t R e s a m p l e F i l t e r V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetResampleFilterVirtualPixelMethod() changes the virtual pixel method % associated with the specified resample filter. % % The format of the SetResampleFilterVirtualPixelMethod method is: % % MagickBooleanType SetResampleFilterVirtualPixelMethod( % ResampleFilter *resample_filter,const VirtualPixelMethod method) % % A description of each parameter follows: % % o resample_filter: the resample filter. % % o method: the virtual pixel method. % */ MagickExport MagickBooleanType SetResampleFilterVirtualPixelMethod( ResampleFilter *resample_filter,const VirtualPixelMethod method) { assert(resample_filter != (ResampleFilter *) NULL); assert(resample_filter->signature == MagickCoreSignature); assert(resample_filter->image != (Image *) NULL); if (resample_filter->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", resample_filter->image->filename); resample_filter->virtual_pixel=method; if (method != UndefinedVirtualPixelMethod) (void) SetCacheViewVirtualPixelMethod(resample_filter->view,method); return(MagickTrue); }
SphereSampler.h
#ifndef SPHERE_SAMPLER_INCLUDED #define SPHERE_SAMPLER_INCLUDED #include <vector> #include <omp.h> #include "Util/Geometry.h" #include "SignalProcessing/CubeGrid.h" #include "SignalProcessing/SphericalGrid.h" #include "SignalProcessing/Fourier.h" template< class Real > void SampleSpheres( const CubeGrid< Real >& grid , std::vector< SphericalGrid< Real > >& spheres , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int threads=1 ); template< class Real > void SampleSpheres( const CubeGrid< Real >& grid , std::vector< FourierKeyS2< Real > >& sphericalHarmonics , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int threads=1 ); template< class Real > void SubSampleSpheres( const CubeGrid< Real >& grid , std::vector< SphericalGrid< Real > >& spheres , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int subSphereResolution , int threads=1 ); template< class Real > void SubSampleSpheres( const CubeGrid< Real >& grid , std::vector< FourierKeyS2< Real > >& sphericalHarmonics , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int subSphereResolution , int threads=1 ); template< class Real > void SampleSpheres( const std::vector< SphericalGrid< Real > >& spheres , CubeGrid< Real >& grid , Point3D< Real > center , Real maxRadius , int gridResolution , int threads=1 ); /////////////////////////////// // SampleSpheres definitions // /////////////////////////////// template< class Real > void SampleSpheres( const CubeGrid< Real >& grid , std::vector< SphericalGrid< Real > >& spheres , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int threads ) { spheres.resize( radii ); for( int i=0 ; i<radii ; i++ ) { Real radius = ( Real(i+0.5)/radii ) * maxRadius; spheres[i].resize( sphereResolution ); grid.SphereSample( &center[0] , radius , spheres[i] , threads ); Real scale = Real( sqrt( 4*M_PI*radius*radius ) ); Real* _sphere = spheres[i][0]; #pragma omp parallel for num_threads( threads ) for( int j=0 ; j<sphereResolution*sphereResolution ; j++ ) _sphere[j] *= scale; } } template< class Real > void SampleSpheres( const CubeGrid< Real >& grid , std::vector< FourierKeyS2< Real > >& sphericalHarmonics , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int threads ) { HarmonicTransform< Real > xForm( sphereResolution ); SphericalGrid< Real > sphere( sphereResolution ); sphericalHarmonics.resize( radii ); for( int i=0 ; i<radii ; i++ ) { Real radius = ( Real(i+0.5)/radii ) * maxRadius; sphericalHarmonics[i].resize( sphereResolution ); grid.SphereSample( &center[0] , radius , sphere , threads ); Real scale = Real( sqrt( 4*M_PI*radius*radius ) ); Real* _sphere = sphere[0]; #pragma omp parallel for num_threads( threads ) for( int j=0 ; j<sphereResolution*sphereResolution ; j++ ) _sphere[j] *= scale; xForm.ForwardFourier( sphere , sphericalHarmonics[i] ); } } template< class Real > void SubSampleSpheres( const CubeGrid< Real >& grid , std::vector< SphericalGrid< Real > >& spheres , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int subSphereResolution , int threads ) { Real thickness = Real( maxRadius/radii ); spheres.resize( radii ); for( int i=0 ; i<radii ; i++ ) { Real radius = ( Real(i+0.5)/radii ) * maxRadius; spheres[i].resize( sphereResolution ); grid.SphereSample( &center[0] , radius , spheres[i] , subSphereResolution , thickness , threads ); Real scale = Real( sqrt( 4*M_PI*radius*radius ) ); Real* _sphere = spheres[i][0]; #pragma omp parallel for num_threads( threads ) for( int j=0 ; j<sphereResolution*sphereResolution ; j++ ) _sphere[j] *= scale; } } template< class Real > void SubSampleSpheres( const CubeGrid< Real >& grid , std::vector< FourierKeyS2< Real > >& sphericalHarmonics , Point3D< Real > center , Real maxRadius , int radii , int sphereResolution , int subSphereResolution , int threads ) { Real thickness = Real( maxRadius/radii ); HarmonicTransform< Real > xForm( sphereResolution ); SphericalGrid< Real > sphere( sphereResolution ); sphericalHarmonics.resize( radii ); for( int i=0 ; i<radii ; i++ ) { Real radius = ( Real(i+0.5)/radii ) * maxRadius; sphericalHarmonics[i].resize( sphereResolution ); grid.SphereSample( &center[0] , radius , sphere , subSphereResolution , thickness , threads ); Real scale = Real( sqrt( 4*M_PI*radius*radius ) ); Real* _sphere = sphere[0]; #pragma omp parallel for num_threads( threads ) for( int j=0 ; j<sphereResolution*sphereResolution ; j++ ) _sphere[j] *= scale; xForm.ForwardFourier( sphere , sphericalHarmonics[i] ); } } template< class Real > void SampleSpheres( const std::vector< SphericalGrid< Real > >& spheres , CubeGrid< Real >& grid , Point3D< Real > center , Real maxRadius , int gridResolution , int threads ) { grid.resize( gridResolution ); #pragma omp parallel for num_threads( threads ) for( int i=0 ; i<gridResolution ; i++ ) for( int j=0 ; j<gridResolution ; j++ ) for( int k=0 ; k<gridResolution ; k++ ) { Point3D< Real > p = ( Point3D< Real >( Real(i) , Real(j) , Real(k) ) - center ) / maxRadius; Real r = Real( sqrt( Point3D< Real >::SquareNorm(p) ) ); p /= r , r *= spheres.size(); Real x , y; Real scale = Real( sqrt( 4*M_PI*r*r ) ); spheres[0].setCoordinates( &p[0] , x , y ); int r1 = int( floor( r ) ) , r2 = r1+1; Real dr = Real( 1. - (r-r1) ); Real temp=0; if( r1>=0 && r1<spheres.size() ) temp += spheres[r1](x,y) * Real( dr); if( r2>=0 && r2<spheres.size() ) temp += spheres[r2](x,y) * Real(1.-dr); grid( i , j , k ) = temp / scale; } } #endif // SPHERE_SAMPLER_INCLUDED
cgeadd.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zgeadd.c, normal z -> c, Fri Sep 28 17:38:05 2018 * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_geadd * * Performs an addition of two general rectangular matrices similarly to the * pcgeadd() function from the PBLAS library: * * \f[ B = \alpha * op( A ) + \beta * B, \f] * * where op( X ) is one of: * \f[ op( X ) = X, \f] * \f[ op( X ) = X^T, \f] * \f[ op( X ) = X^H, \f] * * alpha and beta are scalars and A, B are matrices with op( A ) an m-by-n or * n-by-m matrix depending on the value of transa and B an m-by-n matrix. * ******************************************************************************* * * @param[in] transa * Specifies whether the matrix A is non-transposed, transposed, or * conjugate transposed * - PlasmaNoTrans: op( A ) = A * - PlasmaTrans: op( A ) = A^T * - PlasmaConjTrans: op( A ) = A^H * * @param[in] m * Number of rows of the matrices op( A ) and B. * m >= 0. * * @param[in] n * Number of columns of the matrices op( A ) and B. * n >= 0. * * @param[in] alpha * Scalar factor of A. * * @param[in] pA * Matrix of size lda-by-k, where k is n when transa == PlasmaNoTrans * and m otherwise. * * @param[in] lda * Leading dimension of the array A. lda >= max(1,l), where l is m * when transa = PlasmaNoTrans and n otherwise. * * @param[in] beta * Scalar factor of B. * * @param[in,out] pB * Matrix of size ldb-by-n. * On exit, B = alpha * op( A ) + beta * B * * @param[in] ldb * Leading dimension of the array B. * ldb >= max(1,m). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * ******************************************************************************* * * @sa plasma_omp_cgeadd * @sa plasma_cgeadd * @sa plasma_dgeadd * @sa plasma_sgeadd * ******************************************************************************/ int plasma_cgeadd(plasma_enum_t transa, int m, int n, plasma_complex32_t alpha, plasma_complex32_t *pA, int lda, plasma_complex32_t beta, plasma_complex32_t *pB, int ldb) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); return -1; } if (m < 0) { plasma_error("illegal value of m"); return -2; } if (n < 0) { plasma_error("illegal value of n"); return -3; } if (pA == NULL) { plasma_error("NULL A"); return -5; } int am, an; if (transa == PlasmaNoTrans) { am = m; an = n; } else { am = n; an = m; } int bm = m; int bn = n; if (lda < imax(1, am)) { plasma_error("illegal value of lda"); return -6; } if (pB == NULL) { plasma_error("NULL B"); return -8; } if (ldb < imax(1, bm)) { plasma_error("illegal value of ldb"); return -9; } // quick return if (m == 0 || n == 0 || (alpha == 0.0 && beta == 1.0)) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_geadd(plasma, PlasmaComplexFloat, m, n); // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; plasma_desc_t B; int retval; retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb, am, an, 0, 0, am, an, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb, bm, bn, 0, 0, bm, bn, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_cge2desc(pA, lda, A, &sequence, &request); plasma_omp_cge2desc(pB, ldb, B, &sequence, &request); // Call tile async function. plasma_omp_cgeadd(transa, alpha, A, beta, B, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_cdesc2ge(A, pA, lda, &sequence, &request); plasma_omp_cdesc2ge(B, pB, ldb, &sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&B); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_geadd * * Performs an addition of two general rectangular matrices similarly to the * pcgeadd() function from the PBLAS library. Non-blocking tile version of * plasma_cgeadd(). May return before the computation is finished. Operates on * matrices stored by tiles. All matrices are passed through descriptors. All * dimensions are taken from the descriptors. Allows for pipelining of * operations at runtime. * ******************************************************************************* * * @param[in] transa * Specifies whether the matrix A is non-transposed, transposed, or * conjugate transposed * - PlasmaNoTrans: op( A ) = A * - PlasmaTrans: op( A ) = A^T * - PlasmaConjTrans: op( A ) = A^H * * @param[in] alpha * The scalar alpha. * * @param[in] A * Descriptor of matrix A. * * @param[in] beta * The scalar beta. * * @param[in,out] B * Descriptor of matrix B. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check the * sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_cgeadd * @sa plasma_omp_cgeadd * @sa plasma_omp_dgeadd * @sa plasma_omp_sgeadd * ******************************************************************************/ void plasma_omp_cgeadd(plasma_enum_t transa, plasma_complex32_t alpha, plasma_desc_t A, plasma_complex32_t beta, plasma_desc_t B, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return int am = transa == PlasmaNoTrans ? A.m : A.n; if ((alpha == 0.0 || am == 0) && beta == 1.0) return; // Call the parallel function. plasma_pcgeadd(transa, alpha, A, beta, B, sequence, request); }
sim5interpolation.c
//************************************************************************ // SIM5 library // sim5interpolation.c - interpolation functions //------------------------------------------------------------------------ // Author: // Michal Bursa (bursa@astro.cas.cz) // Astronomical Institute of the Czech Academy of Sciences //************************************************************************ #ifndef CUDA //! \file sim5interpolation.c //! Numerical interpolation. //! //! Provides routines for interpolation of table data. //! \cond SKIP DEVICEFUNC INLINE long sim5_interp_search(const double x_array[], double x, long index_lo, long index_hi) // perform a search of an array of values // - the parameters index_lo and index_hi provide an initial bracket, and it is assumed // that index_lo < index_hi // - the resulting index is guaranteed to be strictly less than index_hi and greater than // or equal to index_lo, so that the implicit bracket [index, index+1] always corresponds // to a region within the implicit value range of the value array // (note that this depends on the result region, i.e. the behaviour at the boundaries // may not correspond to what you expect) // - complete specification of the behaviour is the following: // suppose the input x_array[] = { x0, x1, ..., xN } // if ( x <= x[0] ) then index == 0 // if ( x >= x[i] && x < x[i+1] ) then index == i // if ( x >= x[N] ) then index == N-1 { long ilo = index_lo; long ihi = index_hi; while(ihi > ilo + 1) { long i = (ihi + ilo)/2; if (x < x_array[i]) ihi = i; else ilo = i; } return ilo; } //! \endcond //! \cond SKIP DEVICEFUNC INLINE long sim5_interp_search_accel(sim5interp* interp, double x) // performs an accelerated search of an array of values having cached the last used index { long x_index = interp->last_index; if(x < interp->X[x_index]) { //interp->miss_count++; interp->last_index = sim5_interp_search(interp->X, x, 0, x_index); } else if(x >= interp->X[x_index + 1]) { //interp->miss_count++; interp->last_index = sim5_interp_search(interp->X, x, x_index, interp->N-1); } //else { //interp->hit_count++; //} return interp->last_index; } //! \endcond //! \cond SKIP DEVICEFUNC static void spline(double x[], double y[], int n, double yp1, double ypn, double y2[]) //! Calculates second derivatives of function y[]=f(x[]) for cubic spline interpolation. //! - given arrays x[] and y[] containing a tabulated function y=f(x), //! with and given values yp1 and ypn for the first derivative of the interpolating //! function at points 1 and n , respectively //! - the routine returns an array y2[1..n] that contains the second derivatives //! of the interpolating function at the tabulated points x i . //! - if yp1 and/or ypn are larger than 1e30, respectively, the routine is signaled //! to set the corresponding boundary condition for a natural spline, with zero //! second derivative on that boundary //! (routine from Numerical Recipes in C) { int i,k; double p, qn, sig, un, *u; //MALLOC(u,float,n-1); u = (double*)malloc((n-1)*sizeof(double)); //#ifndef CUDA if (u == NULL) exit(EXIT_FAILURE); //#else //asm("exit;"); //#endif //fprintf(stderr,"ERR %s line %d: Memory allocation failure.\n", __FILE__, __LINE__); if(yp1 > 0.99e30) y2[0] = u[0] = 0.0; else{ y2[0] = -0.5; u[0] = (3.0/(x[1]-x[0]))*((y[1]-y[0])/(x[1]-x[0])-yp1); } for(i = 1; i < n-1; i++){ sig = (x[i] - x[i-1])/(x[i+1] - x[i-1]); p = sig*y2[i-1] + 2.0; y2[i] = (sig - 1.0)/p; u[i] = (y[i+1] - y[i])/(x[i+1] - x[i]) - (y[i] - y[i-1])/(x[i] - x[i-1]); u[i] = (6.0*u[i]/(x[i+1] - x[i-1]) - sig*u[i-1])/p; } if(ypn > 0.99e30) qn = un = 0.0; else{ qn = 0.5; un = (3.0/(x[n-1] - x[n-2]))*(ypn - (y[n-1] - y[n-2])/(x[n-1] - x[n-2])); } y2[n-1] = (un - qn*u[n-2])/(qn*y2[n-2] + 1.0); for(k = n-2; k >= 0; k--){ y2[k] = y2[k]*y2[k+1] + u[k]; } free(u); } //! \endcond //! \cond SKIP DEVICEFUNC static double splint(double xa[], double ya[], double y2a[], int n, double x) //! Cubic spline interpolation. //! - given the arrays xa[] and ya[] of dimension N, which tabulate a function and //! given the array y2a[] , which is the output from spline() routine, //! this routine returns a cubic-spline interpolated value y at point x //! - xa[] must be orderd array //! (routine from Numerical Recipes in C) { int klo,khi,k; double h,b,a; static int pklo=0, pkhi=1; #pragma omp threadprivate(pklo,pkhi) // Assuming that calls to this function are made with closely-spaced, // steadily-increasing values of x, we first try using the same values of klo and khi // as were used in the previous invocation. // If that interval is no longer correct, a standard binary search looks for the correct interval. if(xa[pklo] <= x && xa[pkhi] > x){ klo = pklo; khi = pkhi; } else{ klo = 0; khi = n-1; while (khi-klo > 1){ k = (khi + klo) >> 1; if(xa[k] > x) khi = k; else klo = k; } pklo = klo; pkhi = khi; } h = xa[khi] - xa[klo]; // we can skip this check since have checked that already during sim5interp initialization //if (h == 0.0) { // fprintf(stderr,"-E- %s line %d: Bad xa input to function splint()\n", __FILE__,__LINE__); // exit(EXIT_FAILURE); //} a = (xa[khi] - x)/h; b = (x - xa[klo])/h; return a*ya[klo] + b*ya[khi] + ((a*a*a - a)*y2a[klo] + (b*b*b - b)*y2a[khi])*(h*h)/6.0; } //! \endcond DEVICEFUNC void sim5_interp_init(sim5interp* interp, double xa[], double ya[], long N, int data_model, int interp_type, int interp_options) //! Interpolation initialization. //! Initializes the interpolation object `interp` with the data (xa,ya) where xa and ya are arrays of size N. //! @param interp interpolation object //! @param xa array of x values //! (`xa` data array is always assumed to be strictly ordered, with increasing x values) //! @param ya array of y values //! @param N size of x/y arrays //! @param data_model switch that determines how input data in `xa` and `ya` arrays should be handled: //! INTERP_DATA_REF=X/Y arrays are referenced, INTERP_DATA_COPY=X/Y arrays are copied, //! INTERP_DATA_BUILD=X/Y arrays are not passed, they are build by calls to sim5_interp_data_push(); //! with INTERP_DATA_REF option (default), the interpolation object (interp) does not save the data //! arrays `xa` and `ya`, only saves pointers to them; with INTERP_DATA_COPY it makes an independent //! copy of those arrays, in which case the original arrays can be modified or freed after calling sim5_interp_init() //! @param interp_type determines in which way data will be interpolated: //! INTERP_TYPE_LINLIN=linear interpolation in both X and Y, //! INTERP_TYPE_LINLOG=linear interpolation in X, logarithmic in Y, //! INTERP_TYPE_LOGLIN=logarithmic interpolation in X, linear in Y, //! INTERP_TYPE_LOGLOG=logarithmic interpolation in both X and Y, //! INTERP_TYPE_SPLINE=linear cubic spline interpolation //! @param interp_options specifies additional options (a combination of options can be used): //! INTERP_OPT_ACCEL=interpolation will use acceleration (cashing of index values), //! INTERP_OPT_CAN_EXTRAPOLATE=extrapolation is allowed when an `x` value for an of-out-grid point is requested //! //! @result Returns `interp` object to be used in actual interpolation. { if ((interp_type==INTERP_TYPE_SPLINE) && (interp_options & INTERP_OPT_CAN_EXTRAPOLATE)) { //#ifndef CUDA fprintf(stderr, "ERR (sim5_interp_init): spline interpolation cannot be used with extrapolation option\n"); //#endif return; } interp->datamodel = data_model; interp->type = interp_type; interp->options = interp_options; interp->d2Y = NULL; // check of order if ((interp->datamodel==INTERP_DATA_REF) || (interp->datamodel==INTERP_DATA_COPY)) { long i; for (i=0; i<N-1; i++) { if (xa[i] >= xa[i+1]) { //#ifndef CUDA fprintf(stderr, "ERR (sim5_interp_init): unordered X grid (x[%ld]=%.4e, x[%ld]=%.4e, N=%ld, opt=%d)\n", i, xa[i], i+1, xa[i+1], N, interp_options); backtrace(); //#endif interp->N = 0; interp->X = NULL; interp->Y = NULL; //#ifndef CUDA exit(-1);//return; //#else //asm("exit;"); //#endif } } } switch (interp->datamodel) { case INTERP_DATA_REF: // assign the reference interp->N = N; interp->capa = 0; interp->X = xa; interp->Y = ya; interp->xmin = interp->X[0]; interp->xmax = interp->X[N-1]; interp->last_index = (N-1)/2; break; case INTERP_DATA_COPY: // make copy of arrays interp->N = N; interp->capa = N; interp->X = (double*)malloc(N*sizeof(double)); interp->Y = (double*)malloc(N*sizeof(double)); memcpy (interp->X, xa, N*sizeof(double)); memcpy (interp->Y, ya, N*sizeof(double)); interp->xmin = interp->X[0]; interp->xmax = interp->X[N-1]; interp->last_index = (N-1)/2; break; case INTERP_DATA_BUILD: // make copy of arrays interp->N = 0; interp->capa = N>0 ? N : 100; interp->X = (double*)calloc(interp->capa, sizeof(double)); interp->Y = (double*)calloc(interp->capa, sizeof(double)); interp->xmin = 0.0; interp->xmax = 0.0; interp->last_index = 0; break; default: //#ifndef CUDA fprintf(stderr, "ERR (sim5_interp_init): unimplemented data model (%d)\n", interp->datamodel); exit(-1);//return; //#else //asm("exit;"); //#endif } } DEVICEFUNC void sim5_interp_data_push(sim5interp* interp, double x, double y) //! Pushes data into interpolation object. //! Adds a data point [x,y] into the interpolation object. This function is for filling //! interpolation object that has been created with option INTERP_DATA_BUILD with interolated data. //! The data must come in ordered sequence (x[i] < x[i+1]) //! //! @param interp interpolation object //! @param x x-value of data point //! @param y y-value of data point { if (interp->datamodel != INTERP_DATA_BUILD) { //#ifndef CUDA fprintf(stderr, "ERR (sim5_interp_data_push): you can only push in data with INTERP_DATA_BUILD data model\n"); //#endif return; } long i = interp->N; if ((i>0) && (interp->X[i-1] >= x)) { //#ifndef CUDA fprintf(stderr, "ERR (sim5_interp_data_push): unordered X grid (x[%ld]=%.4e, x[%ld]=%.4e)\n", i-1, interp->X[i-1], i, x); exit(-1);//return; //#else //asm("exit;"); //#endif } interp->X[i] = x; interp->Y[i] = y; interp->N++; if (interp->N >= interp->capa) { interp->capa *= 2; interp->X = (double*)realloc(interp->X, interp->capa*sizeof(double)); interp->Y = (double*)realloc(interp->Y, interp->capa*sizeof(double)); } interp->xmin = interp->X[0]; interp->xmax = interp->X[i]; interp->last_index = i/2; } DEVICEFUNC double sim5_interp_eval(sim5interp* interp, double x) //! Interpolated data evaluation. //! Makes the evalutaion on interpolated grid at given point. //! //! @param interp interpolation object //! @param x value for which to get interpolated value //! //! @result Interpolated value. { double x_lo, x_hi; double y_lo, y_hi; long index; // treat spline interpolation seperately if (interp->type == INTERP_TYPE_SPLINE) { // calculate second derivatives if they are not yet available if (!interp->d2Y) { interp->d2Y = (double*) malloc(interp->N*sizeof(double)); spline(interp->X, interp->Y, interp->N, 1e50, 1e50, interp->d2Y); } return splint(interp->X, interp->Y, interp->d2Y, interp->N, x); } if ((!(interp->options & INTERP_OPT_CAN_EXTRAPOLATE)) && ((x < interp->xmin) || (x > interp->xmax))) { //#ifndef CUDA fprintf(stderr, "WRN (sim5_interp_eval): unwarranted extrapolation (x=%.4e, xmin=%.4e, xmax=%.4e)\n", x, interp->xmin, interp->xmax); //#endif } if (interp->options & INTERP_OPT_ACCEL) { // index search with acceleration index = sim5_interp_search_accel(interp, x); } else { // index search without acceleration index = sim5_interp_search(interp->X, x, 0, interp->N-1); } x_lo = interp->X[index]; x_hi = interp->X[index + 1]; y_lo = interp->Y[index]; y_hi = interp->Y[index + 1]; // seems unnecessary as we have checked on order of X array already on initialization //if (x_lo >= x_hi) { // fprintf(stderr, "ERR (sim5_interp_eval: unordered X grid (x[%ld]=%.4e, x[%ld]=%.4e, N=%ld)\n", index, x_lo, index+1, x_hi, interp->N); // return NAN; //} switch (interp->type) { case INTERP_TYPE_LINLIN: return y_lo + (x-x_lo)/(x_hi-x_lo) * (y_hi-y_lo); case INTERP_TYPE_LOGLOG: return exp(log(y_lo) + (log(x)-log(x_lo)) / (log(x_hi) - log(x_lo)) * (log(y_hi)-log(y_lo))); // equvivalent to: exp(log(y_lo) + (log(x)-log(x_lo)) / (log(x_hi) - log(x_lo)) * (log(y_hi)-log(y_lo))) case INTERP_TYPE_LOGLIN: return y_lo + log(x/x_lo)/log(x_hi/x_lo) * (y_hi-y_lo); // equvivalent to: y_lo + (log(x)-log(x_lo)) / (log(x_hi) - log(x_lo)) * (y_hi - y_lo) default: //#ifndef CUDA fprintf(stderr, "ERR (sim5_interp_eval): unimplemented interpolation type (%d)\n", interp->type); //#endif return NAN; } } /* double sim5_interp_integral(sim5interp* interp, double a, double b) // makes the evalutaion of interpolated grid at point x { int i, N = 500; double result = 0.0; for (i=0; i<N; i++) result += sim5_interp_eval(interp, a+(i+0.5)*(b-a)/(N)); return result*(b-a)/N; } */ DEVICEFUNC void sim5_interp_done(sim5interp* interp) //! Interpolation finalization. //! Frees the interpolation object interp (including a copied data, if necessary). //! //! @param interp interpolation object { if ((interp->datamodel==INTERP_DATA_COPY) || (interp->datamodel==INTERP_DATA_BUILD)){ free(interp->X); free(interp->Y); } if (interp->d2Y) free(interp->d2Y); interp->N = 0; interp->capa = 0; interp->X = NULL; interp->Y = NULL; } DEVICEFUNC sim5interp* sim5_interp_alloc() //! Alloc interpolation object memory. //! Makes a memory allocation for interpolation object. This function should be used for heap-allocated variant of usage: //! //! sim5interp* interp; //! interp = sim5_interp_alloc(); //! sim5_interp_init(interp, ...); //! sim5_interp_free(interp); //! //! @result Interpolation object. { return (sim5interp*)calloc(1, sizeof(sim5interp)); } DEVICEFUNC void sim5_interp_free(sim5interp* interp) //! Free interpolation object memory. //! Frees the interpolation object interp that had been previously alocated by `sim5_interp_alloc()`. //! //! @param interp interpolation object { sim5_interp_done(interp); free(interp); } //#define SIM5FILEIO_TESTING #ifdef SIM5FILEIO_TESTING int main() { double X[5] = {1.,2.,3.,4.,5.}; double Y[5] = {2.,4.,6.,8.,10.}; sim5interp interp; sim5_interp_init(&interp, X, Y, 5, INTERP_TYPE_LINLIN, INTERP_OPT_ALLOW_EXTRAPOLATION+INTERP_OPT_ACCEL); double x; for (x=0.; x<10.; x+=0.1) printf("%e %e\n", x, sim5_interp_eval(&interp, x)); sim5_interp_free(&interp); return 0; } #endif #endif //CUDA
2.norace7.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 20 int main() { double A[N], B[N], sum0 = 0.0, sum1 = 0.0; #pragma omp parallel { #pragma omp for for (int i = 0; i < N; i++) { A[i] = i; B[i] = i * i; } #pragma omp simd reduction(+ : sum0) for (int i = 0; i < N; i++) { sum0 += A[i] * B[i]; } } for (int i = 0; i < N; i++) { sum1 += i * i * i; } return (sum1 - sum0); } // Printing in reverse. Need to fix it. // CHECK: Region is Data Race Free. // CHECK: Region is Data Race Free. // END
xmpp_scram_fmt_plug.c
/* * This software is Copyright (c) 2017, 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. * * References, * * https://tools.ietf.org/html/rfc5802 * https://tools.ietf.org/html/rfc7677 * https://wiki.xmpp.org/web/SASLandSCRAM-SHA-1 * * Hash format -> $scram$0$iterations$salt-len$salt-in-hex$hash */ #if FMT_EXTERNS_H extern struct fmt_main fmt_xmpp_scram; #elif FMT_REGISTERS_H john_register_one(&fmt_xmpp_scram); #else #include <openssl/sha.h> #include <string.h> #include "arch.h" #include "misc.h" #include "memory.h" #include "common.h" #include "formats.h" #include "johnswap.h" #include "sha.h" #include "hmac_sha.h" #include "simd-intrinsics.h" #include "pbkdf2_hmac_sha1.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 #endif #endif #include "memdbg.h" #if defined SIMD_COEF_32 #define SIMD_KEYS (SIMD_COEF_32 * SIMD_PARA_SHA1) #endif #define FORMAT_LABEL "xmpp-scram" #define FORMAT_NAME "" #define ALGORITHM_NAME "XMPP SCRAM PBKDF2-SHA1 " SHA1_ALGORITHM_NAME #define PLAINTEXT_LENGTH 125 #define HASH_LENGTH 28 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(uint32_t) #define BINARY_SIZE 20 #define BINARY_ALIGN sizeof(uint32_t) #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #if !defined(SIMD_COEF_32) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #else #define MIN_KEYS_PER_CRYPT SIMD_KEYS #define MAX_KEYS_PER_CRYPT SIMD_KEYS #endif #define FORMAT_TAG "$xmpp-scram$" #define FORMAT_TAG_LENGTH (sizeof(FORMAT_TAG) - 1) static struct fmt_tests tests[] = { // hash generated by prosody-0.9.12 (taken from a .dat file) {"$xmpp-scram$0$4096$36$37333536663261622d613666622d346333642d396232622d626432646237633338343064$38f79a6e3e64c07f731570d531ec05365aa05306", "openwall123"}, // ejabberd-16.01 generated hash from "ejabberdctl dump output.txt" processed with ejabberd2john.py {"$xmpp-scram$0$4096$16$4f67aec1bd53f5f2f74652e69a3b8f32$4aec3caa8ace5180efa7a671092646c041ab1496", "qwerty"}, // ejabberd hash with a space in password {"$xmpp-scram$0$4096$16$1f7fcb384d5bcc61dfb1231ae1b32a2f$a2d076d56b0152ed557ad7d38fce93159bc63c9b", "password 123"}, // openfire 4.1.6 hash, manually extracted from the database {"$xmpp-scram$0$4096$24$bc1bd6638a1231ffd54f608983425eacf729d8455a469197$aee9254762b23a3950fd7c803caab5f6654587c8", "openwall123"}, {NULL} }; static struct custom_salt { uint32_t saltlen; uint32_t iterations; uint32_t type; unsigned char salt[64+1]; } *cur_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static void init(struct fmt_main *self) { #ifdef _OPENMP static int omp_t = 1; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr, *p; int res, extra; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LENGTH) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += FORMAT_TAG_LENGTH; if ((p = strtokm(ctcopy, "$")) == NULL) /* internal type */ goto err; if (!isdec(p)) goto err; if (atoi(p) != 0) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* iterations */ goto err; if (!isdec(p)) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* salten */ goto err; if (!isdec(p)) goto err; res = atoi(p); if (res > 64) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* salt */ goto err; if (hexlenl(p, &extra) != res * 2 || extra) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* hash */ goto err; if (hexlenl(p, &extra) != BINARY_SIZE * 2 || extra) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { static struct custom_salt cs; char *ctcopy, *keeptr, *p; int i; memset(&cs, 0, sizeof(cs)); ctcopy = strdup(ciphertext); keeptr = ctcopy;; ctcopy += FORMAT_TAG_LENGTH; p = strtokm(ctcopy, "$"); cs.type = atoi(p); p = strtokm(NULL, "$"); cs.iterations = atoi(p); p = strtokm(NULL, "$"); cs.saltlen = atoi(p); p = strtokm(NULL, "$"); for (i = 0; i < cs.saltlen; i++) { cs.salt[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } MEM_FREE(keeptr); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE + 1]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } #define COMMON_GET_HASH_VAR crypt_out #include "common-get-hash.h" static int crypt_all(int *pcount, struct db_salt *salt) { int index; const int count = *pcount; #ifdef _OPENMP #pragma omp parallel for #endif #if defined(_OPENMP) || MAX_KEYS_PER_CRYPT > 1 #endif for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) { #if !defined (SIMD_COEF_32) unsigned char out[BINARY_SIZE]; SHA_CTX ctx; pbkdf2_sha1((unsigned char*)saved_key[index], strlen(saved_key[index]), cur_salt->salt, cur_salt->saltlen, cur_salt->iterations, out, BINARY_SIZE, 0); hmac_sha1(out, BINARY_SIZE, (unsigned char*)"Client Key", 10, out, BINARY_SIZE); SHA1_Init(&ctx); SHA1_Update(&ctx, out, BINARY_SIZE); SHA1_Final((unsigned char*)crypt_out[index], &ctx); #else SHA_CTX ctx; int i; unsigned char *pin[SIMD_KEYS]; int lens[SIMD_KEYS]; unsigned char out_[SIMD_KEYS][BINARY_SIZE], *out[SIMD_KEYS]; for (i = 0; i < SIMD_KEYS; ++i) { pin[i] = (unsigned char*)saved_key[index+i]; lens[i] = strlen(saved_key[index+i]); out[i] = out_[i]; } pbkdf2_sha1_sse((const unsigned char **)pin, lens, cur_salt->salt, cur_salt->saltlen, cur_salt->iterations, out, BINARY_SIZE, 0); for (i = 0; i < SIMD_KEYS; ++i) { hmac_sha1(out[i], BINARY_SIZE, (unsigned char*)"Client Key", 10, out[i], BINARY_SIZE); SHA1_Init(&ctx); SHA1_Update(&ctx, out[i], BINARY_SIZE); SHA1_Final((unsigned char*)crypt_out[index+i], &ctx); } #endif } return count; } static int cmp_all(void *binary, int count) { int index = 0; #if defined(_OPENMP) || MAX_KEYS_PER_CRYPT > 1 for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_xmpp_scram = { { 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 }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_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, set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
convolution_sgemm_pack8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 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 im2col_sgemm_pack8_avx(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { // Mat bottom_im2col(size, maxk, inch, 32u, 8, opt.workspace_allocator); const int size = bottom_im2col.w; const int maxk = bottom_im2col.h; const int inch = bottom_im2col.c; const int outch = top_blob.c; const float* bias = _bias; // permute Mat tmp; if (size >= 12) tmp.create(12 * maxk, inch, size / 12 + (size % 12) / 8 + (size % 12 % 8) / 4 + (size % 12 % 4) / 2 + size % 12 % 2, 32u, 8, opt.workspace_allocator); else if (size >= 8) tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 32u, 8, opt.workspace_allocator); else if (size >= 4) tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 32u, 8, opt.workspace_allocator); else if (size >= 2) tmp.create(2 * maxk, inch, size / 2 + size % 2, 32u, 8, opt.workspace_allocator); else tmp.create(maxk, inch, size, 32u, 8, opt.workspace_allocator); { int nn_size = size / 12; int remain_size_start = 0; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 12; float* tmpptr = tmp.channel(i / 12); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { // transpose 8x12 __m256 _r0 = _mm256_load_ps(img0); __m256 _r1 = _mm256_load_ps(img0 + 8); __m256 _r2 = _mm256_load_ps(img0 + 8 * 2); __m256 _r3 = _mm256_load_ps(img0 + 8 * 3); __m256 _r4 = _mm256_load_ps(img0 + 8 * 4); __m256 _r5 = _mm256_load_ps(img0 + 8 * 5); __m256 _r6 = _mm256_load_ps(img0 + 8 * 6); __m256 _r7 = _mm256_load_ps(img0 + 8 * 7); __m256 _r8 = _mm256_load_ps(img0 + 8 * 8); __m256 _r9 = _mm256_load_ps(img0 + 8 * 9); __m256 _ra = _mm256_load_ps(img0 + 8 * 10); __m256 _rb = _mm256_load_ps(img0 + 8 * 11); __m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1); __m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1); __m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3); __m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3); __m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5); __m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5); __m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7); __m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7); __m256 _tmp8 = _mm256_unpacklo_ps(_r8, _r9); __m256 _tmp9 = _mm256_unpackhi_ps(_r8, _r9); __m256 _tmpa = _mm256_unpacklo_ps(_ra, _rb); __m256 _tmpb = _mm256_unpackhi_ps(_ra, _rb); __m256 _tmpc = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpd = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpe = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpf = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpg = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmph = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpi = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpj = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpk = _mm256_shuffle_ps(_tmp8, _tmpa, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpl = _mm256_shuffle_ps(_tmp8, _tmpa, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpm = _mm256_shuffle_ps(_tmp9, _tmpb, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpn = _mm256_shuffle_ps(_tmp9, _tmpb, _MM_SHUFFLE(3, 2, 3, 2)); _r0 = _mm256_permute2f128_ps(_tmpc, _tmpg, _MM_SHUFFLE(0, 2, 0, 0)); _r1 = _mm256_permute2f128_ps(_tmpk, _tmpd, _MM_SHUFFLE(0, 2, 0, 0)); _r2 = _mm256_permute2f128_ps(_tmph, _tmpl, _MM_SHUFFLE(0, 2, 0, 0)); _r3 = _mm256_permute2f128_ps(_tmpe, _tmpi, _MM_SHUFFLE(0, 2, 0, 0)); _r4 = _mm256_permute2f128_ps(_tmpm, _tmpf, _MM_SHUFFLE(0, 2, 0, 0)); _r5 = _mm256_permute2f128_ps(_tmpj, _tmpn, _MM_SHUFFLE(0, 2, 0, 0)); _r6 = _mm256_permute2f128_ps(_tmpc, _tmpg, _MM_SHUFFLE(0, 3, 0, 1)); _r7 = _mm256_permute2f128_ps(_tmpk, _tmpd, _MM_SHUFFLE(0, 3, 0, 1)); _r8 = _mm256_permute2f128_ps(_tmph, _tmpl, _MM_SHUFFLE(0, 3, 0, 1)); _r9 = _mm256_permute2f128_ps(_tmpe, _tmpi, _MM_SHUFFLE(0, 3, 0, 1)); _ra = _mm256_permute2f128_ps(_tmpm, _tmpf, _MM_SHUFFLE(0, 3, 0, 1)); _rb = _mm256_permute2f128_ps(_tmpj, _tmpn, _MM_SHUFFLE(0, 3, 0, 1)); _mm256_store_ps(tmpptr, _r0); _mm256_store_ps(tmpptr + 8, _r1); _mm256_store_ps(tmpptr + 8 * 2, _r2); _mm256_store_ps(tmpptr + 8 * 3, _r3); _mm256_store_ps(tmpptr + 8 * 4, _r4); _mm256_store_ps(tmpptr + 8 * 5, _r5); _mm256_store_ps(tmpptr + 8 * 6, _r6); _mm256_store_ps(tmpptr + 8 * 7, _r7); _mm256_store_ps(tmpptr + 8 * 8, _r8); _mm256_store_ps(tmpptr + 8 * 9, _r9); _mm256_store_ps(tmpptr + 8 * 10, _ra); _mm256_store_ps(tmpptr + 8 * 11, _rb); img0 += size * 8; tmpptr += 96; } } } remain_size_start += nn_size * 12; nn_size = (size - remain_size_start) >> 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 8; float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { // transpose 8x8 __m256 _r0 = _mm256_load_ps(img0); __m256 _r1 = _mm256_load_ps(img0 + 8); __m256 _r2 = _mm256_load_ps(img0 + 8 * 2); __m256 _r3 = _mm256_load_ps(img0 + 8 * 3); __m256 _r4 = _mm256_load_ps(img0 + 8 * 4); __m256 _r5 = _mm256_load_ps(img0 + 8 * 5); __m256 _r6 = _mm256_load_ps(img0 + 8 * 6); __m256 _r7 = _mm256_load_ps(img0 + 8 * 7); __m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1); __m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1); __m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3); __m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3); __m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5); __m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5); __m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7); __m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7); __m256 _tmp8 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmp9 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpa = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpb = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpc = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpd = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpe = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpf = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2)); _r0 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 2, 0, 0)); _r1 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 2, 0, 0)); _r2 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 2, 0, 0)); _r3 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 2, 0, 0)); _r4 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 3, 0, 1)); _r5 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 3, 0, 1)); _r6 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 3, 0, 1)); _r7 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 3, 0, 1)); _mm256_store_ps(tmpptr, _r0); _mm256_store_ps(tmpptr + 8, _r1); _mm256_store_ps(tmpptr + 8 * 2, _r2); _mm256_store_ps(tmpptr + 8 * 3, _r3); _mm256_store_ps(tmpptr + 8 * 4, _r4); _mm256_store_ps(tmpptr + 8 * 5, _r5); _mm256_store_ps(tmpptr + 8 * 6, _r6); _mm256_store_ps(tmpptr + 8 * 7, _r7); img0 += size * 8; tmpptr += 64; } } } remain_size_start += nn_size << 3; nn_size = (size - remain_size_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 4; float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { // transpose 8x4 __m256 _r0 = _mm256_load_ps(img0); __m256 _r1 = _mm256_load_ps(img0 + 8); __m256 _r2 = _mm256_load_ps(img0 + 8 * 2); __m256 _r3 = _mm256_load_ps(img0 + 8 * 3); __m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1); __m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1); __m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3); __m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3); __m256 _tmp4 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmp5 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmp6 = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmp7 = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2)); _r0 = _mm256_permute2f128_ps(_tmp4, _tmp5, _MM_SHUFFLE(0, 2, 0, 0)); _r1 = _mm256_permute2f128_ps(_tmp6, _tmp7, _MM_SHUFFLE(0, 2, 0, 0)); _r2 = _mm256_permute2f128_ps(_tmp4, _tmp5, _MM_SHUFFLE(0, 3, 0, 1)); _r3 = _mm256_permute2f128_ps(_tmp6, _tmp7, _MM_SHUFFLE(0, 3, 0, 1)); _mm256_store_ps(tmpptr, _r0); _mm256_store_ps(tmpptr + 8, _r1); _mm256_store_ps(tmpptr + 8 * 2, _r2); _mm256_store_ps(tmpptr + 8 * 3, _r3); img0 += size * 8; tmpptr += 32; } } } remain_size_start += nn_size << 2; nn_size = (size - remain_size_start) >> 1; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 2; float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { // transpose 8x2 __m256 _r0 = _mm256_load_ps(img0); __m256 _r1 = _mm256_load_ps(img0 + 8); __m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1); __m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1); _r0 = _mm256_permute2f128_ps(_tmp0, _tmp1, _MM_SHUFFLE(0, 2, 0, 0)); _r1 = _mm256_permute2f128_ps(_tmp0, _tmp1, _MM_SHUFFLE(0, 3, 0, 1)); _mm256_store_ps(tmpptr, _r0); _mm256_store_ps(tmpptr + 8, _r1); img0 += size * 8; tmpptr += 16; } } } remain_size_start += nn_size << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { __m256 _val = _mm256_load_ps(img0); _mm256_store_ps(tmpptr, _val); img0 += size * 8; tmpptr += 8; } } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr0 = top_blob.channel(p); const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; const float* biasptr = bias ? bias + p * 8 : zeros; int i = 0; for (; i + 11 < size; i += 12) { const float* tmpptr = tmp.channel(i / 12); const float* kptr0 = kernel.channel(p); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum0 = _mm256_loadu_ps(biasptr); __m256 _sum1 = _sum0; __m256 _sum2 = _sum0; __m256 _sum3 = _sum0; __m256 _sum4 = _sum0; __m256 _sum5 = _sum0; __m256 _sum6 = _sum0; __m256 _sum7 = _sum0; __m256 _sum8 = _sum0; __m256 _sum9 = _sum0; __m256 _suma = _sum0; __m256 _sumb = _sum0; for (int j = 0; j < nn; j++) { __m256 _w0 = _mm256_load_ps(kptr0); __m256 _val0 = _mm256_broadcast_ss(tmpptr); __m256 _val1 = _mm256_broadcast_ss(tmpptr + 1); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1); __m256 _val2 = _mm256_broadcast_ss(tmpptr + 2); __m256 _val3 = _mm256_broadcast_ss(tmpptr + 3); _sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2); _sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3); __m256 _val4 = _mm256_broadcast_ss(tmpptr + 4); __m256 _val5 = _mm256_broadcast_ss(tmpptr + 5); _sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4); _sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5); __m256 _val6 = _mm256_broadcast_ss(tmpptr + 6); __m256 _val7 = _mm256_broadcast_ss(tmpptr + 7); _sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6); _sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7); __m256 _val8 = _mm256_broadcast_ss(tmpptr + 8); __m256 _val9 = _mm256_broadcast_ss(tmpptr + 9); _sum8 = _mm256_comp_fmadd_ps(_val8, _w0, _sum8); _sum9 = _mm256_comp_fmadd_ps(_val9, _w0, _sum9); __m256 _vala = _mm256_broadcast_ss(tmpptr + 10); __m256 _valb = _mm256_broadcast_ss(tmpptr + 11); _suma = _mm256_comp_fmadd_ps(_vala, _w0, _suma); _sumb = _mm256_comp_fmadd_ps(_valb, _w0, _sumb); tmpptr += 12; kptr0 += 8; } _mm256_store_ps(outptr0, _sum0); _mm256_store_ps(outptr0 + 8, _sum1); _mm256_store_ps(outptr0 + 8 * 2, _sum2); _mm256_store_ps(outptr0 + 8 * 3, _sum3); _mm256_store_ps(outptr0 + 8 * 4, _sum4); _mm256_store_ps(outptr0 + 8 * 5, _sum5); _mm256_store_ps(outptr0 + 8 * 6, _sum6); _mm256_store_ps(outptr0 + 8 * 7, _sum7); _mm256_store_ps(outptr0 + 8 * 8, _sum8); _mm256_store_ps(outptr0 + 8 * 9, _sum9); _mm256_store_ps(outptr0 + 8 * 10, _suma); _mm256_store_ps(outptr0 + 8 * 11, _sumb); outptr0 += 8 * 12; } for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8); const float* kptr0 = kernel.channel(p); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum0 = _mm256_loadu_ps(biasptr); __m256 _sum1 = _sum0; __m256 _sum2 = _sum0; __m256 _sum3 = _sum0; __m256 _sum4 = _sum0; __m256 _sum5 = _sum0; __m256 _sum6 = _sum0; __m256 _sum7 = _sum0; for (int j = 0; j < nn; j++) { __m256 _w0 = _mm256_load_ps(kptr0); __m256 _val0 = _mm256_broadcast_ss(tmpptr); __m256 _val1 = _mm256_broadcast_ss(tmpptr + 1); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1); __m256 _val2 = _mm256_broadcast_ss(tmpptr + 2); __m256 _val3 = _mm256_broadcast_ss(tmpptr + 3); _sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2); _sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3); __m256 _val4 = _mm256_broadcast_ss(tmpptr + 4); __m256 _val5 = _mm256_broadcast_ss(tmpptr + 5); _sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4); _sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5); __m256 _val6 = _mm256_broadcast_ss(tmpptr + 6); __m256 _val7 = _mm256_broadcast_ss(tmpptr + 7); _sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6); _sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7); tmpptr += 8; kptr0 += 8; } _mm256_store_ps(outptr0, _sum0); _mm256_store_ps(outptr0 + 8, _sum1); _mm256_store_ps(outptr0 + 8 * 2, _sum2); _mm256_store_ps(outptr0 + 8 * 3, _sum3); _mm256_store_ps(outptr0 + 8 * 4, _sum4); _mm256_store_ps(outptr0 + 8 * 5, _sum5); _mm256_store_ps(outptr0 + 8 * 6, _sum6); _mm256_store_ps(outptr0 + 8 * 7, _sum7); outptr0 += 8 * 8; } for (; i + 3 < size; i += 4) { const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* kptr0 = kernel.channel(p); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum0 = _mm256_loadu_ps(biasptr); __m256 _sum1 = _sum0; __m256 _sum2 = _sum0; __m256 _sum3 = _sum0; for (int j = 0; j < nn; j++) { __m256 _w0 = _mm256_load_ps(kptr0); __m256 _val0 = _mm256_broadcast_ss(tmpptr); __m256 _val1 = _mm256_broadcast_ss(tmpptr + 1); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1); __m256 _val2 = _mm256_broadcast_ss(tmpptr + 2); __m256 _val3 = _mm256_broadcast_ss(tmpptr + 3); _sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2); _sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3); tmpptr += 4; kptr0 += 8; } _mm256_store_ps(outptr0, _sum0); _mm256_store_ps(outptr0 + 8, _sum1); _mm256_store_ps(outptr0 + 8 * 2, _sum2); _mm256_store_ps(outptr0 + 8 * 3, _sum3); outptr0 += 8 * 4; } for (; i + 1 < size; i += 2) { const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); const float* kptr0 = kernel.channel(p); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum0 = _mm256_loadu_ps(biasptr); __m256 _sum1 = _sum0; for (int j = 0; j < nn; j++) { __m256 _w0 = _mm256_load_ps(kptr0); __m256 _val0 = _mm256_broadcast_ss(tmpptr); __m256 _val1 = _mm256_broadcast_ss(tmpptr + 1); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1); tmpptr += 2; kptr0 += 8; } _mm256_store_ps(outptr0, _sum0); _mm256_store_ps(outptr0 + 8, _sum1); outptr0 += 8 * 2; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); const float* kptr0 = kernel.channel(p); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum = _mm256_loadu_ps(biasptr); for (int j = 0; j < nn; j++) { __m256 _w0 = _mm256_load_ps(kptr0); __m256 _val0 = _mm256_broadcast_ss(tmpptr); _sum = _mm256_comp_fmadd_ps(_val0, _w0, _sum); tmpptr += 1; kptr0 += 8; } _mm256_store_ps(outptr0, _sum); outptr0 += 8; } } } static void convolution_im2col_sgemm_transform_kernel_pack8_avx(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int maxk = kernel_w * kernel_h; // interleave // src = maxk-inch-outch // dst = 8b-8a-maxk-inch/8a-outch/8b Mat kernel = _kernel.reshape(maxk, inch, outch); kernel_tm.create(64 * maxk, inch / 8, outch / 8, (size_t)4u); for (int q = 0; q + 7 < outch; q += 8) { float* g00 = kernel_tm.channel(q / 8); for (int p = 0; p + 7 < inch; p += 8) { for (int k = 0; k < maxk; k++) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { const float* k00 = kernel.channel(q + j).row(p + i); g00[0] = k00[k]; g00++; } } } } } } static void convolution_im2col_sgemm_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = kernel_w * kernel_h; // im2col Mat bottom_im2col(size, maxk, inch, 32u, 8, opt.workspace_allocator); { const int gap = (w * stride_h - outw * stride_w) * 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); float* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const float* sptr = img.row(dilation_h * u) + dilation_w * v * 8; for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { __m256 _v = _mm256_load_ps(sptr); _mm256_store_ps(ptr, _v); sptr += stride_w * 8; ptr += 8; } sptr += gap; } } } } } im2col_sgemm_pack8_avx(bottom_im2col, top_blob, kernel, _bias, opt); }
boundary_val.c
#include "init.h" #include "boundary_val.h" #include "helper.h" #include <omp.h> void boundaryvalues_no_slip( int i, int j, int k, double ***U, double ***V, double ***W, int ***Flag ){ // No-slip boundary conditions for U, V and W. // 26 (6 + 12 + 8) cases in total. //printf( "cell type: %d \n", getcelltype(Flag[i ][j ][k ])); //int flags = (~(2730&Flag[i ][j ][k ]))&getwallbit(0); //printf("flags: %d\n", flags); //int sth = ((flags&2) >> 1); //printf("sth: %d\n", sth); //sth += ((flags >> 2)&2) + ((flags >> 3)&4) + ((flags >> 4)&8) + ((flags >> 5)&16) + ((flags >> 6)&32); //printf("getboundarytype: %d\n", getboundarytype(Flag[i ][j ][k ])); switch(getboundarytype(Flag[i ][j ][k ])){ case B_O: U[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -V[i+1][j-1][k ]; V[i ][j ][k ] = -V[i+1][j ][k ]; W[i ][j ][k-1] = -W[i+1][j ][k-1]; W[i ][j ][k ] = -W[i+1][j ][k ]; break; case B_W: U[i-1][j ][k ] = 0.0; V[i ][j-1][k ] = -V[i-1][j-1][k ]; V[i ][j ][k ] = -V[i-1][j ][k ]; W[i ][j ][k-1] = -W[i-1][j ][k-1]; W[i ][j ][k ] = -W[i-1][j ][k ]; break; case B_N: V[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -U[i-1][j+1][k ]; U[i ][j ][k ] = -U[i ][j+1][k ]; W[i ][j ][k-1] = -W[i ][j+1][k-1]; W[i ][j ][k ] = -W[i ][j+1][k ]; break; case B_S: V[i ][j-1][k ] = 0.0; U[i-1][j ][k ] = -U[i-1][j-1][k ]; U[i ][j ][k ] = -U[i ][j-1][k ]; W[i ][j ][k-1] = -W[i ][j-1][k-1]; W[i ][j ][k ] = -W[i ][j-1][k ]; break; case B_U: W[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -U[i-1][j ][k+1]; U[i ][j ][k ] = -U[i ][j ][k+1]; V[i ][j-1][k ] = -V[i ][j-1][k+1]; V[i ][j ][k ] = -V[i ][j ][k+1]; break; case B_D: W[i ][j ][k-1] = 0.0; U[i-1][j ][k ] = -U[i-1][j ][k-1]; U[i ][j ][k ] = -U[i ][j ][k-1]; V[i ][j-1][k ] = -V[i ][j-1][k-1]; V[i ][j ][k ] = -V[i ][j ][k-1]; break; case B_NO: U[i ][j ][k ] = 0.0; V[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -U[i-1][j+1][k ]; V[i ][j-1][k ] = -V[i+1][j-1][k ]; W[i ][j ][k ] = -(W[i ][j+1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = -(W[i ][j+1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_NW: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -U[i ][j+1][k ]; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -V[i-1][j-1][k ]; W[i ][j ][k ] = -(W[i ][j+1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = -(W[i ][j+1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_NU: V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -V[i ][j-1][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -W[i ][j+1][k-1]; U[i ][j ][k ] = -(U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = -(U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_ND: V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -V[i ][j-1][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -W[i ][j+1][k ]; U[i ][j ][k ] = -(U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = -(U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_SO: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -U[i-1][j-1][k ]; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -V[i+1][j ][k ]; W[i ][j ][k ] = -(W[i ][j-1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = -(W[i ][j-1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_SW: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -U[i ][j-1][k ]; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -V[i-1][j ][k ]; W[i ][j ][k ] = -(W[i ][j-1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = -(W[i ][j-1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_SU: V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -V[i ][j ][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -W[i ][j-1][k-1]; U[i ][j ][k ] = -(U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = -(U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_SD: V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -V[i ][j ][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -W[i ][j-1][k ]; U[i ][j ][k ] = -(U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = -(U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_OU: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -U[i-1][j ][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -W[i+1][j ][k-1]; V[i ][j ][k ] = -(V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = -(V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_WU: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -U[i ][j ][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -W[i-1][j ][k-1]; V[i ][j ][k ] = -(V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = -(V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_OD: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -U[i-1][j ][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -W[i+1][j ][k ]; V[i ][j ][k ] = -(V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = -(V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; case B_WD: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -U[i ][j ][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -W[i-1][j ][k ]; V[i ][j ][k ] = -(V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = -(V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; case B_NOU: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i+1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NWU: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i-1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NOD: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i+1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_NWD: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i-1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_SOU: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i+1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SWU: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i-1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SOD: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i+1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; case B_SWD: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i-1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; default: //case 0 //printf("case 0\n"); break; } } void boundaryvalues_free_slip( int i, int j, int k, double ***U, double ***V, double ***W, int ***Flag ){ // Free slip boundary conditions for U, V and W. // 26 (6 + 12 + 8) cases in total. switch(getboundarytype(Flag[i ][j ][k ])){ case B_O: U[i ][j ][k ] = 0.0; V[i ][j-1][k ] = V[i+1][j-1][k ]; V[i ][j ][k ] = V[i+1][j ][k ]; W[i ][j ][k-1] = W[i+1][j ][k-1]; W[i ][j ][k ] = W[i+1][j ][k ]; break; case B_W: U[i-1][j ][k ] = 0.0; V[i ][j-1][k ] = V[i-1][j-1][k ]; V[i ][j ][k ] = V[i-1][j ][k ]; W[i ][j ][k-1] = W[i-1][j ][k-1]; W[i ][j ][k ] = W[i-1][j ][k ]; break; case B_N: V[i ][j ][k ] = 0.0; U[i-1][j ][k ] = U[i-1][j+1][k ]; U[i ][j ][k ] = U[i ][j+1][k ]; W[i ][j ][k-1] = W[i ][j+1][k-1]; W[i ][j ][k ] = W[i ][j+1][k ]; break; case B_S: V[i ][j-1][k ] = 0.0; U[i-1][j ][k ] = U[i-1][j-1][k ]; U[i ][j ][k ] = U[i ][j-1][k ]; W[i ][j ][k-1] = W[i ][j-1][k-1]; W[i ][j ][k ] = W[i ][j-1][k ]; break; case B_U: W[i ][j ][k ] = 0.0; U[i-1][j ][k ] = U[i-1][j ][k+1]; U[i ][j ][k ] = U[i ][j ][k+1]; V[i ][j-1][k ] = V[i ][j-1][k+1]; V[i ][j ][k ] = V[i ][j ][k+1]; break; case B_D: W[i ][j ][k-1] = 0.0; U[i-1][j ][k ] = U[i-1][j ][k-1]; U[i ][j ][k ] = U[i ][j ][k-1]; V[i ][j-1][k ] = V[i ][j-1][k-1]; V[i ][j ][k ] = V[i ][j ][k-1]; break; case B_NO: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = U[i-1][j+1][k ]; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = V[i+1][j-1][k ]; W[i ][j ][k ] = (W[i ][j+1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j+1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_NW: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = U[i ][j+1][k ]; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = V[i-1][j-1][k ]; W[i ][j ][k ] = (W[i ][j+1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j+1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_NU: V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = V[i ][j-1][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = W[i ][j+1][k-1]; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_ND: V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = V[i ][j-1][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = W[i ][j+1][k ]; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_SO: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = U[i-1][j-1][k ]; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = V[i+1][j ][k ]; W[i ][j ][k ] = (W[i ][j-1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j-1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_SW: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = U[i ][j-1][k ]; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = V[i-1][j ][k ]; W[i ][j ][k ] = (W[i ][j-1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j-1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_SU: V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = V[i ][j ][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = W[i ][j-1][k-1]; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_SD: V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = V[i ][j ][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = W[i ][j-1][k ]; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_OU: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = U[i-1][j ][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = W[i+1][j ][k-1]; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_WU: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = U[i ][j ][k+1]; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = W[i-1][j ][k-1]; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_OD: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = U[i-1][j ][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = W[i+1][j ][k ]; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; case B_WD: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = U[i ][j ][k-1]; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = W[i-1][j ][k ]; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; case B_NOU: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = (W[i+1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NWU: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = (W[i-1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NOD: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = (W[i+1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_NWD: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = (W[i-1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_SOU: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = (W[i+1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SWU: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = (W[i-1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SOD: U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = (W[i+1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; case B_SWD: U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = (W[i-1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; default: //case 0 break; } } void boundaryvalues_moving_wall( int i, int j, int k, double ***U, double ***V, double ***W, int ***Flag, double *velMW ){ // No-slip boundary conditions for U, V and W. // 18 (6 + 12) cases of moving wall in total. // For the remaining 8 cases of B_NOU, B_NWU, B_NOD, B_NWD, B_SOU, B_SWU, B_SOD, B_SWD, // moving wall boundary condition is not allowed, and no slip boundary condition applies. switch(getboundarytype(Flag[i ][j ][k ])){ case B_O: // wall is O. its moving direction is +/-y U[i ][j ][k ] = 0.0; V[i ][j-1][k ] = 2.0*velMW[1] - V[i+1][j-1][k ]; V[i ][j ][k ] = 2.0*velMW[1] - V[i+1][j ][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i+1][j ][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i+1][j ][k ]; break; case B_W: // wall is W. its moving direction is +/-y U[i-1][j ][k ] = 0.0; V[i ][j-1][k ] = 2.0*velMW[1] - V[i-1][j-1][k ]; V[i ][j ][k ] = 2.0*velMW[1] - V[i-1][j ][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i-1][j ][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i-1][j ][k ]; break; case B_N: // wall is N. its moving direction is +/-z V[i ][j ][k ] = 0.0; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j+1][k ]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j+1][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i ][j+1][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i ][j+1][k ]; break; case B_S: // wall is S. its moving direction is +/-z V[i ][j-1][k ] = 0.0; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j-1][k ]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j-1][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i ][j-1][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i ][j-1][k ]; break; case B_U: // wall is U. its moving direction is +/-x W[i ][j ][k ] = 0.0; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j ][k+1]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j ][k+1]; V[i ][j-1][k ] = 2.0*velMW[2] - V[i ][j-1][k+1]; V[i ][j ][k ] = 2.0*velMW[2] - V[i ][j ][k+1]; break; case B_D: // wall is D. its moving direction is +/-x W[i ][j ][k-1] = 0.0; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j ][k-1]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j ][k-1]; V[i ][j-1][k ] = 2.0*velMW[1] - V[i ][j-1][k-1]; V[i ][j ][k ] = 2.0*velMW[1] - V[i ][j ][k-1]; break; case B_NO: // circular moving direction of (O/W, N/S, U/D) is (+y,-x,0) or (-y,+x,0) U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j+1][k ]; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j+1][k ]; V[i ][j ][k ] = 2.0*velMW[1] - V[i+1][j ][k ]; V[i ][j-1][k ] = 2.0*velMW[1] - V[i+1][j-1][k ]; W[i ][j ][k ] = - (W[i ][j+1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = - (W[i ][j+1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_NW: // circular moving direction of (O/W, N/S, U/D) is (+y,+x,0) or (-y,-x,0) U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j+1][k ]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j+1][k ]; V[i ][j ][k ] = 2.0*velMW[1] - V[i-1][j ][k ]; V[i ][j-1][k ] = 2.0*velMW[1] - V[i-1][j-1][k ]; W[i ][j ][k ] = - (W[i ][j+1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = - (W[i ][j+1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_NU: // circular moving direction of (O/W, N/S, U/D) is (0,-z,+y) or (0,+z,-y) V[i ][j ][k ] = 2.0*velMW[1] - V[i ][j ][k+1]; V[i ][j-1][k ] = 2.0*velMW[1] - V[i ][j-1][k+1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i ][j+1][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i ][j+1][k-1]; U[i ][j ][k ] = - (U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = - (U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_ND: // circular moving direction of (O/W, N/S, U/D) is (0,+z,+y) or (0,-z,-y) V[i ][j ][k ] = 2.0*velMW[1] - V[i ][j ][k-1]; V[i ][j-1][k ] = 2.0*velMW[1] - V[i ][j-1][k-1]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i ][j+1][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i ][j+1][k ]; U[i ][j ][k ] = -(U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = -(U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_SO: // circular moving direction of (O/W, N/S, U/D) is (+y,+x,0) or (-y,-x,0) U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j-1][k ]; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j-1][k ]; V[i ][j-1][k ] = 2.0*velMW[1] - V[i+1][j-1][k ]; V[i ][j ][k ] = 2.0*velMW[1] - V[i+1][j ][k ]; W[i ][j ][k ] = - (W[i ][j-1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = - (W[i ][j-1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_SW: // circular moving direction of (O/W, N/S, U/D) is (+y,-x,0) or (-y,+x,0) U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j-1][k ]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j-1][k ]; V[i ][j-1][k ] = 2.0*velMW[1] - V[i-1][j-1][k ]; V[i ][j ][k ] = 2.0*velMW[1] - V[i-1][j ][k ]; W[i ][j ][k ] = - (W[i ][j-1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = - (W[i ][j-1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_SU: // circular moving direction of (O/W, N/S, U/D) is (0,+z,+y) or (0,-z,-y) V[i ][j-1][k ] = 2.0*velMW[1] - V[i ][j-1][k+1]; V[i ][j ][k ] = 2.0*velMW[1] - V[i ][j ][k+1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i ][j-1][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i ][j-1][k-1]; U[i ][j ][k ] = - (U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = - (U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_SD: // circular moving direction of (O/W, N/S, U/D) is (0,-z,+y) or (0,+z,-y) V[i ][j-1][k ] = 2.0*velMW[1] - V[i ][j-1][k-1]; V[i ][j ][k ] = 2.0*velMW[1] - V[i ][j ][k-1]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i ][j-1][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i ][j-1][k ]; U[i ][j ][k ] = - (U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = - (U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_OU: // circular moving direction of (O/W, N/S, U/D) is (+z,0,-x) or (-z,0,+x) U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j ][k+1]; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j ][k+1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i+1][j ][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i+1][j ][k-1]; V[i ][j ][k ] = - (V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = - (V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_WU: // circular moving direction of (O/W, N/S, U/D) is (+z,0,+x) or (-z,0,-x) U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j ][k+1]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j ][k+1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i-1][j ][k ]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i-1][j ][k-1]; V[i ][j ][k ] = - (V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = - (V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_OD: // circular moving direction of (O/W, N/S, U/D) is (+z,0,+x) or (-z,0,-x) U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j ][k-1]; U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j ][k-1]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i+1][j ][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i+1][j ][k ]; V[i ][j ][k ] = - (V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = - (V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; case B_WD: // circular moving direction of (O/W, N/S, U/D) is (+z,0,-x) or (-z,0,+x) U[i-1][j ][k ] = 2.0*velMW[0] - U[i-1][j ][k-1]; U[i ][j ][k ] = 2.0*velMW[0] - U[i ][j ][k-1]; W[i ][j ][k-1] = 2.0*velMW[2] - W[i-1][j ][k-1]; W[i ][j ][k ] = 2.0*velMW[2] - W[i-1][j ][k ]; V[i ][j ][k ] = - (V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = - (V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; //before we find a better solution, the following 8 cases will be respectively same with no-slip. /*case B_NOU: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i+1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NWU: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i-1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NOD: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i+1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_NWD: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j ][k ] = 0.0; V[i ][j-1][k ] = -(V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i-1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_SOU: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i+1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SWU: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = 0.0; W[i ][j ][k-1] = -(W[i-1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SOD: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i ][j ][k ] = 0.0; U[i-1][j ][k ] = -(U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i+1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; case B_SWD: printf("Warning: for now the moving wall condition is set same as no-slip, when the flag is B_NOU, B_NWU etc."); U[i-1][j ][k ] = 0.0; U[i ][j ][k ] = -(U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = 0.0; V[i ][j ][k ] = -(V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = 0.0; W[i ][j ][k ] = -(W[i-1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; */ //before we find a better solution, the following 8 cases will be forbidden. /*case B_NOU: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; case B_NWU: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; case B_NOD: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; case B_NWD: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; case B_SOU: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; case B_SWU: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; case B_SOD: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; case B_SWD: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); break; */ case 0: //case 0: inner cell -> do nothing break; default: printf("Warning: It is forbidden for moving wall, when the flag is B_NOU, B_NWU etc."); //if we come in here, then were delaing with B_??? cell. break; } } void boundaryvalues_outflow( int i, int j, int k, double ***U, double ***V, double ***W, int ***Flag ){ // No-slip boundary conditions for U, V and W. // 26 (6 + 12 + 8) cases in total. switch(getboundarytype(Flag[i ][j ][k ])){ case B_O: U[i ][j ][k ] = U[i+1][j ][k ]; V[i ][j-1][k ] = V[i+1][j-1][k ]; V[i ][j ][k ] = V[i+1][j ][k ]; W[i ][j ][k-1] = W[i+1][j ][k-1]; W[i ][j ][k ] = W[i+1][j ][k ]; break; case B_W: //step outflow U[i-1][j ][k ] = U[i-2][j ][k ]; V[i ][j-1][k ] = V[i-1][j-1][k ]; V[i ][j ][k ] = V[i-1][j ][k ]; W[i ][j ][k-1] = W[i-1][j ][k-1]; W[i ][j ][k ] = W[i-1][j ][k ]; break; case B_N: V[i ][j ][k ] = V[i ][j+1][k ]; U[i-1][j ][k ] = U[i-1][j+1][k ]; U[i ][j ][k ] = U[i ][j+1][k ]; W[i ][j ][k-1] = W[i ][j+1][k-1]; W[i ][j ][k ] = W[i ][j+1][k ]; break; case B_S: V[i ][j-1][k ] = V[i ][j-2][k ]; U[i-1][j ][k ] = U[i-1][j-1][k ]; U[i ][j ][k ] = U[i ][j-1][k ]; W[i ][j ][k-1] = W[i ][j-1][k-1]; W[i ][j ][k ] = W[i ][j-1][k ]; break; case B_U: W[i ][j ][k ] = W[i ][j ][k+1]; U[i-1][j ][k ] = U[i-1][j ][k+1]; U[i ][j ][k ] = U[i ][j ][k+1]; V[i ][j-1][k ] = V[i ][j-1][k+1]; V[i ][j ][k ] = V[i ][j ][k+1]; break; case B_D: W[i ][j ][k-1] = W[i ][j ][k-2]; U[i-1][j ][k ] = U[i-1][j ][k-1]; U[i ][j ][k ] = U[i ][j ][k-1]; V[i ][j-1][k ] = V[i ][j-1][k-1]; V[i ][j ][k ] = V[i ][j ][k-1]; break; case B_NO: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = U[i-1][j+1][k ]; V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = V[i+1][j-1][k ]; W[i ][j ][k ] = (W[i ][j+1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j+1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_NW: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = U[i ][j+1][k ]; V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = V[i-1][j-1][k ]; W[i ][j ][k ] = (W[i ][j+1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j+1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_NU: V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = V[i ][j-1][k+1]; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = W[i ][j+1][k-1]; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_ND: V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = V[i ][j-1][k-1]; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = W[i ][j+1][k ]; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_SO: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = U[i-1][j-1][k ]; V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = V[i+1][j ][k ]; W[i ][j ][k ] = (W[i ][j-1][k ] + W[i+1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j-1][k-1] + W[i+1][j ][k-1]) * 0.5; break; case B_SW: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = U[i ][j-1][k ]; V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = V[i-1][j ][k ]; W[i ][j ][k ] = (W[i ][j-1][k ] + W[i-1][j ][k ]) * 0.5; W[i ][j ][k-1] = (W[i ][j-1][k-1] + W[i-1][j ][k-1]) * 0.5; break; case B_SU: V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = V[i ][j ][k+1]; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = W[i ][j-1][k-1]; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; break; case B_SD: V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = V[i ][j ][k-1]; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = W[i ][j-1][k ]; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; break; case B_OU: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = U[i-1][j ][k+1]; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = W[i+1][j ][k-1]; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_WU: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = U[i ][j ][k+1]; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = W[i-1][j ][k-1]; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; break; case B_OD: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = U[i-1][j ][k-1]; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = W[i+1][j ][k ]; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; case B_WD: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = U[i ][j ][k-1]; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = W[i-1][j ][k ]; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; break; case B_NOU: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = (W[i+1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NWU: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k+1]) * 0.5; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = (W[i-1][j ][k-1] + W[i ][j+1][k-1]) * 0.5; break; case B_NOD: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = (U[i-1][j+1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = (V[i+1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = (W[i+1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_NWD: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = (U[i ][j+1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j ][k ] = V[i ][j+1][k ]; V[i ][j-1][k ] = (V[i-1][j-1][k ] + V[i ][j-1][k-1]) * 0.5; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = (W[i-1][j ][k ] + W[i ][j+1][k ]) * 0.5; break; case B_SOU: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k+1]) * 0.5; V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = (W[i+1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SWU: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k+1]) * 0.5; V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k+1]) * 0.5; W[i ][j ][k ] = W[i ][j ][k+1]; W[i ][j ][k-1] = (W[i-1][j ][k-1] + W[i ][j-1][k-1]) * 0.5; break; case B_SOD: U[i ][j ][k ] = U[i+1][j ][k ]; U[i-1][j ][k ] = (U[i-1][j-1][k ] + U[i-1][j ][k-1]) * 0.5; V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = (V[i+1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = (W[i+1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; case B_SWD: U[i-1][j ][k ] = U[i-2][j ][k ]; U[i ][j ][k ] = (U[i ][j-1][k ] + U[i ][j ][k-1]) * 0.5; V[i ][j-1][k ] = V[i ][j-2][k ]; V[i ][j ][k ] = (V[i-1][j ][k ] + V[i ][j ][k-1]) * 0.5; W[i ][j ][k-1] = W[i ][j ][k-2]; W[i ][j ][k ] = (W[i-1][j ][k ] + W[i ][j-1][k ]) * 0.5; break; default: //case 0 //printf("case 0\n"); break; } } void boundaryvalues_inflow( int i, int j, int k, double ***U, double ***V, double ***W, int ***Flag, double velIN) { //carefull when setting up geometry file: here velIN is assumed to be velocity, perpendicular on the cell-fluid border(s) switch(getboundarytype(Flag[i ][j ][k ])){ case B_O: U[i ][j ][k ] = velIN;break; case B_W: U[i-1][j ][k ] = -velIN; break; case B_N: V[i ][j ][k ] = velIN; break; case B_S: V[i ][j-1][k ] = -velIN; break; case B_U: W[i ][j ][k ] = velIN; break; case B_D: W[i ][j ][k-1] = -velIN; break; case 0: //when bound. cell is inner. this is only to be set if well change velIN to a vector. break; default: printf("Trying to set inflow at edge or corner cells. Not allowed!\n"); break; //when we have B_?? or B_??? we cant set it. } } void boundaryvalues_pressure(double ***P,int ***Flag,int imax,int jmax,int kmax){ int i,j,k; /* set boundary values, here just for the 'real' boundaries - no air included yet (if even needed?) */ #pragma omp parallel for private(j,k) for(i = 0; i <= imax+1; i++) { for(j = 0; j <= jmax+1; j++) { for(k = 0; k <= kmax+1; k++) { switch(getboundarytype(Flag[i ][j ][k ])){ case B_O: P[i ][j ][k ] = P[i+1][j ][k ]; break; case B_W: P[i ][j ][k ] = P[i-1][j ][k ]; break; case B_N: P[i ][j ][k ] = P[i ][j+1][k ]; break; case B_S: P[i ][j ][k ] = P[i ][j-1][k ]; break; case B_U: P[i ][j ][k ] = P[i ][j ][k+1]; break; case B_D: P[i ][j ][k ] = P[i ][j ][k-1]; break; case B_NO: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j+1][k ])*0.5; break; case B_NW: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j+1][k ])*0.5; break; case B_SO: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j-1][k ])*0.5; break; case B_SW: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j-1][k ])*0.5; break; case B_NU: P[i ][j ][k ] = (P[i ][j ][k+1] + P[i ][j+1][k ])*0.5; break; case B_ND: P[i ][j ][k ] = (P[i ][j ][k-1] + P[i ][j+1][k ])*0.5; break; case B_SU: P[i ][j ][k ] = (P[i ][j ][k+1] + P[i ][j-1][k ])*0.5; break; case B_SD: P[i ][j ][k ] = (P[i ][j ][k-1] + P[i ][j-1][k ])*0.5; break; case B_OU: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j ][k+1])*0.5; break; case B_WU: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j ][k+1])*0.5; break; case B_OD: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j ][k-1])*0.5; break; case B_WD: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j ][k-1])*0.5; break; case B_NOU: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j+1][k ] + P[i ][j ][k+1])*1.0/3.0; break; case B_NWU: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j+1][k ] + P[i ][j ][k+1])*1.0/3.0; break; case B_SOU: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j-1][k ] + P[i ][j ][k+1])*1.0/3.0; break; case B_SWU: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j-1][k ] + P[i ][j ][k+1])*1.0/3.0; break; case B_NOD: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j+1][k ] + P[i ][j ][k-1])*1.0/3.0; break; case B_NWD: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j+1][k ] + P[i ][j ][k-1])*1.0/3.0; break; case B_SOD: P[i ][j ][k ] = (P[i+1][j ][k ] + P[i ][j-1][k ] + P[i ][j ][k-1])*1.0/3.0; break; case B_SWD: P[i ][j ][k ] = (P[i-1][j ][k ] + P[i ][j-1][k ] + P[i ][j ][k-1])*1.0/3.0; break; default: break; } switch (getcelltype(Flag[i ][j ][k ])) { case OUTFLOW: if(P[i ][j ][k ]>0) P[i ][j ][k ] = P[i ][j ][k ]*0.1; else P[i ][j ][k ] = P[i ][j ][k ]*1.9; break; } } } } } //the boundary values are set cell by cell void boundaryvalues( int imax, int jmax, int kmax, double ***U, double ***V, double ***W, double ***P, double ***F, double ***G, double ***H, char *problem, //should comment out? probably not needed. int ***Flag, double velIN, double *velMW ) { int i, j, k; #pragma omp parallel for private(j,k) for (i=0; i<imax+2; i++) { for (j=0; j<jmax+2; j++){ for (k=0; k<kmax+2; k++){ //printf("%d,%d,%d - %d (%d)\n",i,j,k,Flag[i ][j ][k ],getcelltype(Flag[i ][j ][k ])); switch (getcelltype(Flag[i ][j ][k ])) { case NO_SLIP: boundaryvalues_no_slip(i, j, k, U, V, W, Flag); //printf("noslip\n"); break; case FREE_SLIP: boundaryvalues_free_slip(i, j, k, U, V, W, Flag); /*printf("free slip\t");*/ break; case INFLOW: boundaryvalues_no_slip(i, j, k, U, V, W, Flag); boundaryvalues_inflow(i, j, k, U, V, W, Flag, velIN); /*printf("inflow\t");*/ break; case OUTFLOW: boundaryvalues_outflow(i, j, k, U, V, W, Flag); /*printf("outflow\n");*/ break; case MOVING_WALL: boundaryvalues_moving_wall(i, j, k, U, V, W, Flag, velMW); /*printf("movingwall\t");*/ break; default: //if we get to here, our cell is air or water. (temp>6) Maybe need to add something here when we do free surfaces. break; } } //printf("\n"); } //printf("\n"); } //printf("ok\n"); }
GB_unop__acosh_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__acosh_fp32_fp32) // op(A') function: GB (_unop_tran__acosh_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = acoshf (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 = acoshf (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] = acoshf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ACOSH || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__acosh_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] = acoshf (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] = acoshf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__acosh_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
DistanceTableData.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign // Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign // Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory // // File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign ////////////////////////////////////////////////////////////////////////////////////// #ifndef QMCPLUSPLUS_DISTANCETABLEDATAIMPL_H #define QMCPLUSPLUS_DISTANCETABLEDATAIMPL_H #include "Particle/ParticleSet.h" #include "OhmmsPETE/OhmmsVector.h" #include "OhmmsPETE/OhmmsMatrix.h" #include "CPU/SIMD/aligned_allocator.hpp" #include "OhmmsSoA/VectorSoaContainer.h" #include <limits> #include <bitset> namespace qmcplusplus { /** @ingroup nnlist * @brief Abstract class to manage pair data between two ParticleSets. * * Each DistanceTableData object is fined by Source and Target of ParticleSet types. * */ class DistanceTableData { public: static constexpr unsigned DIM = OHMMS_DIM; using IndexType = QMCTraits::IndexType; using RealType = QMCTraits::RealType; using PosType = QMCTraits::PosType; using DistRow = Vector<RealType, aligned_allocator<RealType>>; using DisplRow = VectorSoaContainer<RealType, DIM>; protected: const ParticleSet* Origin; int N_sources; int N_targets; int N_walkers; /**defgroup SoA data */ /*@{*/ /** distances_[i][j] , [N_targets][N_sources] * Note: Derived classes decide if it is a memory view or the actual storage * For derived AA, only the lower triangle (j<i) is defined and up-to-date after pbyp move. * The upper triangle is symmetric to the lower one only when the full table is evaluated from scratch. * Avoid using the upper triangle because we may change the code to only allocate the lower triangle part. * For derived AB, the full table is up-to-date after pbyp move */ std::vector<DistRow> distances_; /** displacements_[N_targets]x[3][N_sources] * Note: Derived classes decide if it is a memory view or the actual storage * displacements_[i][j] = r_A2[j] - r_A1[i], the opposite sign of AoS dr * For derived AA, A1=A2=A, only the lower triangle (j<i) is defined. * For derived AB, A1=A, A2=B, the full table is allocated. */ std::vector<DisplRow> displacements_; /** temp_r */ DistRow temp_r_; /** temp_dr */ DisplRow temp_dr_; /*@}*/ /** whether full table needs to be ready at anytime or not * Optimization can be implemented during forward PbyP move when the full table is not needed all the time. * DT consumers should know if full table is needed or not and request via addTable. */ bool need_full_table_; ///name of the table std::string Name; public: ///constructor using source and target ParticleSet DistanceTableData(const ParticleSet& source, const ParticleSet& target) : Origin(&source), N_sources(0), N_targets(0), N_walkers(0), need_full_table_(false) {} ///virutal destructor virtual ~DistanceTableData() = default; ///get need_full_table_ inline bool getFullTableNeeds() const { return need_full_table_; } ///set need_full_table_ inline void setFullTableNeeds(bool is_needed) { need_full_table_ = is_needed; } ///return the name of table inline const std::string& getName() const { return Name; } ///set the name of table inline void setName(const std::string& tname) { Name = tname; } ///returns the reference the origin particleset const ParticleSet& origin() const { return *Origin; } ///returns the number of centers inline IndexType centers() const { return Origin->getTotalNum(); } ///returns the number of centers inline IndexType targets() const { return N_targets; } ///returns the number of source particles inline IndexType sources() const { return N_sources; } /** return full table distances */ const std::vector<DistRow>& getDistances() const { return distances_; } /** return full table displacements */ const std::vector<DisplRow>& getDisplacements() const { return displacements_; } /** return a row of distances for a given target particle */ const DistRow& getDistRow(int iel) const { return distances_[iel]; } /** return a row of displacements for a given target particle */ const DisplRow& getDisplRow(int iel) const { return displacements_[iel]; } /** return old distances set up by move() for optimized distance table consumers */ virtual const DistRow& getOldDists() const { APP_ABORT("DistanceTableData::getOldDists is used incorrectly! Contact developers on github."); return temp_r_; // dummy return to avoid compiler warning. } /** return old displacements set up by move() for optimized distance table consumers */ virtual const DisplRow& getOldDispls() const { APP_ABORT("DistanceTableData::getOldDispls is used incorrectly! Contact developers on github."); return temp_dr_; // dummy return to avoid compiler warning. } /** return the temporary distances when a move is proposed */ const DistRow& getTempDists() const { return temp_r_; } /** return the temporary displacements when a move is proposed */ const DisplRow& getTempDispls() const { return temp_dr_; } /** evaluate the full Distance Table * @param P the target particle set */ virtual void evaluate(ParticleSet& P) = 0; virtual void mw_evaluate(const RefVector<DistanceTableData>& dt_list, const RefVector<ParticleSet>& p_list) { #pragma omp parallel for for (int iw = 0; iw < dt_list.size(); iw++) dt_list[iw].get().evaluate(p_list[iw]); } /** evaluate the temporary pair relations when a move is proposed * @param P the target particle set * @param rnew proposed new position * @param iat the particle to be moved * @param prepare_old if true, prepare (temporary) old distances and displacements for using getOldDists and getOldDispls functions in acceptMove. * * Note: some distance table consumers (WaveFunctionComponent) have optimized code paths which require prepare_old = true for accepting a move. * Drivers/Hamiltonians know whether moves will be accepted or not and manage this flag when calling ParticleSet::makeMoveXXX functions. */ virtual void move(const ParticleSet& P, const PosType& rnew, const IndexType iat = 0, bool prepare_old = true) = 0; virtual void mw_move(const RefVector<DistanceTableData>& dt_list, const RefVector<ParticleSet>& p_list, const std::vector<PosType>& rnew_list, const IndexType iat = 0, bool prepare_old = true) { #pragma omp parallel for for (int iw = 0; iw < dt_list.size(); iw++) dt_list[iw].get().move(p_list[iw], rnew_list[iw], iat, prepare_old); } /** update the distance table by the pair relations if a move is accepted * @param iat the particle with an accepted move * @param partial_update If true, rows after iat will not be updated. If false, upon accept a move, the full table should be up-to-date */ virtual void update(IndexType jat, bool partial_update = false) = 0; /** build a compact list of a neighbor for the iat source * @param iat source particle id * @param rcut cutoff radius * @param jid compressed index * @param dist compressed distance * @param displ compressed displacement * @return number of target particles within rcut */ virtual size_t get_neighbors(int iat, RealType rcut, int* restrict jid, RealType* restrict dist, PosType* restrict displ) const { return 0; } /** find the first nearest neighbor * @param iat source particle id * @param r distance * @param dr displacement * @param newpos if true, use the data in temp_r_ and temp_dr_ for the proposed move. * if false, use the data in distance_[iat] and displacements_[iat] * @return the id of the nearest particle, -1 not found */ virtual int get_first_neighbor(IndexType iat, RealType& r, PosType& dr, bool newpos) const { APP_ABORT("DistanceTableData::get_first_neighbor is not implemented in calling base class"); return 0; } inline void print(std::ostream& os) { APP_ABORT("DistanceTableData::print is not supported") //os << "Table " << Origin->getName() << std::endl; //for (int i = 0; i < r_m.size(); i++) // os << r_m[i] << " "; //os << std::endl; } /**resize the storage *@param npairs number of pairs which is evaluated by a derived class *@param nw number of copies * * The data for the pair distances, displacements *and the distance inverses are stored in a linear storage. * The logical view of these storages is (ipair,iwalker), * where 0 <= ipair < M[N[SourceIndex]] and 0 <= iwalker < N[WalkerIndex] * This scheme can handle both dense and sparse distance tables, * and full or half of the pairs. * Note that this function is protected and the derived classes are * responsible to call this function for memory allocation and any * change in the indices N. */ void resize(int npairs, int nw) { N_walkers = nw; } }; } // namespace qmcplusplus #endif
H2Pack_build_periodic.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <time.h> #include <omp.h> #include "H2Pack_config.h" #include "H2Pack_typedef.h" #include "H2Pack_aux_structs.h" #include "H2Pack_build_periodic.h" #include "H2Pack_utils.h" #include "utils.h" // Build periodic block for root node void H2P_build_periodic_block(H2Pack_p h2pack) { int pt_dim = h2pack->pt_dim; int xpt_dim = h2pack->xpt_dim; int krnl_dim = h2pack->krnl_dim; int root_idx = h2pack->root_idx; int n_lattice = h2pack->n_lattice; void *krnl_param = h2pack->krnl_param; void *pkrnl_param = h2pack->pkrnl_param; DTYPE *enbox0_width = h2pack->enbox + (root_idx * (2 * pt_dim) + pt_dim); DTYPE *per_lattices = h2pack->per_lattices; H2P_dense_mat_p root_J_coord = h2pack->J_coord[root_idx]; H2P_dense_mat_p root_J_coord_s = h2pack->tb[0]->mat0; H2P_dense_mat_p krnl_mat_blk = h2pack->tb[0]->mat1; kernel_eval_fptr krnl_eval = h2pack->krnl_eval; kernel_eval_fptr pkrnl_eval = h2pack->pkrnl_eval; int n_point_root = root_J_coord->ncol; int per_blk_size = n_point_root * krnl_dim; DTYPE *per_blk = (DTYPE*) malloc_aligned(sizeof(DTYPE) * per_blk_size * per_blk_size, 64); ASSERT_PRINTF(per_blk != NULL, "Failed to allocate periodic block of size %d^2\n", per_blk_size); // O = pkernel({root_J_coord, root_J_coord}); pkrnl_eval( root_J_coord->data, root_J_coord->ld, root_J_coord->ncol, root_J_coord->data, root_J_coord->ld, root_J_coord->ncol, pkrnl_param, per_blk, per_blk_size ); DTYPE shift[8] = {0, 0, 0, 0, 0, 0, 0, 0}; H2P_dense_mat_resize(krnl_mat_blk, per_blk_size, per_blk_size); H2P_dense_mat_resize(root_J_coord_s, xpt_dim, n_point_root); copy_matrix_block( sizeof(DTYPE), xpt_dim, n_point_root, root_J_coord->data, root_J_coord->ld, root_J_coord_s->data, root_J_coord_s->ld ); for (int l = 0; l < n_lattice; l++) { // shift = lattice(l, 1 : pt_dim) .* root_box(pt_dim+1 : 2 * pt_dim); // shift = [shift, zeros(1, xpt_dim - pt_dim)]; DTYPE *lattice_l = per_lattices + l * pt_dim; for (int j = 0; j < pt_dim; j++) shift[j] = enbox0_width[j] * lattice_l[j]; // root_J_coord_s = coord_shift(root_J_coord, shift, 1); H2P_shift_coord(root_J_coord_s, shift, 1.0); // O = O - kernel({root_J_coord, root_J_coord_s}); krnl_eval( root_J_coord->data, root_J_coord->ld, root_J_coord->ncol, root_J_coord_s->data, root_J_coord_s->ld, root_J_coord->ncol, krnl_param, krnl_mat_blk->data, krnl_mat_blk->ld ); #pragma omp simd for (int i = 0; i < per_blk_size * per_blk_size; i++) per_blk[i] -= krnl_mat_blk->data[i]; // Reset root_J_coord_s = root_J_coord H2P_shift_coord(root_J_coord_s, shift, -1.0); } h2pack->per_blk = per_blk; } // Build H2 representation with a regular kernel function and // a periodic system kernel (Ewald summation) function void H2P_build_periodic( H2Pack_p h2pack, H2P_dense_mat_p *pp, const int BD_JIT, void *krnl_param, kernel_eval_fptr krnl_eval, void *pkrnl_param, kernel_eval_fptr pkrnl_eval, kernel_mv_fptr krnl_mv, const int krnl_mv_flops ) { double st, et; double *timers = h2pack->timers; if (pp == NULL) { ERROR_PRINTF("You need to provide a set of proxy points.\n"); return; } if (krnl_eval == NULL) { ERROR_PRINTF("You need to provide a valid krnl_eval().\n"); return; } if (BD_JIT != 1) { ERROR_PRINTF("Only support BD_JIT=1 in this function for the moment.\n"); return; } h2pack->pp = pp; h2pack->BD_JIT = BD_JIT; h2pack->krnl_param = krnl_param; h2pack->krnl_eval = krnl_eval; h2pack->pkrnl_param = pkrnl_param; h2pack->pkrnl_eval = pkrnl_eval; h2pack->krnl_mv = krnl_mv; h2pack->krnl_bimv_flops = krnl_mv_flops - 2; if (BD_JIT == 1 && krnl_mv == NULL) WARNING_PRINTF("krnl_eval() will be used in BD_JIT matvec. For better performance, consider using a krnl_mv().\n"); // 1. Build projection matrices and skeleton row sets st = get_wtime_sec(); H2P_build_H2_UJ_proxy(h2pack); et = get_wtime_sec(); timers[U_BUILD_TIMER_IDX] = et - st; // 2. Generate H2 generator matrices metadata st = get_wtime_sec(); H2P_generate_B_metadata(h2pack); et = get_wtime_sec(); timers[B_BUILD_TIMER_IDX] = et - st; // 3. Generate H2 dense blocks metadata st = get_wtime_sec(); H2P_generate_D_metadata(h2pack); et = get_wtime_sec(); timers[D_BUILD_TIMER_IDX] = et - st; // 4. Build periodic block for root node, add its timing to B build timing st = get_wtime_sec(); H2P_build_periodic_block(h2pack); et = get_wtime_sec(); timers[B_BUILD_TIMER_IDX] = et - st; // 5. Set up forward and backward permutation indices int n_point = h2pack->n_point; int krnl_dim = h2pack->krnl_dim; int *coord_idx = h2pack->coord_idx; int *fwd_pmt_idx = (int*) malloc(sizeof(int) * n_point * krnl_dim); int *bwd_pmt_idx = (int*) malloc(sizeof(int) * n_point * krnl_dim); for (int i = 0; i < n_point; i++) { for (int j = 0; j < krnl_dim; j++) { fwd_pmt_idx[i * krnl_dim + j] = coord_idx[i] * krnl_dim + j; bwd_pmt_idx[coord_idx[i] * krnl_dim + j] = i * krnl_dim + j; } } h2pack->fwd_pmt_idx = fwd_pmt_idx; h2pack->bwd_pmt_idx = bwd_pmt_idx; }
AsynchronousUpdate.c
#include "AsynchronousUpdate.h" #include <stdio.h> #include <stdlib.h> #include "constants.h" #include <gsl/gsl_rng.h> #include <omp.h> int getBool(gsl_rng* r) { return gsl_rng_uniform_int(r,2); } void singleStateUpdate(int n, int* state, int** topology, int seed, int* fixed_nodes) { //Perform Asynchronous Updates gsl_rng* asyncer = gsl_rng_alloc(gsl_rng_ranlxs2); gsl_rng_set(asyncer,seed); for (int i = 0; i < ITER_ASYNCHRONOUS; ++i) { int node_to_update = gsl_rng_uniform_int(asyncer,n); if(fixed_nodes[node_to_update] == NORMAL_FLAG) { int val_temp = 0; for (int j = 0; j < n; ++j) { val_temp+= state[j]*topology[node_to_update][j]; } if(val_temp > 0) { state[node_to_update] = 1; } else if(val_temp<0) { state[node_to_update] = LOWER_EXPRESSION; } } } //Free the rng gsl_rng_free(asyncer); } void getFinalState(int n, int state[n], gsl_rng* rangen, int** topology, int* fixed_nodes, int i) { #pragma omp parallel for for (int j = 0; j < n; ++j) { if(fixed_nodes[j]==NORMAL_FLAG) { #pragma omp critical(rand) { state[j] = getBool(rangen); } if(state[j]==0) { state[j] = LOWER_EXPRESSION; } } else{ state[j] = fixed_nodes[j]; } } singleStateUpdate(n,state,topology,i+1,fixed_nodes); } asynclist* updateAsyncList(int n, int** topology, int* fixed_nodes, int height, int seed_init) { if(height) { if(height%2) { gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2); gsl_rng_set(rangen,seed_init); asynclist* to_merge[2]; int seed[2] = {gsl_rng_get(rangen),gsl_rng_get(rangen)}; int i; #pragma omp parallel for shared(n,topology,fixed_nodes,seed,height) private(i) for (i = 0; i < 2; ++i) { to_merge[i] = updateAsyncList(n,topology,fixed_nodes,height-1,seed[i]); } return merge_asynclist(to_merge[0],to_merge[1],n); } else { gsl_rng* rangen = gsl_rng_alloc(gsl_rng_taus2); gsl_rng_set(rangen,seed_init); asynclist* to_merge[2]; int seed[2] = {gsl_rng_get(rangen),gsl_rng_get(rangen)}; int i; #pragma omp parallel for shared(n,topology,fixed_nodes,seed,height) private(i) for (i = 0; i < 2; ++i) { to_merge[i] = updateAsyncList(n,topology,fixed_nodes,height-1,seed[i]); } return merge_asynclist(to_merge[0],to_merge[1],n); } } else{ asynclist* list = (asynclist*)malloc(sizeof(asynclist)); init_asynclist(list); int state[n]; gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2); gsl_rng_set(rangen,seed_init); for (int i = 0; i < n; ++i) { if(fixed_nodes[i] == NORMAL_FLAG) { state[i] = gsl_rng_uniform_int(rangen,2); if(state[i]==0) { state[i] = LOWER_EXPRESSION; } } else { state[i] = fixed_nodes[i]; } } singleStateUpdate(n,state,topology,gsl_rng_get(rangen),fixed_nodes); list->n_elements = 1; asynclistnode* node = (asynclistnode*)malloc(sizeof(asynclistnode)); if(!node) { exit(10); } node->n_occurances = 1; node->state = (int*)malloc(n*sizeof(int)); if(!(node->state)) { exit(11); } for (int i = 0; i < n; ++i) { node->state[i] = state[i]; } node->next = NULL; node->prev = NULL; list->next = node; return list; } } void updateAsyncTree(int n, int** topology, int* fixed_nodes, base* stable) { int iter = (1<<N_SAMPLES); gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2); gsl_rng_set(rangen,0); #pragma omp parallel for for (int i = 0; i < iter; ++i) { /* gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2); gsl_rng_set(rangen,i); */ //int* state=(int*)malloc(n*sizeof(int)); int state[n]; getFinalState(n,state,rangen,topology,fixed_nodes,i); #pragma omp critical(addToTree) { add_node(stable,n,state); } //free(state); } gsl_rng_free(rangen); }
openmp_control.c
/** * * @file runtime_control.c * * @copyright 2009-2014 The University of Tennessee and The University of * Tennessee Research Foundation. All rights reserved. * @copyright 2012-2017 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria, * Univ. Bordeaux. All rights reserved. * @copyright 2018 King Abdullah University of Science and Technology (KAUST). * All rights reserved. * *** * @brief AL4SAN OpenMP control routines * * AL4SAN is a software package provided by King Abdullah University of Science and Technology (KAUST) * * * version 1.1.0 * author Vijay Joshi * author Cedric Castagnede * date 2012-09-15 * * @version 1.1.0 * @author Rabab Alomairy * @date 2019-02-06 */ #include <stdio.h> #include <stdlib.h> #include "al4san_openmp.h" /******************************************************************************* * Initialize AL4SAN **/ int AL4SAN_Openmp_init(AL4SAN_context_t *al4san, int ncpus, int ncudas, int nthreads_per_worker) { int hres = 0; if ( ncudas > 0 ) al4san_warning( "AL4SAN_Openmp_init_scheduler(OpenMP)", "GPUs are not supported for now"); if ( nthreads_per_worker > 0 ) al4san_warning( "AL4SAN_Openmp_init_scheduler(OpenMP)", "Multi-threaded kernels are not supported for now"); omp_set_num_threads(ncpus); al4san->world_size=ncpus; al4san->parallel_enabled = AL4SAN_TRUE; return hres; } /******************************************************************************* * Finalize AL4SAN */ void AL4SAN_Openmp_finalize(AL4SAN_context_t *al4san) { #pragma omp taskwait (void)al4san; return; } /******************************************************************************* * To suspend the processing of new tasks by workers **/ void AL4SAN_Openmp_pause( AL4SAN_context_t *al4san ) { (void)al4san; return; } /******************************************************************************* * This is the symmetrical call to AL4SAN_runtime_pause, * used to resume the workers polling for new tasks. **/ void AL4SAN_Openmp_resume( AL4SAN_context_t *al4san ) { (void)al4san; return; } /******************************************************************************* * Barrier AL4SAN. **/ void AL4SAN_Openmp_barrier(AL4SAN_context_t *al4san) { // #pragma omp taskwait #pragma omp barrier (void)al4san; } //I added it, don't forget to add it to runrime.h void AL4SAN_Openmp_barrier_on(AL4SAN_context_t *al4san, double *ptr) { #pragma omp barrier (void)al4san; } /** * Display a progress information when executing the tasks */ void AL4SAN_Openmp_progress( AL4SAN_context_t *al4san ) { (void)al4san; return; } /******************************************************************************* * Thread rank. **/ int AL4SAN_Openmp_thread_rank(AL4SAN_context_t *al4san) { int thread_rank = omp_get_thread_num(); (void)al4san; return thread_rank; } /** * Number of threads. */ int AL4SAN_Openmp_thread_size( AL4SAN_context_t *al4san ) { (void)al4san; int nworkers; #pragma omp parallel { nworkers=omp_get_num_threads(); } return nworkers; } /** * The process rank */ int AL4SAN_Openmp_comm_rank( AL4SAN_context_t *al4san ) { (void)al4san; return omp_get_thread_num(); } /** * This returns the size of the distributed computation */ int AL4SAN_Openmp_comm_size( AL4SAN_context_t *al4san ) { (void)al4san; return 1; }
MatrixOp.c
#include "../include/MatrixOp.h" //==================== vector operations =========================== // put random values into the matrix if mode == 0 struct Vector * new_vec(int length, int mode) { struct Vector *vecp = (struct Vector *)malloc(sizeof(struct Vector)); vecp->length = length; vecp->vec = (float*)malloc(vecp->length * sizeof(float)); for(int i = 0;i < length;i++) vecp->vec[i] = mode ? 0 : (((float)rand()) / RAND_MAX); return vecp; } void free_vec(struct Vector *vecp) { free(vecp->vec); free(vecp); } void print_vec(struct Vector *vecp) { if(vecp == NULL) return ; for(int i = 0;i < vecp->length;i++) printf("%lf ", vecp->vec[i]); printf("\n"); } //==================== matrix operations =========================== struct Matrix * new_mat(int m, int n, int mode) { struct Matrix *matp = (struct Matrix*)malloc(sizeof(struct Matrix)); matp->m = m, matp->n = n; matp->mat = (struct Vector**)malloc(m * sizeof(struct Vector*)); for(int i = 0;i < m;i++) { matp->mat[i] = new_vec(n, mode); } return matp; } void free_mat(struct Matrix *matp) { for(int i = 0;i < matp->m;i++) free_vec(matp->mat[i]); free(matp); } void print_mat(struct Matrix *matp) { if(matp == NULL) return ; for(int i = 0;i < matp->m;i++) print_vec(matp->mat[i]); printf("\n"); } // take two corners and return the corresponding sub-matrix struct Matrix * subMat(struct Matrix *Mat, int upperLefty, int upperLeftx, int lowerRighty, int lowerRightx) { struct Matrix *resMat = NULL; // size of the matrix must be positive; if(upperLefty > lowerRighty || upperLeftx > lowerRightx) return resMat; // location should fit in valid range; if(upperLefty < 0 || upperLeftx < 0 || lowerRighty >= Mat->m || lowerRightx >= Mat->n) return resMat; resMat = new_mat(lowerRighty - upperLefty + 1, lowerRightx - upperLeftx + 1, 1); for(int i = upperLefty;i <= lowerRighty;i++) for(int j = upperLeftx;j <= lowerRightx;j++) { resMat->mat[i-upperLefty]->vec[j-upperLeftx] = Mat->mat[i]->vec[j]; } return resMat; } // matrix addition/subtraction, optimized by OpenMP and AVX2 // add for mode == 0 and sub for mode == 1 int sign[2]={1,-1}; struct Matrix * matrixAddSub(struct Matrix *mata, struct Matrix *matb, int mode) { struct Matrix *resMat = NULL; if(mata->m != matb->m || mata->n != matb->n) return resMat; resMat = new_mat(mata->m, mata->n, 1); int i, threadCount = omp_get_num_procs(); #ifdef OPENMP #pragma omp parallel for num_threads(threadCount) shared(resMat, mata, matb, sign, mode) private(i) #endif for(i = 0;i < mata->m;i++) { #ifndef AVX for(int j = 0;j < mata->n;j++) resMat->mat[i]->vec[j] = mata->mat[i]->vec[j] + sign[mode] * matb->mat[i]->vec[j]; #else for(int k = 0;k < mata->n / 8;k++) { __m256 intVec1 = _mm256_loadu_ps(&mata->mat[i]->vec[8*k]); __m256 intVec2 = _mm256_loadu_ps(&matb->mat[i]->vec[8*k]); __m256 intVec3 = mode ? _mm256_sub_ps(intVec1, intVec2) : _mm256_add_ps(intVec1, intVec2); _mm256_storeu_ps(&resMat->mat[i]->vec[8*k], intVec3); } for(int k = (mata->n / 8)*8;k < mata->n;k++) resMat->mat[i]->vec[k] = mata->mat[i]->vec[k] + sign[mode] * matb->mat[i]->vec[k]; #endif } return resMat; } // combine four sub-matrices into one matrix; struct Matrix *combineMatrix(struct Matrix *upperLeftMat, struct Matrix *upperRightMat, struct Matrix *lowerLeftMat, struct Matrix *lowerRightMat) { struct Matrix *resMat = NULL; if(upperLeftMat->n != lowerLeftMat->n || upperRightMat->n != lowerRightMat->n) return resMat; if(upperLeftMat->m != upperRightMat->m || lowerLeftMat->m != lowerRightMat->m) return resMat; resMat = new_mat(upperLeftMat->m + lowerLeftMat->m, upperLeftMat->n + upperRightMat->n, 1); int i, threadCount = omp_get_num_procs(); #ifdef OPENMP #pragma omp parallel for num_threads(threadCount) default(none) shared(upperLeftMat, upperRightMat, resMat) private(i) #endif for(i = 0;i < upperLeftMat->m;i++) { for(int j = 0;j < upperLeftMat->n;j++) resMat->mat[i]->vec[j] = upperLeftMat->mat[i]->vec[j]; for(int j = 0;j < upperRightMat->n;j++) resMat->mat[i]->vec[j+upperLeftMat->n] = upperRightMat->mat[i]->vec[j]; } #ifdef OPENMP #pragma omp parallel for num_threads(threadCount) default(none) shared(upperLeftMat, lowerLeftMat, lowerRightMat, resMat) private(i) #endif for(i = 0;i < lowerLeftMat->m;i++) { for(int j = 0;j < lowerLeftMat->n;j++) resMat->mat[i+upperLeftMat->m]->vec[j] = lowerLeftMat->mat[i]->vec[j]; for(int j = 0;j < lowerRightMat->n;j++) resMat->mat[i+upperLeftMat->m]->vec[j+upperLeftMat->n] = lowerRightMat->mat[i]->vec[j]; } return resMat; } // optimization for the brutal multiplication void mul_1_by_1(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { #ifdef REGISTERS register float res = 0; for(int k = 0;k < mata->n;k++) res += mata->mat[i]->vec[k] * matb->mat[k]->vec[j]; resMat->mat[i]->vec[j] = res; #else for(int k = 0;k < mata->n;k++) resMat->mat[i]->vec[j] += mata->mat[i]->vec[k] * matb->mat[k]->vec[j]; #endif } void mul_1_by_4(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { #ifdef REGISTERS register float resMat0, resMat1, resMat2, resMat3, mata0; resMat0 = resMat1 = resMat2 = resMat3 = 0; for(int k = 0;k < mata->n;k++) { mata0 = mata->mat[i]->vec[k]; resMat0 += mata0 * matb->mat[k]->vec[j]; resMat1 += mata0 * matb->mat[k]->vec[j+1]; resMat2 += mata0 * matb->mat[k]->vec[j+2]; resMat3 += mata0 * matb->mat[k]->vec[j+3]; } resMat->mat[i]->vec[j] = resMat0; resMat->mat[i]->vec[j+1] = resMat1; resMat->mat[i]->vec[j+2] = resMat2; resMat->mat[i]->vec[j+3] = resMat3; #else for(int k = 0;k < mata->n;k++) { resMat->mat[i]->vec[j] += mata->mat[i]->vec[k] * matb->mat[k]->vec[j]; resMat->mat[i]->vec[j+1] += mata->mat[i]->vec[k] * matb->mat[k]->vec[j+1]; resMat->mat[i]->vec[j+2] += mata->mat[i]->vec[k] * matb->mat[k]->vec[j+2]; resMat->mat[i]->vec[j+3] += mata->mat[i]->vec[k] * matb->mat[k]->vec[j+3]; } #endif } void mul_1_by_8(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { register float resMat0, resMat1, resMat2, resMat3, resMat4, resMat5, resMat6, resMat7, mata0; resMat0 = resMat1 = resMat2 = resMat3 = resMat4 = resMat5 = resMat6 = resMat7 = 0; for(int k = 0;k < mata->n;k++) { mata0 = mata->mat[i]->vec[k]; resMat0 += mata0 * matb->mat[k]->vec[j]; resMat1 += mata0 * matb->mat[k]->vec[j+1]; resMat2 += mata0 * matb->mat[k]->vec[j+2]; resMat3 += mata0 * matb->mat[k]->vec[j+3]; resMat4 += mata0 * matb->mat[k]->vec[j+4]; resMat5 += mata0 * matb->mat[k]->vec[j+5]; resMat6 += mata0 * matb->mat[k]->vec[j+6]; resMat7 += mata0 * matb->mat[k]->vec[j+7]; } resMat->mat[i]->vec[j] = resMat0; resMat->mat[i]->vec[j+1] = resMat1; resMat->mat[i]->vec[j+2] = resMat2; resMat->mat[i]->vec[j+3] = resMat3; resMat->mat[i]->vec[j+4] = resMat4; resMat->mat[i]->vec[j+5] = resMat5; resMat->mat[i]->vec[j+6] = resMat6; resMat->mat[i]->vec[j+7] = resMat7; } void mul_4_by_1(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { mul_1_by_1(resMat, mata, matb, i, j); mul_1_by_1(resMat, mata, matb, i+1, j); mul_1_by_1(resMat, mata, matb, i+2, j); mul_1_by_1(resMat, mata, matb, i+3, j); } void mul_8_by_1(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { mul_1_by_1(resMat, mata, matb, i, j); mul_1_by_1(resMat, mata, matb, i+1, j); mul_1_by_1(resMat, mata, matb, i+2, j); mul_1_by_1(resMat, mata, matb, i+3, j); mul_1_by_1(resMat, mata, matb, i+4, j); mul_1_by_1(resMat, mata, matb, i+5, j); mul_1_by_1(resMat, mata, matb, i+6, j); mul_1_by_1(resMat, mata, matb, i+7, j); } void mul_4_by_4(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { #ifdef REGISTERS register float resMat00, resMat01, resMat02, resMat03, resMat10, resMat11, resMat12, resMat13, resMat20, resMat21, resMat22, resMat23, resMat30, resMat31, resMat32, resMat33, mata0, mata1, mata2, mata3; resMat00 = resMat01 = resMat02 = resMat03 = 0; resMat10 = resMat11 = resMat12 = resMat13 = 0; resMat20 = resMat21 = resMat22 = resMat23 = 0; resMat30 = resMat31 = resMat32 = resMat33 = 0; for(int k = 0;k < mata->n;k++) { mata0 = mata->mat[i]->vec[k]; mata1 = mata->mat[i+1]->vec[k]; mata2 = mata->mat[i+2]->vec[k]; mata3 = mata->mat[i+3]->vec[k]; resMat00 += mata0 * matb->mat[k]->vec[j]; resMat01 += mata0 * matb->mat[k]->vec[j+1]; resMat02 += mata0 * matb->mat[k]->vec[j+2]; resMat03 += mata0 * matb->mat[k]->vec[j+3]; resMat10 += mata1 * matb->mat[k]->vec[j]; resMat11 += mata1 * matb->mat[k]->vec[j+1]; resMat12 += mata1 * matb->mat[k]->vec[j+2]; resMat13 += mata1 * matb->mat[k]->vec[j+3]; resMat20 += mata2 * matb->mat[k]->vec[j]; resMat21 += mata2 * matb->mat[k]->vec[j+1]; resMat22 += mata2 * matb->mat[k]->vec[j+2]; resMat23 += mata2 * matb->mat[k]->vec[j+3]; resMat30 += mata3 * matb->mat[k]->vec[j]; resMat31 += mata3 * matb->mat[k]->vec[j+1]; resMat32 += mata3 * matb->mat[k]->vec[j+2]; resMat33 += mata3 * matb->mat[k]->vec[j+3]; } resMat->mat[i]->vec[j] = resMat00; resMat->mat[i]->vec[j+1] = resMat01; resMat->mat[i]->vec[j+2] = resMat02; resMat->mat[i]->vec[j+3] = resMat03; resMat->mat[i+1]->vec[j] = resMat10; resMat->mat[i+1]->vec[j+1] = resMat11; resMat->mat[i+1]->vec[j+2] = resMat12; resMat->mat[i+1]->vec[j+3] = resMat13; resMat->mat[i+2]->vec[j] = resMat20; resMat->mat[i+2]->vec[j+1] = resMat21; resMat->mat[i+2]->vec[j+2] = resMat22; resMat->mat[i+2]->vec[j+3] = resMat23; resMat->mat[i+3]->vec[j] = resMat30; resMat->mat[i+3]->vec[j+1] = resMat31; resMat->mat[i+3]->vec[j+2] = resMat32; resMat->mat[i+3]->vec[j+3] = resMat33; #else mul_1_by_4(resMat, mata, matb, i, j); mul_1_by_4(resMat, mata, matb, i+1, j); mul_1_by_4(resMat, mata, matb, i+2, j); mul_1_by_4(resMat, mata, matb, i+3, j); #endif } void mul_4_by_4_AVX(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { __m256 resMat01, resMat23, veca, vecb; register float tmpa[8]; for(int k = 0;k < mata->n;k++) { vecb = _mm256_broadcast_ps((const __m128*)&matb->mat[k]->vec[j]); tmpa[0] = tmpa[1] = tmpa[2] = tmpa[3] = mata->mat[i]->vec[k]; tmpa[4] = tmpa[5] = tmpa[6] = tmpa[7] = mata->mat[i+1]->vec[k]; veca = _mm256_loadu_ps(tmpa); // make assignment at the first update; resMat01 = k ? _mm256_add_ps(resMat01, _mm256_mul_ps(veca, vecb)) : _mm256_mul_ps(veca, vecb); tmpa[0] = tmpa[1] = tmpa[2] = tmpa[3] = mata->mat[i+2]->vec[k]; tmpa[4] = tmpa[5] = tmpa[6] = tmpa[7] = mata->mat[i+3]->vec[k]; veca = _mm256_loadu_ps(tmpa); resMat23 = k ? _mm256_add_ps(resMat23, _mm256_mul_ps(veca, vecb)) : _mm256_mul_ps(veca, vecb); } _mm256_storeu_ps(tmpa, resMat01); for(int k = 0;k < 4;k++) { resMat->mat[i]->vec[j+k] = tmpa[k]; resMat->mat[i+1]->vec[j+k] = tmpa[k+4]; } _mm256_storeu_ps(tmpa, resMat23); for(int k = 0;k < 4;k++) { resMat->mat[i+2]->vec[j+k] = tmpa[k]; resMat->mat[i+3]->vec[j+k] = tmpa[k+4]; } } void mul_8_by_8(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { __m256 vecb, veca0, veca1, veca2, veca3, veca4, veca5, veca6, veca7, resMat0, resMat1, resMat2, resMat3, resMat4, resMat5, resMat6, resMat7; for(int k = 0;k < mata->n;k++) { vecb = _mm256_loadu_ps(&matb->mat[k]->vec[j]); veca0 = _mm256_broadcast_ss(&mata->mat[i]->vec[k]); veca1 = _mm256_broadcast_ss(&mata->mat[i+1]->vec[k]); veca2 = _mm256_broadcast_ss(&mata->mat[i+2]->vec[k]); veca3 = _mm256_broadcast_ss(&mata->mat[i+3]->vec[k]); veca4 = _mm256_broadcast_ss(&mata->mat[i+4]->vec[k]); veca5 = _mm256_broadcast_ss(&mata->mat[i+5]->vec[k]); veca6 = _mm256_broadcast_ss(&mata->mat[i+6]->vec[k]); veca7 = _mm256_broadcast_ss(&mata->mat[i+7]->vec[k]); resMat0 = k ? _mm256_add_ps(resMat0, _mm256_mul_ps(veca0, vecb)) : _mm256_mul_ps(veca0, vecb); resMat1 = k ? _mm256_add_ps(resMat1, _mm256_mul_ps(veca1, vecb)) : _mm256_mul_ps(veca1, vecb); resMat2 = k ? _mm256_add_ps(resMat2, _mm256_mul_ps(veca2, vecb)) : _mm256_mul_ps(veca2, vecb); resMat3 = k ? _mm256_add_ps(resMat3, _mm256_mul_ps(veca3, vecb)) : _mm256_mul_ps(veca3, vecb); resMat4 = k ? _mm256_add_ps(resMat4, _mm256_mul_ps(veca4, vecb)) : _mm256_mul_ps(veca4, vecb); resMat5 = k ? _mm256_add_ps(resMat5, _mm256_mul_ps(veca5, vecb)) : _mm256_mul_ps(veca5, vecb); resMat6 = k ? _mm256_add_ps(resMat6, _mm256_mul_ps(veca6, vecb)) : _mm256_mul_ps(veca6, vecb); resMat7 = k ? _mm256_add_ps(resMat7, _mm256_mul_ps(veca7, vecb)) : _mm256_mul_ps(veca7, vecb); } _mm256_storeu_ps(&resMat->mat[i]->vec[j], resMat0); _mm256_storeu_ps(&resMat->mat[i+1]->vec[j], resMat1); _mm256_storeu_ps(&resMat->mat[i+2]->vec[j], resMat2); _mm256_storeu_ps(&resMat->mat[i+3]->vec[j], resMat3); _mm256_storeu_ps(&resMat->mat[i+4]->vec[j], resMat4); _mm256_storeu_ps(&resMat->mat[i+5]->vec[j], resMat5); _mm256_storeu_ps(&resMat->mat[i+6]->vec[j], resMat6); _mm256_storeu_ps(&resMat->mat[i+7]->vec[j], resMat7); } //==================== Other helper operations =========================== int Min(int a, int b) { return a > b ? b : a; } int Max(int a, int b) { return a > b ? a : b; }
ompfor5.c
/* * test decremental loop iteration space * Liao 9/22/2009 */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif void foo(int iend, int ist) { int i; #pragma omp parallel { #pragma omp single printf ("Using %d threads.\n",omp_get_num_threads()); #pragma omp for nowait schedule(static) for (i=iend;i>=ist;i--) { printf("Iteration %d is carried out by thread %d\n",i, omp_get_thread_num()); } } }
pi_omp_atomic.c
/* * Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x) * between 0 and 1. * * Parallel version using OpenMP */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <omp.h> /* OpenMP */ double getusec_() { struct timeval time; gettimeofday(&time, NULL); return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec); } #define START_COUNT_TIME stamp = getusec_(); #define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\ stamp = stamp/1e6;\ printf ("%0.6f\n", stamp); int main(int argc, char *argv[]) { double stamp; double x, sum=0.0, pi=0.0; double step; const char Usage[] = "Usage: pi <num_steps> <num_threads>\n"; if (argc < 3) { fprintf(stderr, Usage); exit(1); } long int num_steps = atoi(argv[1]); step = 1.0/(double) num_steps; int num_threads = atoi(argv[2]); START_COUNT_TIME; #pragma omp parallel private(x) num_threads(num_threads) { #pragma omp for for (long int i=0; i<num_steps; ++i) { x = (i+0.5)*step; #pragma omp atomic sum += 4.0/(1.0+x*x); } } pi = step * sum; STOP_COUNT_TIME("Total execution time"); /* print results */ //printf("Number pi after %ld iterations = %.15f\n", num_steps, pi); return EXIT_SUCCESS; }